Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- PPMacroExpansion.cpp - Top level Macro Expansion -----------------===//
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 top level handling of macro expansion for the
10
// preprocessor.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Basic/Attributes.h"
15
#include "clang/Basic/Builtins.h"
16
#include "clang/Basic/FileManager.h"
17
#include "clang/Basic/IdentifierTable.h"
18
#include "clang/Basic/LLVM.h"
19
#include "clang/Basic/LangOptions.h"
20
#include "clang/Basic/ObjCRuntime.h"
21
#include "clang/Basic/SourceLocation.h"
22
#include "clang/Basic/TargetInfo.h"
23
#include "clang/Lex/CodeCompletionHandler.h"
24
#include "clang/Lex/DirectoryLookup.h"
25
#include "clang/Lex/ExternalPreprocessorSource.h"
26
#include "clang/Lex/HeaderSearch.h"
27
#include "clang/Lex/LexDiagnostic.h"
28
#include "clang/Lex/LiteralSupport.h"
29
#include "clang/Lex/MacroArgs.h"
30
#include "clang/Lex/MacroInfo.h"
31
#include "clang/Lex/Preprocessor.h"
32
#include "clang/Lex/PreprocessorLexer.h"
33
#include "clang/Lex/PreprocessorOptions.h"
34
#include "clang/Lex/Token.h"
35
#include "llvm/ADT/ArrayRef.h"
36
#include "llvm/ADT/DenseMap.h"
37
#include "llvm/ADT/DenseSet.h"
38
#include "llvm/ADT/FoldingSet.h"
39
#include "llvm/ADT/None.h"
40
#include "llvm/ADT/Optional.h"
41
#include "llvm/ADT/STLExtras.h"
42
#include "llvm/ADT/SmallString.h"
43
#include "llvm/ADT/SmallVector.h"
44
#include "llvm/ADT/StringRef.h"
45
#include "llvm/ADT/StringSwitch.h"
46
#include "llvm/Support/Casting.h"
47
#include "llvm/Support/ErrorHandling.h"
48
#include "llvm/Support/Format.h"
49
#include "llvm/Support/Path.h"
50
#include "llvm/Support/raw_ostream.h"
51
#include <algorithm>
52
#include <cassert>
53
#include <cstddef>
54
#include <cstring>
55
#include <ctime>
56
#include <string>
57
#include <tuple>
58
#include <utility>
59
60
using namespace clang;
61
62
MacroDirective *
63
2.43M
Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
64
2.43M
  if (!II->hadMacroDefinition())
65
0
    return nullptr;
66
2.43M
  auto Pos = CurSubmoduleState->Macros.find(II);
67
2.43M
  return Pos == CurSubmoduleState->Macros.end() ? 
nullptr286
68
2.43M
                                                : 
Pos->second.getLatest()2.43M
;
69
2.43M
}
70
71
44.0M
void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
72
44.0M
  assert(MD && "MacroDirective should be non-zero!");
73
0
  assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
74
75
0
  MacroState &StoredMD = CurSubmoduleState->Macros[II];
76
44.0M
  auto *OldMD = StoredMD.getLatest();
77
44.0M
  MD->setPrevious(OldMD);
78
44.0M
  StoredMD.setLatest(MD);
79
44.0M
  StoredMD.overrideActiveModuleMacros(*this, II);
80
81
44.0M
  if (needModuleMacros()) {
82
    // Track that we created a new macro directive, so we know we should
83
    // consider building a ModuleMacro for it when we get to the end of
84
    // the module.
85
324k
    PendingModuleMacroNames.push_back(II);
86
324k
  }
87
88
  // Set up the identifier as having associated macro history.
89
44.0M
  II->setHasMacroDefinition(true);
90
44.0M
  if (!MD->isDefined() && 
LeafModuleMacros.find(II) == LeafModuleMacros.end()76.4k
)
91
75.4k
    II->setHasMacroDefinition(false);
92
44.0M
  if (II->isFromAST())
93
1.23k
    II->setChangedSinceDeserialization();
94
44.0M
}
95
96
void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
97
                                           MacroDirective *ED,
98
45.1k
                                           MacroDirective *MD) {
99
  // Normally, when a macro is defined, it goes through appendMacroDirective()
100
  // above, which chains a macro to previous defines, undefs, etc.
101
  // However, in a pch, the whole macro history up to the end of the pch is
102
  // stored, so ASTReader goes through this function instead.
103
  // However, built-in macros are already registered in the Preprocessor
104
  // ctor, and ASTWriter stops writing the macro chain at built-in macros,
105
  // so in that case the chain from the pch needs to be spliced to the existing
106
  // built-in.
107
108
45.1k
  assert(II && MD);
109
0
  MacroState &StoredMD = CurSubmoduleState->Macros[II];
110
111
45.1k
  if (auto *OldMD = StoredMD.getLatest()) {
112
    // shouldIgnoreMacro() in ASTWriter also stops at macros from the
113
    // predefines buffer in module builds. However, in module builds, modules
114
    // are loaded completely before predefines are processed, so StoredMD
115
    // will be nullptr for them when they're loaded. StoredMD should only be
116
    // non-nullptr for builtins read from a pch file.
117
3
    assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
118
3
           "only built-ins should have an entry here");
119
0
    assert(!OldMD->getPrevious() && "builtin should only have a single entry");
120
0
    ED->setPrevious(OldMD);
121
3
    StoredMD.setLatest(MD);
122
45.1k
  } else {
123
45.1k
    StoredMD = MD;
124
45.1k
  }
125
126
  // Setup the identifier as having associated macro history.
127
0
  II->setHasMacroDefinition(true);
128
45.1k
  if (!MD->isDefined() && 
LeafModuleMacros.find(II) == LeafModuleMacros.end()25
)
129
25
    II->setHasMacroDefinition(false);
130
45.1k
}
131
132
ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
133
                                          MacroInfo *Macro,
134
                                          ArrayRef<ModuleMacro *> Overrides,
135
1.99M
                                          bool &New) {
136
1.99M
  llvm::FoldingSetNodeID ID;
137
1.99M
  ModuleMacro::Profile(ID, Mod, II);
138
139
1.99M
  void *InsertPos;
140
1.99M
  if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
141
1.84k
    New = false;
142
1.84k
    return MM;
143
1.84k
  }
144
145
1.99M
  auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
146
1.99M
  ModuleMacros.InsertNode(MM, InsertPos);
147
148
  // Each overridden macro is now overridden by one more macro.
149
1.99M
  bool HidAny = false;
150
1.99M
  for (auto *O : Overrides) {
151
9.91k
    HidAny |= (O->NumOverriddenBy == 0);
152
9.91k
    ++O->NumOverriddenBy;
153
9.91k
  }
154
155
  // If we were the first overrider for any macro, it's no longer a leaf.
156
1.99M
  auto &LeafMacros = LeafModuleMacros[II];
157
1.99M
  if (HidAny) {
158
9.62k
    llvm::erase_if(LeafMacros,
159
9.71k
                   [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; });
160
9.62k
  }
161
162
  // The new macro is always a leaf macro.
163
1.99M
  LeafMacros.push_back(MM);
164
  // The identifier now has defined macros (that may or may not be visible).
165
1.99M
  II->setHasMacroDefinition(true);
166
167
1.99M
  New = true;
168
1.99M
  return MM;
169
1.99M
}
170
171
ModuleMacro *Preprocessor::getModuleMacro(Module *Mod,
172
6.60k
                                          const IdentifierInfo *II) {
173
6.60k
  llvm::FoldingSetNodeID ID;
174
6.60k
  ModuleMacro::Profile(ID, Mod, II);
175
176
6.60k
  void *InsertPos;
177
6.60k
  return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
178
6.60k
}
179
180
void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
181
331k
                                         ModuleMacroInfo &Info) {
182
331k
  assert(Info.ActiveModuleMacrosGeneration !=
183
331k
             CurSubmoduleState->VisibleModules.getGeneration() &&
184
331k
         "don't need to update this macro name info");
185
0
  Info.ActiveModuleMacrosGeneration =
186
331k
      CurSubmoduleState->VisibleModules.getGeneration();
187
188
331k
  auto Leaf = LeafModuleMacros.find(II);
189
331k
  if (Leaf == LeafModuleMacros.end()) {
190
    // No imported macros at all: nothing to do.
191
82.5k
    return;
192
82.5k
  }
193
194
248k
  Info.ActiveModuleMacros.clear();
195
196
  // Every macro that's locally overridden is overridden by a visible macro.
197
248k
  llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
198
248k
  for (auto *O : Info.OverriddenMacros)
199
18
    NumHiddenOverrides[O] = -1;
200
201
  // Collect all macros that are not overridden by a visible macro.
202
248k
  llvm::SmallVector<ModuleMacro *, 16> Worklist;
203
249k
  for (auto *LeafMM : Leaf->second) {
204
249k
    assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
205
249k
    if (NumHiddenOverrides.lookup(LeafMM) == 0)
206
249k
      Worklist.push_back(LeafMM);
207
249k
  }
208
498k
  while (!Worklist.empty()) {
209
250k
    auto *MM = Worklist.pop_back_val();
210
250k
    if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
211
      // We only care about collecting definitions; undefinitions only act
212
      // to override other definitions.
213
247k
      if (MM->getMacroInfo())
214
247k
        Info.ActiveModuleMacros.push_back(MM);
215
247k
    } else {
216
2.12k
      for (auto *O : MM->overrides())
217
195
        if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
218
154
          Worklist.push_back(O);
219
2.12k
    }
220
250k
  }
221
  // Our reverse postorder walk found the macros in reverse order.
222
248k
  std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
223
224
  // Determine whether the macro name is ambiguous.
225
248k
  MacroInfo *MI = nullptr;
226
248k
  bool IsSystemMacro = true;
227
248k
  bool IsAmbiguous = false;
228
248k
  if (auto *MD = Info.MD) {
229
131
    while (MD && isa<VisibilityMacroDirective>(MD))
230
0
      MD = MD->getPrevious();
231
131
    if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
232
131
      MI = DMD->getInfo();
233
131
      IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
234
131
    }
235
131
  }
236
248k
  for (auto *Active : Info.ActiveModuleMacros) {
237
247k
    auto *NewMI = Active->getMacroInfo();
238
239
    // Before marking the macro as ambiguous, check if this is a case where
240
    // both macros are in system headers. If so, we trust that the system
241
    // did not get it wrong. This also handles cases where Clang's own
242
    // headers have a different spelling of certain system macros:
243
    //   #define LONG_MAX __LONG_MAX__ (clang's limits.h)
244
    //   #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
245
    //
246
    // FIXME: Remove the defined-in-system-headers check. clang's limits.h
247
    // overrides the system limits.h's macros, so there's no conflict here.
248
247k
    if (MI && 
NewMI != MI398
&&
249
247k
        
!MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true)397
)
250
70
      IsAmbiguous = true;
