InitHeaderSearch.cpp 26 KB

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