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