251
247k
    IsSystemMacro &= Active->getOwningModule()->IsSystem ||
252
247k
                     
SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc())678
;
253
247k
    MI = NewMI;
254
247k
  }
255
248k
  Info.IsAmbiguous = IsAmbiguous && 
!IsSystemMacro70
;
256
248k
}
257
258
10
void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
259
10
  ArrayRef<ModuleMacro*> Leaf;
260
10
  auto LeafIt = LeafModuleMacros.find(II);
261
10
  if (LeafIt != LeafModuleMacros.end())
262
10
    Leaf = LeafIt->second;
263
10
  const MacroState *State = nullptr;
264
10
  auto Pos = CurSubmoduleState->Macros.find(II);
265
10
  if (Pos != CurSubmoduleState->Macros.end())
266
10
    State = &Pos->second;
267
268
10
  llvm::errs() << "MacroState " << State << " " << II->getNameStart();
269
10
  if (State && State->isAmbiguous(*this, II))
270
9
    llvm::errs() << " ambiguous";
271
10
  if (State && !State->getOverriddenMacros().empty()) {
272
0
    llvm::errs() << " overrides";
273
0
    for (auto *O : State->getOverriddenMacros())
274
0
      llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
275
0
  }
276
10
  llvm::errs() << "\n";
277
278
  // Dump local macro directives.
279
10
  for (auto *MD = State ? State->getLatest() : 
nullptr0
; MD;
280
10
       
MD = MD->getPrevious()0
) {
281
0
    llvm::errs() << " ";
282
0
    MD->dump();
283
0
  }
284
285
  // Dump module macros.
286
10
  llvm::DenseSet<ModuleMacro*> Active;
287
10
  for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : 
None0
)
288
18
    Active.insert(MM);
289
10
  llvm::DenseSet<ModuleMacro*> Visited;
290
10
  llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
291
29
  while (!Worklist.empty()) {
292
19
    auto *MM = Worklist.pop_back_val();
293
19
    llvm::errs() << " ModuleMacro " << MM << " "
294
19
                 << MM->getOwningModule()->getFullModuleName();
295
19
    if (!MM->getMacroInfo())
296
0
      llvm::errs() << " undef";
297
298
19
    if (Active.count(MM))
299
18
      llvm::errs() << " active";
300
1
    else if (!CurSubmoduleState->VisibleModules.isVisible(
301
1
                 MM->getOwningModule()))
302
1
      llvm::errs() << " hidden";
303
0
    else if (MM->getMacroInfo())
304
0
      llvm::errs() << " overridden";
305
306
19
    if (!MM->overrides().empty()) {
307
0
      llvm::errs() << " overrides";
308
0
      for (auto *O : MM->overrides()) {
309
0
        llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
310
0
        if (Visited.insert(O).second)
311
0
          Worklist.push_back(O);
312
0
      }
313
0
    }
314
19
    llvm::errs() << "\n";
315
19
    if (auto *MI = MM->getMacroInfo()) {
316
19
      llvm::errs() << "  ";
317
19
      MI->dump();
318
19
      llvm::errs() << "\n";
319
19
    }
320
19
  }
321
10
}
322
323
/// RegisterBuiltinMacro - Register the specified identifier in the identifier
324
/// table and mark it as a builtin macro to be expanded.
325
2.22M
static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
326
  // Get the identifier.
327
2.22M
  IdentifierInfo *Id = PP.getIdentifierInfo(Name);
328
329
  // Mark it as being a macro that is builtin.
330
2.22M
  MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
331
2.22M
  MI->setIsBuiltinMacro();
332
2.22M
  PP.appendDefMacroDirective(Id, MI);
333
2.22M
  return Id;
334
2.22M
}
335
336
/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
337
/// identifier table.
338
87.8k
void Preprocessor::RegisterBuiltinMacros() {
339
87.8k
  Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
340
87.8k
  Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
341
87.8k
  Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
342
87.8k
  Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
343
87.8k
  Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
344
87.8k
  Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
345
346
  // C++ Standing Document Extensions.
347
87.8k
  if (getLangOpts().CPlusPlus)
348
67.2k
    Ident__has_cpp_attribute =
349
67.2k
        RegisterBuiltinMacro(*this, "__has_cpp_attribute");
350
20.6k
  else
351
20.6k
    Ident__has_cpp_attribute = nullptr;
352
353
  // GCC Extensions.
354
87.8k
  Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
355
87.8k
  Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
356
87.8k
  Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
357
358
  // Microsoft Extensions.
359
87.8k
  if (getLangOpts().MicrosoftExt) {
360
11.1k
    Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
361
11.1k
    Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
362
76.6k
  } else {
363
76.6k
    Ident__identifier = nullptr;
364
76.6k
    Ident__pragma = nullptr;
365
76.6k
  }
366
367
  // Clang Extensions.
368
87.8k
  Ident__FILE_NAME__      = RegisterBuiltinMacro(*this, "__FILE_NAME__");
369
87.8k
  Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
370
87.8k
  Ident__has_extension    = RegisterBuiltinMacro(*this, "__has_extension");
371
87.8k
  Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
372
87.8k
  Ident__has_attribute    = RegisterBuiltinMacro(*this, "__has_attribute");
373
87.8k
  if (!getLangOpts().CPlusPlus)
374
20.6k
    Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute");
375
67.2k
  else
376
67.2k
    Ident__has_c_attribute = nullptr;
377
378
87.8k
  Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
379
87.8k
  Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
380
87.8k
  Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
381
87.8k
  Ident__has_warning      = RegisterBuiltinMacro(*this, "__has_warning");
382
87.8k
  Ident__is_identifier    = RegisterBuiltinMacro(*this, "__is_identifier");
383
87.8k
  Ident__is_target_arch   = RegisterBuiltinMacro(*this, "__is_target_arch");
384
87.8k
  Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor");
385
87.8k
  Ident__is_target_os     = RegisterBuiltinMacro(*this, "__is_target_os");
386
87.8k
  Ident__is_target_environment =
387
87.8k
      RegisterBuiltinMacro(*this, "__is_target_environment");
388
389
  // Modules.
390
87.8k
  Ident__building_module  = RegisterBuiltinMacro(*this, "__building_module");
391
87.8k
  if (!getLangOpts().CurrentModule.empty())
392
2.05k
    Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
393
85.8k
  else
394
85.8k
    Ident__MODULE__ = nullptr;
395
87.8k
}
396
397
/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
398
/// in its expansion, currently expands to that token literally.
399
static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
400
                                          const IdentifierInfo *MacroIdent,
401
8.11M
                                          Preprocessor &PP) {
402
8.11M
  IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
403
404
  // If the token isn't an identifier, it's always literally expanded.
405
8.11M
  if (!II) 
return true1.68M
;
406
407
  // If the information about this identifier is out of date, update it from
408
  // the external source.
409
6.42M
  if (II->isOutOfDate())
410
622
    PP.getExternalSource()->updateOutOfDateIdentifier(*II);
411
412
  // If the identifier is a macro, and if that macro is enabled, it may be
413
  // expanded so it's not a trivial expansion.
414
6.42M
  if (auto *ExpansionMI = PP.getMacroInfo(II))
415
1.47M
    if (ExpansionMI->isEnabled() &&
416
        // Fast expanding "#define X X" is ok, because X would be disabled.
417
1.47M
        
II != MacroIdent1.47M
)
418
1.47M
      return false;
419
420
  // If this is an object-like macro invocation, it is safe to trivially expand
421
  // it.
422
4.95M
  if (MI->isObjectLike()) 
return true2.38M
;
423
424
  // If this is a function-like macro invocation, it's safe to trivially expand
425
  // as long as the identifier is not a macro argument.
426
2.57M
  return !llvm::is_contained(MI->params(), II);
427
4.95M
}
428
429
/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
430
/// lexed is a '('.  If so, consume the token and return true, if not, this
431
/// method should have no observable side-effect on the lexed tokens.
432
21.9M
bool Preprocessor::isNextPPTokenLParen() {
433
  // Do some quick tests for rejection cases.
434
21.9M
  unsigned Val;
435
21.9M
  if (CurLexer)
436
3.00M
    Val = CurLexer->isNextPPTokenLParen();
437
18.9M
  else
438
18.9M
    Val = CurTokenLexer->isNextTokenLParen();
439
440
21.9M
  if (Val == 2) {
441
    // We have run off the end.  If it's a source file we don't
442
    // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
443
    // macro stack.
444
2.27M
    if (CurPPLexer)
445
1
      return false;
446
2.27M
    
for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack))2.27M
{
447
2.27M
      if (Entry.TheLexer)
448
1.26k
        Val = Entry.TheLexer->isNextPPTokenLParen();
449
2.27M
      else
450
2.27M
        Val = Entry.TheTokenLexer->isNextTokenLParen();
451
452
2.27M
      if (Val != 2)
453
2.27M
        break;
454
455
      // Ran off the end of a source file?
456
12
      if (Entry.ThePPLexer)
457
2
        return false;
458
12
    }
459
2.27M
  }
460
461
  // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
462
  // have found something that isn't a '(' or we found the end of the
463
  // translation unit.  In either case, return false.
464
21.9M
  return Val == 1;
465
21.9M
}
466
467
/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
468
/// expanded as a macro, handle it and return the next token as 'Identifier'.
469
bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
470
58.8M
                                                 const MacroDefinition &M) {
471
58.8M
  emitMacroExpansionWarnings(Identifier);
472
473
58.8M
  MacroInfo *MI = M.getMacroInfo();
474
475
  // If this is a macro expansion in the "#if !defined(x)" line for the file,
476
  // then the macro could expand to different things in other contexts, we need
477
  // to disable the optimization in this case.
478
58.8M
  if (CurPPLexer) 
CurPPLexer->MIOpt.ExpandedMacro()34.8M
;
479
480
  // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
481
58.8M
  if (MI->isBuiltinMacro()) {
482
984k
    if (Callbacks)
483
984k
      Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
484
984k
                              /*Args=*/nullptr);
485
984k
    ExpandBuiltinMacro(Identifier);
486
984k
    return true;
487
984k
  }
488
489
  /// Args - If this is a function-like macro expansion, this contains,
