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