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