490
  /// for each macro argument, the list of tokens that were provided to the
491
  /// invocation.
492
57.8M
  MacroArgs *Args = nullptr;
493
494
  // Remember where the end of the expansion occurred.  For an object-like
495
  // macro, this is the identifier.  For a function-like macro, this is the ')'.
496
57.8M
  SourceLocation ExpansionEnd = Identifier.getLocation();
497
498
  // If this is a function-like macro, read the arguments.
499
57.8M
  if (MI->isFunctionLike()) {
500
    // Remember that we are now parsing the arguments to a macro invocation.
501
    // Preprocessor directives used inside macro arguments are not portable, and
502
    // this enables the warning.
503
19.6M
    InMacroArgs = true;
504
19.6M
    ArgMacro = &Identifier;
505
506
19.6M
    Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
507
508
    // Finished parsing args.
509
19.6M
    InMacroArgs = false;
510
19.6M
    ArgMacro = nullptr;
511
512
    // If there was an error parsing the arguments, bail out.
513
19.6M
    if (!Args) 
return true54
;
514
515
19.6M
    ++NumFnMacroExpanded;
516
38.1M
  } else {
517
38.1M
    ++NumMacroExpanded;
518
38.1M
  }
519
520
  // Notice that this macro has been used.
521
57.8M
  markMacroAsUsed(MI);
522
523
  // Remember where the token is expanded.
524
57.8M
  SourceLocation ExpandLoc = Identifier.getLocation();
525
57.8M
  SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
526
527
57.8M
  if (Callbacks) {
528
57.8M
    if (InMacroArgs) {
529
      // We can have macro expansion inside a conditional directive while
530
      // reading the function macro arguments. To ensure, in that case, that
531
      // MacroExpands callbacks still happen in source order, queue this
532
      // callback to have it happen after the function macro callback.
533
6
      DelayedMacroExpandsCallbacks.push_back(
534
6
          MacroExpandsInfo(Identifier, M, ExpansionRange));
535
57.8M
    } else {
536
57.8M
      Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
537
57.8M
      if (!DelayedMacroExpandsCallbacks.empty()) {
538
4
        for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
539
          // FIXME: We lose macro args info with delayed callback.
540
4
          Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
541
4
                                  /*Args=*/nullptr);
542
4
        }
543
3
        DelayedMacroExpandsCallbacks.clear();
544
3
      }
545
57.8M
    }
546
57.8M
  }
547
548
  // If the macro definition is ambiguous, complain.
549
57.8M
  if (M.isAmbiguous()) {
550
45
    Diag(Identifier, diag::warn_pp_ambiguous_macro)
551
45
      << Identifier.getIdentifierInfo();
552
45
    Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
553
45
      << Identifier.getIdentifierInfo();
554
90
    M.forAllDefinitions([&](const MacroInfo *OtherMI) {
555
90
      if (OtherMI != MI)
556
45
        Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
557
45
          << Identifier.getIdentifierInfo();
558
90
    });
559
45
  }
560
561
  // If we started lexing a macro, enter the macro expansion body.
562
563
  // If this macro expands to no tokens, don't bother to push it onto the
564
  // expansion stack, only to take it right back off.
565
57.8M
  if (MI->getNumTokens() == 0) {
566
    // No need for arg info.
567
880k
    if (Args) 
Args->destroy(*this)12.4k
;
568
569
    // Propagate whitespace info as if we had pushed, then popped,
570
    // a macro context.
571
880k
    Identifier.setFlag(Token::LeadingEmptyMacro);
572
880k
    PropagateLineStartLeadingSpaceInfo(Identifier);
573
880k
    ++NumFastMacroExpanded;
574
880k
    return false;
575
56.9M
  } else if (MI->getNumTokens() == 1 &&
576
56.9M
             isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
577
8.11M
                                           *this)) {
578
    // Otherwise, if this macro expands into a single trivially-expanded
579
    // token: expand it now.  This handles common cases like
580
    // "#define VAL 42".
581
582
    // No need for arg info.
583
4.06M
    if (Args) 
Args->destroy(*this)104
;
584
585
    // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
586
    // identifier to the expanded token.
587
4.06M
    bool isAtStartOfLine = Identifier.isAtStartOfLine();
588
4.06M
    bool hasLeadingSpace = Identifier.hasLeadingSpace();
589
590
    // Replace the result token.
591
4.06M
    Identifier = MI->getReplacementToken(0);
592
593
    // Restore the StartOfLine/LeadingSpace markers.
594
4.06M
    Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
595
4.06M
    Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
596
597
    // Update the tokens location to include both its expansion and physical
598
    // locations.
599
4.06M
    SourceLocation Loc =
600
4.06M
      SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
601
4.06M
                                   ExpansionEnd,Identifier.getLength());
602
4.06M
    Identifier.setLocation(Loc);
603
604
    // If this is a disabled macro or #define X X, we must mark the result as
605
    // unexpandable.
606
4.06M
    if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
607
2.38M
      if (MacroInfo *NewMI = getMacroInfo(NewII))
608
3.05k
        if (!NewMI->isEnabled() || 
NewMI == MI3.04k
) {
609
3.05k
          Identifier.setFlag(Token::DisableExpand);
610
          // Don't warn for "#define X X" like "#define bool bool" from
611
          // stdbool.h.
612
3.05k
          if (NewMI != MI || 
MI->isFunctionLike()3.04k
)
613
6
            Diag(Identifier, diag::pp_disabled_macro_expansion);
614
3.05k
        }
615
2.38M
    }
616
617
    // Since this is not an identifier token, it can't be macro expanded, so
618
    // we're done.
619
4.06M
    ++NumFastMacroExpanded;
620
4.06M
    return true;
621
4.06M
  }
622
623
  // Start expanding the macro.
624
52.8M
  EnterMacro(Identifier, ExpansionEnd, MI, Args);
625
52.8M
  return false;
626
57.8M
}
627
628
enum Bracket {
629
  Brace,
630
  Paren
631
};
632
633
/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
634
/// token vector are properly nested.
635
48
static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
636
48
  SmallVector<Bracket, 8> Brackets;
637
48
  for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
638
48
                                              E = Tokens.end();
639
1.01k
       I != E; 
++I969
) {
640
969
    if (I->is(tok::l_paren)) {
641
4
      Brackets.push_back(Paren);
642
965
    } else if (I->is(tok::r_paren)) {
643
4
      if (Brackets.empty() || Brackets.back() == Brace)
644
0
        return false;
645
4
      Brackets.pop_back();
646
961
    } else if (I->is(tok::l_brace)) {
647
101
      Brackets.push_back(Brace);
648
860
    } else if (I->is(tok::r_brace)) {
649
101
      if (Brackets.empty() || Brackets.back() == Paren)
650
0
        return false;
651
101
      Brackets.pop_back();
652
101
    }
653
969
  }
654
48
  return Brackets.empty();
655
48
}
656
657
/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
658
/// vector of tokens in NewTokens.  The new number of arguments will be placed
659
/// in NumArgs and the ranges which need to surrounded in parentheses will be
660
/// in ParenHints.
661
/// Returns false if the token stream cannot be changed.  If this is because
662
/// of an initializer list starting a macro argument, the range of those
663
/// initializer lists will be place in InitLists.
664
static bool GenerateNewArgTokens(Preprocessor &PP,
665
                                 SmallVectorImpl<Token> &OldTokens,
666
                                 SmallVectorImpl<Token> &NewTokens,
667
                                 unsigned &NumArgs,
668
                                 SmallVectorImpl<SourceRange> &ParenHints,
669
48
                                 SmallVectorImpl<SourceRange> &InitLists) {
670
48
  if (!CheckMatchedBrackets(OldTokens))
671
0
    return false;
672
673
  // Once it is known that the brackets are matched, only a simple count of the
674
  // braces is needed.
675
48
  unsigned Braces = 0;
676
677
  // First token of a new macro argument.
678
48
  SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
679
680
  // First closing brace in a new macro argument.  Used to generate
681
  // SourceRanges for InitLists.
682
48
  SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
683
48
  NumArgs = 0;
684
48
  Token TempToken;
685
  // Set to true when a macro separator token is found inside a braced list.
686
  // If true, the fixed argument spans multiple old arguments and ParenHints
687
  // will be updated.
688
48
  bool FoundSeparatorToken = false;
689
48
  for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
690
48
                                        E = OldTokens.end();
691
1.01k
       I != E; 
++I969
) {
692
969
    if (I->is(tok::l_brace)) {
693
101
      ++Braces;
694
868
    } else if (I->is(tok::r_brace)) {
695
101
      --Braces;
696
101
      if (Braces == 0 && ClosingBrace == E && 
FoundSeparatorToken65
)
697
61
        ClosingBrace = I;
698
767
    } else if (I->is(tok::eof)) {
699
      // EOF token is used to separate macro arguments
700
326
      if (Braces != 0) {
701
        // Assume comma separator is actually braced list separator and change
702
        // it back to a comma.
703
189
        FoundSeparatorToken = true;
704
189
        I->setKind(tok::comma);
705
189
        I->setLength(1);
706
189
      } else { // Braces == 0
707
        // Separator token still separates arguments.
708
137
        ++NumArgs;
709
710
        // If the argument starts with a brace, it can't be fixed with
711
        // parentheses.  A different diagnostic will be given.
712
137
        if (FoundSeparatorToken && 
ArgStartIterator->is(tok::l_brace)87
) {
713
28
          InitLists.push_back(
714
28
              SourceRange(ArgStartIterator->getLocation(),
715
28
                          PP.getLocForEndOfToken(ClosingBrace->getLocation())));
716
28
          ClosingBrace = E;
717
28
        }
718
719
        // Add left paren
720
137
        if (FoundSeparatorToken) {
721
87
          TempToken.startToken();
722
87
          TempToken.setKind(tok::l_paren);
723
87
          TempToken.setLocation(ArgStartIterator->getLocation());
724
87
          TempToken.setLength(0);
725
87
          NewTokens.push_back(TempToken);
726
87
        }
727
728
        // Copy over argument tokens
729
137
        NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
730
731
        // Add right paren and store the paren locations in ParenHints
732
137
        if (FoundSeparatorToken) {
733
87
          SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
734
87
          TempToken.startToken();
735
87
          TempToken.setKind(tok::r_paren);
736
87
          TempToken.setLocation(Loc);
737
87
          TempToken.setLength(0);
738
87
          NewTokens.push_back(TempToken);
739
87
          ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
740
87
                                           Loc));
741
87
        }
742
743
        // Copy separator token
744
137
        NewTokens.push_back(*I);
745
746
        // Reset values
747
137
        ArgStartIterator = I + 1;
748
137
        FoundSeparatorToken = false;
749
137
      }
