InitHeaderSearch.cpp 26 KB

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