Preprocessor.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. //===- Preprocess.cpp - C Language Family Preprocessor Implementation -----===//
  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 Preprocessor interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Options to support:
  15. // -H - Print the name of each header file used.
  16. // -d[DNI] - Dump various things.
  17. // -fworking-directory - #line's with preprocessor's working dir.
  18. // -fpreprocessed
  19. // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
  20. // -W*
  21. // -w
  22. //
  23. // Messages to emit:
  24. // "Multiple include guards may be useful for:\n"
  25. //
  26. //===----------------------------------------------------------------------===//
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Basic/FileManager.h"
  29. #include "clang/Basic/FileSystemStatCache.h"
  30. #include "clang/Basic/IdentifierTable.h"
  31. #include "clang/Basic/LLVM.h"
  32. #include "clang/Basic/LangOptions.h"
  33. #include "clang/Basic/Module.h"
  34. #include "clang/Basic/SourceLocation.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Lex/CodeCompletionHandler.h"
  38. #include "clang/Lex/ExternalPreprocessorSource.h"
  39. #include "clang/Lex/HeaderSearch.h"
  40. #include "clang/Lex/LexDiagnostic.h"
  41. #include "clang/Lex/Lexer.h"
  42. #include "clang/Lex/LiteralSupport.h"
  43. #include "clang/Lex/MacroArgs.h"
  44. #include "clang/Lex/MacroInfo.h"
  45. #include "clang/Lex/ModuleLoader.h"
  46. #include "clang/Lex/PTHLexer.h"
  47. #include "clang/Lex/PTHManager.h"
  48. #include "clang/Lex/Pragma.h"
  49. #include "clang/Lex/PreprocessingRecord.h"
  50. #include "clang/Lex/PreprocessorLexer.h"
  51. #include "clang/Lex/PreprocessorOptions.h"
  52. #include "clang/Lex/ScratchBuffer.h"
  53. #include "clang/Lex/Token.h"
  54. #include "clang/Lex/TokenLexer.h"
  55. #include "llvm/ADT/APInt.h"
  56. #include "llvm/ADT/ArrayRef.h"
  57. #include "llvm/ADT/DenseMap.h"
  58. #include "llvm/ADT/SmallString.h"
  59. #include "llvm/ADT/SmallVector.h"
  60. #include "llvm/ADT/STLExtras.h"
  61. #include "llvm/ADT/StringRef.h"
  62. #include "llvm/ADT/StringSwitch.h"
  63. #include "llvm/Support/Capacity.h"
  64. #include "llvm/Support/ErrorHandling.h"
  65. #include "llvm/Support/MemoryBuffer.h"
  66. #include "llvm/Support/raw_ostream.h"
  67. #include <algorithm>
  68. #include <cassert>
  69. #include <memory>
  70. #include <string>
  71. #include <utility>
  72. #include <vector>
  73. using namespace clang;
  74. LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
  75. ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
  76. Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
  77. DiagnosticsEngine &diags, LangOptions &opts,
  78. SourceManager &SM, MemoryBufferCache &PCMCache,
  79. HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
  80. IdentifierInfoLookup *IILookup, bool OwnsHeaders,
  81. TranslationUnitKind TUKind)
  82. : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
  83. FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache),
  84. ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
  85. TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
  86. // As the language options may have not been loaded yet (when
  87. // deserializing an ASTUnit), adding keywords to the identifier table is
  88. // deferred to Preprocessor::Initialize().
  89. Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
  90. TUKind(TUKind), SkipMainFilePreamble(0, true),
  91. CurSubmoduleState(&NullSubmoduleState) {
  92. OwnsHeaderSearch = OwnsHeaders;
  93. // Default to discarding comments.
  94. KeepComments = false;
  95. KeepMacroComments = false;
  96. SuppressIncludeNotFoundError = false;
  97. // Macro expansion is enabled.
  98. DisableMacroExpansion = false;
  99. MacroExpansionInDirectivesOverride = false;
  100. InMacroArgs = false;
  101. InMacroArgPreExpansion = false;
  102. NumCachedTokenLexers = 0;
  103. PragmasEnabled = true;
  104. ParsingIfOrElifDirective = false;
  105. PreprocessedOutput = false;
  106. // We haven't read anything from the external source.
  107. ReadMacrosFromExternalSource = false;
  108. // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
  109. // a macro. They get unpoisoned where it is allowed.
  110. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
  111. SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
  112. if (getLangOpts().CPlusPlus2a) {
  113. (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
  114. SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
  115. } else {
  116. Ident__VA_OPT__ = nullptr;
  117. }
  118. // Initialize the pragma handlers.
  119. RegisterBuiltinPragmas();
  120. // Initialize builtin macros like __LINE__ and friends.
  121. RegisterBuiltinMacros();
  122. if(LangOpts.Borland) {
  123. Ident__exception_info = getIdentifierInfo("_exception_info");
  124. Ident___exception_info = getIdentifierInfo("__exception_info");
  125. Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
  126. Ident__exception_code = getIdentifierInfo("_exception_code");
  127. Ident___exception_code = getIdentifierInfo("__exception_code");
  128. Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
  129. Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
  130. Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
  131. Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
  132. } else {
  133. Ident__exception_info = Ident__exception_code = nullptr;
  134. Ident__abnormal_termination = Ident___exception_info = nullptr;
  135. Ident___exception_code = Ident___abnormal_termination = nullptr;
  136. Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
  137. Ident_AbnormalTermination = nullptr;
  138. }
  139. if (this->PPOpts->GeneratePreamble)
  140. PreambleConditionalStack.startRecording();
  141. }
  142. Preprocessor::~Preprocessor() {
  143. assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
  144. IncludeMacroStack.clear();
  145. // Destroy any macro definitions.
  146. while (MacroInfoChain *I = MIChainHead) {
  147. MIChainHead = I->Next;
  148. I->~MacroInfoChain();
  149. }
  150. // Free any cached macro expanders.
  151. // This populates MacroArgCache, so all TokenLexers need to be destroyed
  152. // before the code below that frees up the MacroArgCache list.
  153. std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
  154. CurTokenLexer.reset();
  155. // Free any cached MacroArgs.
  156. for (MacroArgs *ArgList = MacroArgCache; ArgList;)
  157. ArgList = ArgList->deallocate();
  158. // Delete the header search info, if we own it.
  159. if (OwnsHeaderSearch)
  160. delete &HeaderInfo;
  161. }
  162. void Preprocessor::Initialize(const TargetInfo &Target,
  163. const TargetInfo *AuxTarget) {
  164. assert((!this->Target || this->Target == &Target) &&
  165. "Invalid override of target information");
  166. this->Target = &Target;
  167. assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
  168. "Invalid override of aux target information.");
  169. this->AuxTarget = AuxTarget;
  170. // Initialize information about built-ins.
  171. BuiltinInfo.InitializeTarget(Target, AuxTarget);
  172. HeaderInfo.setTarget(Target);
  173. // Populate the identifier table with info about keywords for the current language.
  174. Identifiers.AddKeywords(LangOpts);
  175. }
  176. void Preprocessor::InitializeForModelFile() {
  177. NumEnteredSourceFiles = 0;
  178. // Reset pragmas
  179. PragmaHandlersBackup = std::move(PragmaHandlers);
  180. PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
  181. RegisterBuiltinPragmas();
  182. // Reset PredefinesFileID
  183. PredefinesFileID = FileID();
  184. }
  185. void Preprocessor::FinalizeForModelFile() {
  186. NumEnteredSourceFiles = 1;
  187. PragmaHandlers = std::move(PragmaHandlersBackup);
  188. }
  189. void Preprocessor::setPTHManager(PTHManager* pm) {
  190. PTH.reset(pm);
  191. FileMgr.addStatCache(PTH->createStatCache());
  192. }
  193. void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
  194. llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
  195. << getSpelling(Tok) << "'";
  196. if (!DumpFlags) return;
  197. llvm::errs() << "\t";
  198. if (Tok.isAtStartOfLine())
  199. llvm::errs() << " [StartOfLine]";
  200. if (Tok.hasLeadingSpace())
  201. llvm::errs() << " [LeadingSpace]";
  202. if (Tok.isExpandDisabled())
  203. llvm::errs() << " [ExpandDisabled]";
  204. if (Tok.needsCleaning()) {
  205. const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
  206. llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
  207. << "']";
  208. }
  209. llvm::errs() << "\tLoc=<";
  210. DumpLocation(Tok.getLocation());
  211. llvm::errs() << ">";
  212. }
  213. void Preprocessor::DumpLocation(SourceLocation Loc) const {
  214. Loc.dump(SourceMgr);
  215. }
  216. void Preprocessor::DumpMacro(const MacroInfo &MI) const {
  217. llvm::errs() << "MACRO: ";
  218. for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
  219. DumpToken(MI.getReplacementToken(i));
  220. llvm::errs() << " ";
  221. }
  222. llvm::errs() << "\n";
  223. }
  224. void Preprocessor::PrintStats() {
  225. llvm::errs() << "\n*** Preprocessor Stats:\n";
  226. llvm::errs() << NumDirectives << " directives found:\n";
  227. llvm::errs() << " " << NumDefined << " #define.\n";
  228. llvm::errs() << " " << NumUndefined << " #undef.\n";
  229. llvm::errs() << " #include/#include_next/#import:\n";
  230. llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
  231. llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
  232. llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
  233. llvm::errs() << " " << NumElse << " #else/#elif.\n";
  234. llvm::errs() << " " << NumEndif << " #endif.\n";
  235. llvm::errs() << " " << NumPragma << " #pragma.\n";
  236. llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
  237. llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
  238. << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
  239. << NumFastMacroExpanded << " on the fast path.\n";
  240. llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
  241. << " token paste (##) operations performed, "
  242. << NumFastTokenPaste << " on the fast path.\n";
  243. llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
  244. llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
  245. llvm::errs() << "\n Macro Expanded Tokens: "
  246. << llvm::capacity_in_bytes(MacroExpandedTokens);
  247. llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
  248. // FIXME: List information for all submodules.
  249. llvm::errs() << "\n Macros: "
  250. << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
  251. llvm::errs() << "\n #pragma push_macro Info: "
  252. << llvm::capacity_in_bytes(PragmaPushMacroInfo);
  253. llvm::errs() << "\n Poison Reasons: "
  254. << llvm::capacity_in_bytes(PoisonReasons);
  255. llvm::errs() << "\n Comment Handlers: "
  256. << llvm::capacity_in_bytes(CommentHandlers) << "\n";
  257. }
  258. Preprocessor::macro_iterator
  259. Preprocessor::macro_begin(bool IncludeExternalMacros) const {
  260. if (IncludeExternalMacros && ExternalSource &&
  261. !ReadMacrosFromExternalSource) {
  262. ReadMacrosFromExternalSource = true;
  263. ExternalSource->ReadDefinedMacros();
  264. }
  265. // Make sure we cover all macros in visible modules.
  266. for (const ModuleMacro &Macro : ModuleMacros)
  267. CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
  268. return CurSubmoduleState->Macros.begin();
  269. }
  270. size_t Preprocessor::getTotalMemory() const {
  271. return BP.getTotalMemory()
  272. + llvm::capacity_in_bytes(MacroExpandedTokens)
  273. + Predefines.capacity() /* Predefines buffer. */
  274. // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
  275. // and ModuleMacros.
  276. + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
  277. + llvm::capacity_in_bytes(PragmaPushMacroInfo)
  278. + llvm::capacity_in_bytes(PoisonReasons)
  279. + llvm::capacity_in_bytes(CommentHandlers);
  280. }
  281. Preprocessor::macro_iterator
  282. Preprocessor::macro_end(bool IncludeExternalMacros) const {
  283. if (IncludeExternalMacros && ExternalSource &&
  284. !ReadMacrosFromExternalSource) {
  285. ReadMacrosFromExternalSource = true;
  286. ExternalSource->ReadDefinedMacros();
  287. }
  288. return CurSubmoduleState->Macros.end();
  289. }
  290. /// \brief Compares macro tokens with a specified token value sequence.
  291. static bool MacroDefinitionEquals(const MacroInfo *MI,
  292. ArrayRef<TokenValue> Tokens) {
  293. return Tokens.size() == MI->getNumTokens() &&
  294. std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
  295. }
  296. StringRef Preprocessor::getLastMacroWithSpelling(
  297. SourceLocation Loc,
  298. ArrayRef<TokenValue> Tokens) const {
  299. SourceLocation BestLocation;
  300. StringRef BestSpelling;
  301. for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
  302. I != E; ++I) {
  303. const MacroDirective::DefInfo
  304. Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
  305. if (!Def || !Def.getMacroInfo())
  306. continue;
  307. if (!Def.getMacroInfo()->isObjectLike())
  308. continue;
  309. if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
  310. continue;
  311. SourceLocation Location = Def.getLocation();
  312. // Choose the macro defined latest.
  313. if (BestLocation.isInvalid() ||
  314. (Location.isValid() &&
  315. SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
  316. BestLocation = Location;
  317. BestSpelling = I->first->getName();
  318. }
  319. }
  320. return BestSpelling;
  321. }
  322. void Preprocessor::recomputeCurLexerKind() {
  323. if (CurLexer)
  324. CurLexerKind = CLK_Lexer;
  325. else if (CurPTHLexer)
  326. CurLexerKind = CLK_PTHLexer;
  327. else if (CurTokenLexer)
  328. CurLexerKind = CLK_TokenLexer;
  329. else
  330. CurLexerKind = CLK_CachingLexer;
  331. }
  332. bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
  333. unsigned CompleteLine,
  334. unsigned CompleteColumn) {
  335. assert(File);
  336. assert(CompleteLine && CompleteColumn && "Starts from 1:1");
  337. assert(!CodeCompletionFile && "Already set");
  338. using llvm::MemoryBuffer;
  339. // Load the actual file's contents.
  340. bool Invalid = false;
  341. const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
  342. if (Invalid)
  343. return true;
  344. // Find the byte position of the truncation point.
  345. const char *Position = Buffer->getBufferStart();
  346. for (unsigned Line = 1; Line < CompleteLine; ++Line) {
  347. for (; *Position; ++Position) {
  348. if (*Position != '\r' && *Position != '\n')
  349. continue;
  350. // Eat \r\n or \n\r as a single line.
  351. if ((Position[1] == '\r' || Position[1] == '\n') &&
  352. Position[0] != Position[1])
  353. ++Position;
  354. ++Position;
  355. break;
  356. }
  357. }
  358. Position += CompleteColumn - 1;
  359. // If pointing inside the preamble, adjust the position at the beginning of
  360. // the file after the preamble.
  361. if (SkipMainFilePreamble.first &&
  362. SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
  363. if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
  364. Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
  365. }
  366. if (Position > Buffer->getBufferEnd())
  367. Position = Buffer->getBufferEnd();
  368. CodeCompletionFile = File;
  369. CodeCompletionOffset = Position - Buffer->getBufferStart();
  370. auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
  371. Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
  372. char *NewBuf = NewBuffer->getBufferStart();
  373. char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
  374. *NewPos = '\0';
  375. std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
  376. SourceMgr.overrideFileContents(File, std::move(NewBuffer));
  377. return false;
  378. }
  379. void Preprocessor::CodeCompleteNaturalLanguage() {
  380. if (CodeComplete)
  381. CodeComplete->CodeCompleteNaturalLanguage();
  382. setCodeCompletionReached();
  383. }
  384. /// getSpelling - This method is used to get the spelling of a token into a
  385. /// SmallVector. Note that the returned StringRef may not point to the
  386. /// supplied buffer if a copy can be avoided.
  387. StringRef Preprocessor::getSpelling(const Token &Tok,
  388. SmallVectorImpl<char> &Buffer,
  389. bool *Invalid) const {
  390. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  391. if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
  392. // Try the fast path.
  393. if (const IdentifierInfo *II = Tok.getIdentifierInfo())
  394. return II->getName();
  395. }
  396. // Resize the buffer if we need to copy into it.
  397. if (Tok.needsCleaning())
  398. Buffer.resize(Tok.getLength());
  399. const char *Ptr = Buffer.data();
  400. unsigned Len = getSpelling(Tok, Ptr, Invalid);
  401. return StringRef(Ptr, Len);
  402. }
  403. /// CreateString - Plop the specified string into a scratch buffer and return a
  404. /// location for it. If specified, the source location provides a source
  405. /// location for the token.
  406. void Preprocessor::CreateString(StringRef Str, Token &Tok,
  407. SourceLocation ExpansionLocStart,
  408. SourceLocation ExpansionLocEnd) {
  409. Tok.setLength(Str.size());
  410. const char *DestPtr;
  411. SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
  412. if (ExpansionLocStart.isValid())
  413. Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
  414. ExpansionLocEnd, Str.size());
  415. Tok.setLocation(Loc);
  416. // If this is a raw identifier or a literal token, set the pointer data.
  417. if (Tok.is(tok::raw_identifier))
  418. Tok.setRawIdentifierData(DestPtr);
  419. else if (Tok.isLiteral())
  420. Tok.setLiteralData(DestPtr);
  421. }
  422. SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
  423. auto &SM = getSourceManager();
  424. SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
  425. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
  426. bool Invalid = false;
  427. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  428. if (Invalid)
  429. return SourceLocation();
  430. // FIXME: We could consider re-using spelling for tokens we see repeatedly.
  431. const char *DestPtr;
  432. SourceLocation Spelling =
  433. ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
  434. return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
  435. }
  436. Module *Preprocessor::getCurrentModule() {
  437. if (!getLangOpts().isCompilingModule())
  438. return nullptr;
  439. return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
  440. }
  441. //===----------------------------------------------------------------------===//
  442. // Preprocessor Initialization Methods
  443. //===----------------------------------------------------------------------===//
  444. /// EnterMainSourceFile - Enter the specified FileID as the main source file,
  445. /// which implicitly adds the builtin defines etc.
  446. void Preprocessor::EnterMainSourceFile() {
  447. // We do not allow the preprocessor to reenter the main file. Doing so will
  448. // cause FileID's to accumulate information from both runs (e.g. #line
  449. // information) and predefined macros aren't guaranteed to be set properly.
  450. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
  451. FileID MainFileID = SourceMgr.getMainFileID();
  452. // If MainFileID is loaded it means we loaded an AST file, no need to enter
  453. // a main file.
  454. if (!SourceMgr.isLoadedFileID(MainFileID)) {
  455. // Enter the main file source buffer.
  456. EnterSourceFile(MainFileID, nullptr, SourceLocation());
  457. // If we've been asked to skip bytes in the main file (e.g., as part of a
  458. // precompiled preamble), do so now.
  459. if (SkipMainFilePreamble.first > 0)
  460. CurLexer->SetByteOffset(SkipMainFilePreamble.first,
  461. SkipMainFilePreamble.second);
  462. // Tell the header info that the main file was entered. If the file is later
  463. // #imported, it won't be re-entered.
  464. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
  465. HeaderInfo.IncrementIncludeCount(FE);
  466. }
  467. // Preprocess Predefines to populate the initial preprocessor state.
  468. std::unique_ptr<llvm::MemoryBuffer> SB =
  469. llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
  470. assert(SB && "Cannot create predefined source buffer");
  471. FileID FID = SourceMgr.createFileID(std::move(SB));
  472. assert(FID.isValid() && "Could not create FileID for predefines?");
  473. setPredefinesFileID(FID);
  474. // Start parsing the predefines.
  475. EnterSourceFile(FID, nullptr, SourceLocation());
  476. }
  477. void Preprocessor::replayPreambleConditionalStack() {
  478. // Restore the conditional stack from the preamble, if there is one.
  479. if (PreambleConditionalStack.isReplaying()) {
  480. assert(CurPPLexer &&
  481. "CurPPLexer is null when calling replayPreambleConditionalStack.");
  482. CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
  483. PreambleConditionalStack.doneReplaying();
  484. if (PreambleConditionalStack.reachedEOFWhileSkipping())
  485. SkipExcludedConditionalBlock(
  486. PreambleConditionalStack.SkipInfo->HashTokenLoc,
  487. PreambleConditionalStack.SkipInfo->IfTokenLoc,
  488. PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
  489. PreambleConditionalStack.SkipInfo->FoundElse,
  490. PreambleConditionalStack.SkipInfo->ElseLoc);
  491. }
  492. }
  493. void Preprocessor::EndSourceFile() {
  494. // Notify the client that we reached the end of the source file.
  495. if (Callbacks)
  496. Callbacks->EndOfMainFile();
  497. }
  498. //===----------------------------------------------------------------------===//
  499. // Lexer Event Handling.
  500. //===----------------------------------------------------------------------===//
  501. /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
  502. /// identifier information for the token and install it into the token,
  503. /// updating the token kind accordingly.
  504. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  505. assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
  506. // Look up this token, see if it is a macro, or if it is a language keyword.
  507. IdentifierInfo *II;
  508. if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
  509. // No cleaning needed, just use the characters from the lexed buffer.
  510. II = getIdentifierInfo(Identifier.getRawIdentifier());
  511. } else {
  512. // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
  513. SmallString<64> IdentifierBuffer;
  514. StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
  515. if (Identifier.hasUCN()) {
  516. SmallString<64> UCNIdentifierBuffer;
  517. expandUCNs(UCNIdentifierBuffer, CleanedStr);
  518. II = getIdentifierInfo(UCNIdentifierBuffer);
  519. } else {
  520. II = getIdentifierInfo(CleanedStr);
  521. }
  522. }
  523. // Update the token info (identifier info and appropriate token kind).
  524. Identifier.setIdentifierInfo(II);
  525. if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
  526. getSourceManager().isInSystemHeader(Identifier.getLocation()))
  527. Identifier.setKind(tok::identifier);
  528. else
  529. Identifier.setKind(II->getTokenID());
  530. return II;
  531. }
  532. void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
  533. PoisonReasons[II] = DiagID;
  534. }
  535. void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
  536. assert(Ident__exception_code && Ident__exception_info);
  537. assert(Ident___exception_code && Ident___exception_info);
  538. Ident__exception_code->setIsPoisoned(Poison);
  539. Ident___exception_code->setIsPoisoned(Poison);
  540. Ident_GetExceptionCode->setIsPoisoned(Poison);
  541. Ident__exception_info->setIsPoisoned(Poison);
  542. Ident___exception_info->setIsPoisoned(Poison);
  543. Ident_GetExceptionInfo->setIsPoisoned(Poison);
  544. Ident__abnormal_termination->setIsPoisoned(Poison);
  545. Ident___abnormal_termination->setIsPoisoned(Poison);
  546. Ident_AbnormalTermination->setIsPoisoned(Poison);
  547. }
  548. void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
  549. assert(Identifier.getIdentifierInfo() &&
  550. "Can't handle identifiers without identifier info!");
  551. llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
  552. PoisonReasons.find(Identifier.getIdentifierInfo());
  553. if(it == PoisonReasons.end())
  554. Diag(Identifier, diag::err_pp_used_poisoned_id);
  555. else
  556. Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
  557. }
  558. /// \brief Returns a diagnostic message kind for reporting a future keyword as
  559. /// appropriate for the identifier and specified language.
  560. static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
  561. const LangOptions &LangOpts) {
  562. assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
  563. if (LangOpts.CPlusPlus)
  564. return llvm::StringSwitch<diag::kind>(II.getName())
  565. #define CXX11_KEYWORD(NAME, FLAGS) \
  566. .Case(#NAME, diag::warn_cxx11_keyword)
  567. #define CXX2A_KEYWORD(NAME, FLAGS) \
  568. .Case(#NAME, diag::warn_cxx2a_keyword)
  569. #include "clang/Basic/TokenKinds.def"
  570. ;
  571. llvm_unreachable(
  572. "Keyword not known to come from a newer Standard or proposed Standard");
  573. }
  574. void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
  575. assert(II.isOutOfDate() && "not out of date");
  576. getExternalSource()->updateOutOfDateIdentifier(II);
  577. }
  578. /// HandleIdentifier - This callback is invoked when the lexer reads an
  579. /// identifier. This callback looks up the identifier in the map and/or
  580. /// potentially macro expands it or turns it into a named token (like 'for').
  581. ///
  582. /// Note that callers of this method are guarded by checking the
  583. /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
  584. /// IdentifierInfo methods that compute these properties will need to change to
  585. /// match.
  586. bool Preprocessor::HandleIdentifier(Token &Identifier) {
  587. assert(Identifier.getIdentifierInfo() &&
  588. "Can't handle identifiers without identifier info!");
  589. IdentifierInfo &II = *Identifier.getIdentifierInfo();
  590. // If the information about this identifier is out of date, update it from
  591. // the external source.
  592. // We have to treat __VA_ARGS__ in a special way, since it gets
  593. // serialized with isPoisoned = true, but our preprocessor may have
  594. // unpoisoned it if we're defining a C99 macro.
  595. if (II.isOutOfDate()) {
  596. bool CurrentIsPoisoned = false;
  597. const bool IsSpecialVariadicMacro =
  598. &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
  599. if (IsSpecialVariadicMacro)
  600. CurrentIsPoisoned = II.isPoisoned();
  601. updateOutOfDateIdentifier(II);
  602. Identifier.setKind(II.getTokenID());
  603. if (IsSpecialVariadicMacro)
  604. II.setIsPoisoned(CurrentIsPoisoned);
  605. }
  606. // If this identifier was poisoned, and if it was not produced from a macro
  607. // expansion, emit an error.
  608. if (II.isPoisoned() && CurPPLexer) {
  609. HandlePoisonedIdentifier(Identifier);
  610. }
  611. // If this is a macro to be expanded, do it.
  612. if (MacroDefinition MD = getMacroDefinition(&II)) {
  613. auto *MI = MD.getMacroInfo();
  614. assert(MI && "macro definition with no macro info?");
  615. if (!DisableMacroExpansion) {
  616. if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
  617. // C99 6.10.3p10: If the preprocessing token immediately after the
  618. // macro name isn't a '(', this macro should not be expanded.
  619. if (!MI->isFunctionLike() || isNextPPTokenLParen())
  620. return HandleMacroExpandedIdentifier(Identifier, MD);
  621. } else {
  622. // C99 6.10.3.4p2 says that a disabled macro may never again be
  623. // expanded, even if it's in a context where it could be expanded in the
  624. // future.
  625. Identifier.setFlag(Token::DisableExpand);
  626. if (MI->isObjectLike() || isNextPPTokenLParen())
  627. Diag(Identifier, diag::pp_disabled_macro_expansion);
  628. }
  629. }
  630. }
  631. // If this identifier is a keyword in a newer Standard or proposed Standard,
  632. // produce a warning. Don't warn if we're not considering macro expansion,
  633. // since this identifier might be the name of a macro.
  634. // FIXME: This warning is disabled in cases where it shouldn't be, like
  635. // "#define constexpr constexpr", "int constexpr;"
  636. if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
  637. Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
  638. << II.getName();
  639. // Don't diagnose this keyword again in this translation unit.
  640. II.setIsFutureCompatKeyword(false);
  641. }
  642. // If this is an extension token, diagnose its use.
  643. // We avoid diagnosing tokens that originate from macro definitions.
  644. // FIXME: This warning is disabled in cases where it shouldn't be,
  645. // like "#define TY typeof", "TY(1) x".
  646. if (II.isExtensionToken() && !DisableMacroExpansion)
  647. Diag(Identifier, diag::ext_token_used);
  648. // If this is the 'import' contextual keyword following an '@', note
  649. // that the next token indicates a module name.
  650. //
  651. // Note that we do not treat 'import' as a contextual
  652. // keyword when we're in a caching lexer, because caching lexers only get
  653. // used in contexts where import declarations are disallowed.
  654. //
  655. // Likewise if this is the C++ Modules TS import keyword.
  656. if (((LastTokenWasAt && II.isModulesImport()) ||
  657. Identifier.is(tok::kw_import)) &&
  658. !InMacroArgs && !DisableMacroExpansion &&
  659. (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
  660. CurLexerKind != CLK_CachingLexer) {
  661. ModuleImportLoc = Identifier.getLocation();
  662. ModuleImportPath.clear();
  663. ModuleImportExpectsIdentifier = true;
  664. CurLexerKind = CLK_LexAfterModuleImport;
  665. }
  666. return true;
  667. }
  668. void Preprocessor::Lex(Token &Result) {
  669. // We loop here until a lex function returns a token; this avoids recursion.
  670. bool ReturnedToken;
  671. do {
  672. switch (CurLexerKind) {
  673. case CLK_Lexer:
  674. ReturnedToken = CurLexer->Lex(Result);
  675. break;
  676. case CLK_PTHLexer:
  677. ReturnedToken = CurPTHLexer->Lex(Result);
  678. break;
  679. case CLK_TokenLexer:
  680. ReturnedToken = CurTokenLexer->Lex(Result);
  681. break;
  682. case CLK_CachingLexer:
  683. CachingLex(Result);
  684. ReturnedToken = true;
  685. break;
  686. case CLK_LexAfterModuleImport:
  687. LexAfterModuleImport(Result);
  688. ReturnedToken = true;
  689. break;
  690. }
  691. } while (!ReturnedToken);
  692. if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
  693. // Remember the identifier before code completion token.
  694. setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
  695. // Set IdenfitierInfo to null to avoid confusing code that handles both
  696. // identifiers and completion tokens.
  697. Result.setIdentifierInfo(nullptr);
  698. }
  699. LastTokenWasAt = Result.is(tok::at);
  700. }
  701. /// \brief Lex a token following the 'import' contextual keyword.
  702. ///
  703. void Preprocessor::LexAfterModuleImport(Token &Result) {
  704. // Figure out what kind of lexer we actually have.
  705. recomputeCurLexerKind();
  706. // Lex the next token.
  707. Lex(Result);
  708. // The token sequence
  709. //
  710. // import identifier (. identifier)*
  711. //
  712. // indicates a module import directive. We already saw the 'import'
  713. // contextual keyword, so now we're looking for the identifiers.
  714. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
  715. // We expected to see an identifier here, and we did; continue handling
  716. // identifiers.
  717. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
  718. Result.getLocation()));
  719. ModuleImportExpectsIdentifier = false;
  720. CurLexerKind = CLK_LexAfterModuleImport;
  721. return;
  722. }
  723. // If we're expecting a '.' or a ';', and we got a '.', then wait until we
  724. // see the next identifier. (We can also see a '[[' that begins an
  725. // attribute-specifier-seq here under the C++ Modules TS.)
  726. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
  727. ModuleImportExpectsIdentifier = true;
  728. CurLexerKind = CLK_LexAfterModuleImport;
  729. return;
  730. }
  731. // If we have a non-empty module path, load the named module.
  732. if (!ModuleImportPath.empty()) {
  733. // Under the Modules TS, the dot is just part of the module name, and not
  734. // a real hierarachy separator. Flatten such module names now.
  735. //
  736. // FIXME: Is this the right level to be performing this transformation?
  737. std::string FlatModuleName;
  738. if (getLangOpts().ModulesTS) {
  739. for (auto &Piece : ModuleImportPath) {
  740. if (!FlatModuleName.empty())
  741. FlatModuleName += ".";
  742. FlatModuleName += Piece.first->getName();
  743. }
  744. SourceLocation FirstPathLoc = ModuleImportPath[0].second;
  745. ModuleImportPath.clear();
  746. ModuleImportPath.push_back(
  747. std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
  748. }
  749. Module *Imported = nullptr;
  750. if (getLangOpts().Modules) {
  751. Imported = TheModuleLoader.loadModule(ModuleImportLoc,
  752. ModuleImportPath,
  753. Module::Hidden,
  754. /*IsIncludeDirective=*/false);
  755. if (Imported)
  756. makeModuleVisible(Imported, ModuleImportLoc);
  757. }
  758. if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
  759. Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
  760. }
  761. }
  762. void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
  763. CurSubmoduleState->VisibleModules.setVisible(
  764. M, Loc, [](Module *) {},
  765. [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
  766. // FIXME: Include the path in the diagnostic.
  767. // FIXME: Include the import location for the conflicting module.
  768. Diag(ModuleImportLoc, diag::warn_module_conflict)
  769. << Path[0]->getFullModuleName()
  770. << Conflict->getFullModuleName()
  771. << Message;
  772. });
  773. // Add this module to the imports list of the currently-built submodule.
  774. if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
  775. BuildingSubmoduleStack.back().M->Imports.insert(M);
  776. }
  777. bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
  778. const char *DiagnosticTag,
  779. bool AllowMacroExpansion) {
  780. // We need at least one string literal.
  781. if (Result.isNot(tok::string_literal)) {
  782. Diag(Result, diag::err_expected_string_literal)
  783. << /*Source='in...'*/0 << DiagnosticTag;
  784. return false;
  785. }
  786. // Lex string literal tokens, optionally with macro expansion.
  787. SmallVector<Token, 4> StrToks;
  788. do {
  789. StrToks.push_back(Result);
  790. if (Result.hasUDSuffix())
  791. Diag(Result, diag::err_invalid_string_udl);
  792. if (AllowMacroExpansion)
  793. Lex(Result);
  794. else
  795. LexUnexpandedToken(Result);
  796. } while (Result.is(tok::string_literal));
  797. // Concatenate and parse the strings.
  798. StringLiteralParser Literal(StrToks, *this);
  799. assert(Literal.isAscii() && "Didn't allow wide strings in");
  800. if (Literal.hadError)
  801. return false;
  802. if (Literal.Pascal) {
  803. Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
  804. << /*Source='in...'*/0 << DiagnosticTag;
  805. return false;
  806. }
  807. String = Literal.GetString();
  808. return true;
  809. }
  810. bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
  811. assert(Tok.is(tok::numeric_constant));
  812. SmallString<8> IntegerBuffer;
  813. bool NumberInvalid = false;
  814. StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
  815. if (NumberInvalid)
  816. return false;
  817. NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
  818. if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
  819. return false;
  820. llvm::APInt APVal(64, 0);
  821. if (Literal.GetIntegerValue(APVal))
  822. return false;
  823. Lex(Tok);
  824. Value = APVal.getLimitedValue();
  825. return true;
  826. }
  827. void Preprocessor::addCommentHandler(CommentHandler *Handler) {
  828. assert(Handler && "NULL comment handler");
  829. assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
  830. CommentHandlers.end() && "Comment handler already registered");
  831. CommentHandlers.push_back(Handler);
  832. }
  833. void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
  834. std::vector<CommentHandler *>::iterator Pos =
  835. std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
  836. assert(Pos != CommentHandlers.end() && "Comment handler not registered");
  837. CommentHandlers.erase(Pos);
  838. }
  839. bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
  840. bool AnyPendingTokens = false;
  841. for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
  842. HEnd = CommentHandlers.end();
  843. H != HEnd; ++H) {
  844. if ((*H)->HandleComment(*this, Comment))
  845. AnyPendingTokens = true;
  846. }
  847. if (!AnyPendingTokens || getCommentRetentionState())
  848. return false;
  849. Lex(result);
  850. return true;
  851. }
  852. ModuleLoader::~ModuleLoader() = default;
  853. CommentHandler::~CommentHandler() = default;
  854. CodeCompletionHandler::~CodeCompletionHandler() = default;
  855. void Preprocessor::createPreprocessingRecord() {
  856. if (Record)
  857. return;
  858. Record = new PreprocessingRecord(getSourceManager());
  859. addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
  860. }