xref: /llvm-project/clang/lib/Lex/Preprocessor.cpp (revision 65780f4d8e34461e6bd3baf2ff77496f97874b94)
1 //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
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 Preprocessor interface.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // Options to support:
14 //   -H       - Print the name of each header file used.
15 //   -d[DNI] - Dump various things.
16 //   -fworking-directory - #line's with preprocessor's working dir.
17 //   -fpreprocessed
18 //   -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
19 //   -W*
20 //   -w
21 //
22 // Messages to emit:
23 //   "Multiple include guards may be useful for:\n"
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/FileSystemStatCache.h"
31 #include "clang/Basic/IdentifierTable.h"
32 #include "clang/Basic/LLVM.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Lex/CodeCompletionHandler.h"
39 #include "clang/Lex/ExternalPreprocessorSource.h"
40 #include "clang/Lex/HeaderSearch.h"
41 #include "clang/Lex/LexDiagnostic.h"
42 #include "clang/Lex/Lexer.h"
43 #include "clang/Lex/LiteralSupport.h"
44 #include "clang/Lex/MacroArgs.h"
45 #include "clang/Lex/MacroInfo.h"
46 #include "clang/Lex/ModuleLoader.h"
47 #include "clang/Lex/Pragma.h"
48 #include "clang/Lex/PreprocessingRecord.h"
49 #include "clang/Lex/PreprocessorLexer.h"
50 #include "clang/Lex/PreprocessorOptions.h"
51 #include "clang/Lex/ScratchBuffer.h"
52 #include "clang/Lex/Token.h"
53 #include "clang/Lex/TokenLexer.h"
54 #include "llvm/ADT/APInt.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallString.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/StringRef.h"
61 #include "llvm/ADT/iterator_range.h"
62 #include "llvm/Support/Capacity.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MemoryBuffer.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <memory>
69 #include <optional>
70 #include <string>
71 #include <utility>
72 #include <vector>
73 
74 using namespace clang;
75 
76 /// Minimum distance between two check points, in tokens.
77 static constexpr unsigned CheckPointStepSize = 1024;
78 
79 LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
80 
81 ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
82 
83 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
84                            DiagnosticsEngine &diags, const LangOptions &opts,
85                            SourceManager &SM, HeaderSearch &Headers,
86                            ModuleLoader &TheModuleLoader,
87                            IdentifierInfoLookup *IILookup, bool OwnsHeaders,
88                            TranslationUnitKind TUKind)
89     : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
90       FileMgr(Headers.getFileMgr()), SourceMgr(SM),
91       ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
92       TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
93       // As the language options may have not been loaded yet (when
94       // deserializing an ASTUnit), adding keywords to the identifier table is
95       // deferred to Preprocessor::Initialize().
96       Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
97       TUKind(TUKind), SkipMainFilePreamble(0, true),
98       CurSubmoduleState(&NullSubmoduleState) {
99   OwnsHeaderSearch = OwnsHeaders;
100 
101   // Default to discarding comments.
102   KeepComments = false;
103   KeepMacroComments = false;
104   SuppressIncludeNotFoundError = false;
105 
106   // Macro expansion is enabled.
107   DisableMacroExpansion = false;
108   MacroExpansionInDirectivesOverride = false;
109   InMacroArgs = false;
110   ArgMacro = nullptr;
111   InMacroArgPreExpansion = false;
112   NumCachedTokenLexers = 0;
113   PragmasEnabled = true;
114   ParsingIfOrElifDirective = false;
115   PreprocessedOutput = false;
116 
117   // We haven't read anything from the external source.
118   ReadMacrosFromExternalSource = false;
119 
120   BuiltinInfo = std::make_unique<Builtin::Context>();
121 
122   // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
123   // a macro. They get unpoisoned where it is allowed.
124   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
125   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
126   (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
127   SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
128 
129   // Initialize the pragma handlers.
130   RegisterBuiltinPragmas();
131 
132   // Initialize builtin macros like __LINE__ and friends.
133   RegisterBuiltinMacros();
134 
135   if(LangOpts.Borland) {
136     Ident__exception_info        = getIdentifierInfo("_exception_info");
137     Ident___exception_info       = getIdentifierInfo("__exception_info");
138     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
139     Ident__exception_code        = getIdentifierInfo("_exception_code");
140     Ident___exception_code       = getIdentifierInfo("__exception_code");
141     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
142     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
143     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
144     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
145   } else {
146     Ident__exception_info = Ident__exception_code = nullptr;
147     Ident__abnormal_termination = Ident___exception_info = nullptr;
148     Ident___exception_code = Ident___abnormal_termination = nullptr;
149     Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
150     Ident_AbnormalTermination = nullptr;
151   }
152 
153   // Default incremental processing to -fincremental-extensions, clients can
154   // override with `enableIncrementalProcessing` if desired.
155   IncrementalProcessing = LangOpts.IncrementalExtensions;
156 
157   // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
158   if (usingPCHWithPragmaHdrStop())
159     SkippingUntilPragmaHdrStop = true;
160 
161   // If using a PCH with a through header, start skipping tokens.
162   if (!this->PPOpts->PCHThroughHeader.empty() &&
163       !this->PPOpts->ImplicitPCHInclude.empty())
164     SkippingUntilPCHThroughHeader = true;
165 
166   if (this->PPOpts->GeneratePreamble)
167     PreambleConditionalStack.startRecording();
168 
169   MaxTokens = LangOpts.MaxTokens;
170 }
171 
172 Preprocessor::~Preprocessor() {
173   assert(!isBacktrackEnabled() && "EnableBacktrack/Backtrack imbalance!");
174 
175   IncludeMacroStack.clear();
176 
177   // Free any cached macro expanders.
178   // This populates MacroArgCache, so all TokenLexers need to be destroyed
179   // before the code below that frees up the MacroArgCache list.
180   std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
181   CurTokenLexer.reset();
182 
183   // Free any cached MacroArgs.
184   for (MacroArgs *ArgList = MacroArgCache; ArgList;)
185     ArgList = ArgList->deallocate();
186 
187   // Delete the header search info, if we own it.
188   if (OwnsHeaderSearch)
189     delete &HeaderInfo;
190 }
191 
192 void Preprocessor::Initialize(const TargetInfo &Target,
193                               const TargetInfo *AuxTarget) {
194   assert((!this->Target || this->Target == &Target) &&
195          "Invalid override of target information");
196   this->Target = &Target;
197 
198   assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
199          "Invalid override of aux target information.");
200   this->AuxTarget = AuxTarget;
201 
202   // Initialize information about built-ins.
203   BuiltinInfo->InitializeTarget(Target, AuxTarget);
204   HeaderInfo.setTarget(Target);
205 
206   // Populate the identifier table with info about keywords for the current language.
207   Identifiers.AddKeywords(LangOpts);
208 
209   // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
210   setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
211 
212   if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
213     // Use setting from TargetInfo.
214     setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
215   else
216     // Set initial value of __FLT_EVAL_METHOD__ from the command line.
217     setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
218 }
219 
220 void Preprocessor::InitializeForModelFile() {
221   NumEnteredSourceFiles = 0;
222 
223   // Reset pragmas
224   PragmaHandlersBackup = std::move(PragmaHandlers);
225   PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
226   RegisterBuiltinPragmas();
227 
228   // Reset PredefinesFileID
229   PredefinesFileID = FileID();
230 }
231 
232 void Preprocessor::FinalizeForModelFile() {
233   NumEnteredSourceFiles = 1;
234 
235   PragmaHandlers = std::move(PragmaHandlersBackup);
236 }
237 
238 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
239   llvm::errs() << tok::getTokenName(Tok.getKind());
240 
241   if (!Tok.isAnnotation())
242     llvm::errs() << " '" << getSpelling(Tok) << "'";
243 
244   if (!DumpFlags) return;
245 
246   llvm::errs() << "\t";
247   if (Tok.isAtStartOfLine())
248     llvm::errs() << " [StartOfLine]";
249   if (Tok.hasLeadingSpace())
250     llvm::errs() << " [LeadingSpace]";
251   if (Tok.isExpandDisabled())
252     llvm::errs() << " [ExpandDisabled]";
253   if (Tok.needsCleaning()) {
254     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
255     llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
256                  << "']";
257   }
258 
259   llvm::errs() << "\tLoc=<";
260   DumpLocation(Tok.getLocation());
261   llvm::errs() << ">";
262 }
263 
264 void Preprocessor::DumpLocation(SourceLocation Loc) const {
265   Loc.print(llvm::errs(), SourceMgr);
266 }
267 
268 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
269   llvm::errs() << "MACRO: ";
270   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
271     DumpToken(MI.getReplacementToken(i));
272     llvm::errs() << "  ";
273   }
274   llvm::errs() << "\n";
275 }
276 
277 void Preprocessor::PrintStats() {
278   llvm::errs() << "\n*** Preprocessor Stats:\n";
279   llvm::errs() << NumDirectives << " directives found:\n";
280   llvm::errs() << "  " << NumDefined << " #define.\n";
281   llvm::errs() << "  " << NumUndefined << " #undef.\n";
282   llvm::errs() << "  #include/#include_next/#import:\n";
283   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
284   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
285   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
286   llvm::errs() << "  " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
287   llvm::errs() << "  " << NumEndif << " #endif.\n";
288   llvm::errs() << "  " << NumPragma << " #pragma.\n";
289   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
290 
291   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
292              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
293              << NumFastMacroExpanded << " on the fast path.\n";
294   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
295              << " token paste (##) operations performed, "
296              << NumFastTokenPaste << " on the fast path.\n";
297 
298   llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
299 
300   llvm::errs() << "\n  BumpPtr: " << BP.getTotalMemory();
301   llvm::errs() << "\n  Macro Expanded Tokens: "
302                << llvm::capacity_in_bytes(MacroExpandedTokens);
303   llvm::errs() << "\n  Predefines Buffer: " << Predefines.capacity();
304   // FIXME: List information for all submodules.
305   llvm::errs() << "\n  Macros: "
306                << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
307   llvm::errs() << "\n  #pragma push_macro Info: "
308                << llvm::capacity_in_bytes(PragmaPushMacroInfo);
309   llvm::errs() << "\n  Poison Reasons: "
310                << llvm::capacity_in_bytes(PoisonReasons);
311   llvm::errs() << "\n  Comment Handlers: "
312                << llvm::capacity_in_bytes(CommentHandlers) << "\n";
313 }
314 
315 Preprocessor::macro_iterator
316 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
317   if (IncludeExternalMacros && ExternalSource &&
318       !ReadMacrosFromExternalSource) {
319     ReadMacrosFromExternalSource = true;
320     ExternalSource->ReadDefinedMacros();
321   }
322 
323   // Make sure we cover all macros in visible modules.
324   for (const ModuleMacro &Macro : ModuleMacros)
325     CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
326 
327   return CurSubmoduleState->Macros.begin();
328 }
329 
330 size_t Preprocessor::getTotalMemory() const {
331   return BP.getTotalMemory()
332     + llvm::capacity_in_bytes(MacroExpandedTokens)
333     + Predefines.capacity() /* Predefines buffer. */
334     // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
335     // and ModuleMacros.
336     + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
337     + llvm::capacity_in_bytes(PragmaPushMacroInfo)
338     + llvm::capacity_in_bytes(PoisonReasons)
339     + llvm::capacity_in_bytes(CommentHandlers);
340 }
341 
342 Preprocessor::macro_iterator
343 Preprocessor::macro_end(bool IncludeExternalMacros) const {
344   if (IncludeExternalMacros && ExternalSource &&
345       !ReadMacrosFromExternalSource) {
346     ReadMacrosFromExternalSource = true;
347     ExternalSource->ReadDefinedMacros();
348   }
349 
350   return CurSubmoduleState->Macros.end();
351 }
352 
353 /// Compares macro tokens with a specified token value sequence.
354 static bool MacroDefinitionEquals(const MacroInfo *MI,
355                                   ArrayRef<TokenValue> Tokens) {
356   return Tokens.size() == MI->getNumTokens() &&
357       std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
358 }
359 
360 StringRef Preprocessor::getLastMacroWithSpelling(
361                                     SourceLocation Loc,
362                                     ArrayRef<TokenValue> Tokens) const {
363   SourceLocation BestLocation;
364   StringRef BestSpelling;
365   for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
366        I != E; ++I) {
367     const MacroDirective::DefInfo
368       Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
369     if (!Def || !Def.getMacroInfo())
370       continue;
371     if (!Def.getMacroInfo()->isObjectLike())
372       continue;
373     if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
374       continue;
375     SourceLocation Location = Def.getLocation();
376     // Choose the macro defined latest.
377     if (BestLocation.isInvalid() ||
378         (Location.isValid() &&
379          SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
380       BestLocation = Location;
381       BestSpelling = I->first->getName();
382     }
383   }
384   return BestSpelling;
385 }
386 
387 void Preprocessor::recomputeCurLexerKind() {
388   if (CurLexer)
389     CurLexerCallback = CurLexer->isDependencyDirectivesLexer()
390                            ? CLK_DependencyDirectivesLexer
391                            : CLK_Lexer;
392   else if (CurTokenLexer)
393     CurLexerCallback = CLK_TokenLexer;
394   else
395     CurLexerCallback = CLK_CachingLexer;
396 }
397 
398 bool Preprocessor::SetCodeCompletionPoint(FileEntryRef File,
399                                           unsigned CompleteLine,
400                                           unsigned CompleteColumn) {
401   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
402   assert(!CodeCompletionFile && "Already set");
403 
404   // Load the actual file's contents.
405   std::optional<llvm::MemoryBufferRef> Buffer =
406       SourceMgr.getMemoryBufferForFileOrNone(File);
407   if (!Buffer)
408     return true;
409 
410   // Find the byte position of the truncation point.
411   const char *Position = Buffer->getBufferStart();
412   for (unsigned Line = 1; Line < CompleteLine; ++Line) {
413     for (; *Position; ++Position) {
414       if (*Position != '\r' && *Position != '\n')
415         continue;
416 
417       // Eat \r\n or \n\r as a single line.
418       if ((Position[1] == '\r' || Position[1] == '\n') &&
419           Position[0] != Position[1])
420         ++Position;
421       ++Position;
422       break;
423     }
424   }
425 
426   Position += CompleteColumn - 1;
427 
428   // If pointing inside the preamble, adjust the position at the beginning of
429   // the file after the preamble.
430   if (SkipMainFilePreamble.first &&
431       SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
432     if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
433       Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
434   }
435 
436   if (Position > Buffer->getBufferEnd())
437     Position = Buffer->getBufferEnd();
438 
439   CodeCompletionFile = File;
440   CodeCompletionOffset = Position - Buffer->getBufferStart();
441 
442   auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
443       Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
444   char *NewBuf = NewBuffer->getBufferStart();
445   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
446   *NewPos = '\0';
447   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
448   SourceMgr.overrideFileContents(File, std::move(NewBuffer));
449 
450   return false;
451 }
452 
453 void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
454                                             bool IsAngled) {
455   setCodeCompletionReached();
456   if (CodeComplete)
457     CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
458 }
459 
460 void Preprocessor::CodeCompleteNaturalLanguage() {
461   setCodeCompletionReached();
462   if (CodeComplete)
463     CodeComplete->CodeCompleteNaturalLanguage();
464 }
465 
466 /// getSpelling - This method is used to get the spelling of a token into a
467 /// SmallVector. Note that the returned StringRef may not point to the
468 /// supplied buffer if a copy can be avoided.
469 StringRef Preprocessor::getSpelling(const Token &Tok,
470                                           SmallVectorImpl<char> &Buffer,
471                                           bool *Invalid) const {
472   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
473   if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
474     // Try the fast path.
475     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
476       return II->getName();
477   }
478 
479   // Resize the buffer if we need to copy into it.
480   if (Tok.needsCleaning())
481     Buffer.resize(Tok.getLength());
482 
483   const char *Ptr = Buffer.data();
484   unsigned Len = getSpelling(Tok, Ptr, Invalid);
485   return StringRef(Ptr, Len);
486 }
487 
488 /// CreateString - Plop the specified string into a scratch buffer and return a
489 /// location for it.  If specified, the source location provides a source
490 /// location for the token.
491 void Preprocessor::CreateString(StringRef Str, Token &Tok,
492                                 SourceLocation ExpansionLocStart,
493                                 SourceLocation ExpansionLocEnd) {
494   Tok.setLength(Str.size());
495 
496   const char *DestPtr;
497   SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
498 
499   if (ExpansionLocStart.isValid())
500     Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
501                                        ExpansionLocEnd, Str.size());
502   Tok.setLocation(Loc);
503 
504   // If this is a raw identifier or a literal token, set the pointer data.
505   if (Tok.is(tok::raw_identifier))
506     Tok.setRawIdentifierData(DestPtr);
507   else if (Tok.isLiteral())
508     Tok.setLiteralData(DestPtr);
509 }
510 
511 SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
512   auto &SM = getSourceManager();
513   SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
514   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
515   bool Invalid = false;
516   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
517   if (Invalid)
518     return SourceLocation();
519 
520   // FIXME: We could consider re-using spelling for tokens we see repeatedly.
521   const char *DestPtr;
522   SourceLocation Spelling =
523       ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
524   return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
525 }
526 
527 Module *Preprocessor::getCurrentModule() {
528   if (!getLangOpts().isCompilingModule())
529     return nullptr;
530 
531   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
532 }
533 
534 Module *Preprocessor::getCurrentModuleImplementation() {
535   if (!getLangOpts().isCompilingModuleImplementation())
536     return nullptr;
537 
538   return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
539 }
540 
541 //===----------------------------------------------------------------------===//
542 // Preprocessor Initialization Methods
543 //===----------------------------------------------------------------------===//
544 
545 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
546 /// which implicitly adds the builtin defines etc.
547 void Preprocessor::EnterMainSourceFile() {
548   // We do not allow the preprocessor to reenter the main file.  Doing so will
549   // cause FileID's to accumulate information from both runs (e.g. #line
550   // information) and predefined macros aren't guaranteed to be set properly.
551   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
552   FileID MainFileID = SourceMgr.getMainFileID();
553 
554   // If MainFileID is loaded it means we loaded an AST file, no need to enter
555   // a main file.
556   if (!SourceMgr.isLoadedFileID(MainFileID)) {
557     // Enter the main file source buffer.
558     EnterSourceFile(MainFileID, nullptr, SourceLocation());
559 
560     // If we've been asked to skip bytes in the main file (e.g., as part of a
561     // precompiled preamble), do so now.
562     if (SkipMainFilePreamble.first > 0)
563       CurLexer->SetByteOffset(SkipMainFilePreamble.first,
564                               SkipMainFilePreamble.second);
565 
566     // Tell the header info that the main file was entered.  If the file is later
567     // #imported, it won't be re-entered.
568     if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(MainFileID))
569       markIncluded(*FE);
570   }
571 
572   // Preprocess Predefines to populate the initial preprocessor state.
573   std::unique_ptr<llvm::MemoryBuffer> SB =
574     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
575   assert(SB && "Cannot create predefined source buffer");
576   FileID FID = SourceMgr.createFileID(std::move(SB));
577   assert(FID.isValid() && "Could not create FileID for predefines?");
578   setPredefinesFileID(FID);
579 
580   // Start parsing the predefines.
581   EnterSourceFile(FID, nullptr, SourceLocation());
582 
583   if (!PPOpts->PCHThroughHeader.empty()) {
584     // Lookup and save the FileID for the through header. If it isn't found
585     // in the search path, it's a fatal error.
586     OptionalFileEntryRef File = LookupFile(
587         SourceLocation(), PPOpts->PCHThroughHeader,
588         /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
589         /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
590         /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
591         /*IsFrameworkFound=*/nullptr);
592     if (!File) {
593       Diag(SourceLocation(), diag::err_pp_through_header_not_found)
594           << PPOpts->PCHThroughHeader;
595       return;
596     }
597     setPCHThroughHeaderFileID(
598         SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
599   }
600 
601   // Skip tokens from the Predefines and if needed the main file.
602   if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
603       (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
604     SkipTokensWhileUsingPCH();
605 }
606 
607 void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
608   assert(PCHThroughHeaderFileID.isInvalid() &&
609          "PCHThroughHeaderFileID already set!");
610   PCHThroughHeaderFileID = FID;
611 }
612 
613 bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
614   assert(PCHThroughHeaderFileID.isValid() &&
615          "Invalid PCH through header FileID");
616   return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
617 }
618 
619 bool Preprocessor::creatingPCHWithThroughHeader() {
620   return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
621          PCHThroughHeaderFileID.isValid();
622 }
623 
624 bool Preprocessor::usingPCHWithThroughHeader() {
625   return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
626          PCHThroughHeaderFileID.isValid();
627 }
628 
629 bool Preprocessor::creatingPCHWithPragmaHdrStop() {
630   return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
631 }
632 
633 bool Preprocessor::usingPCHWithPragmaHdrStop() {
634   return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
635 }
636 
637 /// Skip tokens until after the #include of the through header or
638 /// until after a #pragma hdrstop is seen. Tokens in the predefines file
639 /// and the main file may be skipped. If the end of the predefines file
640 /// is reached, skipping continues into the main file. If the end of the
641 /// main file is reached, it's a fatal error.
642 void Preprocessor::SkipTokensWhileUsingPCH() {
643   bool ReachedMainFileEOF = false;
644   bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
645   bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
646   Token Tok;
647   while (true) {
648     bool InPredefines =
649         (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
650     CurLexerCallback(*this, Tok);
651     if (Tok.is(tok::eof) && !InPredefines) {
652       ReachedMainFileEOF = true;
653       break;
654     }
655     if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
656       break;
657     if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
658       break;
659   }
660   if (ReachedMainFileEOF) {
661     if (UsingPCHThroughHeader)
662       Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
663           << PPOpts->PCHThroughHeader << 1;
664     else if (!PPOpts->PCHWithHdrStopCreate)
665       Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
666   }
667 }
668 
669 void Preprocessor::replayPreambleConditionalStack() {
670   // Restore the conditional stack from the preamble, if there is one.
671   if (PreambleConditionalStack.isReplaying()) {
672     assert(CurPPLexer &&
673            "CurPPLexer is null when calling replayPreambleConditionalStack.");
674     CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
675     PreambleConditionalStack.doneReplaying();
676     if (PreambleConditionalStack.reachedEOFWhileSkipping())
677       SkipExcludedConditionalBlock(
678           PreambleConditionalStack.SkipInfo->HashTokenLoc,
679           PreambleConditionalStack.SkipInfo->IfTokenLoc,
680           PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
681           PreambleConditionalStack.SkipInfo->FoundElse,
682           PreambleConditionalStack.SkipInfo->ElseLoc);
683   }
684 }
685 
686 void Preprocessor::EndSourceFile() {
687   // Notify the client that we reached the end of the source file.
688   if (Callbacks)
689     Callbacks->EndOfMainFile();
690 }
691 
692 //===----------------------------------------------------------------------===//
693 // Lexer Event Handling.
694 //===----------------------------------------------------------------------===//
695 
696 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
697 /// identifier information for the token and install it into the token,
698 /// updating the token kind accordingly.
699 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
700   assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
701 
702   // Look up this token, see if it is a macro, or if it is a language keyword.
703   IdentifierInfo *II;
704   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
705     // No cleaning needed, just use the characters from the lexed buffer.
706     II = getIdentifierInfo(Identifier.getRawIdentifier());
707   } else {
708     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
709     SmallString<64> IdentifierBuffer;
710     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
711 
712     if (Identifier.hasUCN()) {
713       SmallString<64> UCNIdentifierBuffer;
714       expandUCNs(UCNIdentifierBuffer, CleanedStr);
715       II = getIdentifierInfo(UCNIdentifierBuffer);
716     } else {
717       II = getIdentifierInfo(CleanedStr);
718     }
719   }
720 
721   // Update the token info (identifier info and appropriate token kind).
722   // FIXME: the raw_identifier may contain leading whitespace which is removed
723   // from the cleaned identifier token. The SourceLocation should be updated to
724   // refer to the non-whitespace character. For instance, the text "\\\nB" (a
725   // line continuation before 'B') is parsed as a single tok::raw_identifier and
726   // is cleaned to tok::identifier "B". After cleaning the token's length is
727   // still 3 and the SourceLocation refers to the location of the backslash.
728   Identifier.setIdentifierInfo(II);
729   Identifier.setKind(II->getTokenID());
730 
731   return II;
732 }
733 
734 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
735   PoisonReasons[II] = DiagID;
736 }
737 
738 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
739   assert(Ident__exception_code && Ident__exception_info);
740   assert(Ident___exception_code && Ident___exception_info);
741   Ident__exception_code->setIsPoisoned(Poison);
742   Ident___exception_code->setIsPoisoned(Poison);
743   Ident_GetExceptionCode->setIsPoisoned(Poison);
744   Ident__exception_info->setIsPoisoned(Poison);
745   Ident___exception_info->setIsPoisoned(Poison);
746   Ident_GetExceptionInfo->setIsPoisoned(Poison);
747   Ident__abnormal_termination->setIsPoisoned(Poison);
748   Ident___abnormal_termination->setIsPoisoned(Poison);
749   Ident_AbnormalTermination->setIsPoisoned(Poison);
750 }
751 
752 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
753   assert(Identifier.getIdentifierInfo() &&
754          "Can't handle identifiers without identifier info!");
755   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
756     PoisonReasons.find(Identifier.getIdentifierInfo());
757   if(it == PoisonReasons.end())
758     Diag(Identifier, diag::err_pp_used_poisoned_id);
759   else
760     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
761 }
762 
763 void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const {
764   assert(II.isOutOfDate() && "not out of date");
765   getExternalSource()->updateOutOfDateIdentifier(II);
766 }
767 
768 /// HandleIdentifier - This callback is invoked when the lexer reads an
769 /// identifier.  This callback looks up the identifier in the map and/or
770 /// potentially macro expands it or turns it into a named token (like 'for').
771 ///
772 /// Note that callers of this method are guarded by checking the
773 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
774 /// IdentifierInfo methods that compute these properties will need to change to
775 /// match.
776 bool Preprocessor::HandleIdentifier(Token &Identifier) {
777   assert(Identifier.getIdentifierInfo() &&
778          "Can't handle identifiers without identifier info!");
779 
780   IdentifierInfo &II = *Identifier.getIdentifierInfo();
781 
782   // If the information about this identifier is out of date, update it from
783   // the external source.
784   // We have to treat __VA_ARGS__ in a special way, since it gets
785   // serialized with isPoisoned = true, but our preprocessor may have
786   // unpoisoned it if we're defining a C99 macro.
787   if (II.isOutOfDate()) {
788     bool CurrentIsPoisoned = false;
789     const bool IsSpecialVariadicMacro =
790         &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
791     if (IsSpecialVariadicMacro)
792       CurrentIsPoisoned = II.isPoisoned();
793 
794     updateOutOfDateIdentifier(II);
795     Identifier.setKind(II.getTokenID());
796 
797     if (IsSpecialVariadicMacro)
798       II.setIsPoisoned(CurrentIsPoisoned);
799   }
800 
801   // If this identifier was poisoned, and if it was not produced from a macro
802   // expansion, emit an error.
803   if (II.isPoisoned() && CurPPLexer) {
804     HandlePoisonedIdentifier(Identifier);
805   }
806 
807   // If this is a macro to be expanded, do it.
808   if (const MacroDefinition MD = getMacroDefinition(&II)) {
809     const auto *MI = MD.getMacroInfo();
810     assert(MI && "macro definition with no macro info?");
811     if (!DisableMacroExpansion) {
812       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
813         // C99 6.10.3p10: If the preprocessing token immediately after the
814         // macro name isn't a '(', this macro should not be expanded.
815         if (!MI->isFunctionLike() || isNextPPTokenLParen())
816           return HandleMacroExpandedIdentifier(Identifier, MD);
817       } else {
818         // C99 6.10.3.4p2 says that a disabled macro may never again be
819         // expanded, even if it's in a context where it could be expanded in the
820         // future.
821         Identifier.setFlag(Token::DisableExpand);
822         if (MI->isObjectLike() || isNextPPTokenLParen())
823           Diag(Identifier, diag::pp_disabled_macro_expansion);
824       }
825     }
826   }
827 
828   // If this identifier is a keyword in a newer Standard or proposed Standard,
829   // produce a warning. Don't warn if we're not considering macro expansion,
830   // since this identifier might be the name of a macro.
831   // FIXME: This warning is disabled in cases where it shouldn't be, like
832   //   "#define constexpr constexpr", "int constexpr;"
833   if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
834     Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
835         << II.getName();
836     // Don't diagnose this keyword again in this translation unit.
837     II.setIsFutureCompatKeyword(false);
838   }
839 
840   // If this is an extension token, diagnose its use.
841   // We avoid diagnosing tokens that originate from macro definitions.
842   // FIXME: This warning is disabled in cases where it shouldn't be,
843   // like "#define TY typeof", "TY(1) x".
844   if (II.isExtensionToken() && !DisableMacroExpansion)
845     Diag(Identifier, diag::ext_token_used);
846 
847   // If this is the 'import' contextual keyword following an '@', note
848   // that the next token indicates a module name.
849   //
850   // Note that we do not treat 'import' as a contextual
851   // keyword when we're in a caching lexer, because caching lexers only get
852   // used in contexts where import declarations are disallowed.
853   //
854   // Likewise if this is the standard C++ import keyword.
855   if (((LastTokenWasAt && II.isModulesImport()) ||
856        Identifier.is(tok::kw_import)) &&
857       !InMacroArgs && !DisableMacroExpansion &&
858       (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
859       CurLexerCallback != CLK_CachingLexer) {
860     ModuleImportLoc = Identifier.getLocation();
861     NamedModuleImportPath.clear();
862     IsAtImport = true;
863     ModuleImportExpectsIdentifier = true;
864     CurLexerCallback = CLK_LexAfterModuleImport;
865   }
866   return true;
867 }
868 
869 void Preprocessor::Lex(Token &Result) {
870   ++LexLevel;
871 
872   // We loop here until a lex function returns a token; this avoids recursion.
873   while (!CurLexerCallback(*this, Result))
874     ;
875 
876   if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
877     return;
878 
879   if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
880     // Remember the identifier before code completion token.
881     setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
882     setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
883     // Set IdenfitierInfo to null to avoid confusing code that handles both
884     // identifiers and completion tokens.
885     Result.setIdentifierInfo(nullptr);
886   }
887 
888   // Update StdCXXImportSeqState to track our position within a C++20 import-seq
889   // if this token is being produced as a result of phase 4 of translation.
890   // Update TrackGMFState to decide if we are currently in a Global Module
891   // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
892   // depends on the prevailing StdCXXImportSeq state in two cases.
893   if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
894       !Result.getFlag(Token::IsReinjected)) {
895     switch (Result.getKind()) {
896     case tok::l_paren: case tok::l_square: case tok::l_brace:
897       StdCXXImportSeqState.handleOpenBracket();
898       break;
899     case tok::r_paren: case tok::r_square:
900       StdCXXImportSeqState.handleCloseBracket();
901       break;
902     case tok::r_brace:
903       StdCXXImportSeqState.handleCloseBrace();
904       break;
905 #define PRAGMA_ANNOTATION(X) case tok::annot_##X:
906 // For `#pragma ...` mimic ';'.
907 #include "clang/Basic/TokenKinds.def"
908 #undef PRAGMA_ANNOTATION
909     // This token is injected to represent the translation of '#include "a.h"'
910     // into "import a.h;". Mimic the notional ';'.
911     case tok::annot_module_include:
912     case tok::semi:
913       TrackGMFState.handleSemi();
914       StdCXXImportSeqState.handleSemi();
915       ModuleDeclState.handleSemi();
916       break;
917     case tok::header_name:
918     case tok::annot_header_unit:
919       StdCXXImportSeqState.handleHeaderName();
920       break;
921     case tok::kw_export:
922       TrackGMFState.handleExport();
923       StdCXXImportSeqState.handleExport();
924       ModuleDeclState.handleExport();
925       break;
926     case tok::colon:
927       ModuleDeclState.handleColon();
928       break;
929     case tok::period:
930       ModuleDeclState.handlePeriod();
931       break;
932     case tok::identifier:
933       // Check "import" and "module" when there is no open bracket. The two
934       // identifiers are not meaningful with open brackets.
935       if (StdCXXImportSeqState.atTopLevel()) {
936         if (Result.getIdentifierInfo()->isModulesImport()) {
937           TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
938           StdCXXImportSeqState.handleImport();
939           if (StdCXXImportSeqState.afterImportSeq()) {
940             ModuleImportLoc = Result.getLocation();
941             NamedModuleImportPath.clear();
942             IsAtImport = false;
943             ModuleImportExpectsIdentifier = true;
944             CurLexerCallback = CLK_LexAfterModuleImport;
945           }
946           break;
947         } else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {
948           TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
949           ModuleDeclState.handleModule();
950           break;
951         }
952       }
953       ModuleDeclState.handleIdentifier(Result.getIdentifierInfo());
954       if (ModuleDeclState.isModuleCandidate())
955         break;
956       [[fallthrough]];
957     default:
958       TrackGMFState.handleMisc();
959       StdCXXImportSeqState.handleMisc();
960       ModuleDeclState.handleMisc();
961       break;
962     }
963   }
964 
965   if (CurLexer && ++CheckPointCounter == CheckPointStepSize) {
966     CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);
967     CheckPointCounter = 0;
968   }
969 
970   LastTokenWasAt = Result.is(tok::at);
971   --LexLevel;
972 
973   if ((LexLevel == 0 || PreprocessToken) &&
974       !Result.getFlag(Token::IsReinjected)) {
975     if (LexLevel == 0)
976       ++TokenCount;
977     if (OnToken)
978       OnToken(Result);
979   }
980 }
981 
982 void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) {
983   while (1) {
984     Token Tok;
985     Lex(Tok);
986     if (Tok.isOneOf(tok::unknown, tok::eof, tok::eod,
987                     tok::annot_repl_input_end))
988       break;
989     if (Tokens != nullptr)
990       Tokens->push_back(Tok);
991   }
992 }
993 
994 /// Lex a header-name token (including one formed from header-name-tokens if
995 /// \p AllowMacroExpansion is \c true).
996 ///
997 /// \param FilenameTok Filled in with the next token. On success, this will
998 ///        be either a header_name token. On failure, it will be whatever other
999 ///        token was found instead.
1000 /// \param AllowMacroExpansion If \c true, allow the header name to be formed
1001 ///        by macro expansion (concatenating tokens as necessary if the first
1002 ///        token is a '<').
1003 /// \return \c true if we reached EOD or EOF while looking for a > token in
1004 ///         a concatenated header name and diagnosed it. \c false otherwise.
1005 bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
1006   // Lex using header-name tokenization rules if tokens are being lexed from
1007   // a file. Just grab a token normally if we're in a macro expansion.
1008   if (CurPPLexer)
1009     CurPPLexer->LexIncludeFilename(FilenameTok);
1010   else
1011     Lex(FilenameTok);
1012 
1013   // This could be a <foo/bar.h> file coming from a macro expansion.  In this
1014   // case, glue the tokens together into an angle_string_literal token.
1015   SmallString<128> FilenameBuffer;
1016   if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
1017     bool StartOfLine = FilenameTok.isAtStartOfLine();
1018     bool LeadingSpace = FilenameTok.hasLeadingSpace();
1019     bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
1020 
1021     SourceLocation Start = FilenameTok.getLocation();
1022     SourceLocation End;
1023     FilenameBuffer.push_back('<');
1024 
1025     // Consume tokens until we find a '>'.
1026     // FIXME: A header-name could be formed starting or ending with an
1027     // alternative token. It's not clear whether that's ill-formed in all
1028     // cases.
1029     while (FilenameTok.isNot(tok::greater)) {
1030       Lex(FilenameTok);
1031       if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
1032         Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
1033         Diag(Start, diag::note_matching) << tok::less;
1034         return true;
1035       }
1036 
1037       End = FilenameTok.getLocation();
1038 
1039       // FIXME: Provide code completion for #includes.
1040       if (FilenameTok.is(tok::code_completion)) {
1041         setCodeCompletionReached();
1042         Lex(FilenameTok);
1043         continue;
1044       }
1045 
1046       // Append the spelling of this token to the buffer. If there was a space
1047       // before it, add it now.
1048       if (FilenameTok.hasLeadingSpace())
1049         FilenameBuffer.push_back(' ');
1050 
1051       // Get the spelling of the token, directly into FilenameBuffer if
1052       // possible.
1053       size_t PreAppendSize = FilenameBuffer.size();
1054       FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
1055 
1056       const char *BufPtr = &FilenameBuffer[PreAppendSize];
1057       unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
1058 
1059       // If the token was spelled somewhere else, copy it into FilenameBuffer.
1060       if (BufPtr != &FilenameBuffer[PreAppendSize])
1061         memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1062 
1063       // Resize FilenameBuffer to the correct size.
1064       if (FilenameTok.getLength() != ActualLen)
1065         FilenameBuffer.resize(PreAppendSize + ActualLen);
1066     }
1067 
1068     FilenameTok.startToken();
1069     FilenameTok.setKind(tok::header_name);
1070     FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
1071     FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
1072     FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
1073     CreateString(FilenameBuffer, FilenameTok, Start, End);
1074   } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
1075     // Convert a string-literal token of the form " h-char-sequence "
1076     // (produced by macro expansion) into a header-name token.
1077     //
1078     // The rules for header-names don't quite match the rules for
1079     // string-literals, but all the places where they differ result in
1080     // undefined behavior, so we can and do treat them the same.
1081     //
1082     // A string-literal with a prefix or suffix is not translated into a
1083     // header-name. This could theoretically be observable via the C++20
1084     // context-sensitive header-name formation rules.
1085     StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
1086     if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
1087       FilenameTok.setKind(tok::header_name);
1088   }
1089 
1090   return false;
1091 }
1092 
1093 /// Collect the tokens of a C++20 pp-import-suffix.
1094 void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
1095   // FIXME: For error recovery, consider recognizing attribute syntax here
1096   // and terminating / diagnosing a missing semicolon if we find anything
1097   // else? (Can we leave that to the parser?)
1098   unsigned BracketDepth = 0;
1099   while (true) {
1100     Toks.emplace_back();
1101     Lex(Toks.back());
1102 
1103     switch (Toks.back().getKind()) {
1104     case tok::l_paren: case tok::l_square: case tok::l_brace:
1105       ++BracketDepth;
1106       break;
1107 
1108     case tok::r_paren: case tok::r_square: case tok::r_brace:
1109       if (BracketDepth == 0)
1110         return;
1111       --BracketDepth;
1112       break;
1113 
1114     case tok::semi:
1115       if (BracketDepth == 0)
1116         return;
1117     break;
1118 
1119     case tok::eof:
1120       return;
1121 
1122     default:
1123       break;
1124     }
1125   }
1126 }
1127 
1128 
1129 /// Lex a token following the 'import' contextual keyword.
1130 ///
1131 ///     pp-import: [C++20]
1132 ///           import header-name pp-import-suffix[opt] ;
1133 ///           import header-name-tokens pp-import-suffix[opt] ;
1134 /// [ObjC]    @ import module-name ;
1135 /// [Clang]   import module-name ;
1136 ///
1137 ///     header-name-tokens:
1138 ///           string-literal
1139 ///           < [any sequence of preprocessing-tokens other than >] >
1140 ///
1141 ///     module-name:
1142 ///           module-name-qualifier[opt] identifier
1143 ///
1144 ///     module-name-qualifier
1145 ///           module-name-qualifier[opt] identifier .
1146 ///
1147 /// We respond to a pp-import by importing macros from the named module.
1148 bool Preprocessor::LexAfterModuleImport(Token &Result) {
1149   // Figure out what kind of lexer we actually have.
1150   recomputeCurLexerKind();
1151 
1152   // Lex the next token. The header-name lexing rules are used at the start of
1153   // a pp-import.
1154   //
1155   // For now, we only support header-name imports in C++20 mode.
1156   // FIXME: Should we allow this in all language modes that support an import
1157   // declaration as an extension?
1158   if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
1159     if (LexHeaderName(Result))
1160       return true;
1161 
1162     if (Result.is(tok::colon) && ModuleDeclState.isNamedModule()) {
1163       std::string Name = ModuleDeclState.getPrimaryName().str();
1164       Name += ":";
1165       NamedModuleImportPath.push_back(
1166           {getIdentifierInfo(Name), Result.getLocation()});
1167       CurLexerCallback = CLK_LexAfterModuleImport;
1168       return true;
1169     }
1170   } else {
1171     Lex(Result);
1172   }
1173 
1174   // Allocate a holding buffer for a sequence of tokens and introduce it into
1175   // the token stream.
1176   auto EnterTokens = [this](ArrayRef<Token> Toks) {
1177     auto ToksCopy = std::make_unique<Token[]>(Toks.size());
1178     std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
1179     EnterTokenStream(std::move(ToksCopy), Toks.size(),
1180                      /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
1181   };
1182 
1183   bool ImportingHeader = Result.is(tok::header_name);
1184   // Check for a header-name.
1185   SmallVector<Token, 32> Suffix;
1186   if (ImportingHeader) {
1187     // Enter the header-name token into the token stream; a Lex action cannot
1188     // both return a token and cache tokens (doing so would corrupt the token
1189     // cache if the call to Lex comes from CachingLex / PeekAhead).
1190     Suffix.push_back(Result);
1191 
1192     // Consume the pp-import-suffix and expand any macros in it now. We'll add
1193     // it back into the token stream later.
1194     CollectPpImportSuffix(Suffix);
1195     if (Suffix.back().isNot(tok::semi)) {
1196       // This is not a pp-import after all.
1197       EnterTokens(Suffix);
1198       return false;
1199     }
1200 
1201     // C++2a [cpp.module]p1:
1202     //   The ';' preprocessing-token terminating a pp-import shall not have
1203     //   been produced by macro replacement.
1204     SourceLocation SemiLoc = Suffix.back().getLocation();
1205     if (SemiLoc.isMacroID())
1206       Diag(SemiLoc, diag::err_header_import_semi_in_macro);
1207 
1208     // Reconstitute the import token.
1209     Token ImportTok;
1210     ImportTok.startToken();
1211     ImportTok.setKind(tok::kw_import);
1212     ImportTok.setLocation(ModuleImportLoc);
1213     ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
1214     ImportTok.setLength(6);
1215 
1216     auto Action = HandleHeaderIncludeOrImport(
1217         /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
1218     switch (Action.Kind) {
1219     case ImportAction::None:
1220       break;
1221 
1222     case ImportAction::ModuleBegin:
1223       // Let the parser know we're textually entering the module.
1224       Suffix.emplace_back();
1225       Suffix.back().startToken();
1226       Suffix.back().setKind(tok::annot_module_begin);
1227       Suffix.back().setLocation(SemiLoc);
1228       Suffix.back().setAnnotationEndLoc(SemiLoc);
1229       Suffix.back().setAnnotationValue(Action.ModuleForHeader);
1230       [[fallthrough]];
1231 
1232     case ImportAction::ModuleImport:
1233     case ImportAction::HeaderUnitImport:
1234     case ImportAction::SkippedModuleImport:
1235       // We chose to import (or textually enter) the file. Convert the
1236       // header-name token into a header unit annotation token.
1237       Suffix[0].setKind(tok::annot_header_unit);
1238       Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
1239       Suffix[0].setAnnotationValue(Action.ModuleForHeader);
1240       // FIXME: Call the moduleImport callback?
1241       break;
1242     case ImportAction::Failure:
1243       assert(TheModuleLoader.HadFatalFailure &&
1244              "This should be an early exit only to a fatal error");
1245       Result.setKind(tok::eof);
1246       CurLexer->cutOffLexing();
1247       EnterTokens(Suffix);
1248       return true;
1249     }
1250 
1251     EnterTokens(Suffix);
1252     return false;
1253   }
1254 
1255   // The token sequence
1256   //
1257   //   import identifier (. identifier)*
1258   //
1259   // indicates a module import directive. We already saw the 'import'
1260   // contextual keyword, so now we're looking for the identifiers.
1261   if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
1262     // We expected to see an identifier here, and we did; continue handling
1263     // identifiers.
1264     NamedModuleImportPath.push_back(
1265         std::make_pair(Result.getIdentifierInfo(), Result.getLocation()));
1266     ModuleImportExpectsIdentifier = false;
1267     CurLexerCallback = CLK_LexAfterModuleImport;
1268     return true;
1269   }
1270 
1271   // If we're expecting a '.' or a ';', and we got a '.', then wait until we
1272   // see the next identifier. (We can also see a '[[' that begins an
1273   // attribute-specifier-seq here under the Standard C++ Modules.)
1274   if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
1275     ModuleImportExpectsIdentifier = true;
1276     CurLexerCallback = CLK_LexAfterModuleImport;
1277     return true;
1278   }
1279 
1280   // If we didn't recognize a module name at all, this is not a (valid) import.
1281   if (NamedModuleImportPath.empty() || Result.is(tok::eof))
1282     return true;
1283 
1284   // Consume the pp-import-suffix and expand any macros in it now, if we're not
1285   // at the semicolon already.
1286   SourceLocation SemiLoc = Result.getLocation();
1287   if (Result.isNot(tok::semi)) {
1288     Suffix.push_back(Result);
1289     CollectPpImportSuffix(Suffix);
1290     if (Suffix.back().isNot(tok::semi)) {
1291       // This is not an import after all.
1292       EnterTokens(Suffix);
1293       return false;
1294     }
1295     SemiLoc = Suffix.back().getLocation();
1296   }
1297 
1298   // Under the standard C++ Modules, the dot is just part of the module name,
1299   // and not a real hierarchy separator. Flatten such module names now.
1300   //
1301   // FIXME: Is this the right level to be performing this transformation?
1302   std::string FlatModuleName;
1303   if (getLangOpts().CPlusPlusModules) {
1304     for (auto &Piece : NamedModuleImportPath) {
1305       // If the FlatModuleName ends with colon, it implies it is a partition.
1306       if (!FlatModuleName.empty() && FlatModuleName.back() != ':')
1307         FlatModuleName += ".";
1308       FlatModuleName += Piece.first->getName();
1309     }
1310     SourceLocation FirstPathLoc = NamedModuleImportPath[0].second;
1311     NamedModuleImportPath.clear();
1312     NamedModuleImportPath.push_back(
1313         std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
1314   }
1315 
1316   Module *Imported = nullptr;
1317   // We don't/shouldn't load the standard c++20 modules when preprocessing.
1318   if (getLangOpts().Modules && !isInImportingCXXNamedModules()) {
1319     Imported = TheModuleLoader.loadModule(ModuleImportLoc,
1320                                           NamedModuleImportPath,
1321                                           Module::Hidden,
1322                                           /*IsInclusionDirective=*/false);
1323     if (Imported)
1324       makeModuleVisible(Imported, SemiLoc);
1325   }
1326 
1327   if (Callbacks)
1328     Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported);
1329 
1330   if (!Suffix.empty()) {
1331     EnterTokens(Suffix);
1332     return false;
1333   }
1334   return true;
1335 }
1336 
1337 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
1338   CurSubmoduleState->VisibleModules.setVisible(
1339       M, Loc, [](Module *) {},
1340       [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
1341         // FIXME: Include the path in the diagnostic.
1342         // FIXME: Include the import location for the conflicting module.
1343         Diag(ModuleImportLoc, diag::warn_module_conflict)
1344             << Path[0]->getFullModuleName()
1345             << Conflict->getFullModuleName()
1346             << Message;
1347       });
1348 
1349   // Add this module to the imports list of the currently-built submodule.
1350   if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
1351     BuildingSubmoduleStack.back().M->Imports.insert(M);
1352 }
1353 
1354 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
1355                                           const char *DiagnosticTag,
1356                                           bool AllowMacroExpansion) {
1357   // We need at least one string literal.
1358   if (Result.isNot(tok::string_literal)) {
1359     Diag(Result, diag::err_expected_string_literal)
1360       << /*Source='in...'*/0 << DiagnosticTag;
1361     return false;
1362   }
1363 
1364   // Lex string literal tokens, optionally with macro expansion.
1365   SmallVector<Token, 4> StrToks;
1366   do {
1367     StrToks.push_back(Result);
1368 
1369     if (Result.hasUDSuffix())
1370       Diag(Result, diag::err_invalid_string_udl);
1371 
1372     if (AllowMacroExpansion)
1373       Lex(Result);
1374     else
1375       LexUnexpandedToken(Result);
1376   } while (Result.is(tok::string_literal));
1377 
1378   // Concatenate and parse the strings.
1379   StringLiteralParser Literal(StrToks, *this);
1380   assert(Literal.isOrdinary() && "Didn't allow wide strings in");
1381 
1382   if (Literal.hadError)
1383     return false;
1384 
1385   if (Literal.Pascal) {
1386     Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1387       << /*Source='in...'*/0 << DiagnosticTag;
1388     return false;
1389   }
1390 
1391   String = std::string(Literal.GetString());
1392   return true;
1393 }
1394 
1395 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
1396   assert(Tok.is(tok::numeric_constant));
1397   SmallString<8> IntegerBuffer;
1398   bool NumberInvalid = false;
1399   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1400   if (NumberInvalid)
1401     return false;
1402   NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
1403                                getLangOpts(), getTargetInfo(),
1404                                getDiagnostics());
1405   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1406     return false;
1407   llvm::APInt APVal(64, 0);
1408   if (Literal.GetIntegerValue(APVal))
1409     return false;
1410   Lex(Tok);
1411   Value = APVal.getLimitedValue();
1412   return true;
1413 }
1414 
1415 void Preprocessor::addCommentHandler(CommentHandler *Handler) {
1416   assert(Handler && "NULL comment handler");
1417   assert(!llvm::is_contained(CommentHandlers, Handler) &&
1418          "Comment handler already registered");
1419   CommentHandlers.push_back(Handler);
1420 }
1421 
1422 void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
1423   std::vector<CommentHandler *>::iterator Pos =
1424       llvm::find(CommentHandlers, Handler);
1425   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1426   CommentHandlers.erase(Pos);
1427 }
1428 
1429 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
1430   bool AnyPendingTokens = false;
1431   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
1432        HEnd = CommentHandlers.end();
1433        H != HEnd; ++H) {
1434     if ((*H)->HandleComment(*this, Comment))
1435       AnyPendingTokens = true;
1436   }
1437   if (!AnyPendingTokens || getCommentRetentionState())
1438     return false;
1439   Lex(result);
1440   return true;
1441 }
1442 
1443 void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
1444   const MacroAnnotations &A =
1445       getMacroAnnotations(Identifier.getIdentifierInfo());
1446   assert(A.DeprecationInfo &&
1447          "Macro deprecation warning without recorded annotation!");
1448   const MacroAnnotationInfo &Info = *A.DeprecationInfo;
1449   if (Info.Message.empty())
1450     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1451         << Identifier.getIdentifierInfo() << 0;
1452   else
1453     Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
1454         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1455   Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
1456 }
1457 
1458 void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
1459   const MacroAnnotations &A =
1460       getMacroAnnotations(Identifier.getIdentifierInfo());
1461   assert(A.RestrictExpansionInfo &&
1462          "Macro restricted expansion warning without recorded annotation!");
1463   const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
1464   if (Info.Message.empty())
1465     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1466         << Identifier.getIdentifierInfo() << 0;
1467   else
1468     Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
1469         << Identifier.getIdentifierInfo() << 1 << Info.Message;
1470   Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
1471 }
1472 
1473 void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier,
1474                                              unsigned DiagSelection) const {
1475   Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;
1476 }
1477 
1478 void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
1479                                          bool IsUndef) const {
1480   const MacroAnnotations &A =
1481       getMacroAnnotations(Identifier.getIdentifierInfo());
1482   assert(A.FinalAnnotationLoc &&
1483          "Final macro warning without recorded annotation!");
1484 
1485   Diag(Identifier, diag::warn_pragma_final_macro)
1486       << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
1487   Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
1488 }
1489 
1490 bool Preprocessor::isSafeBufferOptOut(const SourceManager &SourceMgr,
1491                                       const SourceLocation &Loc) const {
1492   // The lambda that tests if a `Loc` is in an opt-out region given one opt-out
1493   // region map:
1494   auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map,
1495                                 const SourceLocation &Loc) -> bool {
1496     // Try to find a region in `SafeBufferOptOutMap` where `Loc` is in:
1497     auto FirstRegionEndingAfterLoc = llvm::partition_point(
1498         Map, [&SourceMgr,
1499               &Loc](const std::pair<SourceLocation, SourceLocation> &Region) {
1500           return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);
1501         });
1502 
1503     if (FirstRegionEndingAfterLoc != Map.end()) {
1504       // To test if the start location of the found region precedes `Loc`:
1505       return SourceMgr.isBeforeInTranslationUnit(
1506           FirstRegionEndingAfterLoc->first, Loc);
1507     }
1508     // If we do not find a region whose end location passes `Loc`, we want to
1509     // check if the current region is still open:
1510     if (!Map.empty() && Map.back().first == Map.back().second)
1511       return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);
1512     return false;
1513   };
1514 
1515   // What the following does:
1516   //
1517   // If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`.
1518   // Otherwise, `Loc` is from a loaded AST.  We look up the
1519   // `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the
1520   // loaded AST where `Loc` is at.  Then we find if `Loc` is in an opt-out
1521   // region w.r.t. the region map.  If the region map is absent, it means there
1522   // is no opt-out pragma in that loaded AST.
1523   //
1524   // Opt-out pragmas in the local TU or a loaded AST is not visible to another
1525   // one of them.  That means if you put the pragmas around a `#include
1526   // "module.h"`, where module.h is a module, it is not actually suppressing
1527   // warnings in module.h.  This is fine because warnings in module.h will be
1528   // reported when module.h is compiled in isolation and nothing in module.h
1529   // will be analyzed ever again.  So you will not see warnings from the file
1530   // that imports module.h anyway. And you can't even do the same thing for PCHs
1531   //  because they can only be included from the command line.
1532 
1533   if (SourceMgr.isLocalSourceLocation(Loc))
1534     return TestInMap(SafeBufferOptOutMap, Loc);
1535 
1536   const SafeBufferOptOutRegionsTy *LoadedRegions =
1537       LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);
1538 
1539   if (LoadedRegions)
1540     return TestInMap(*LoadedRegions, Loc);
1541   return false;
1542 }
1543 
1544 bool Preprocessor::enterOrExitSafeBufferOptOutRegion(
1545     bool isEnter, const SourceLocation &Loc) {
1546   if (isEnter) {
1547     if (isPPInSafeBufferOptOutRegion())
1548       return true; // invalid enter action
1549     InSafeBufferOptOutRegion = true;
1550     CurrentSafeBufferOptOutStart = Loc;
1551 
1552     // To set the start location of a new region:
1553 
1554     if (!SafeBufferOptOutMap.empty()) {
1555       [[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back();
1556       assert(PrevRegion->first != PrevRegion->second &&
1557              "Shall not begin a safe buffer opt-out region before closing the "
1558              "previous one.");
1559     }
1560     // If the start location equals to the end location, we call the region a
1561     // open region or a unclosed region (i.e., end location has not been set
1562     // yet).
1563     SafeBufferOptOutMap.emplace_back(Loc, Loc);
1564   } else {
1565     if (!isPPInSafeBufferOptOutRegion())
1566       return true; // invalid enter action
1567     InSafeBufferOptOutRegion = false;
1568 
1569     // To set the end location of the current open region:
1570 
1571     assert(!SafeBufferOptOutMap.empty() &&
1572            "Misordered safe buffer opt-out regions");
1573     auto *CurrRegion = &SafeBufferOptOutMap.back();
1574     assert(CurrRegion->first == CurrRegion->second &&
1575            "Set end location to a closed safe buffer opt-out region");
1576     CurrRegion->second = Loc;
1577   }
1578   return false;
1579 }
1580 
1581 bool Preprocessor::isPPInSafeBufferOptOutRegion() {
1582   return InSafeBufferOptOutRegion;
1583 }
1584 bool Preprocessor::isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc) {
1585   StartLoc = CurrentSafeBufferOptOutStart;
1586   return InSafeBufferOptOutRegion;
1587 }
1588 
1589 SmallVector<SourceLocation, 64>
1590 Preprocessor::serializeSafeBufferOptOutMap() const {
1591   assert(!InSafeBufferOptOutRegion &&
1592          "Attempt to serialize safe buffer opt-out regions before file being "
1593          "completely preprocessed");
1594 
1595   SmallVector<SourceLocation, 64> SrcSeq;
1596 
1597   for (const auto &[begin, end] : SafeBufferOptOutMap) {
1598     SrcSeq.push_back(begin);
1599     SrcSeq.push_back(end);
1600   }
1601   // Only `SafeBufferOptOutMap` gets serialized. No need to serialize
1602   // `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every
1603   // pch/module in the pch-chain/module-DAG will be loaded one by one in order.
1604   // It means that for each loading pch/module m, it just needs to load m's own
1605   // `SafeBufferOptOutMap`.
1606   return SrcSeq;
1607 }
1608 
1609 bool Preprocessor::setDeserializedSafeBufferOptOutMap(
1610     const SmallVectorImpl<SourceLocation> &SourceLocations) {
1611   if (SourceLocations.size() == 0)
1612     return false;
1613 
1614   assert(SourceLocations.size() % 2 == 0 &&
1615          "ill-formed SourceLocation sequence");
1616 
1617   auto It = SourceLocations.begin();
1618   SafeBufferOptOutRegionsTy &Regions =
1619       LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);
1620 
1621   do {
1622     SourceLocation Begin = *It++;
1623     SourceLocation End = *It++;
1624 
1625     Regions.emplace_back(Begin, End);
1626   } while (It != SourceLocations.end());
1627   return true;
1628 }
1629 
1630 ModuleLoader::~ModuleLoader() = default;
1631 
1632 CommentHandler::~CommentHandler() = default;
1633 
1634 EmptylineHandler::~EmptylineHandler() = default;
1635 
1636 CodeCompletionHandler::~CodeCompletionHandler() = default;
1637 
1638 void Preprocessor::createPreprocessingRecord() {
1639   if (Record)
1640     return;
1641 
1642   Record = new PreprocessingRecord(getSourceManager());
1643   addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
1644 }
1645 
1646 const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const {
1647   if (auto It = CheckPoints.find(FID); It != CheckPoints.end()) {
1648     const SmallVector<const char *> &FileCheckPoints = It->second;
1649     const char *Last = nullptr;
1650     // FIXME: Do better than a linear search.
1651     for (const char *P : FileCheckPoints) {
1652       if (P > Start)
1653         break;
1654       Last = P;
1655     }
1656     return Last;
1657   }
1658 
1659   return nullptr;
1660 }
1661