750
326
    }
751
969
  }
752
753
48
  return !ParenHints.empty() && 
InitLists.empty()39
;
754
48
}
755
756
/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
757
/// token is the '(' of the macro, this method is invoked to read all of the
758
/// actual arguments specified for the macro invocation.  This returns null on
759
/// error.
760
MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
761
                                                   MacroInfo *MI,
762
19.6M
                                                   SourceLocation &MacroEnd) {
763
  // The number of fixed arguments to parse.
764
19.6M
  unsigned NumFixedArgsLeft = MI->getNumParams();
765
19.6M
  bool isVariadic = MI->isVariadic();
766
767
  // Outer loop, while there are more arguments, keep reading them.
768
19.6M
  Token Tok;
769
770
  // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
771
  // an argument value in a macro could expand to ',' or '(' or ')'.
772
19.6M
  LexUnexpandedToken(Tok);
773
19.6M
  assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
774
775
  // ArgTokens - Build up a list of tokens that make up each argument.  Each
776
  // argument is separated by an EOF token.  Use a SmallVector so we can avoid
777
  // heap allocations in the common case.
778
0
  SmallVector<Token, 64> ArgTokens;
779
19.6M
  bool ContainsCodeCompletionTok = false;
780
19.6M
  bool FoundElidedComma = false;
781
782
19.6M
  SourceLocation TooManyArgsLoc;
783
784
19.6M
  unsigned NumActuals = 0;
785
64.5M
  while (Tok.isNot(tok::r_paren)) {
786
45.2M
    if (ContainsCodeCompletionTok && 
Tok.isOneOf(tok::eof, tok::eod)16
)
787
9
      break;
788
789
45.2M
    assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
790
45.2M
           "only expect argument separators here");
791
792
0
    size_t ArgTokenStart = ArgTokens.size();
793
45.2M
    SourceLocation ArgStartLoc = Tok.getLocation();
794
795
    // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
796
    // that we already consumed the first one.
797
45.2M
    unsigned NumParens = 0;
798
799
158M
    while (true) {
800
      // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
801
      // an argument value in a macro could expand to ',' or '(' or ')'.
802
158M
      LexUnexpandedToken(Tok);
803
804
158M
      if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
805
27
        if (!ContainsCodeCompletionTok) {
806
18
          Diag(MacroName, diag::err_unterm_macro_invoc);
807
18
          Diag(MI->getDefinitionLoc(), diag::note_macro_here)
808
18
            << MacroName.getIdentifierInfo();
809
          // Do not lose the EOF/EOD.  Return it to the client.
810
18
          MacroName = Tok;
811
18
          return nullptr;
812
18
        }
813
        // Do not lose the EOF/EOD.
814
9
        auto Toks = std::make_unique<Token[]>(1);
815
9
        Toks[0] = Tok;
816
9
        EnterTokenStream(std::move(Toks), 1, true, /*IsReinject*/ false);
817
9
        break;
818
158M
      } else if (Tok.is(tok::r_paren)) {
819
        // If we found the ) token, the macro arg list is done.
820
35.4M
        if (NumParens-- == 0) {
821
19.6M
          MacroEnd = Tok.getLocation();
822
19.6M
          if (!ArgTokens.empty() &&
823
19.6M
              
ArgTokens.back().commaAfterElided()19.3M
) {
824
853
            FoundElidedComma = true;
825
853
          }
826
19.6M
          break;
827
19.6M
        }
828
122M
      } else if (Tok.is(tok::l_paren)) {
829
15.7M
        ++NumParens;
830
107M
      } else if (Tok.is(tok::comma)) {
831
        // In Microsoft-compatibility mode, single commas from nested macro
832
        // expansions should not be considered as argument separators. We test
833
        // for this with the IgnoredComma token flag.
834
35.1M
        if (Tok.getFlags() & Token::IgnoredComma) {
835
          // However, in MSVC's preprocessor, subsequent expansions do treat
836
          // these commas as argument separators. This leads to a common
837
          // workaround used in macros that need to work in both MSVC and
838
          // compliant preprocessors. Therefore, the IgnoredComma flag can only
839
          // apply once to any given token.
840
3
          Tok.clearFlag(Token::IgnoredComma);
841
35.1M
        } else if (NumParens == 0) {
842
          // Comma ends this argument if there are more fixed arguments
843
          // expected. However, if this is a variadic macro, and this is part of
844
          // the variadic part, then the comma is just an argument token.
845
32.5M
          if (!isVariadic)
846
8.88M
            break;
847
23.7M
          if (NumFixedArgsLeft > 1)
848
16.6M
            break;
849
23.7M
        }
850
71.9M
      } else if (Tok.is(tok::comment) && 
!KeepMacroComments0
) {
851
        // If this is a comment token in the argument list and we're just in
852
        // -C mode (not -CC mode), discard the comment.
853
0
        continue;
854
71.9M
      } else if (!Tok.isAnnotation() && 
Tok.getIdentifierInfo() != nullptr71.9M
) {
855
        // Reading macro arguments can cause macros that we are currently
856
        // expanding from to be popped off the expansion stack.  Doing so causes
857
        // them to be reenabled for expansion.  Here we record whether any
858
        // identifiers we lex as macro arguments correspond to disabled macros.
859
        // If so, we mark the token as noexpand.  This is a subtle aspect of
860
        // C99 6.10.3.4p2.
861
42.1M
        if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
862
16.7M
          if (!MI->isEnabled())
863
1.70k
            Tok.setFlag(Token::DisableExpand);
864
42.1M
      } else 
if (29.8M
Tok.is(tok::code_completion)29.8M
) {
865
25
        ContainsCodeCompletionTok = true;
866
25
        if (CodeComplete)
867
25
          CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
868
25
                                                  MI, NumActuals);
869
        // Don't mark that we reached the code-completion point because the
870
        // parser is going to handle the token and there will be another
871
        // code-completion callback.
872
25
      }
873
874
113M
      ArgTokens.push_back(Tok);
875
113M
    }
876
877
    // If this was an empty argument list foo(), don't add this as an empty
878
    // argument.
879
45.2M
    if (ArgTokens.empty() && 
Tok.getKind() == tok::r_paren353k
)
880
353k
      break;
881
882
    // If this is not a variadic macro, and too many args were specified, emit
883
    // an error.
884
44.8M
    if (!isVariadic && 
NumFixedArgsLeft == 023.3M
&&
TooManyArgsLoc.isInvalid()200
) {
885
48
      if (ArgTokens.size() != ArgTokenStart)
886
46
        TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
887
2
      else
888
2
        TooManyArgsLoc = ArgStartLoc;
889
48
    }
890
891
    // Empty arguments are standard in C99 and C++0x, and are supported as an
892
    // extension in other modes.
893
44.8M
    if (ArgTokens.size() == ArgTokenStart && 
!getLangOpts().C9987.2k
)
894
23.4k
      Diag(Tok, getLangOpts().CPlusPlus11
895
23.4k
                    ? 
diag::warn_cxx98_compat_empty_fnmacro_arg23.4k
896
23.4k
                    : 
diag::ext_empty_fnmacro_arg22
);
897
898
    // Add a marker EOF token to the end of the token list for this argument.
899
44.8M
    Token EOFTok;
900
44.8M
    EOFTok.startToken();
901
44.8M
    EOFTok.setKind(tok::eof);
902
44.8M
    EOFTok.setLocation(Tok.getLocation());
903
44.8M
    EOFTok.setLength(0);
904
44.8M
    ArgTokens.push_back(EOFTok);
905
44.8M
    ++NumActuals;
906
44.8M
    if (!ContainsCodeCompletionTok && 
NumFixedArgsLeft != 044.8M
)
907
44.8M
      --NumFixedArgsLeft;
908
44.8M
  }
909
910
  // Okay, we either found the r_paren.  Check to see if we parsed too few
911
  // arguments.
912
19.6M
  unsigned MinArgsExpected = MI->getNumParams();
913
914
  // If this is not a variadic macro, and too many args were specified, emit
915
  // an error.
916
19.6M
  if (!isVariadic && 
NumActuals > MinArgsExpected14.7M
&&
917
19.6M
      
!ContainsCodeCompletionTok49
) {
918
    // Emit the diagnostic at the macro name in case there is a missing ).
919
    // Emitting it at the , could be far away from the macro name.
920
48
    Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
921
48
    Diag(MI->getDefinitionLoc(), diag::note_macro_here)
922
48
      << MacroName.getIdentifierInfo();
923
924
    // Commas from braced initializer lists will be treated as argument
925
    // separators inside macros.  Attempt to correct for this with parentheses.
926
    // TODO: See if this can be generalized to angle brackets for templates
927
    // inside macro arguments.
928
929
48
    SmallVector<Token, 4> FixedArgTokens;
930
48
    unsigned FixedNumArgs = 0;
931
48
    SmallVector<SourceRange, 4> ParenHints, InitLists;
932
48
    if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
933
48
                              ParenHints, InitLists)) {
934
15
      if (!InitLists.empty()) {
935
6
        DiagnosticBuilder DB =
936
6
            Diag(MacroName,
937
6
                 diag::note_init_list_at_beginning_of_macro_argument);
938
6
        for (SourceRange Range : InitLists)
939
28
          DB << Range;
940
6
      }
941
15
      return nullptr;
942
15
    }
943
33
    if (FixedNumArgs != MinArgsExpected)
944
0
      return nullptr;
945
946
33
    DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
947
59
    for (SourceRange ParenLocation : ParenHints) {
948
59
      DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
949
59
      DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
950
59
    }
951
33
    ArgTokens.swap(FixedArgTokens);
952
33
    NumActuals = FixedNumArgs;
953
33
  }
954
955
  // See MacroArgs instance var for description of this.
956
19.6M
  bool isVarargsElided = false;
957
958
19.6M
  if (ContainsCodeCompletionTok) {
959
    // Recover from not-fully-formed macro invocation during code-completion.
960
25
    Token EOFTok;
961
25
    EOFTok.startToken();
962
25
    EOFTok.setKind(tok::eof);
963
25
    EOFTok.setLocation(Tok.getLocation());
964
25
    EOFTok.setLength(0);
965
35
    for (; NumActuals < MinArgsExpected; 
++NumActuals10
)
966
10
      ArgTokens.push_back(EOFTok);
967
25
  }
