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