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