968
969
19.6M
  if (NumActuals < MinArgsExpected) {
970
    // There are several cases where too few arguments is ok, handle them now.
971
461k
    if (NumActuals == 0 && 
MinArgsExpected == 1350k
) {
972
      // #define A(X)  or  #define A(...)   ---> A()
973
974
      // If there is exactly one argument, and that argument is missing,
975
      // then we have an empty "()" argument empty list.  This is fine, even if
976
      // the macro expects one argument (the argument is just empty).
977
350k
      isVarargsElided = MI->isVariadic();
978
350k
    } else 
if (111k
(111k
FoundElidedComma111k
||
MI->isVariadic()110k
) &&
979
111k
               
(111k
NumActuals+1 == MinArgsExpected111k
|| // A(x, ...) -> A(X)
980
111k
                
(30
NumActuals == 030
&&
MinArgsExpected == 230
))) {// A(x,...) -> A()
981
      // Varargs where the named vararg parameter is missing: OK as extension.
982
      //   #define A(x, ...)
983
      //   A("blah")
984
      //
985
      // If the macro contains the comma pasting extension, the diagnostic
986
      // is suppressed; we know we'll get another diagnostic later.
987
111k
      if (!MI->hasCommaPasting()) {
988
        // C++20 allows this construct, but standards before C++20 and all C
989
        // standards do not allow the construct (we allow it as an extension).
990
99.9k
        Diag(Tok, getLangOpts().CPlusPlus20
991
99.9k
                      ? 
diag::warn_cxx17_compat_missing_varargs_arg15
992
99.9k
                      : 
diag::ext_missing_varargs_arg99.9k
);
993
99.9k
        Diag(MI->getDefinitionLoc(), diag::note_macro_here)
994
99.9k
          << MacroName.getIdentifierInfo();
995
99.9k
      }
996
997
      // Remember this occurred, allowing us to elide the comma when used for
998
      // cases like:
999
      //   #define A(x, foo...) blah(a, ## foo)
1000
      //   #define B(x, ...) blah(a, ## __VA_ARGS__)
1001
      //   #define C(...) blah(a, ## __VA_ARGS__)
1002
      //  A(x) B(x) C()
1003
111k
      isVarargsElided = true;
1004
111k
    } else 
if (21
!ContainsCodeCompletionTok21
) {
1005
      // Otherwise, emit the error.
1006
21
      Diag(Tok, diag::err_too_few_args_in_macro_invoc);
1007
21
      Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1008
21
        << MacroName.getIdentifierInfo();
1009
21
      return nullptr;
1010
21
    }
1011
1012
    // Add a marker EOF token to the end of the token list for this argument.
1013
461k
    SourceLocation EndLoc = Tok.getLocation();
1014
461k
    Tok.startToken();
1015
461k
    Tok.setKind(tok::eof);
1016
461k
    Tok.setLocation(EndLoc);
1017
461k
    Tok.setLength(0);
1018
461k
    ArgTokens.push_back(Tok);
1019
1020
    // If we expect two arguments, add both as empty.
1021
461k
    if (NumActuals == 0 && 
MinArgsExpected == 2350k
)
1022
30
      ArgTokens.push_back(Tok);
1023
1024
19.2M
  } else if (NumActuals > MinArgsExpected && 
!MI->isVariadic()1
&&
1025
19.2M
             
!ContainsCodeCompletionTok1
) {
1026
    // Emit the diagnostic at the macro name in case there is a missing ).
1027
    // Emitting it at the , could be far away from the macro name.
1028
0
    Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
1029
0
    Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1030
0
      << MacroName.getIdentifierInfo();
1031
0
    return nullptr;
1032
0
  }
1033
1034
19.6M
  return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
1035
19.6M
}
1036
1037
/// Keeps macro expanded tokens for TokenLexers.
1038
//
1039
/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1040
/// going to lex in the cache and when it finishes the tokens are removed
1041
/// from the end of the cache.
1042
Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1043
19.6M
                                              ArrayRef<Token> tokens) {
1044
19.6M
  assert(tokLexer);
1045
19.6M
  if (tokens.empty())
1046
262k
    return nullptr;
1047
1048
19.3M
  size_t newIndex = MacroExpandedTokens.size();
1049
19.3M
  bool cacheNeedsToGrow = tokens.size() >
1050
19.3M
                      MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1051
19.3M
  MacroExpandedTokens.append(tokens.begin(), tokens.end());
1052
1053
19.3M
  if (cacheNeedsToGrow) {
1054
    // Go through all the TokenLexers whose 'Tokens' pointer points in the
1055
    // buffer and update the pointers to the (potential) new buffer array.
1056
13.0k
    for (const auto &Lexer : MacroExpandingLexersStack) {
1057
11.4k
      TokenLexer *prevLexer;
1058
11.4k
      size_t tokIndex;
1059
11.4k
      std::tie(prevLexer, tokIndex) = Lexer;
1060
11.4k
      prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1061
11.4k
    }
1062
13.0k
  }
1063
1064
19.3M
  MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1065
19.3M
  return MacroExpandedTokens.data() + newIndex;
1066
19.6M
}
1067
1068
19.3M
void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1069
19.3M
  assert(!MacroExpandingLexersStack.empty());
1070
0
  size_t tokIndex = MacroExpandingLexersStack.back().second;
1071
19.3M
  assert(tokIndex < MacroExpandedTokens.size());
1072
  // Pop the cached macro expanded tokens from the end.
1073
0
  MacroExpandedTokens.resize(tokIndex);
1074
19.3M
  MacroExpandingLexersStack.pop_back();
1075
19.3M
}
1076
1077
/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1078
/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1079
/// the identifier tokens inserted.
1080
static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1081
7
                             Preprocessor &PP) {
1082
7
  time_t TT = time(nullptr);
1083
7
  struct tm *TM = localtime(&TT);
1084
1085
7
  static const char * const Months[] = {
1086
7
    "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1087
7
  };
1088
1089
7
  {
1090
7
    SmallString<32> TmpBuffer;
1091
7
    llvm::raw_svector_ostream TmpStream(TmpBuffer);
1092
7
    TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1093
7
                              TM->tm_mday, TM->tm_year + 1900);
1094
7
    Token TmpTok;
1095
7
    TmpTok.startToken();
1096
7
    PP.CreateString(TmpStream.str(), TmpTok);
1097
7
    DATELoc = TmpTok.getLocation();
1098
7
  }
1099
1100
7
  {
1101
7
    SmallString<32> TmpBuffer;
1102
7
    llvm::raw_svector_ostream TmpStream(TmpBuffer);
1103
7
    TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1104
7
                              TM->tm_hour, TM->tm_min, TM->tm_sec);
1105
7
    Token TmpTok;
1106
7
    TmpTok.startToken();
1107
7
    PP.CreateString(TmpStream.str(), TmpTok);
1108
7
    TIMELoc = TmpTok.getLocation();
1109
7
  }
1110
7
}
1111
1112
/// HasFeature - Return true if we recognize and implement the feature
1113
/// specified by the identifier as a standard language feature.
1114
474k
static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
1115
474k
  const LangOptions &LangOpts = PP.getLangOpts();
1116
1117
  // Normalize the feature name, __foo__ becomes foo.
1118
474k
  if (Feature.startswith("__") && 
Feature.endswith("__")5
&&
Feature.size() >= 44
)
1119
4
    Feature = Feature.substr(2, Feature.size() - 4);
1120
1121
78.2M
#define FEATURE(Name, Predicate) .Case(#Name, 
Predicate4.18M
)
1122
474k
  return llvm::StringSwitch<bool>(Feature)
1123
474k
#include "clang/Basic/Features.def"
1124
474k
      .Default(false);
1125
474k
#undef FEATURE
1126
474k
}
1127
1128
/// HasExtension - Return true if we recognize and implement the feature
1129
/// specified by the identifier, either as an extension or a standard language
1130
/// feature.
1131
16.6k
static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1132
16.6k
  if (HasFeature(PP, Extension))
1133
9.28k
    return true;
1134
1135
  // If the use of an extension results in an error diagnostic, extensions are
1136
  // effectively unavailable, so just return false here.
1137
7.33k
  if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1138
7.33k
      diag::Severity::Error)
1139
6
    return false;
1140
1141
7.33k
  const LangOptions &LangOpts = PP.getLangOpts();
1142
1143
  // Normalize the extension name, __foo__ becomes foo.
1144
7.33k
  if (Extension.startswith("__") && 
Extension.endswith("__")1
&&
1145
7.33k
      
Extension.size() >= 41
)
1146
1
    Extension = Extension.substr(2, Extension.size() - 4);
1147
1148
    // Because we inherit the feature list from HasFeature, this string switch
1149
    // must be less restrictive than HasFeature's.
1150
227k
#define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
1151
7.33k
  return llvm::StringSwitch<bool>(Extension)
1152
7.33k
#include "clang/Basic/Features.def"
1153
7.33k
      .Default(false);
