1 //===--- InitHeaderSearch.cpp - Initialize header search paths ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the InitHeaderSearch class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Config/config.h" // C_INCLUDE_DIRS
16 #include "clang/Frontend/FrontendDiagnostic.h"
17 #include "clang/Frontend/Utils.h"
18 #include "clang/Lex/HeaderMap.h"
19 #include "clang/Lex/HeaderSearch.h"
20 #include "clang/Lex/HeaderSearchOptions.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/raw_ostream.h"
30 
31 using namespace clang;
32 using namespace clang::frontend;
33 
34 namespace {
35 /// Holds information about a single DirectoryLookup object.
36 struct DirectoryLookupInfo {
37   IncludeDirGroup Group;
38   DirectoryLookup Lookup;
39 
DirectoryLookupInfo__anon3858ab560111::DirectoryLookupInfo40   DirectoryLookupInfo(IncludeDirGroup Group, DirectoryLookup Lookup)
41       : Group(Group), Lookup(Lookup) {}
42 };
43 
44 /// InitHeaderSearch - This class makes it easier to set the search paths of
45 ///  a HeaderSearch object. InitHeaderSearch stores several search path lists
46 ///  internally, which can be sent to a HeaderSearch object in one swoop.
47 class InitHeaderSearch {
48   std::vector<DirectoryLookupInfo> IncludePath;
49   std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
50   HeaderSearch &Headers;
51   bool Verbose;
52   std::string IncludeSysroot;
53   bool HasSysroot;
54 
55 public:
InitHeaderSearch(HeaderSearch & HS,bool verbose,StringRef sysroot)56   InitHeaderSearch(HeaderSearch &HS, bool verbose, StringRef sysroot)
57       : Headers(HS), Verbose(verbose), IncludeSysroot(std::string(sysroot)),
58         HasSysroot(!(sysroot.empty() || sysroot == "/")) {}
59 
60   /// AddPath - Add the specified path to the specified group list, prefixing
61   /// the sysroot if used.
62   /// Returns true if the path exists, false if it was ignored.
63   bool AddPath(const Twine &Path, IncludeDirGroup Group, bool isFramework);
64 
65   /// AddUnmappedPath - Add the specified path to the specified group list,
66   /// without performing any sysroot remapping.
67   /// Returns true if the path exists, false if it was ignored.
68   bool AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
69                        bool isFramework);
70 
71   /// AddSystemHeaderPrefix - Add the specified prefix to the system header
72   /// prefix list.
AddSystemHeaderPrefix(StringRef Prefix,bool IsSystemHeader)73   void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader) {
74     SystemHeaderPrefixes.emplace_back(std::string(Prefix), IsSystemHeader);
75   }
76 
77   /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to support a gnu
78   ///  libstdc++.
79   /// Returns true if the \p Base path was found, false if it does not exist.
80   bool AddGnuCPlusPlusIncludePaths(StringRef Base, StringRef ArchDir,
81                                    StringRef Dir32, StringRef Dir64,
82                                    const llvm::Triple &triple);
83 
84   /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to support a MinGW
85   ///  libstdc++.
86   void AddMinGWCPlusPlusIncludePaths(StringRef Base,
87                                      StringRef Arch,
88                                      StringRef Version);
89 
90   // AddDefaultCIncludePaths - Add paths that should always be searched.
91   void AddDefaultCIncludePaths(const llvm::Triple &triple,
92                                const HeaderSearchOptions &HSOpts);
93 
94   // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
95   //  compiling c++.
96   void AddDefaultCPlusPlusIncludePaths(const LangOptions &LangOpts,
97                                        const llvm::Triple &triple,
98                                        const HeaderSearchOptions &HSOpts);
99 
100   /// AddDefaultSystemIncludePaths - Adds the default system include paths so
101   ///  that e.g. stdio.h is found.
102   void AddDefaultIncludePaths(const LangOptions &Lang,
103                               const llvm::Triple &triple,
104                               const HeaderSearchOptions &HSOpts);
105 
106   /// Realize - Merges all search path lists into one list and send it to
107   /// HeaderSearch.
108   void Realize(const LangOptions &Lang);
109 };
110 
111 }  // end anonymous namespace.
112 
CanPrefixSysroot(StringRef Path)113 static bool CanPrefixSysroot(StringRef Path) {
114 #if defined(_WIN32)
115   return !Path.empty() && llvm::sys::path::is_separator(Path[0]);
116 #else
117   return llvm::sys::path::is_absolute(Path);
118 #endif
119 }
120 
AddPath(const Twine & Path,IncludeDirGroup Group,bool isFramework)121 bool InitHeaderSearch::AddPath(const Twine &Path, IncludeDirGroup Group,
122                                bool isFramework) {
123   // Add the path with sysroot prepended, if desired and this is a system header
124   // group.
125   if (HasSysroot) {
126     SmallString<256> MappedPathStorage;
127     StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
128     if (CanPrefixSysroot(MappedPathStr)) {
129       return AddUnmappedPath(IncludeSysroot + Path, Group, isFramework);
130     }
131   }
132 
133   return AddUnmappedPath(Path, Group, isFramework);
134 }
135 
AddUnmappedPath(const Twine & Path,IncludeDirGroup Group,bool isFramework)136 bool InitHeaderSearch::AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
137                                        bool isFramework) {
138   assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
139 
140   FileManager &FM = Headers.getFileMgr();
141   SmallString<256> MappedPathStorage;
142   StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
143 
144   // If use system headers while cross-compiling, emit the warning.
145   if (HasSysroot && (MappedPathStr.startswith("/usr/include") ||
146                      MappedPathStr.startswith("/usr/local/include"))) {
147     Headers.getDiags().Report(diag::warn_poison_system_directories)
148         << MappedPathStr;
149   }
150 
151   // Compute the DirectoryLookup type.
152   SrcMgr::CharacteristicKind Type;
153   if (Group == Quoted || Group == Angled || Group == IndexHeaderMap) {
154     Type = SrcMgr::C_User;
155   } else if (Group == ExternCSystem) {
156     Type = SrcMgr::C_ExternCSystem;
157   } else {
158     Type = SrcMgr::C_System;
159   }
160 
161   // If the directory exists, add it.
162   if (auto DE = FM.getOptionalDirectoryRef(MappedPathStr)) {
163     IncludePath.emplace_back(Group, DirectoryLookup(*DE, Type, isFramework));
164     return true;
165   }
166 
167   // Check to see if this is an apple-style headermap (which are not allowed to
168   // be frameworks).
169   if (!isFramework) {
170     if (auto FE = FM.getFile(MappedPathStr)) {
171       if (const HeaderMap *HM = Headers.CreateHeaderMap(*FE)) {
172         // It is a headermap, add it to the search path.
173         IncludePath.emplace_back(
174             Group, DirectoryLookup(HM, Type, Group == IndexHeaderMap));
175         return true;
176       }
177     }
178   }
179 
180   if (Verbose)
181     llvm::errs() << "ignoring nonexistent directory \""
182                  << MappedPathStr << "\"\n";
183   return false;
184 }
185 
AddGnuCPlusPlusIncludePaths(StringRef Base,StringRef ArchDir,StringRef Dir32,StringRef Dir64,const llvm::Triple & triple)186 bool InitHeaderSearch::AddGnuCPlusPlusIncludePaths(StringRef Base,
187                                                    StringRef ArchDir,
188                                                    StringRef Dir32,
189                                                    StringRef Dir64,
190                                                    const llvm::Triple &triple) {
191   // Add the base dir
192   bool IsBaseFound = AddPath(Base, CXXSystem, false);
193 
194   // Add the multilib dirs
195   llvm::Triple::ArchType arch = triple.getArch();
196   bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
197   if (is64bit)
198     AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, false);
199   else
200     AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, false);
201 
202   // Add the backward dir
203   AddPath(Base + "/backward", CXXSystem, false);
204   return IsBaseFound;
205 }
206 
AddMinGWCPlusPlusIncludePaths(StringRef Base,StringRef Arch,StringRef Version)207 void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(StringRef Base,
208                                                      StringRef Arch,
209                                                      StringRef Version) {
210   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
211           CXXSystem, false);
212   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/" + Arch,
213           CXXSystem, false);
214   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
215           CXXSystem, false);
216 }
217 
AddDefaultCIncludePaths(const llvm::Triple & triple,const HeaderSearchOptions & HSOpts)218 void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
219                                             const HeaderSearchOptions &HSOpts) {
220   llvm::Triple::OSType os = triple.getOS();
221 
222   if (triple.isOSDarwin()) {
223     llvm_unreachable("Include management is handled in the driver.");
224   }
225 
226   if (HSOpts.UseStandardSystemIncludes) {
227     switch (os) {
228     case llvm::Triple::CloudABI:
229     case llvm::Triple::FreeBSD:
230     case llvm::Triple::NetBSD:
231     case llvm::Triple::OpenBSD:
232     case llvm::Triple::NaCl:
233     case llvm::Triple::PS4:
234     case llvm::Triple::ELFIAMCU:
235     case llvm::Triple::Fuchsia:
236       break;
237     case llvm::Triple::Win32:
238       if (triple.getEnvironment() != llvm::Triple::Cygnus)
239         break;
240       LLVM_FALLTHROUGH;
241     default:
242       // FIXME: temporary hack: hard-coded paths.
243       AddPath("/usr/local/include", System, false);
244       break;
245     }
246   }
247 
248   // Builtin includes use #include_next directives and should be positioned
249   // just prior C include dirs.
250   if (HSOpts.UseBuiltinIncludes) {
251     // Ignore the sys root, we *always* look for clang headers relative to
252     // supplied path.
253     SmallString<128> P = StringRef(HSOpts.ResourceDir);
254     llvm::sys::path::append(P, "include");
255     AddUnmappedPath(P, ExternCSystem, false);
256   }
257 
258   // All remaining additions are for system include directories, early exit if
259   // we aren't using them.
260   if (!HSOpts.UseStandardSystemIncludes)
261     return;
262 
263   // Add dirs specified via 'configure --with-c-include-dirs'.
264   StringRef CIncludeDirs(C_INCLUDE_DIRS);
265   if (CIncludeDirs != "") {
266     SmallVector<StringRef, 5> dirs;
267     CIncludeDirs.split(dirs, ":");
268     for (StringRef dir : dirs)
269       AddPath(dir, ExternCSystem, false);
270     return;
271   }
272 
273   switch (os) {
274   case llvm::Triple::Linux:
275   case llvm::Triple::Hurd:
276   case llvm::Triple::Solaris:
277   case llvm::Triple::OpenBSD:
278     llvm_unreachable("Include management is handled in the driver.");
279 
280   case llvm::Triple::CloudABI: {
281     // <sysroot>/<triple>/include
282     SmallString<128> P = StringRef(HSOpts.ResourceDir);
283     llvm::sys::path::append(P, "../../..", triple.str(), "include");
284     AddPath(P, System, false);
285     break;
286   }
287 
288   case llvm::Triple::Haiku:
289     AddPath("/boot/system/non-packaged/develop/headers", System, false);
290     AddPath("/boot/system/develop/headers/os", System, false);
291     AddPath("/boot/system/develop/headers/os/app", System, false);
292     AddPath("/boot/system/develop/headers/os/arch", System, false);
293     AddPath("/boot/system/develop/headers/os/device", System, false);
294     AddPath("/boot/system/develop/headers/os/drivers", System, false);
295     AddPath("/boot/system/develop/headers/os/game", System, false);
296     AddPath("/boot/system/develop/headers/os/interface", System, false);
297     AddPath("/boot/system/develop/headers/os/kernel", System, false);
298     AddPath("/boot/system/develop/headers/os/locale", System, false);
299     AddPath("/boot/system/develop/headers/os/mail", System, false);
300     AddPath("/boot/system/develop/headers/os/media", System, false);
301     AddPath("/boot/system/develop/headers/os/midi", System, false);
302     AddPath("/boot/system/develop/headers/os/midi2", System, false);
303     AddPath("/boot/system/develop/headers/os/net", System, false);
304     AddPath("/boot/system/develop/headers/os/opengl", System, false);
305     AddPath("/boot/system/develop/headers/os/storage", System, false);
306     AddPath("/boot/system/develop/headers/os/support", System, false);
307     AddPath("/boot/system/develop/headers/os/translation", System, false);
308     AddPath("/boot/system/develop/headers/os/add-ons/graphics", System, false);
309     AddPath("/boot/system/develop/headers/os/add-ons/input_server", System, false);
310     AddPath("/boot/system/develop/headers/os/add-ons/mail_daemon", System, false);
311     AddPath("/boot/system/develop/headers/os/add-ons/registrar", System, false);
312     AddPath("/boot/system/develop/headers/os/add-ons/screen_saver", System, false);
313     AddPath("/boot/system/develop/headers/os/add-ons/tracker", System, false);
314     AddPath("/boot/system/develop/headers/os/be_apps/Deskbar", System, false);
315     AddPath("/boot/system/develop/headers/os/be_apps/NetPositive", System, false);
316     AddPath("/boot/system/develop/headers/os/be_apps/Tracker", System, false);
317     AddPath("/boot/system/develop/headers/3rdparty", System, false);
318     AddPath("/boot/system/develop/headers/bsd", System, false);
319     AddPath("/boot/system/develop/headers/glibc", System, false);
320     AddPath("/boot/system/develop/headers/posix", System, false);
321     AddPath("/boot/system/develop/headers",  System, false);
322     break;
323   case llvm::Triple::RTEMS:
324     break;
325   case llvm::Triple::Win32:
326     switch (triple.getEnvironment()) {
327     default: llvm_unreachable("Include management is handled in the driver.");
328     case llvm::Triple::Cygnus:
329       AddPath("/usr/include/w32api", System, false);
330       break;
331     case llvm::Triple::GNU:
332       break;
333     }
334     break;
335   default:
336     break;
337   }
338 
339   switch (os) {
340   case llvm::Triple::CloudABI:
341   case llvm::Triple::RTEMS:
342   case llvm::Triple::NaCl:
343   case llvm::Triple::ELFIAMCU:
344   case llvm::Triple::Fuchsia:
345     break;
346   case llvm::Triple::PS4: {
347     // <isysroot> gets prepended later in AddPath().
348     std::string BaseSDKPath = "";
349     if (!HasSysroot) {
350       const char *envValue = getenv("SCE_ORBIS_SDK_DIR");
351       if (envValue)
352         BaseSDKPath = envValue;
353       else {
354         // HSOpts.ResourceDir variable contains the location of Clang's
355         // resource files.
356         // Assuming that Clang is configured for PS4 without
357         // --with-clang-resource-dir option, the location of Clang's resource
358         // files is <SDK_DIR>/host_tools/lib/clang
359         SmallString<128> P = StringRef(HSOpts.ResourceDir);
360         llvm::sys::path::append(P, "../../..");
361         BaseSDKPath = std::string(P.str());
362       }
363     }
364     AddPath(BaseSDKPath + "/target/include", System, false);
365     if (triple.isPS4CPU())
366       AddPath(BaseSDKPath + "/target/include_common", System, false);
367     LLVM_FALLTHROUGH;
368   }
369   default:
370     AddPath("/usr/include", ExternCSystem, false);
371     break;
372   }
373 }
374 
AddDefaultCPlusPlusIncludePaths(const LangOptions & LangOpts,const llvm::Triple & triple,const HeaderSearchOptions & HSOpts)375 void InitHeaderSearch::AddDefaultCPlusPlusIncludePaths(
376     const LangOptions &LangOpts, const llvm::Triple &triple,
377     const HeaderSearchOptions &HSOpts) {
378   llvm::Triple::OSType os = triple.getOS();
379   // FIXME: temporary hack: hard-coded paths.
380 
381   if (triple.isOSDarwin()) {
382     llvm_unreachable("Include management is handled in the driver.");
383   }
384 
385   switch (os) {
386   case llvm::Triple::Linux:
387   case llvm::Triple::Hurd:
388   case llvm::Triple::Solaris:
389   case llvm::Triple::AIX:
390     llvm_unreachable("Include management is handled in the driver.");
391     break;
392   case llvm::Triple::Win32:
393     switch (triple.getEnvironment()) {
394     default: llvm_unreachable("Include management is handled in the driver.");
395     case llvm::Triple::Cygnus:
396       // Cygwin-1.7
397       AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.7.3");
398       AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.5.3");
399       AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.4");
400       // g++-4 / Cygwin-1.5
401       AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.2");
402       break;
403     }
404     break;
405   case llvm::Triple::DragonFly:
406     AddPath("/usr/include/c++/8.0", CXXSystem, false);
407     break;
408   case llvm::Triple::Minix:
409     AddGnuCPlusPlusIncludePaths("/usr/gnu/include/c++/4.4.3",
410                                 "", "", "", triple);
411     break;
412   default:
413     break;
414   }
415 }
416 
AddDefaultIncludePaths(const LangOptions & Lang,const llvm::Triple & triple,const HeaderSearchOptions & HSOpts)417 void InitHeaderSearch::AddDefaultIncludePaths(const LangOptions &Lang,
418                                               const llvm::Triple &triple,
419                                             const HeaderSearchOptions &HSOpts) {
420   // NB: This code path is going away. All of the logic is moving into the
421   // driver which has the information necessary to do target-specific
422   // selections of default include paths. Each target which moves there will be
423   // exempted from this logic here until we can delete the entire pile of code.
424   switch (triple.getOS()) {
425   default:
426     break; // Everything else continues to use this routine's logic.
427 
428   case llvm::Triple::Emscripten:
429   case llvm::Triple::Linux:
430   case llvm::Triple::Hurd:
431   case llvm::Triple::OpenBSD:
432   case llvm::Triple::Solaris:
433   case llvm::Triple::WASI:
434   case llvm::Triple::AIX:
435     return;
436 
437   case llvm::Triple::Win32:
438     if (triple.getEnvironment() != llvm::Triple::Cygnus ||
439         triple.isOSBinFormatMachO())
440       return;
441     break;
442 
443   case llvm::Triple::UnknownOS:
444     if (triple.isWasm())
445       return;
446     break;
447   }
448 
449   // All header search logic is handled in the Driver for Darwin.
450   if (triple.isOSDarwin()) {
451     if (HSOpts.UseStandardSystemIncludes) {
452       // Add the default framework include paths on Darwin.
453       AddPath("/System/Library/Frameworks", System, true);
454       AddPath("/Library/Frameworks", System, true);
455     }
456     return;
457   }
458 
459   if (Lang.CPlusPlus && !Lang.AsmPreprocessor &&
460       HSOpts.UseStandardCXXIncludes && HSOpts.UseStandardSystemIncludes) {
461     if (HSOpts.UseLibcxx) {
462       AddPath("/usr/include/c++/v1", CXXSystem, false);
463     } else {
464       AddDefaultCPlusPlusIncludePaths(Lang, triple, HSOpts);
465     }
466   }
467 
468   AddDefaultCIncludePaths(triple, HSOpts);
469 }
470 
471 /// RemoveDuplicates - If there are duplicate directory entries in the specified
472 /// search list, remove the later (dead) ones.  Returns the number of non-system
473 /// headers removed, which is used to update NumAngled.
RemoveDuplicates(std::vector<DirectoryLookup> & SearchList,unsigned First,bool Verbose)474 static unsigned RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
475                                  unsigned First, bool Verbose) {
476   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
477   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
478   llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
479   unsigned NonSystemRemoved = 0;
480   for (unsigned i = First; i != SearchList.size(); ++i) {
481     unsigned DirToRemove = i;
482 
483     const DirectoryLookup &CurEntry = SearchList[i];
484 
485     if (CurEntry.isNormalDir()) {
486       // If this isn't the first time we've seen this dir, remove it.
487       if (SeenDirs.insert(CurEntry.getDir()).second)
488         continue;
489     } else if (CurEntry.isFramework()) {
490       // If this isn't the first time we've seen this framework dir, remove it.
491       if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()).second)
492         continue;
493     } else {
494       assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
495       // If this isn't the first time we've seen this headermap, remove it.
496       if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()).second)
497         continue;
498     }
499 
500     // If we have a normal #include dir/framework/headermap that is shadowed
501     // later in the chain by a system include location, we actually want to
502     // ignore the user's request and drop the user dir... keeping the system
503     // dir.  This is weird, but required to emulate GCC's search path correctly.
504     //
505     // Since dupes of system dirs are rare, just rescan to find the original
506     // that we're nuking instead of using a DenseMap.
507     if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
508       // Find the dir that this is the same of.
509       unsigned FirstDir;
510       for (FirstDir = First;; ++FirstDir) {
511         assert(FirstDir != i && "Didn't find dupe?");
512 
513         const DirectoryLookup &SearchEntry = SearchList[FirstDir];
514 
515         // If these are different lookup types, then they can't be the dupe.
516         if (SearchEntry.getLookupType() != CurEntry.getLookupType())
517           continue;
518 
519         bool isSame;
520         if (CurEntry.isNormalDir())
521           isSame = SearchEntry.getDir() == CurEntry.getDir();
522         else if (CurEntry.isFramework())
523           isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
524         else {
525           assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
526           isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
527         }
528 
529         if (isSame)
530           break;
531       }
532 
533       // If the first dir in the search path is a non-system dir, zap it
534       // instead of the system one.
535       if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
536         DirToRemove = FirstDir;
537     }
538 
539     if (Verbose) {
540       llvm::errs() << "ignoring duplicate directory \""
541                    << CurEntry.getName() << "\"\n";
542       if (DirToRemove != i)
543         llvm::errs() << "  as it is a non-system directory that duplicates "
544                      << "a system directory\n";
545     }
546     if (DirToRemove != i)
547       ++NonSystemRemoved;
548 
549     // This is reached if the current entry is a duplicate.  Remove the
550     // DirToRemove (usually the current dir).
551     SearchList.erase(SearchList.begin()+DirToRemove);
552     --i;
553   }
554   return NonSystemRemoved;
555 }
556 
557 
Realize(const LangOptions & Lang)558 void InitHeaderSearch::Realize(const LangOptions &Lang) {
559   // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
560   std::vector<DirectoryLookup> SearchList;
561   SearchList.reserve(IncludePath.size());
562 
563   // Quoted arguments go first.
564   for (auto &Include : IncludePath)
565     if (Include.Group == Quoted)
566       SearchList.push_back(Include.Lookup);
567 
568   // Deduplicate and remember index.
569   RemoveDuplicates(SearchList, 0, Verbose);
570   unsigned NumQuoted = SearchList.size();
571 
572   for (auto &Include : IncludePath)
573     if (Include.Group == Angled || Include.Group == IndexHeaderMap)
574       SearchList.push_back(Include.Lookup);
575 
576   RemoveDuplicates(SearchList, NumQuoted, Verbose);
577   unsigned NumAngled = SearchList.size();
578 
579   for (auto &Include : IncludePath)
580     if (Include.Group == System || Include.Group == ExternCSystem ||
581         (!Lang.ObjC && !Lang.CPlusPlus && Include.Group == CSystem) ||
582         (/*FIXME !Lang.ObjC && */ Lang.CPlusPlus &&
583          Include.Group == CXXSystem) ||
584         (Lang.ObjC && !Lang.CPlusPlus && Include.Group == ObjCSystem) ||
585         (Lang.ObjC && Lang.CPlusPlus && Include.Group == ObjCXXSystem))
586       SearchList.push_back(Include.Lookup);
587 
588   for (auto &Include : IncludePath)
589     if (Include.Group == After)
590       SearchList.push_back(Include.Lookup);
591 
592   // Remove duplicates across both the Angled and System directories.  GCC does
593   // this and failing to remove duplicates across these two groups breaks
594   // #include_next.
595   unsigned NonSystemRemoved = RemoveDuplicates(SearchList, NumQuoted, Verbose);
596   NumAngled -= NonSystemRemoved;
597 
598   bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
599   Headers.SetSearchPaths(SearchList, NumQuoted, NumAngled, DontSearchCurDir);
600 
601   Headers.SetSystemHeaderPrefixes(SystemHeaderPrefixes);
602 
603   // If verbose, print the list of directories that will be searched.
604   if (Verbose) {
605     llvm::errs() << "#include \"...\" search starts here:\n";
606     for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
607       if (i == NumQuoted)
608         llvm::errs() << "#include <...> search starts here:\n";
609       StringRef Name = SearchList[i].getName();
610       const char *Suffix;
611       if (SearchList[i].isNormalDir())
612         Suffix = "";
613       else if (SearchList[i].isFramework())
614         Suffix = " (framework directory)";
615       else {
616         assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
617         Suffix = " (headermap)";
618       }
619       llvm::errs() << " " << Name << Suffix << "\n";
620     }
621     llvm::errs() << "End of search list.\n";
622   }
623 }
624 
ApplyHeaderSearchOptions(HeaderSearch & HS,const HeaderSearchOptions & HSOpts,const LangOptions & Lang,const llvm::Triple & Triple)625 void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
626                                      const HeaderSearchOptions &HSOpts,
627                                      const LangOptions &Lang,
628                                      const llvm::Triple &Triple) {
629   InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
630 
631   // Add the user defined entries.
632   for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
633     const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
634     if (E.IgnoreSysRoot) {
635       Init.AddUnmappedPath(E.Path, E.Group, E.IsFramework);
636     } else {
637       Init.AddPath(E.Path, E.Group, E.IsFramework);
638     }
639   }
640 
641   Init.AddDefaultIncludePaths(Lang, Triple, HSOpts);
642 
643   for (unsigned i = 0, e = HSOpts.SystemHeaderPrefixes.size(); i != e; ++i)
644     Init.AddSystemHeaderPrefix(HSOpts.SystemHeaderPrefixes[i].Prefix,
645                                HSOpts.SystemHeaderPrefixes[i].IsSystemHeader);
646 
647   if (HSOpts.UseBuiltinIncludes) {
648     // Set up the builtin include directory in the module map.
649     SmallString<128> P = StringRef(HSOpts.ResourceDir);
650     llvm::sys::path::append(P, "include");
651     if (auto Dir = HS.getFileMgr().getDirectory(P))
652       HS.getModuleMap().setBuiltinIncludeDir(*Dir);
653   }
654 
655   Init.Realize(Lang);
656 }
657