Coverage Report

Created: 2022-01-18 06:27

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