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