1154
7.33k
#undef EXTENSION
1155
7.33k
}
1156
1157
/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1158
/// or '__has_include_next("path")' expression.
1159
/// Returns true if successful.
1160
static bool EvaluateHasIncludeCommon(Token &Tok,
1161
                                     IdentifierInfo *II, Preprocessor &PP,
1162
                                     const DirectoryLookup *LookupFrom,
1163
15.3k
                                     const FileEntry *LookupFromFile) {
1164
  // Save the location of the current token.  If a '(' is later found, use
1165
  // that location.  If not, use the end of this location instead.
1166
15.3k
  SourceLocation LParenLoc = Tok.getLocation();
1167
1168
  // These expressions are only allowed within a preprocessor directive.
1169
15.3k
  if (!PP.isParsingIfOrElifDirective()) {
1170
8
    PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
1171
    // Return a valid identifier token.
1172
8
    assert(Tok.is(tok::identifier));
1173
0
    Tok.setIdentifierInfo(II);
1174
8
    return false;
1175
8
  }
1176
1177
  // Get '('. If we don't have a '(', try to form a header-name token.
1178
15.3k
  do {
1179
15.3k
    if (PP.LexHeaderName(Tok))
1180
0
      return false;
1181
15.3k
  } while (Tok.getKind() == tok::comment);
1182
1183
  // Ensure we have a '('.
1184
15.3k
  if (Tok.isNot(tok::l_paren)) {
1185
    // No '(', use end of last token.
1186
6
    LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1187
6
    PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
1188
    // If the next token looks like a filename or the start of one,
1189
    // assume it is and process it as such.
1190
6
    if (Tok.isNot(tok::header_name))
1191
4
      return false;
1192
15.3k
  } else {
1193
    // Save '(' location for possible missing ')' message.
1194
15.3k
    LParenLoc = Tok.getLocation();
1195
15.3k
    if (PP.LexHeaderName(Tok))
1196
2
      return false;
1197
15.3k
  }
1198
1199
15.3k
  if (Tok.isNot(tok::header_name)) {
1200
9
    PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1201
9
    return false;
1202
9
  }
1203
1204
  // Reserve a buffer to get the spelling.
1205
15.3k
  SmallString<128> FilenameBuffer;
1206
15.3k
  bool Invalid = false;
1207
15.3k
  StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1208
15.3k
  if (Invalid)
1209
0
    return false;
1210
1211
15.3k
  SourceLocation FilenameLoc = Tok.getLocation();
1212
1213
  // Get ')'.
1214
15.3k
  PP.LexNonComment(Tok);
1215
1216
  // Ensure we have a trailing ).
1217
15.3k
  if (Tok.isNot(tok::r_paren)) {
1218
2
    PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1219
2
        << II << tok::r_paren;
1220
2
    PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1221
2
    return false;
1222
2
  }
1223
1224
15.3k
  bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1225
  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1226
  // error.
1227
15.3k
  if (Filename.empty())
1228
1
    return false;
1229
1230
  // Search include directories.
1231
15.3k
  const DirectoryLookup *CurDir;
1232
15.3k
  Optional<FileEntryRef> File =
1233
15.3k
      PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1234
15.3k
                    CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
1235
1236
15.3k
  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
1237
15.3k
    SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;
1238
15.3k
    if (File)
1239
7.38k
      FileType =
1240
7.38k
          PP.getHeaderSearchInfo().getFileDirFlavor(&File->getFileEntry());
1241
15.3k
    Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
1242
15.3k
  }
1243
1244
  // Get the result value.  A result of true means the file exists.
1245
15.3k
  return File.hasValue();
1246
15.3k
}
1247
1248
/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1249
/// Returns true if successful.
1250
static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1251
10.0k
                               Preprocessor &PP) {
1252
10.0k
  return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
1253
10.0k
}
1254
1255
/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1256
/// Returns true if successful.
1257
static bool EvaluateHasIncludeNext(Token &Tok,
1258
5.32k
                                   IdentifierInfo *II, Preprocessor &PP) {
1259
  // __has_include_next is like __has_include, except that we start
1260
  // searching after the current found directory.  If we can't do this,
1261
  // issue a diagnostic.
1262
  // FIXME: Factor out duplication with
1263
  // Preprocessor::HandleIncludeNextDirective.
1264
5.32k
  const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1265
5.32k
  const FileEntry *LookupFromFile = nullptr;
1266
5.32k
  if (PP.isInPrimaryFile() && 
PP.getLangOpts().IsHeaderFile7
) {
1267
    // If the main file is a header, then it's either for PCH/AST generation,
1268
    // or libclang opened it. Either way, handle it as a normal include below
1269
    // and do not complain about __has_include_next.
1270
5.32k
  } else if (PP.isInPrimaryFile()) {
1271
6
    Lookup = nullptr;
1272
6
    PP.Diag(Tok, diag::pp_include_next_in_primary);
1273
5.32k
  } else if (PP.getCurrentLexerSubmodule()) {
1274
    // Start looking up in the directory *after* the one in which the current
1275
    // file would be found, if any.
1276
164
    assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1277
0
    LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1278
164
    Lookup = nullptr;
1279
5.15k
  } else if (!Lookup) {
1280
0
    PP.Diag(Tok, diag::pp_include_next_absolute_path);
1281
5.15k
  } else {
1282
    // Start looking up in the next directory.
1283
5.15k
    ++Lookup;
1284
5.15k
  }
1285
1286
0
  return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
1287
5.32k
}
1288
1289
/// Process single-argument builtin feature-like macros that return
1290
/// integer values.
1291
static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1292
                                            Token &Tok, IdentifierInfo *II,
1293
                                            Preprocessor &PP, bool ExpandArgs,
1294
                                            llvm::function_ref<
1295
                                              int(Token &Tok,
1296
603k
                                                  bool &HasLexedNextTok)> Op) {
1297
  // Parse the initial '('.
1298
603k
  PP.LexUnexpandedToken(Tok);
1299
603k
  if (Tok.isNot(tok::l_paren)) {
1300
3
    PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1301
3
                                                            << tok::l_paren;
1302
1303
    // Provide a dummy '0' value on output stream to elide further errors.
1304
3
    if (!Tok.isOneOf(tok::eof, tok::eod)) {
1305
2
      OS << 0;
1306
2
      Tok.setKind(tok::numeric_constant);
1307
2
    }
1308
3
    return;
1309
3
  }
1310
1311
603k
  unsigned ParenDepth = 1;
1312
603k
  SourceLocation LParenLoc = Tok.getLocation();
1313
603k
  llvm::Optional<int> Result;
1314
1315
603k
  Token ResultTok;
1316
603k
  bool SuppressDiagnostic = false;
1317
1.20M
  while (true) {
1318
    // Parse next token.
1319
1.20M
    if (ExpandArgs)
1320
122k
      PP.Lex(Tok);
1321
1.08M
    else
1322
1.08M
      PP.LexUnexpandedToken(Tok);
1323
1324
1.20M
already_lexed:
1325
1.20M
    switch (Tok.getKind()) {
1326
1
      case tok::eof:
1327
3
      case tok::eod:
1328
        // Don't provide even a dummy value if the eod or eof marker is
1329
        // reached.  Simply provide a diagnostic.
1330
3
        PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1331
3
        return;
1332
1333
1
      case tok::comma:
1334
1
        if (!SuppressDiagnostic) {
1335
1
          PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1336
1
          SuppressDiagnostic = true;
1337
1
        }
1338
1
        continue;
1339
1340
3
      case tok::l_paren:
1341
3
        ++ParenDepth;
1342
3
        if (Result.hasValue())
1343
1
          break;
1344
2
        if (!SuppressDiagnostic) {
1345
1
          PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1346
1
          SuppressDiagnostic = true;
1347
1
        }
1348
2
        continue;
1349
1350
603k
      case tok::r_paren:
1351
603k
        if (--ParenDepth > 0)
1352
3
          continue;
1353
1354
        // The last ')' has been reached; return the value if one found or
1355
        // a diagnostic and a dummy value.
1356
603k
        if (Result.hasValue()) {
1357
603k
          OS << Result.getValue();
1358
          // For strict conformance to __has_cpp_attribute rules, use 'L'
1359
          // suffix for dated literals.
1360
603k
          if (Result.getValue() > 1)
1361
4.53k
            OS << 'L';
1362
603k
        } else {
1363
3
          OS << 0;
1364
3
          if (!SuppressDiagnostic)
1365
2
            PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1366
3
        }
1367
603k
        Tok.setKind(tok::numeric_constant);
1368
603k
        return;
1369
1370
603k
      default: {
1371
        // Parse the macro argument, if one not found so far.
1372
603k
        if (Result.hasValue())
1373
5
          break;
1374
1375
603k
        bool HasLexedNextToken = false;
1376
603k
        Result = Op(Tok, HasLexedNextToken);
1377
603k
        ResultTok = Tok;
1378
603k
        if (HasLexedNextToken)
1379
1.86k
          goto already_lexed;
1380
601k
        continue;
1381
603k
      }
1382
1.20M
    }
1383
1384
    // Diagnose missing ')'.
1385
6
    if (!SuppressDiagnostic) {
1386
5
      if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1387
5
        if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1388
2
          Diag << LastII;
1389
3
        else
1390
3
          Diag << ResultTok.getKind();
1391
5
        Diag << tok::r_paren << ResultTok.getLocation();
1392
5
      }
1393
5
      PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1394
5
      SuppressDiagnostic = true;
1395
5
    }
1396
6
  }
1397
603k
}
1398
1399
/// Helper function to return the IdentifierInfo structure of a Token
1400
/// or generate a diagnostic if none available.
1401
static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
1402
                                                   Preprocessor &PP,
1403
589k
                                                   signed DiagID) {
1404
589k
  IdentifierInfo *II;
1405
589k
  if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1406
589k
    return II;
1407
1408
3
  PP.Diag(Tok.getLocation(), DiagID);
1409
3
  return nullptr;
1410
589k
}
1411
1412
/// Implements the __is_target_arch builtin macro.
1413
1.32k
static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
1414
1.32k
  std::string ArchName = II->getName().lower() + "--";
1415
1.32k
  llvm::Triple Arch(ArchName);
1416
1.32k
  const llvm::Triple &TT = TI.getTriple();
1417
1.32k
  if (TT.isThumb()) {
1418
    // arm matches thumb or thumbv7. armv7 matches thumbv7.
1419
11
    if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
1420
11
         
Arch.getSubArch() == TT.getSubArch()7
) &&
1421
11
        
(8
(8
TT.getArch() == llvm::Triple::thumb8
&&
1422
8
          Arch.getArch() == llvm::Triple::arm) ||
1423
8
         
(6
TT.getArch() == llvm::Triple::thumbeb6
&&
1424
6
          
Arch.getArch() == llvm::Triple::armeb0
)))
1425
2
      return true;
1426
11
  }
1427
  // Check the parsed arch when it has no sub arch to allow Clang to
1428
  // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
1429
1.32k
  return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
1430
1.32k
          
Arch.getSubArch() == TT.getSubArch()15
) &&
1431
1.32k
         
Arch.getArch() == TT.getArch()1.31k
;
1432
1.32k
}
1433
1434
/// Implements the __is_target_vendor builtin macro.
1435
1.30k
static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
1436
1.30k
  StringRef VendorName = TI.getTriple().getVendorName();
1437
1.30k
  if (VendorName.empty())
1438
0
    VendorName = "unknown";
1439
1.30k
  return VendorName.equals_insensitive(II->getName());
1440
1.30k
}
1441
1442
/// Implements the __is_target_os builtin macro.
1443
1.31k
static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
1444
1.31k
  std::string OSName =
1445
1.31k
      (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
1446
1.31k
  llvm::Triple OS(OSName);
1447
1.31k
  if (OS.getOS() == llvm::Triple::Darwin) {
1448
    // Darwin matches macos, ios, etc.
1449
6
    return TI.getTriple().isOSDarwin();
1450
6
  }
1451
1.31k
  return TI.getTriple().getOS() == OS.getOS();
1452
1.31k
}
1453
1454
/// Implements the __is_target_environment builtin macro.
1455
static bool isTargetEnvironment(const TargetInfo &TI,
1456
871
                                const IdentifierInfo *II) {
1457
871
  std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
1458
871
  llvm::Triple Env(EnvName);
1459
871
  return TI.getTriple().getEnvironment() == Env.getEnvironment();
1460
871
}
1461
1462
/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1463
/// as a builtin macro, handle it and return the next token as 'Tok'.
1464
984k
void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1465
  // Figure out which token this is.
