PreprocessingRecord.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. //===- PreprocessingRecord.cpp - Record of Preprocessing ------------------===//
  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 PreprocessingRecord class, which maintains a record
  10. // of what occurred during preprocessing, and its helpers.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/PreprocessingRecord.h"
  14. #include "clang/Basic/IdentifierTable.h"
  15. #include "clang/Basic/LLVM.h"
  16. #include "clang/Basic/SourceLocation.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/Basic/TokenKinds.h"
  19. #include "clang/Lex/MacroInfo.h"
  20. #include "clang/Lex/Token.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/iterator_range.h"
  24. #include "llvm/Support/Capacity.h"
  25. #include "llvm/Support/Casting.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <cstddef>
  30. #include <cstring>
  31. #include <iterator>
  32. #include <optional>
  33. #include <utility>
  34. #include <vector>
  35. using namespace clang;
  36. ExternalPreprocessingRecordSource::~ExternalPreprocessingRecordSource() =
  37. default;
  38. InclusionDirective::InclusionDirective(PreprocessingRecord &PPRec,
  39. InclusionKind Kind, StringRef FileName,
  40. bool InQuotes, bool ImportedModule,
  41. OptionalFileEntryRef File,
  42. SourceRange Range)
  43. : PreprocessingDirective(InclusionDirectiveKind, Range), InQuotes(InQuotes),
  44. Kind(Kind), ImportedModule(ImportedModule), File(File) {
  45. char *Memory = (char *)PPRec.Allocate(FileName.size() + 1, alignof(char));
  46. memcpy(Memory, FileName.data(), FileName.size());
  47. Memory[FileName.size()] = 0;
  48. this->FileName = StringRef(Memory, FileName.size());
  49. }
  50. PreprocessingRecord::PreprocessingRecord(SourceManager &SM) : SourceMgr(SM) {}
  51. /// Returns a pair of [Begin, End) iterators of preprocessed entities
  52. /// that source range \p Range encompasses.
  53. llvm::iterator_range<PreprocessingRecord::iterator>
  54. PreprocessingRecord::getPreprocessedEntitiesInRange(SourceRange Range) {
  55. if (Range.isInvalid())
  56. return llvm::make_range(iterator(), iterator());
  57. if (CachedRangeQuery.Range == Range) {
  58. return llvm::make_range(iterator(this, CachedRangeQuery.Result.first),
  59. iterator(this, CachedRangeQuery.Result.second));
  60. }
  61. std::pair<int, int> Res = getPreprocessedEntitiesInRangeSlow(Range);
  62. CachedRangeQuery.Range = Range;
  63. CachedRangeQuery.Result = Res;
  64. return llvm::make_range(iterator(this, Res.first),
  65. iterator(this, Res.second));
  66. }
  67. static bool isPreprocessedEntityIfInFileID(PreprocessedEntity *PPE, FileID FID,
  68. SourceManager &SM) {
  69. assert(FID.isValid());
  70. if (!PPE)
  71. return false;
  72. SourceLocation Loc = PPE->getSourceRange().getBegin();
  73. if (Loc.isInvalid())
  74. return false;
  75. return SM.isInFileID(SM.getFileLoc(Loc), FID);
  76. }
  77. /// Returns true if the preprocessed entity that \arg PPEI iterator
  78. /// points to is coming from the file \arg FID.
  79. ///
  80. /// Can be used to avoid implicit deserializations of preallocated
  81. /// preprocessed entities if we only care about entities of a specific file
  82. /// and not from files \#included in the range given at
  83. /// \see getPreprocessedEntitiesInRange.
  84. bool PreprocessingRecord::isEntityInFileID(iterator PPEI, FileID FID) {
  85. if (FID.isInvalid())
  86. return false;
  87. int Pos = std::distance(iterator(this, 0), PPEI);
  88. if (Pos < 0) {
  89. if (unsigned(-Pos-1) >= LoadedPreprocessedEntities.size()) {
  90. assert(0 && "Out-of bounds loaded preprocessed entity");
  91. return false;
  92. }
  93. assert(ExternalSource && "No external source to load from");
  94. unsigned LoadedIndex = LoadedPreprocessedEntities.size()+Pos;
  95. if (PreprocessedEntity *PPE = LoadedPreprocessedEntities[LoadedIndex])
  96. return isPreprocessedEntityIfInFileID(PPE, FID, SourceMgr);
  97. // See if the external source can see if the entity is in the file without
  98. // deserializing it.
  99. if (std::optional<bool> IsInFile =
  100. ExternalSource->isPreprocessedEntityInFileID(LoadedIndex, FID))
  101. return *IsInFile;
  102. // The external source did not provide a definite answer, go and deserialize
  103. // the entity to check it.
  104. return isPreprocessedEntityIfInFileID(
  105. getLoadedPreprocessedEntity(LoadedIndex),
  106. FID, SourceMgr);
  107. }
  108. if (unsigned(Pos) >= PreprocessedEntities.size()) {
  109. assert(0 && "Out-of bounds local preprocessed entity");
  110. return false;
  111. }
  112. return isPreprocessedEntityIfInFileID(PreprocessedEntities[Pos],
  113. FID, SourceMgr);
  114. }
  115. /// Returns a pair of [Begin, End) iterators of preprocessed entities
  116. /// that source range \arg R encompasses.
  117. std::pair<int, int>
  118. PreprocessingRecord::getPreprocessedEntitiesInRangeSlow(SourceRange Range) {
  119. assert(Range.isValid());
  120. assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
  121. std::pair<unsigned, unsigned>
  122. Local = findLocalPreprocessedEntitiesInRange(Range);
  123. // Check if range spans local entities.
  124. if (!ExternalSource || SourceMgr.isLocalSourceLocation(Range.getBegin()))
  125. return std::make_pair(Local.first, Local.second);
  126. std::pair<unsigned, unsigned>
  127. Loaded = ExternalSource->findPreprocessedEntitiesInRange(Range);
  128. // Check if range spans local entities.
  129. if (Loaded.first == Loaded.second)
  130. return std::make_pair(Local.first, Local.second);
  131. unsigned TotalLoaded = LoadedPreprocessedEntities.size();
  132. // Check if range spans loaded entities.
  133. if (Local.first == Local.second)
  134. return std::make_pair(int(Loaded.first)-TotalLoaded,
  135. int(Loaded.second)-TotalLoaded);
  136. // Range spands loaded and local entities.
  137. return std::make_pair(int(Loaded.first)-TotalLoaded, Local.second);
  138. }
  139. std::pair<unsigned, unsigned>
  140. PreprocessingRecord::findLocalPreprocessedEntitiesInRange(
  141. SourceRange Range) const {
  142. if (Range.isInvalid())
  143. return std::make_pair(0,0);
  144. assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
  145. unsigned Begin = findBeginLocalPreprocessedEntity(Range.getBegin());
  146. unsigned End = findEndLocalPreprocessedEntity(Range.getEnd());
  147. return std::make_pair(Begin, End);
  148. }
  149. namespace {
  150. template <SourceLocation (SourceRange::*getRangeLoc)() const>
  151. struct PPEntityComp {
  152. const SourceManager &SM;
  153. explicit PPEntityComp(const SourceManager &SM) : SM(SM) {}
  154. bool operator()(PreprocessedEntity *L, PreprocessedEntity *R) const {
  155. SourceLocation LHS = getLoc(L);
  156. SourceLocation RHS = getLoc(R);
  157. return SM.isBeforeInTranslationUnit(LHS, RHS);
  158. }
  159. bool operator()(PreprocessedEntity *L, SourceLocation RHS) const {
  160. SourceLocation LHS = getLoc(L);
  161. return SM.isBeforeInTranslationUnit(LHS, RHS);
  162. }
  163. bool operator()(SourceLocation LHS, PreprocessedEntity *R) const {
  164. SourceLocation RHS = getLoc(R);
  165. return SM.isBeforeInTranslationUnit(LHS, RHS);
  166. }
  167. SourceLocation getLoc(PreprocessedEntity *PPE) const {
  168. SourceRange Range = PPE->getSourceRange();
  169. return (Range.*getRangeLoc)();
  170. }
  171. };
  172. } // namespace
  173. unsigned PreprocessingRecord::findBeginLocalPreprocessedEntity(
  174. SourceLocation Loc) const {
  175. if (SourceMgr.isLoadedSourceLocation(Loc))
  176. return 0;
  177. size_t Count = PreprocessedEntities.size();
  178. size_t Half;
  179. std::vector<PreprocessedEntity *>::const_iterator
  180. First = PreprocessedEntities.begin();
  181. std::vector<PreprocessedEntity *>::const_iterator I;
  182. // Do a binary search manually instead of using std::lower_bound because
  183. // The end locations of entities may be unordered (when a macro expansion
  184. // is inside another macro argument), but for this case it is not important
  185. // whether we get the first macro expansion or its containing macro.
  186. while (Count > 0) {
  187. Half = Count/2;
  188. I = First;
  189. std::advance(I, Half);
  190. if (SourceMgr.isBeforeInTranslationUnit((*I)->getSourceRange().getEnd(),
  191. Loc)){
  192. First = I;
  193. ++First;
  194. Count = Count - Half - 1;
  195. } else
  196. Count = Half;
  197. }
  198. return First - PreprocessedEntities.begin();
  199. }
  200. unsigned
  201. PreprocessingRecord::findEndLocalPreprocessedEntity(SourceLocation Loc) const {
  202. if (SourceMgr.isLoadedSourceLocation(Loc))
  203. return 0;
  204. auto I = llvm::upper_bound(PreprocessedEntities, Loc,
  205. PPEntityComp<&SourceRange::getBegin>(SourceMgr));
  206. return I - PreprocessedEntities.begin();
  207. }
  208. PreprocessingRecord::PPEntityID
  209. PreprocessingRecord::addPreprocessedEntity(PreprocessedEntity *Entity) {
  210. assert(Entity);
  211. SourceLocation BeginLoc = Entity->getSourceRange().getBegin();
  212. if (isa<MacroDefinitionRecord>(Entity)) {
  213. assert((PreprocessedEntities.empty() ||
  214. !SourceMgr.isBeforeInTranslationUnit(
  215. BeginLoc,
  216. PreprocessedEntities.back()->getSourceRange().getBegin())) &&
  217. "a macro definition was encountered out-of-order");
  218. PreprocessedEntities.push_back(Entity);
  219. return getPPEntityID(PreprocessedEntities.size()-1, /*isLoaded=*/false);
  220. }
  221. // Check normal case, this entity begin location is after the previous one.
  222. if (PreprocessedEntities.empty() ||
  223. !SourceMgr.isBeforeInTranslationUnit(BeginLoc,
  224. PreprocessedEntities.back()->getSourceRange().getBegin())) {
  225. PreprocessedEntities.push_back(Entity);
  226. return getPPEntityID(PreprocessedEntities.size()-1, /*isLoaded=*/false);
  227. }
  228. // The entity's location is not after the previous one; this can happen with
  229. // include directives that form the filename using macros, e.g:
  230. // "#include MACRO(STUFF)"
  231. // or with macro expansions inside macro arguments where the arguments are
  232. // not expanded in the same order as listed, e.g:
  233. // \code
  234. // #define M1 1
  235. // #define M2 2
  236. // #define FM(x,y) y x
  237. // FM(M1, M2)
  238. // \endcode
  239. using pp_iter = std::vector<PreprocessedEntity *>::iterator;
  240. // Usually there are few macro expansions when defining the filename, do a
  241. // linear search for a few entities.
  242. unsigned count = 0;
  243. for (pp_iter RI = PreprocessedEntities.end(),
  244. Begin = PreprocessedEntities.begin();
  245. RI != Begin && count < 4; --RI, ++count) {
  246. pp_iter I = RI;
  247. --I;
  248. if (!SourceMgr.isBeforeInTranslationUnit(BeginLoc,
  249. (*I)->getSourceRange().getBegin())) {
  250. pp_iter insertI = PreprocessedEntities.insert(RI, Entity);
  251. return getPPEntityID(insertI - PreprocessedEntities.begin(),
  252. /*isLoaded=*/false);
  253. }
  254. }
  255. // Linear search unsuccessful. Do a binary search.
  256. pp_iter I =
  257. llvm::upper_bound(PreprocessedEntities, BeginLoc,
  258. PPEntityComp<&SourceRange::getBegin>(SourceMgr));
  259. pp_iter insertI = PreprocessedEntities.insert(I, Entity);
  260. return getPPEntityID(insertI - PreprocessedEntities.begin(),
  261. /*isLoaded=*/false);
  262. }
  263. void PreprocessingRecord::SetExternalSource(
  264. ExternalPreprocessingRecordSource &Source) {
  265. assert(!ExternalSource &&
  266. "Preprocessing record already has an external source");
  267. ExternalSource = &Source;
  268. }
  269. unsigned PreprocessingRecord::allocateLoadedEntities(unsigned NumEntities) {
  270. unsigned Result = LoadedPreprocessedEntities.size();
  271. LoadedPreprocessedEntities.resize(LoadedPreprocessedEntities.size()
  272. + NumEntities);
  273. return Result;
  274. }
  275. unsigned PreprocessingRecord::allocateSkippedRanges(unsigned NumRanges) {
  276. unsigned Result = SkippedRanges.size();
  277. SkippedRanges.resize(SkippedRanges.size() + NumRanges);
  278. SkippedRangesAllLoaded = false;
  279. return Result;
  280. }
  281. void PreprocessingRecord::ensureSkippedRangesLoaded() {
  282. if (SkippedRangesAllLoaded || !ExternalSource)
  283. return;
  284. for (unsigned Index = 0; Index != SkippedRanges.size(); ++Index) {
  285. if (SkippedRanges[Index].isInvalid())
  286. SkippedRanges[Index] = ExternalSource->ReadSkippedRange(Index);
  287. }
  288. SkippedRangesAllLoaded = true;
  289. }
  290. void PreprocessingRecord::RegisterMacroDefinition(MacroInfo *Macro,
  291. MacroDefinitionRecord *Def) {
  292. MacroDefinitions[Macro] = Def;
  293. }
  294. /// Retrieve the preprocessed entity at the given ID.
  295. PreprocessedEntity *PreprocessingRecord::getPreprocessedEntity(PPEntityID PPID){
  296. if (PPID.ID < 0) {
  297. unsigned Index = -PPID.ID - 1;
  298. assert(Index < LoadedPreprocessedEntities.size() &&
  299. "Out-of bounds loaded preprocessed entity");
  300. return getLoadedPreprocessedEntity(Index);
  301. }
  302. if (PPID.ID == 0)
  303. return nullptr;
  304. unsigned Index = PPID.ID - 1;
  305. assert(Index < PreprocessedEntities.size() &&
  306. "Out-of bounds local preprocessed entity");
  307. return PreprocessedEntities[Index];
  308. }
  309. /// Retrieve the loaded preprocessed entity at the given index.
  310. PreprocessedEntity *
  311. PreprocessingRecord::getLoadedPreprocessedEntity(unsigned Index) {
  312. assert(Index < LoadedPreprocessedEntities.size() &&
  313. "Out-of bounds loaded preprocessed entity");
  314. assert(ExternalSource && "No external source to load from");
  315. PreprocessedEntity *&Entity = LoadedPreprocessedEntities[Index];
  316. if (!Entity) {
  317. Entity = ExternalSource->ReadPreprocessedEntity(Index);
  318. if (!Entity) // Failed to load.
  319. Entity = new (*this)
  320. PreprocessedEntity(PreprocessedEntity::InvalidKind, SourceRange());
  321. }
  322. return Entity;
  323. }
  324. MacroDefinitionRecord *
  325. PreprocessingRecord::findMacroDefinition(const MacroInfo *MI) {
  326. llvm::DenseMap<const MacroInfo *, MacroDefinitionRecord *>::iterator Pos =
  327. MacroDefinitions.find(MI);
  328. if (Pos == MacroDefinitions.end())
  329. return nullptr;
  330. return Pos->second;
  331. }
  332. void PreprocessingRecord::addMacroExpansion(const Token &Id,
  333. const MacroInfo *MI,
  334. SourceRange Range) {
  335. // We don't record nested macro expansions.
  336. if (Id.getLocation().isMacroID())
  337. return;
  338. if (MI->isBuiltinMacro())
  339. addPreprocessedEntity(new (*this)
  340. MacroExpansion(Id.getIdentifierInfo(), Range));
  341. else if (MacroDefinitionRecord *Def = findMacroDefinition(MI))
  342. addPreprocessedEntity(new (*this) MacroExpansion(Def, Range));
  343. }
  344. void PreprocessingRecord::Ifdef(SourceLocation Loc, const Token &MacroNameTok,
  345. const MacroDefinition &MD) {
  346. // This is not actually a macro expansion but record it as a macro reference.
  347. if (MD)
  348. addMacroExpansion(MacroNameTok, MD.getMacroInfo(),
  349. MacroNameTok.getLocation());
  350. }
  351. void PreprocessingRecord::Elifdef(SourceLocation Loc, const Token &MacroNameTok,
  352. const MacroDefinition &MD) {
  353. // This is not actually a macro expansion but record it as a macro reference.
  354. if (MD)
  355. addMacroExpansion(MacroNameTok, MD.getMacroInfo(),
  356. MacroNameTok.getLocation());
  357. }
  358. void PreprocessingRecord::Ifndef(SourceLocation Loc, const Token &MacroNameTok,
  359. const MacroDefinition &MD) {
  360. // This is not actually a macro expansion but record it as a macro reference.
  361. if (MD)
  362. addMacroExpansion(MacroNameTok, MD.getMacroInfo(),
  363. MacroNameTok.getLocation());
  364. }
  365. void PreprocessingRecord::Elifndef(SourceLocation Loc,
  366. const Token &MacroNameTok,
  367. const MacroDefinition &MD) {
  368. // This is not actually a macro expansion but record it as a macro reference.
  369. if (MD)
  370. addMacroExpansion(MacroNameTok, MD.getMacroInfo(),
  371. MacroNameTok.getLocation());
  372. }
  373. void PreprocessingRecord::Defined(const Token &MacroNameTok,
  374. const MacroDefinition &MD,
  375. SourceRange Range) {
  376. // This is not actually a macro expansion but record it as a macro reference.
  377. if (MD)
  378. addMacroExpansion(MacroNameTok, MD.getMacroInfo(),
  379. MacroNameTok.getLocation());
  380. }
  381. void PreprocessingRecord::SourceRangeSkipped(SourceRange Range,
  382. SourceLocation EndifLoc) {
  383. assert(Range.isValid());
  384. SkippedRanges.emplace_back(Range.getBegin(), EndifLoc);
  385. }
  386. void PreprocessingRecord::MacroExpands(const Token &Id,
  387. const MacroDefinition &MD,
  388. SourceRange Range,
  389. const MacroArgs *Args) {
  390. addMacroExpansion(Id, MD.getMacroInfo(), Range);
  391. }
  392. void PreprocessingRecord::MacroDefined(const Token &Id,
  393. const MacroDirective *MD) {
  394. const MacroInfo *MI = MD->getMacroInfo();
  395. SourceRange R(MI->getDefinitionLoc(), MI->getDefinitionEndLoc());
  396. MacroDefinitionRecord *Def =
  397. new (*this) MacroDefinitionRecord(Id.getIdentifierInfo(), R);
  398. addPreprocessedEntity(Def);
  399. MacroDefinitions[MI] = Def;
  400. }
  401. void PreprocessingRecord::MacroUndefined(const Token &Id,
  402. const MacroDefinition &MD,
  403. const MacroDirective *Undef) {
  404. MD.forAllDefinitions([&](MacroInfo *MI) { MacroDefinitions.erase(MI); });
  405. }
  406. void PreprocessingRecord::InclusionDirective(
  407. SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
  408. bool IsAngled, CharSourceRange FilenameRange, OptionalFileEntryRef File,
  409. StringRef SearchPath, StringRef RelativePath, const Module *Imported,
  410. SrcMgr::CharacteristicKind FileType) {
  411. InclusionDirective::InclusionKind Kind = InclusionDirective::Include;
  412. switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
  413. case tok::pp_include:
  414. Kind = InclusionDirective::Include;
  415. break;
  416. case tok::pp_import:
  417. Kind = InclusionDirective::Import;
  418. break;
  419. case tok::pp_include_next:
  420. Kind = InclusionDirective::IncludeNext;
  421. break;
  422. case tok::pp___include_macros:
  423. Kind = InclusionDirective::IncludeMacros;
  424. break;
  425. default:
  426. llvm_unreachable("Unknown include directive kind");
  427. }
  428. SourceLocation EndLoc;
  429. if (!IsAngled) {
  430. EndLoc = FilenameRange.getBegin();
  431. } else {
  432. EndLoc = FilenameRange.getEnd();
  433. if (FilenameRange.isCharRange())
  434. EndLoc = EndLoc.getLocWithOffset(-1); // the InclusionDirective expects
  435. // a token range.
  436. }
  437. clang::InclusionDirective *ID =
  438. new (*this) clang::InclusionDirective(*this, Kind, FileName, !IsAngled,
  439. (bool)Imported, File,
  440. SourceRange(HashLoc, EndLoc));
  441. addPreprocessedEntity(ID);
  442. }
  443. size_t PreprocessingRecord::getTotalMemory() const {
  444. return BumpAlloc.getTotalMemory()
  445. + llvm::capacity_in_bytes(MacroDefinitions)
  446. + llvm::capacity_in_bytes(PreprocessedEntities)
  447. + llvm::capacity_in_bytes(LoadedPreprocessedEntities)
  448. + llvm::capacity_in_bytes(SkippedRanges);
  449. }