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