1466
984k
  IdentifierInfo *II = Tok.getIdentifierInfo();
1467
984k
  assert(II && "Can't be a macro without id info!");
1468
1469
  // If this is an _Pragma or Microsoft __pragma directive, expand it,
1470
  // invoke the pragma handler, then lex the token after it.
1471
984k
  if (II == Ident_Pragma)
1472
361k
    return Handle_Pragma(Tok);
1473
623k
  else if (II == Ident__pragma) // in non-MS mode this is null
1474
35
    return HandleMicrosoft__pragma(Tok);
1475
1476
623k
  ++NumBuiltinMacroExpanded;
1477
1478
623k
  SmallString<128> TmpBuffer;
1479
623k
  llvm::raw_svector_ostream OS(TmpBuffer);
1480
1481
  // Set up the return result.
1482
623k
  Tok.setIdentifierInfo(nullptr);
1483
623k
  Tok.clearFlag(Token::NeedsCleaning);
1484
623k
  bool IsAtStartOfLine = Tok.isAtStartOfLine();
1485
623k
  bool HasLeadingSpace = Tok.hasLeadingSpace();
1486
1487
623k
  if (II == Ident__LINE__) {
1488
    // C99 6.10.8: "__LINE__: The presumed line number (within the current
1489
    // source file) of the current source line (an integer constant)".  This can
1490
    // be affected by #line.
1491
2.94k
    SourceLocation Loc = Tok.getLocation();
1492
1493
    // Advance to the location of the first _, this might not be the first byte
1494
    // of the token if it starts with an escaped newline.
1495
2.94k
    Loc = AdvanceToTokenCharacter(Loc, 0);
1496
1497
    // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1498
    // a macro expansion.  This doesn't matter for object-like macros, but
1499
    // can matter for a function-like macro that expands to contain __LINE__.
1500
    // Skip down through expansion points until we find a file loc for the
1501
    // end of the expansion history.
1502
2.94k
    Loc = SourceMgr.getExpansionRange(Loc).getEnd();
1503
2.94k
    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1504
1505
    // __LINE__ expands to a simple numeric value.
1506
2.94k
    OS << (PLoc.isValid()? PLoc.getLine() : 
10
);
1507
2.94k
    Tok.setKind(tok::numeric_constant);
1508
620k
  } else if (II == Ident__FILE__ || 
II == Ident__BASE_FILE__619k
||
1509
620k
             
II == Ident__FILE_NAME__619k
) {
1510
    // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1511
    // character string literal)". This can be affected by #line.
1512
345
    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1513
1514
    // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1515
    // #include stack instead of the current file.
1516
345
    if (II == Ident__BASE_FILE__ && 
PLoc.isValid()4
) {
1517
4
      SourceLocation NextLoc = PLoc.getIncludeLoc();
1518
8
      while (NextLoc.isValid()) {
1519
4
        PLoc = SourceMgr.getPresumedLoc(NextLoc);
1520
4
        if (PLoc.isInvalid())
1521
0
          break;
1522
1523
4
        NextLoc = PLoc.getIncludeLoc();
1524
4
      }
1525
4
    }
1526
1527
    // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
1528
345
    SmallString<256> FN;
1529
345
    if (PLoc.isValid()) {
1530
      // __FILE_NAME__ is a Clang-specific extension that expands to the
1531
      // the last part of __FILE__.
1532
345
      if (II == Ident__FILE_NAME__) {
1533
        // Try to get the last path component, failing that return the original
1534
        // presumed location.
1535
11
        StringRef PLFileName = llvm::sys::path::filename(PLoc.getFilename());
1536
11
        if (PLFileName != "")
1537
11
          FN += PLFileName;
1538
0
        else
1539
0
          FN += PLoc.getFilename();
1540
334
      } else {
1541
334
        FN += PLoc.getFilename();
1542
334
      }
1543
345
      getLangOpts().remapPathPrefix(FN);
1544
345
      Lexer::Stringify(FN);
1545
345
      OS << '"' << FN << '"';
1546
345
    }
1547
345
    Tok.setKind(tok::string_literal);
1548
619k
  } else if (II == Ident__DATE__) {
1549
7
    Diag(Tok.getLocation(), diag::warn_pp_date_time);
1550
7
    if (!DATELoc.isValid())
1551
4
      ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1552
7
    Tok.setKind(tok::string_literal);
1553
7
    Tok.setLength(strlen("\"Mmm dd yyyy\""));
1554
7
    Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1555
7
                                                 Tok.getLocation(),
1556
7
                                                 Tok.getLength()));
1557
7
    return;
1558
619k
  } else if (II == Ident__TIME__) {
1559
6
    Diag(Tok.getLocation(), diag::warn_pp_date_time);
1560
6
    if (!TIMELoc.isValid())
1561
3
      ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1562
6
    Tok.setKind(tok::string_literal);
1563
6
    Tok.setLength(strlen("\"hh:mm:ss\""));
1564
6
    Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1565
6
                                                 Tok.getLocation(),
1566
6
                                                 Tok.getLength()));
1567
6
    return;
1568
619k
  } else if (II == Ident__INCLUDE_LEVEL__) {
1569
    // Compute the presumed include depth of this token.  This can be affected
1570
    // by GNU line markers.
1571
9
    unsigned Depth = 0;
1572
1573
9
    PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1574
9
    if (PLoc.isValid()) {
1575
9
      PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1576
15
      for (; PLoc.isValid(); 
++Depth6
)
1577
6
        PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1578
9
    }
1579
1580
    // __INCLUDE_LEVEL__ expands to a simple numeric value.
1581
9
    OS << Depth;
1582
9
    Tok.setKind(tok::numeric_constant);
1583
619k
  } else if (II == Ident__TIMESTAMP__) {
1584
3
    Diag(Tok.getLocation(), diag::warn_pp_date_time);
1585
    // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
1586
    // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1587
1588
    // Get the file that we are lexing out of.  If we're currently lexing from
1589
    // a macro, dig into the include stack.
1590
3
    const FileEntry *CurFile = nullptr;
1591
3
    PreprocessorLexer *TheLexer = getCurrentFileLexer();
1592
1593
3
    if (TheLexer)
1594
3
      CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1595
1596
3
    const char *Result;
1597
3
    if (CurFile) {
1598
3
      time_t TT = CurFile->getModificationTime();
1599
3
      struct tm *TM = localtime(&TT);
1600
3
      Result = asctime(TM);
1601
3
    } else {
1602
0
      Result = "??? ??? ?? ??:??:?? ????\n";
1603
0
    }
1604
    // Surround the string with " and strip the trailing newline.
1605
3
    OS << '"' << StringRef(Result).drop_back() << '"';
1606
3
    Tok.setKind(tok::string_literal);
1607
619k
  } else if (II == Ident__COUNTER__) {
1608
    // __COUNTER__ expands to a simple numeric value.
1609
1.14k
    OS << CounterValue++;
1610
1.14k
    Tok.setKind(tok::numeric_constant);
1611
618k
  } else if (II == Ident__has_feature) {
1612
457k
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1613
457k
      [this](Token &Tok, bool &HasLexedNextToken) -> int {
1614
457k
        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1615
457k
                                           diag::err_feature_check_malformed);
1616
457k
        return II && 
HasFeature(*this, II->getName())457k
;
1617
457k
      });
1618
457k
  } else 
if (161k
II == Ident__has_extension161k
) {
1619
16.6k
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1620
16.6k
      [this](Token &Tok, bool &HasLexedNextToken) -> int {
1621
16.6k
        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1622
16.6k
                                           diag::err_feature_check_malformed);
1623
16.6k
        return II && HasExtension(*this, II->getName());
1624
16.6k
      });
1625
144k
  } else if (II == Ident__has_builtin) {
1626
46.8k
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1627
46.8k
      [this](Token &Tok, bool &HasLexedNextToken) -> int {
1628
46.8k
        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1629
46.8k
                                           diag::err_feature_check_malformed);
1630
46.8k
        if (!II)
1631
0
          return false;
1632
46.8k
        else if (II->getBuiltinID() != 0) {
1633
27.7k
          switch (II->getBuiltinID()) {
1634
880
          case Builtin::BI__builtin_operator_new:
1635
1.76k
          case Builtin::BI__builtin_operator_delete:
1636
            // denotes date of behavior change to support calling arbitrary
1637
            // usual allocation and deallocation functions. Required by libc++
1638
1.76k
            return 201802;
1639
25.9k
          default:
1640
25.9k
            return true;
1641
27.7k
          }
1642
0
          return true;
1643
27.7k
        } else 
if (19.1k
II->getTokenID() != tok::identifier19.1k
||
1644
19.1k
                   
II->hasRevertedTokenIDToIdentifier()19.0k
) {
1645
          // Treat all keywords that introduce a custom syntax of the form
1646
          //
1647
          //   '__some_keyword' '(' [...] ')'
1648
          //
1649
          // as being "builtin functions", even if the syntax isn't a valid
1650
          // function call (for example, because the builtin takes a type
1651
          // argument).
1652
22
          if (II->getName().startswith("__builtin_") ||
1653
22
              
II->getName().startswith("__is_")5
||
1654
22
              
II->getName().startswith("__has_")3
)
1655
20
            return true;
1656
2
          return llvm::StringSwitch<bool>(II->getName())
1657
2
              .Case("__array_rank", true)
1658
2
              .Case("__array_extent", true)
1659
2
              .Case("__reference_binds_to_temporary", true)
1660
2
              .Case("__underlying_type", true)
1661
2
              .Default(false);
1662
19.0k
        } else {
1663
19.0k
          return llvm::StringSwitch<bool>(II->getName())
1664
              // Report builtin templates as being builtins.
1665
19.0k
              .Case("__make_integer_seq", getLangOpts().CPlusPlus)
1666
19.0k
              .Case("__type_pack_element", getLangOpts().CPlusPlus)
1667
              // Likewise for some builtin preprocessor macros.
1668
              // FIXME: This is inconsistent; we usually suggest detecting
1669
              // builtin macros via #ifdef. Don't add more cases here.
1670
19.0k
              .Case("__is_target_arch", true)
1671
19.0k
              .Case("__is_target_vendor", true)
1672
19.0k
              .Case("__is_target_os", true)
1673
19.0k
              .Case("__is_target_environment", true)
1674
19.0k
              .Default(false);
1675
19.0k
        }
1676
46.8k
      });
