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