HeaderSearch.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the DirectoryLookup and HeaderSearch interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/HeaderSearch.h"
  14. #include "clang/Lex/HeaderMap.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/IdentifierTable.h"
  17. #include "llvm/System/Path.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include <cstdio>
  20. using namespace clang;
  21. const IdentifierInfo *
  22. HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) {
  23. if (ControllingMacro)
  24. return ControllingMacro;
  25. if (!ControllingMacroID || !External)
  26. return 0;
  27. ControllingMacro = External->GetIdentifier(ControllingMacroID);
  28. return ControllingMacro;
  29. }
  30. HeaderSearch::HeaderSearch(FileManager &FM)
  31. : FileMgr(FM), FrameworkMap(64) {
  32. SystemDirIdx = 0;
  33. NoCurDirSearch = false;
  34. ExternalLookup = 0;
  35. NumIncluded = 0;
  36. NumMultiIncludeFileOptzn = 0;
  37. NumFrameworkLookups = NumSubFrameworkLookups = 0;
  38. }
  39. HeaderSearch::~HeaderSearch() {
  40. // Delete headermaps.
  41. for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
  42. delete HeaderMaps[i].second;
  43. }
  44. void HeaderSearch::PrintStats() {
  45. fprintf(stderr, "\n*** HeaderSearch Stats:\n");
  46. fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
  47. unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
  48. for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
  49. NumOnceOnlyFiles += FileInfo[i].isImport;
  50. if (MaxNumIncludes < FileInfo[i].NumIncludes)
  51. MaxNumIncludes = FileInfo[i].NumIncludes;
  52. NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
  53. }
  54. fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
  55. fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
  56. fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
  57. fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
  58. fprintf(stderr, " %d #includes skipped due to"
  59. " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
  60. fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
  61. fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
  62. }
  63. /// CreateHeaderMap - This method returns a HeaderMap for the specified
  64. /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
  65. const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
  66. // We expect the number of headermaps to be small, and almost always empty.
  67. // If it ever grows, use of a linear search should be re-evaluated.
  68. if (!HeaderMaps.empty()) {
  69. for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
  70. // Pointer equality comparison of FileEntries works because they are
  71. // already uniqued by inode.
  72. if (HeaderMaps[i].first == FE)
  73. return HeaderMaps[i].second;
  74. }
  75. if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
  76. HeaderMaps.push_back(std::make_pair(FE, HM));
  77. return HM;
  78. }
  79. return 0;
  80. }
  81. //===----------------------------------------------------------------------===//
  82. // File lookup within a DirectoryLookup scope
  83. //===----------------------------------------------------------------------===//
  84. /// getName - Return the directory or filename corresponding to this lookup
  85. /// object.
  86. const char *DirectoryLookup::getName() const {
  87. if (isNormalDir())
  88. return getDir()->getName();
  89. if (isFramework())
  90. return getFrameworkDir()->getName();
  91. assert(isHeaderMap() && "Unknown DirectoryLookup");
  92. return getHeaderMap()->getFileName();
  93. }
  94. /// LookupFile - Lookup the specified file in this search path, returning it
  95. /// if it exists or returning null if not.
  96. const FileEntry *DirectoryLookup::LookupFile(llvm::StringRef Filename,
  97. HeaderSearch &HS) const {
  98. llvm::SmallString<1024> TmpDir;
  99. if (isNormalDir()) {
  100. // Concatenate the requested file onto the directory.
  101. // FIXME: Portability. Filename concatenation should be in sys::Path.
  102. TmpDir += getDir()->getName();
  103. TmpDir.push_back('/');
  104. TmpDir.append(Filename.begin(), Filename.end());
  105. return HS.getFileMgr().getFile(TmpDir.str());
  106. }
  107. if (isFramework())
  108. return DoFrameworkLookup(Filename, HS);
  109. assert(isHeaderMap() && "Unknown directory lookup");
  110. return getHeaderMap()->LookupFile(Filename, HS.getFileMgr());
  111. }
  112. /// DoFrameworkLookup - Do a lookup of the specified file in the current
  113. /// DirectoryLookup, which is a framework directory.
  114. const FileEntry *DirectoryLookup::DoFrameworkLookup(llvm::StringRef Filename,
  115. HeaderSearch &HS) const {
  116. FileManager &FileMgr = HS.getFileMgr();
  117. // Framework names must have a '/' in the filename.
  118. size_t SlashPos = Filename.find('/');
  119. if (SlashPos == llvm::StringRef::npos) return 0;
  120. // Find out if this is the home for the specified framework, by checking
  121. // HeaderSearch. Possible answer are yes/no and unknown.
  122. const DirectoryEntry *&FrameworkDirCache =
  123. HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
  124. // If it is known and in some other directory, fail.
  125. if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
  126. return 0;
  127. // Otherwise, construct the path to this framework dir.
  128. // FrameworkName = "/System/Library/Frameworks/"
  129. llvm::SmallString<1024> FrameworkName;
  130. FrameworkName += getFrameworkDir()->getName();
  131. if (FrameworkName.empty() || FrameworkName.back() != '/')
  132. FrameworkName.push_back('/');
  133. // FrameworkName = "/System/Library/Frameworks/Cocoa"
  134. FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
  135. // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
  136. FrameworkName += ".framework/";
  137. // If the cache entry is still unresolved, query to see if the cache entry is
  138. // still unresolved. If so, check its existence now.
  139. if (FrameworkDirCache == 0) {
  140. HS.IncrementFrameworkLookupCount();
  141. // If the framework dir doesn't exist, we fail.
  142. // FIXME: It's probably more efficient to query this with FileMgr.getDir.
  143. if (!llvm::sys::Path(std::string(FrameworkName.begin(),
  144. FrameworkName.end())).exists())
  145. return 0;
  146. // Otherwise, if it does, remember that this is the right direntry for this
  147. // framework.
  148. FrameworkDirCache = getFrameworkDir();
  149. }
  150. // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
  151. unsigned OrigSize = FrameworkName.size();
  152. FrameworkName += "Headers/";
  153. FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
  154. if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str()))
  155. return FE;
  156. // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
  157. const char *Private = "Private";
  158. FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
  159. Private+strlen(Private));
  160. return FileMgr.getFile(FrameworkName.str());
  161. }
  162. //===----------------------------------------------------------------------===//
  163. // Header File Location.
  164. //===----------------------------------------------------------------------===//
  165. /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
  166. /// return null on failure. isAngled indicates whether the file reference is
  167. /// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
  168. /// non-null, indicates where the #including file is, in case a relative search
  169. /// is needed.
  170. const FileEntry *HeaderSearch::LookupFile(llvm::StringRef Filename,
  171. bool isAngled,
  172. const DirectoryLookup *FromDir,
  173. const DirectoryLookup *&CurDir,
  174. const FileEntry *CurFileEnt) {
  175. // If 'Filename' is absolute, check to see if it exists and no searching.
  176. if (llvm::sys::Path::isAbsolute(Filename.begin(), Filename.size())) {
  177. CurDir = 0;
  178. // If this was an #include_next "/absolute/file", fail.
  179. if (FromDir) return 0;
  180. // Otherwise, just return the file.
  181. return FileMgr.getFile(Filename);
  182. }
  183. // Step #0, unless disabled, check to see if the file is in the #includer's
  184. // directory. This has to be based on CurFileEnt, not CurDir, because
  185. // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
  186. // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
  187. // This search is not done for <> headers.
  188. if (CurFileEnt && !isAngled && !NoCurDirSearch) {
  189. llvm::SmallString<1024> TmpDir;
  190. // Concatenate the requested file onto the directory.
  191. // FIXME: Portability. Filename concatenation should be in sys::Path.
  192. TmpDir += CurFileEnt->getDir()->getName();
  193. TmpDir.push_back('/');
  194. TmpDir.append(Filename.begin(), Filename.end());
  195. if (const FileEntry *FE = FileMgr.getFile(TmpDir.str())) {
  196. // Leave CurDir unset.
  197. // This file is a system header or C++ unfriendly if the old file is.
  198. //
  199. // Note that the temporary 'DirInfo' is required here, as either call to
  200. // getFileInfo could resize the vector and we don't want to rely on order
  201. // of evaluation.
  202. unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo;
  203. getFileInfo(FE).DirInfo = DirInfo;
  204. return FE;
  205. }
  206. }
  207. CurDir = 0;
  208. // If this is a system #include, ignore the user #include locs.
  209. unsigned i = isAngled ? SystemDirIdx : 0;
  210. // If this is a #include_next request, start searching after the directory the
  211. // file was found in.
  212. if (FromDir)
  213. i = FromDir-&SearchDirs[0];
  214. // Cache all of the lookups performed by this method. Many headers are
  215. // multiply included, and the "pragma once" optimization prevents them from
  216. // being relex/pp'd, but they would still have to search through a
  217. // (potentially huge) series of SearchDirs to find it.
  218. std::pair<unsigned, unsigned> &CacheLookup =
  219. LookupFileCache.GetOrCreateValue(Filename).getValue();
  220. // If the entry has been previously looked up, the first value will be
  221. // non-zero. If the value is equal to i (the start point of our search), then
  222. // this is a matching hit.
  223. if (CacheLookup.first == i+1) {
  224. // Skip querying potentially lots of directories for this lookup.
  225. i = CacheLookup.second;
  226. } else {
  227. // Otherwise, this is the first query, or the previous query didn't match
  228. // our search start. We will fill in our found location below, so prime the
  229. // start point value.
  230. CacheLookup.first = i+1;
  231. }
  232. // Check each directory in sequence to see if it contains this file.
  233. for (; i != SearchDirs.size(); ++i) {
  234. const FileEntry *FE =
  235. SearchDirs[i].LookupFile(Filename, *this);
  236. if (!FE) continue;
  237. CurDir = &SearchDirs[i];
  238. // This file is a system header or C++ unfriendly if the dir is.
  239. getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
  240. // Remember this location for the next lookup we do.
  241. CacheLookup.second = i;
  242. return FE;
  243. }
  244. // Otherwise, didn't find it. Remember we didn't find this.
  245. CacheLookup.second = SearchDirs.size();
  246. return 0;
  247. }
  248. /// LookupSubframeworkHeader - Look up a subframework for the specified
  249. /// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
  250. /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
  251. /// is a subframework within Carbon.framework. If so, return the FileEntry
  252. /// for the designated file, otherwise return null.
  253. const FileEntry *HeaderSearch::
  254. LookupSubframeworkHeader(llvm::StringRef Filename,
  255. const FileEntry *ContextFileEnt) {
  256. assert(ContextFileEnt && "No context file?");
  257. // Framework names must have a '/' in the filename. Find it.
  258. size_t SlashPos = Filename.find('/');
  259. if (SlashPos == llvm::StringRef::npos) return 0;
  260. // Look up the base framework name of the ContextFileEnt.
  261. const char *ContextName = ContextFileEnt->getName();
  262. // If the context info wasn't a framework, couldn't be a subframework.
  263. const char *FrameworkPos = strstr(ContextName, ".framework/");
  264. if (FrameworkPos == 0)
  265. return 0;
  266. llvm::SmallString<1024> FrameworkName(ContextName,
  267. FrameworkPos+strlen(".framework/"));
  268. // Append Frameworks/HIToolbox.framework/
  269. FrameworkName += "Frameworks/";
  270. FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
  271. FrameworkName += ".framework/";
  272. llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
  273. FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
  274. // Some other location?
  275. if (CacheLookup.getValue() &&
  276. CacheLookup.getKeyLength() == FrameworkName.size() &&
  277. memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
  278. CacheLookup.getKeyLength()) != 0)
  279. return 0;
  280. // Cache subframework.
  281. if (CacheLookup.getValue() == 0) {
  282. ++NumSubFrameworkLookups;
  283. // If the framework dir doesn't exist, we fail.
  284. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str());
  285. if (Dir == 0) return 0;
  286. // Otherwise, if it does, remember that this is the right direntry for this
  287. // framework.
  288. CacheLookup.setValue(Dir);
  289. }
  290. const FileEntry *FE = 0;
  291. // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
  292. llvm::SmallString<1024> HeadersFilename(FrameworkName);
  293. HeadersFilename += "Headers/";
  294. HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
  295. if (!(FE = FileMgr.getFile(HeadersFilename.str()))) {
  296. // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
  297. HeadersFilename = FrameworkName;
  298. HeadersFilename += "PrivateHeaders/";
  299. HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
  300. if (!(FE = FileMgr.getFile(HeadersFilename.str())))
  301. return 0;
  302. }
  303. // This file is a system header or C++ unfriendly if the old file is.
  304. //
  305. // Note that the temporary 'DirInfo' is required here, as either call to
  306. // getFileInfo could resize the vector and we don't want to rely on order
  307. // of evaluation.
  308. unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
  309. getFileInfo(FE).DirInfo = DirInfo;
  310. return FE;
  311. }
  312. //===----------------------------------------------------------------------===//
  313. // File Info Management.
  314. //===----------------------------------------------------------------------===//
  315. /// getFileInfo - Return the HeaderFileInfo structure for the specified
  316. /// FileEntry.
  317. HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
  318. if (FE->getUID() >= FileInfo.size())
  319. FileInfo.resize(FE->getUID()+1);
  320. return FileInfo[FE->getUID()];
  321. }
  322. void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) {
  323. if (UID >= FileInfo.size())
  324. FileInfo.resize(UID+1);
  325. FileInfo[UID] = HFI;
  326. }
  327. /// ShouldEnterIncludeFile - Mark the specified file as a target of of a
  328. /// #include, #include_next, or #import directive. Return false if #including
  329. /// the file will have no effect or true if we should include it.
  330. bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
  331. ++NumIncluded; // Count # of attempted #includes.
  332. // Get information about this file.
  333. HeaderFileInfo &FileInfo = getFileInfo(File);
  334. // If this is a #import directive, check that we have not already imported
  335. // this header.
  336. if (isImport) {
  337. // If this has already been imported, don't import it again.
  338. FileInfo.isImport = true;
  339. // Has this already been #import'ed or #include'd?
  340. if (FileInfo.NumIncludes) return false;
  341. } else {
  342. // Otherwise, if this is a #include of a file that was previously #import'd
  343. // or if this is the second #include of a #pragma once file, ignore it.
  344. if (FileInfo.isImport)
  345. return false;
  346. }
  347. // Next, check to see if the file is wrapped with #ifndef guards. If so, and
  348. // if the macro that guards it is defined, we know the #include has no effect.
  349. if (const IdentifierInfo *ControllingMacro
  350. = FileInfo.getControllingMacro(ExternalLookup))
  351. if (ControllingMacro->hasMacroDefinition()) {
  352. ++NumMultiIncludeFileOptzn;
  353. return false;
  354. }
  355. // Increment the number of times this file has been included.
  356. ++FileInfo.NumIncludes;
  357. return true;
  358. }