1677
97.6k
  } else if (II == Ident__is_identifier) {
1678
14.8k
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1679
14.8k
      [](Token &Tok, bool &HasLexedNextToken) -> int {
1680
14.8k
        return Tok.is(tok::identifier);
1681
14.8k
      });
1682
82.7k
  } else if (II == Ident__has_attribute) {
1683
58.2k
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1684
58.2k
      [this](Token &Tok, bool &HasLexedNextToken) -> int {
1685
58.2k
        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1686
58.2k
                                           diag::err_feature_check_malformed);
1687
58.2k
        return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
1688
58.2k
                                 getTargetInfo(), getLangOpts()) : 
00
;
1689
58.2k
      });
1690
58.2k
  } else 
if (24.5k
II == Ident__has_declspec24.5k
) {
1691
915
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1692
915
      [this](Token &Tok, bool &HasLexedNextToken) -> int {
1693
915
        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1694
915
                                           diag::err_feature_check_malformed);
1695
915
        if (II) {
1696
915
          const LangOptions &LangOpts = getLangOpts();
1697
915
          return LangOpts.DeclSpecKeyword &&
1698
915
                 hasAttribute(AttrSyntax::Declspec, nullptr, II,
1699
8
                              getTargetInfo(), LangOpts);
1700
915
        }
1701
1702
0
        return false;
1703
915
      });
1704
23.5k
  } else if (II == Ident__has_cpp_attribute ||
1705
23.5k
             
II == Ident__has_c_attribute20.8k
) {
1706
2.82k
    bool IsCXX = II == Ident__has_cpp_attribute;
1707
2.82k
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1708
2.82k
        [&](Token &Tok, bool &HasLexedNextToken) -> int {
1709
2.82k
          IdentifierInfo *ScopeII = nullptr;
1710
2.82k
          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1711
2.82k
              Tok, *this, diag::err_feature_check_malformed);
1712
2.82k
          if (!II)
1713
1
            return false;
1714
1715
          // It is possible to receive a scope token.  Read the "::", if it is
1716
          // available, and the subsequent identifier.
1717
2.82k
          LexUnexpandedToken(Tok);
1718
2.82k
          if (Tok.isNot(tok::coloncolon))
1719
1.86k
            HasLexedNextToken = true;
1720
965
          else {
1721
965
            ScopeII = II;
1722
            // Lex an expanded token for the attribute name.
1723
965
            Lex(Tok);
1724
965
            II = ExpectFeatureIdentifierInfo(Tok, *this,
1725
965
                                             diag::err_feature_check_malformed);
1726
965
          }
1727
1728
2.82k
          AttrSyntax Syntax = IsCXX ? 
AttrSyntax::CXX2.78k
:
AttrSyntax::C43
;
1729
2.82k
          return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
1730
2.82k
                                   getLangOpts())
1731
2.82k
                    : 
00
;
1732
2.82k
        });
1733
20.7k
  } else if (II == Ident__has_include ||
1734
20.7k
             
II == Ident__has_include_next10.7k
) {
1735
    // The argument to these two builtins should be a parenthesized
1736
    // file name string literal using angle brackets (<>) or
1737
    // double-quotes ("").
1738
15.3k
    bool Value;
1739
15.3k
    if (II == Ident__has_include)
1740
10.0k
      Value = EvaluateHasInclude(Tok, II, *this);
1741
5.32k
    else
1742
5.32k
      Value = EvaluateHasIncludeNext(Tok, II, *this);
1743
1744
15.3k
    if (Tok.isNot(tok::r_paren))
1745
23
      return;
1746
15.3k
    OS << (int)Value;
1747
15.3k
    Tok.setKind(tok::numeric_constant);
1748
15.3k
  } else 
if (5.39k
II == Ident__has_warning5.39k
) {
1749
    // The argument should be a parenthesized string literal.
1750
10
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1751
10
      [this](Token &Tok, bool &HasLexedNextToken) -> int {
1752
7
        std::string WarningName;
1753
7
        SourceLocation StrStartLoc = Tok.getLocation();
1754
1755
7
        HasLexedNextToken = Tok.is(tok::string_literal);
1756
7
        if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1757
7
                                    /*AllowMacroExpansion=*/false))
1758
2
          return false;
1759
1760
        // FIXME: Should we accept "-R..." flags here, or should that be
1761
        // handled by a separate __has_remark?
1762
5
        if (WarningName.size() < 3 || WarningName[0] != '-' ||
1763
5
            
WarningName[1] != 'W'4
) {
1764
1
          Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1765
1
          return false;
1766
1
        }
1767
1768
        // Finally, check if the warning flags maps to a diagnostic group.
1769
        // We construct a SmallVector here to talk to getDiagnosticIDs().
1770
        // Although we don't use the result, this isn't a hot path, and not
1771
        // worth special casing.
1772
4
        SmallVector<diag::kind, 10> Diags;
1773
4
        return !getDiagnostics().getDiagnosticIDs()->
1774
4
                getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1775
4
                                      WarningName.substr(2), Diags);
1776
5
      });
1777
5.38k
  } else if (II == Ident__building_module) {
1778
    // The argument to this builtin should be an identifier. The
1779
    // builtin evaluates to 1 when that identifier names the module we are
1780
    // currently building.
1781
539
    EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1782
539
      [this](Token &Tok, bool &HasLexedNextToken) -> int {
1783
539
        IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1784
539
                                       diag::err_expected_id_building_module);
1785
539
        return getLangOpts().isCompilingModule() && 
II27
&&
1786
539
               
(II->getName() == getLangOpts().CurrentModule)27
;
1787
539
      });
1788
4.85k
  } else if (II == Ident__MODULE__) {
1789
    // The current module as an identifier.
1790
7
    OS << getLangOpts().CurrentModule;
1791
7
    IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1792
7
    Tok.setIdentifierInfo(ModuleII);
1793
7
    Tok.setKind(ModuleII->getTokenID());
1794
4.84k
  } else if (II == Ident__identifier) {
1795
24
    SourceLocation Loc = Tok.getLocation();
1796
1797
    // We're expecting '__identifier' '(' identifier ')'. Try to recover
1798
    // if the parens are missing.
1799
24
    LexNonComment(Tok);
1800
24
    if (Tok.isNot(tok::l_paren)) {
1801
      // No '(', use end of last token.
1802
1
      Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1803
1
        << II << tok::l_paren;
1804
      // If the next token isn't valid as our argument, we can't recover.
1805
1
      if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1806
1
        Tok.setKind(tok::identifier);
1807
1
      return;
1808
1
    }
1809
1810
23
    SourceLocation LParenLoc = Tok.getLocation();
1811
23
    LexNonComment(Tok);
1812
1813
23
    if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1814
13
      Tok.setKind(tok::identifier);
1815
10
    else if (Tok.is(tok::string_literal) && 
!Tok.hasUDSuffix()5
) {
1816
5
      StringLiteralParser Literal(Tok, *this);
1817
5
      if (Literal.hadError)
1818
0
        return;
1819
1820
5
      Tok.setIdentifierInfo(getIdentifierInfo(Literal.GetString()));
1821
5
      Tok.setKind(tok::identifier);
1822
5
    } else {
1823
5
      Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1824
5
        << Tok.getKind();
1825
      // Don't walk past anything that's not a real token.
1826
5
      if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
1827
0
        return;
1828
5
    }
1829
1830
    // Discard the ')', preserving 'Tok' as our result.
1831
23
    Token RParen;
1832
23
    LexNonComment(RParen);
1833
23
    if (RParen.isNot(tok::r_paren)) {
1834
1
      Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1835
1
        << Tok.getKind() << tok::r_paren;
1836
1
      Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1837
1
    }
1838
23
    return;
1839
4.81k
  } else if (II == Ident__is_target_arch) {
1840
1.32k
    EvaluateFeatureLikeBuiltinMacro(
1841
1.32k
        OS, Tok, II, *this, false,
1842
1.32k
        [this](Token &Tok, bool &HasLexedNextToken) -> int {
1843
1.32k
          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1844
1.32k
              Tok, *this, diag::err_feature_check_malformed);
1845
1.32k
          return II && 
isTargetArch(getTargetInfo(), II)1.32k
;
1846
1.32k
        });
1847
3.49k
  } else if (II == Ident__is_target_vendor) {
1848
1.30k
    EvaluateFeatureLikeBuiltinMacro(
1849
1.30k
        OS, Tok, II, *this, false,
1850
1.30k
        [this](Token &Tok, bool &HasLexedNextToken) -> int {
1851
1.30k
          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1852
1.30k
              Tok, *this, diag::err_feature_check_malformed);
1853
1.30k
          return II && isTargetVendor(getTargetInfo(), II);
1854
1.30k
        });
1855
2.18k
  } else if (II == Ident__is_target_os) {
1856
1.31k
    EvaluateFeatureLikeBuiltinMacro(
1857
1.31k
        OS, Tok, II, *this, false,
1858
1.31k
        [this](Token &Tok, bool &HasLexedNextToken) -> int {
1859
1.31k
          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1860
1.31k
              Tok, *this, diag::err_feature_check_malformed);
1861
1.31k
          return II && isTargetOS(getTargetInfo(), II);
1862
1.31k
        });
1863
1.31k
  } else 
if (871
II == Ident__is_target_environment871
) {
1864
871
    EvaluateFeatureLikeBuiltinMacro(
1865
871
        OS, Tok, II, *this, false,
1866
871
        [this](Token &Tok, bool &HasLexedNextToken) -> int {
1867
871
          IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1868
871
              Tok, *this, diag::err_feature_check_malformed);
1869
871
          return II && isTargetEnvironment(getTargetInfo(), II);
1870
871
        });
1871
871
  } else {
1872
0
    llvm_unreachable("Unknown identifier!");
1873
0
  }
1874
622k
  CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
1875
622k
  Tok.setFlagValue(Token::StartOfLine, IsAtStartOfLine);
1876
622k
  Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
1877
622k
}
1878
1879
59.3M
void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1880
  // If the 'used' status changed, and the macro requires 'unused' warning,
1881
  // remove its SourceLocation from the warn-for-unused-macro locations.
1882
59.3M
  if (MI->isWarnIfUnused() && 
!MI->isUsed()4
)
1883
4
    WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1884
59.3M
  MI->setIsUsed(true);
1885
59.3M
}