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 expasion for the
11 // preprocessor.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Lex/Preprocessor.h"
16 #include "MacroArgs.h"
17 #include "clang/Lex/MacroInfo.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Lex/LexDiagnostic.h"
22 #include "clang/Lex/CodeCompletionHandler.h"
23 #include "clang/Lex/ExternalPreprocessorSource.h"
24 #include "clang/Lex/LiteralSupport.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include <cstdio>
31 #include <ctime>
32 using namespace clang;
33 
34 MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
35   assert(II->hasMacroDefinition() && "Identifier is not a macro!");
36 
37   llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
38     = Macros.find(II);
39   if (Pos == Macros.end()) {
40     // Load this macro from the external source.
41     getExternalSource()->LoadMacroDefinition(II);
42     Pos = Macros.find(II);
43   }
44   assert(Pos != Macros.end() && "Identifier macro info is missing!");
45   return Pos->second;
46 }
47 
48 /// setMacroInfo - Specify a macro for this identifier.
49 ///
50 void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
51                                 bool LoadedFromAST) {
52   if (MI) {
53     Macros[II] = MI;
54     II->setHasMacroDefinition(true);
55     if (II->isFromAST() && !LoadedFromAST)
56       II->setChangedSinceDeserialization();
57   } else if (II->hasMacroDefinition()) {
58     Macros.erase(II);
59     II->setHasMacroDefinition(false);
60     if (II->isFromAST() && !LoadedFromAST)
61       II->setChangedSinceDeserialization();
62   }
63 }
64 
65 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
66 /// table and mark it as a builtin macro to be expanded.
67 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
68   // Get the identifier.
69   IdentifierInfo *Id = PP.getIdentifierInfo(Name);
70 
71   // Mark it as being a macro that is builtin.
72   MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
73   MI->setIsBuiltinMacro();
74   PP.setMacroInfo(Id, MI);
75   return Id;
76 }
77 
78 
79 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
80 /// identifier table.
81 void Preprocessor::RegisterBuiltinMacros() {
82   Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
83   Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
84   Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
85   Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
86   Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
87   Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
88 
89   // GCC Extensions.
90   Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
91   Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
92   Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
93 
94   // Clang Extensions.
95   Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
96   Ident__has_extension    = RegisterBuiltinMacro(*this, "__has_extension");
97   Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
98   Ident__has_attribute    = RegisterBuiltinMacro(*this, "__has_attribute");
99   Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
100   Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
101   Ident__has_warning      = RegisterBuiltinMacro(*this, "__has_warning");
102 
103   // Microsoft Extensions.
104   if (LangOpts.MicrosoftExt)
105     Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
106   else
107     Ident__pragma = 0;
108 }
109 
110 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
111 /// in its expansion, currently expands to that token literally.
112 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
113                                           const IdentifierInfo *MacroIdent,
114                                           Preprocessor &PP) {
115   IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
116 
117   // If the token isn't an identifier, it's always literally expanded.
118   if (II == 0) return true;
119 
120   // If the information about this identifier is out of date, update it from
121   // the external source.
122   if (II->isOutOfDate())
123     PP.getExternalSource()->updateOutOfDateIdentifier(*II);
124 
125   // If the identifier is a macro, and if that macro is enabled, it may be
126   // expanded so it's not a trivial expansion.
127   if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
128       // Fast expanding "#define X X" is ok, because X would be disabled.
129       II != MacroIdent)
130     return false;
131 
132   // If this is an object-like macro invocation, it is safe to trivially expand
133   // it.
134   if (MI->isObjectLike()) return true;
135 
136   // If this is a function-like macro invocation, it's safe to trivially expand
137   // as long as the identifier is not a macro argument.
138   for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
139        I != E; ++I)
140     if (*I == II)
141       return false;   // Identifier is a macro argument.
142 
143   return true;
144 }
145 
146 
147 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
148 /// lexed is a '('.  If so, consume the token and return true, if not, this
149 /// method should have no observable side-effect on the lexed tokens.
150 bool Preprocessor::isNextPPTokenLParen() {
151   // Do some quick tests for rejection cases.
152   unsigned Val;
153   if (CurLexer)
154     Val = CurLexer->isNextPPTokenLParen();
155   else if (CurPTHLexer)
156     Val = CurPTHLexer->isNextPPTokenLParen();
157   else
158     Val = CurTokenLexer->isNextTokenLParen();
159 
160   if (Val == 2) {
161     // We have run off the end.  If it's a source file we don't
162     // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
163     // macro stack.
164     if (CurPPLexer)
165       return false;
166     for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
167       IncludeStackInfo &Entry = IncludeMacroStack[i-1];
168       if (Entry.TheLexer)
169         Val = Entry.TheLexer->isNextPPTokenLParen();
170       else if (Entry.ThePTHLexer)
171         Val = Entry.ThePTHLexer->isNextPPTokenLParen();
172       else
173         Val = Entry.TheTokenLexer->isNextTokenLParen();
174 
175       if (Val != 2)
176         break;
177 
178       // Ran off the end of a source file?
179       if (Entry.ThePPLexer)
180         return false;
181     }
182   }
183 
184   // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
185   // have found something that isn't a '(' or we found the end of the
186   // translation unit.  In either case, return false.
187   return Val == 1;
188 }
189 
190 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
191 /// expanded as a macro, handle it and return the next token as 'Identifier'.
192 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
193                                                  MacroInfo *MI) {
194   // If this is a macro expansion in the "#if !defined(x)" line for the file,
195   // then the macro could expand to different things in other contexts, we need
196   // to disable the optimization in this case.
197   if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
198 
199   // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
200   if (MI->isBuiltinMacro()) {
201     if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
202                                            Identifier.getLocation());
203     ExpandBuiltinMacro(Identifier);
204     return false;
205   }
206 
207   /// Args - If this is a function-like macro expansion, this contains,
208   /// for each macro argument, the list of tokens that were provided to the
209   /// invocation.
210   MacroArgs *Args = 0;
211 
212   // Remember where the end of the expansion occurred.  For an object-like
213   // macro, this is the identifier.  For a function-like macro, this is the ')'.
214   SourceLocation ExpansionEnd = Identifier.getLocation();
215 
216   // If this is a function-like macro, read the arguments.
217   if (MI->isFunctionLike()) {
218     // C99 6.10.3p10: If the preprocessing token immediately after the the macro
219     // name isn't a '(', this macro should not be expanded.
220     if (!isNextPPTokenLParen())
221       return true;
222 
223     // Remember that we are now parsing the arguments to a macro invocation.
224     // Preprocessor directives used inside macro arguments are not portable, and
225     // this enables the warning.
226     InMacroArgs = true;
227     Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
228 
229     // Finished parsing args.
230     InMacroArgs = false;
231 
232     // If there was an error parsing the arguments, bail out.
233     if (Args == 0) return false;
234 
235     ++NumFnMacroExpanded;
236   } else {
237     ++NumMacroExpanded;
238   }
239 
240   // Notice that this macro has been used.
241   markMacroAsUsed(MI);
242 
243   // Remember where the token is expanded.
244   SourceLocation ExpandLoc = Identifier.getLocation();
245   SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
246 
247   if (Callbacks) {
248     if (InMacroArgs) {
249       // We can have macro expansion inside a conditional directive while
250       // reading the function macro arguments. To ensure, in that case, that
251       // MacroExpands callbacks still happen in source order, queue this
252       // callback to have it happen after the function macro callback.
253       DelayedMacroExpandsCallbacks.push_back(
254                               MacroExpandsInfo(Identifier, MI, ExpansionRange));
255     } else {
256       Callbacks->MacroExpands(Identifier, MI, ExpansionRange);
257       if (!DelayedMacroExpandsCallbacks.empty()) {
258         for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
259           MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
260           Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range);
261         }
262         DelayedMacroExpandsCallbacks.clear();
263       }
264     }
265   }
266 
267   // If we started lexing a macro, enter the macro expansion body.
268 
269   // If this macro expands to no tokens, don't bother to push it onto the
270   // expansion stack, only to take it right back off.
271   if (MI->getNumTokens() == 0) {
272     // No need for arg info.
273     if (Args) Args->destroy(*this);
274 
275     // Ignore this macro use, just return the next token in the current
276     // buffer.
277     bool HadLeadingSpace = Identifier.hasLeadingSpace();
278     bool IsAtStartOfLine = Identifier.isAtStartOfLine();
279 
280     Lex(Identifier);
281 
282     // If the identifier isn't on some OTHER line, inherit the leading
283     // whitespace/first-on-a-line property of this token.  This handles
284     // stuff like "! XX," -> "! ," and "   XX," -> "    ,", when XX is
285     // empty.
286     if (!Identifier.isAtStartOfLine()) {
287       if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
288       if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
289     }
290     Identifier.setFlag(Token::LeadingEmptyMacro);
291     ++NumFastMacroExpanded;
292     return false;
293 
294   } else if (MI->getNumTokens() == 1 &&
295              isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
296                                            *this)) {
297     // Otherwise, if this macro expands into a single trivially-expanded
298     // token: expand it now.  This handles common cases like
299     // "#define VAL 42".
300 
301     // No need for arg info.
302     if (Args) Args->destroy(*this);
303 
304     // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
305     // identifier to the expanded token.
306     bool isAtStartOfLine = Identifier.isAtStartOfLine();
307     bool hasLeadingSpace = Identifier.hasLeadingSpace();
308 
309     // Replace the result token.
310     Identifier = MI->getReplacementToken(0);
311 
312     // Restore the StartOfLine/LeadingSpace markers.
313     Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
314     Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
315 
316     // Update the tokens location to include both its expansion and physical
317     // locations.
318     SourceLocation Loc =
319       SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
320                                    ExpansionEnd,Identifier.getLength());
321     Identifier.setLocation(Loc);
322 
323     // If this is a disabled macro or #define X X, we must mark the result as
324     // unexpandable.
325     if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
326       if (MacroInfo *NewMI = getMacroInfo(NewII))
327         if (!NewMI->isEnabled() || NewMI == MI) {
328           Identifier.setFlag(Token::DisableExpand);
329           Diag(Identifier, diag::pp_disabled_macro_expansion);
330         }
331     }
332 
333     // Since this is not an identifier token, it can't be macro expanded, so
334     // we're done.
335     ++NumFastMacroExpanded;
336     return false;
337   }
338 
339   // Start expanding the macro.
340   EnterMacro(Identifier, ExpansionEnd, Args);
341 
342   // Now that the macro is at the top of the include stack, ask the
343   // preprocessor to read the next token from it.
344   Lex(Identifier);
345   return false;
346 }
347 
348 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
349 /// token is the '(' of the macro, this method is invoked to read all of the
350 /// actual arguments specified for the macro invocation.  This returns null on
351 /// error.
352 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
353                                                    MacroInfo *MI,
354                                                    SourceLocation &MacroEnd) {
355   // The number of fixed arguments to parse.
356   unsigned NumFixedArgsLeft = MI->getNumArgs();
357   bool isVariadic = MI->isVariadic();
358 
359   // Outer loop, while there are more arguments, keep reading them.
360   Token Tok;
361 
362   // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
363   // an argument value in a macro could expand to ',' or '(' or ')'.
364   LexUnexpandedToken(Tok);
365   assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
366 
367   // ArgTokens - Build up a list of tokens that make up each argument.  Each
368   // argument is separated by an EOF token.  Use a SmallVector so we can avoid
369   // heap allocations in the common case.
370   SmallVector<Token, 64> ArgTokens;
371 
372   unsigned NumActuals = 0;
373   while (Tok.isNot(tok::r_paren)) {
374     assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
375            "only expect argument separators here");
376 
377     unsigned ArgTokenStart = ArgTokens.size();
378     SourceLocation ArgStartLoc = Tok.getLocation();
379 
380     // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
381     // that we already consumed the first one.
382     unsigned NumParens = 0;
383 
384     while (1) {
385       // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
386       // an argument value in a macro could expand to ',' or '(' or ')'.
387       LexUnexpandedToken(Tok);
388 
389       if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
390         Diag(MacroName, diag::err_unterm_macro_invoc);
391         // Do not lose the EOF/EOD.  Return it to the client.
392         MacroName = Tok;
393         return 0;
394       } else if (Tok.is(tok::r_paren)) {
395         // If we found the ) token, the macro arg list is done.
396         if (NumParens-- == 0) {
397           MacroEnd = Tok.getLocation();
398           break;
399         }
400       } else if (Tok.is(tok::l_paren)) {
401         ++NumParens;
402       } else if (Tok.is(tok::comma) && NumParens == 0) {
403         // Comma ends this argument if there are more fixed arguments expected.
404         // However, if this is a variadic macro, and this is part of the
405         // variadic part, then the comma is just an argument token.
406         if (!isVariadic) break;
407         if (NumFixedArgsLeft > 1)
408           break;
409       } else if (Tok.is(tok::comment) && !KeepMacroComments) {
410         // If this is a comment token in the argument list and we're just in
411         // -C mode (not -CC mode), discard the comment.
412         continue;
413       } else if (Tok.getIdentifierInfo() != 0) {
414         // Reading macro arguments can cause macros that we are currently
415         // expanding from to be popped off the expansion stack.  Doing so causes
416         // them to be reenabled for expansion.  Here we record whether any
417         // identifiers we lex as macro arguments correspond to disabled macros.
418         // If so, we mark the token as noexpand.  This is a subtle aspect of
419         // C99 6.10.3.4p2.
420         if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
421           if (!MI->isEnabled())
422             Tok.setFlag(Token::DisableExpand);
423       } else if (Tok.is(tok::code_completion)) {
424         if (CodeComplete)
425           CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
426                                                   MI, NumActuals);
427         // Don't mark that we reached the code-completion point because the
428         // parser is going to handle the token and there will be another
429         // code-completion callback.
430       }
431 
432       ArgTokens.push_back(Tok);
433     }
434 
435     // If this was an empty argument list foo(), don't add this as an empty
436     // argument.
437     if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
438       break;
439 
440     // If this is not a variadic macro, and too many args were specified, emit
441     // an error.
442     if (!isVariadic && NumFixedArgsLeft == 0) {
443       if (ArgTokens.size() != ArgTokenStart)
444         ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
445 
446       // Emit the diagnostic at the macro name in case there is a missing ).
447       // Emitting it at the , could be far away from the macro name.
448       Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
449       return 0;
450     }
451 
452     // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
453     // other modes.
454     if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
455       Diag(Tok, LangOpts.CPlusPlus0x ?
456            diag::warn_cxx98_compat_empty_fnmacro_arg :
457            diag::ext_empty_fnmacro_arg);
458 
459     // Add a marker EOF token to the end of the token list for this argument.
460     Token EOFTok;
461     EOFTok.startToken();
462     EOFTok.setKind(tok::eof);
463     EOFTok.setLocation(Tok.getLocation());
464     EOFTok.setLength(0);
465     ArgTokens.push_back(EOFTok);
466     ++NumActuals;
467     assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
468     --NumFixedArgsLeft;
469   }
470 
471   // Okay, we either found the r_paren.  Check to see if we parsed too few
472   // arguments.
473   unsigned MinArgsExpected = MI->getNumArgs();
474 
475   // See MacroArgs instance var for description of this.
476   bool isVarargsElided = false;
477 
478   if (NumActuals < MinArgsExpected) {
479     // There are several cases where too few arguments is ok, handle them now.
480     if (NumActuals == 0 && MinArgsExpected == 1) {
481       // #define A(X)  or  #define A(...)   ---> A()
482 
483       // If there is exactly one argument, and that argument is missing,
484       // then we have an empty "()" argument empty list.  This is fine, even if
485       // the macro expects one argument (the argument is just empty).
486       isVarargsElided = MI->isVariadic();
487     } else if (MI->isVariadic() &&
488                (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
489                 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
490       // Varargs where the named vararg parameter is missing: OK as extension.
491       //   #define A(x, ...)
492       //   A("blah")
493       Diag(Tok, diag::ext_missing_varargs_arg);
494       Diag(MI->getDefinitionLoc(), diag::note_macro_here)
495         << MacroName.getIdentifierInfo();
496 
497       // Remember this occurred, allowing us to elide the comma when used for
498       // cases like:
499       //   #define A(x, foo...) blah(a, ## foo)
500       //   #define B(x, ...) blah(a, ## __VA_ARGS__)
501       //   #define C(...) blah(a, ## __VA_ARGS__)
502       //  A(x) B(x) C()
503       isVarargsElided = true;
504     } else {
505       // Otherwise, emit the error.
506       Diag(Tok, diag::err_too_few_args_in_macro_invoc);
507       return 0;
508     }
509 
510     // Add a marker EOF token to the end of the token list for this argument.
511     SourceLocation EndLoc = Tok.getLocation();
512     Tok.startToken();
513     Tok.setKind(tok::eof);
514     Tok.setLocation(EndLoc);
515     Tok.setLength(0);
516     ArgTokens.push_back(Tok);
517 
518     // If we expect two arguments, add both as empty.
519     if (NumActuals == 0 && MinArgsExpected == 2)
520       ArgTokens.push_back(Tok);
521 
522   } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
523     // Emit the diagnostic at the macro name in case there is a missing ).
524     // Emitting it at the , could be far away from the macro name.
525     Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
526     return 0;
527   }
528 
529   return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
530 }
531 
532 /// \brief Keeps macro expanded tokens for TokenLexers.
533 //
534 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
535 /// going to lex in the cache and when it finishes the tokens are removed
536 /// from the end of the cache.
537 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
538                                               ArrayRef<Token> tokens) {
539   assert(tokLexer);
540   if (tokens.empty())
541     return 0;
542 
543   size_t newIndex = MacroExpandedTokens.size();
544   bool cacheNeedsToGrow = tokens.size() >
545                       MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
546   MacroExpandedTokens.append(tokens.begin(), tokens.end());
547 
548   if (cacheNeedsToGrow) {
549     // Go through all the TokenLexers whose 'Tokens' pointer points in the
550     // buffer and update the pointers to the (potential) new buffer array.
551     for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
552       TokenLexer *prevLexer;
553       size_t tokIndex;
554       llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
555       prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
556     }
557   }
558 
559   MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
560   return MacroExpandedTokens.data() + newIndex;
561 }
562 
563 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
564   assert(!MacroExpandingLexersStack.empty());
565   size_t tokIndex = MacroExpandingLexersStack.back().second;
566   assert(tokIndex < MacroExpandedTokens.size());
567   // Pop the cached macro expanded tokens from the end.
568   MacroExpandedTokens.resize(tokIndex);
569   MacroExpandingLexersStack.pop_back();
570 }
571 
572 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
573 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
574 /// the identifier tokens inserted.
575 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
576                              Preprocessor &PP) {
577   time_t TT = time(0);
578   struct tm *TM = localtime(&TT);
579 
580   static const char * const Months[] = {
581     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
582   };
583 
584   char TmpBuffer[32];
585 #ifdef LLVM_ON_WIN32
586   sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
587           TM->tm_year+1900);
588 #else
589   snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
590           TM->tm_year+1900);
591 #endif
592 
593   Token TmpTok;
594   TmpTok.startToken();
595   PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
596   DATELoc = TmpTok.getLocation();
597 
598 #ifdef LLVM_ON_WIN32
599   sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
600 #else
601   snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
602 #endif
603   PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
604   TIMELoc = TmpTok.getLocation();
605 }
606 
607 
608 /// HasFeature - Return true if we recognize and implement the feature
609 /// specified by the identifier as a standard language feature.
610 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
611   const LangOptions &LangOpts = PP.getLangOpts();
612   StringRef Feature = II->getName();
613 
614   // Normalize the feature name, __foo__ becomes foo.
615   if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
616     Feature = Feature.substr(2, Feature.size() - 4);
617 
618   return llvm::StringSwitch<bool>(Feature)
619            .Case("address_sanitizer", LangOpts.AddressSanitizer)
620            .Case("attribute_analyzer_noreturn", true)
621            .Case("attribute_availability", true)
622            .Case("attribute_cf_returns_not_retained", true)
623            .Case("attribute_cf_returns_retained", true)
624            .Case("attribute_deprecated_with_message", true)
625            .Case("attribute_ext_vector_type", true)
626            .Case("attribute_ns_returns_not_retained", true)
627            .Case("attribute_ns_returns_retained", true)
628            .Case("attribute_ns_consumes_self", true)
629            .Case("attribute_ns_consumed", true)
630            .Case("attribute_cf_consumed", true)
631            .Case("attribute_objc_ivar_unused", true)
632            .Case("attribute_objc_method_family", true)
633            .Case("attribute_overloadable", true)
634            .Case("attribute_unavailable_with_message", true)
635            .Case("attribute_unused_on_fields", true)
636            .Case("blocks", LangOpts.Blocks)
637            .Case("cxx_exceptions", LangOpts.Exceptions)
638            .Case("cxx_rtti", LangOpts.RTTI)
639            .Case("enumerator_attributes", true)
640            // Objective-C features
641            .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
642            .Case("objc_arc", LangOpts.ObjCAutoRefCount)
643            .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
644                  LangOpts.ObjCRuntimeHasWeak)
645            .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
646            .Case("objc_fixed_enum", LangOpts.ObjC2)
647            .Case("objc_instancetype", LangOpts.ObjC2)
648            .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
649            .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
650            .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
651            .Case("ownership_holds", true)
652            .Case("ownership_returns", true)
653            .Case("ownership_takes", true)
654            .Case("objc_bool", true)
655            .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
656            .Case("objc_array_literals", LangOpts.ObjC2)
657            .Case("objc_dictionary_literals", LangOpts.ObjC2)
658            .Case("objc_boxed_expressions", LangOpts.ObjC2)
659            .Case("arc_cf_code_audited", true)
660            // C11 features
661            .Case("c_alignas", LangOpts.C11)
662            .Case("c_atomic", LangOpts.C11)
663            .Case("c_generic_selections", LangOpts.C11)
664            .Case("c_static_assert", LangOpts.C11)
665            // C++11 features
666            .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
667            .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
668            .Case("cxx_alignas", LangOpts.CPlusPlus0x)
669            .Case("cxx_atomic", LangOpts.CPlusPlus0x)
670            .Case("cxx_attributes", LangOpts.CPlusPlus0x)
671            .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
672            .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
673            .Case("cxx_decltype", LangOpts.CPlusPlus0x)
674            .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus0x)
675            .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
676            .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
677            .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
678            .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
679            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
680            .Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
681            .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
682          //.Case("cxx_inheriting_constructors", false)
683            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
684            .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
685            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus0x)
686            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
687            .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
688            .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
689            .Case("cxx_override_control", LangOpts.CPlusPlus0x)
690            .Case("cxx_range_for", LangOpts.CPlusPlus0x)
691            .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
692            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
693            .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
694            .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
695            .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
696            .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
697            .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
698            .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus0x)
699            .Case("cxx_user_literals", LangOpts.CPlusPlus0x)
700            .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
701            // Type traits
702            .Case("has_nothrow_assign", LangOpts.CPlusPlus)
703            .Case("has_nothrow_copy", LangOpts.CPlusPlus)
704            .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
705            .Case("has_trivial_assign", LangOpts.CPlusPlus)
706            .Case("has_trivial_copy", LangOpts.CPlusPlus)
707            .Case("has_trivial_constructor", LangOpts.CPlusPlus)
708            .Case("has_trivial_destructor", LangOpts.CPlusPlus)
709            .Case("has_virtual_destructor", LangOpts.CPlusPlus)
710            .Case("is_abstract", LangOpts.CPlusPlus)
711            .Case("is_base_of", LangOpts.CPlusPlus)
712            .Case("is_class", LangOpts.CPlusPlus)
713            .Case("is_convertible_to", LangOpts.CPlusPlus)
714             // __is_empty is available only if the horrible
715             // "struct __is_empty" parsing hack hasn't been needed in this
716             // translation unit. If it has, __is_empty reverts to a normal
717             // identifier and __has_feature(is_empty) evaluates false.
718            .Case("is_empty",
719                  LangOpts.CPlusPlus &&
720                  PP.getIdentifierInfo("__is_empty")->getTokenID()
721                                                             != tok::identifier)
722            .Case("is_enum", LangOpts.CPlusPlus)
723            .Case("is_final", LangOpts.CPlusPlus)
724            .Case("is_literal", LangOpts.CPlusPlus)
725            .Case("is_standard_layout", LangOpts.CPlusPlus)
726            // __is_pod is available only if the horrible
727            // "struct __is_pod" parsing hack hasn't been needed in this
728            // translation unit. If it has, __is_pod reverts to a normal
729            // identifier and __has_feature(is_pod) evaluates false.
730            .Case("is_pod",
731                  LangOpts.CPlusPlus &&
732                  PP.getIdentifierInfo("__is_pod")->getTokenID()
733                                                             != tok::identifier)
734            .Case("is_polymorphic", LangOpts.CPlusPlus)
735            .Case("is_trivial", LangOpts.CPlusPlus)
736            .Case("is_trivially_assignable", LangOpts.CPlusPlus)
737            .Case("is_trivially_constructible", LangOpts.CPlusPlus)
738            .Case("is_trivially_copyable", LangOpts.CPlusPlus)
739            .Case("is_union", LangOpts.CPlusPlus)
740            .Case("modules", LangOpts.Modules)
741            .Case("tls", PP.getTargetInfo().isTLSSupported())
742            .Case("underlying_type", LangOpts.CPlusPlus)
743            .Default(false);
744 }
745 
746 /// HasExtension - Return true if we recognize and implement the feature
747 /// specified by the identifier, either as an extension or a standard language
748 /// feature.
749 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
750   if (HasFeature(PP, II))
751     return true;
752 
753   // If the use of an extension results in an error diagnostic, extensions are
754   // effectively unavailable, so just return false here.
755   if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
756       DiagnosticsEngine::Ext_Error)
757     return false;
758 
759   const LangOptions &LangOpts = PP.getLangOpts();
760   StringRef Extension = II->getName();
761 
762   // Normalize the extension name, __foo__ becomes foo.
763   if (Extension.startswith("__") && Extension.endswith("__") &&
764       Extension.size() >= 4)
765     Extension = Extension.substr(2, Extension.size() - 4);
766 
767   // Because we inherit the feature list from HasFeature, this string switch
768   // must be less restrictive than HasFeature's.
769   return llvm::StringSwitch<bool>(Extension)
770            // C11 features supported by other languages as extensions.
771            .Case("c_alignas", true)
772            .Case("c_atomic", true)
773            .Case("c_generic_selections", true)
774            .Case("c_static_assert", true)
775            // C++0x features supported by other languages as extensions.
776            .Case("cxx_atomic", LangOpts.CPlusPlus)
777            .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
778            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
779            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
780            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
781            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
782            .Case("cxx_override_control", LangOpts.CPlusPlus)
783            .Case("cxx_range_for", LangOpts.CPlusPlus)
784            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
785            .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
786            .Default(false);
787 }
788 
789 /// HasAttribute -  Return true if we recognize and implement the attribute
790 /// specified by the given identifier.
791 static bool HasAttribute(const IdentifierInfo *II) {
792   StringRef Name = II->getName();
793   // Normalize the attribute name, __foo__ becomes foo.
794   if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
795     Name = Name.substr(2, Name.size() - 4);
796 
797   // FIXME: Do we need to handle namespaces here?
798   return llvm::StringSwitch<bool>(Name)
799 #include "clang/Lex/AttrSpellings.inc"
800         .Default(false);
801 }
802 
803 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
804 /// or '__has_include_next("path")' expression.
805 /// Returns true if successful.
806 static bool EvaluateHasIncludeCommon(Token &Tok,
807                                      IdentifierInfo *II, Preprocessor &PP,
808                                      const DirectoryLookup *LookupFrom) {
809   SourceLocation LParenLoc;
810 
811   // Get '('.
812   PP.LexNonComment(Tok);
813 
814   // Ensure we have a '('.
815   if (Tok.isNot(tok::l_paren)) {
816     PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
817     return false;
818   }
819 
820   // Save '(' location for possible missing ')' message.
821   LParenLoc = Tok.getLocation();
822 
823   // Get the file name.
824   PP.getCurrentLexer()->LexIncludeFilename(Tok);
825 
826   // Reserve a buffer to get the spelling.
827   SmallString<128> FilenameBuffer;
828   StringRef Filename;
829   SourceLocation EndLoc;
830 
831   switch (Tok.getKind()) {
832   case tok::eod:
833     // If the token kind is EOD, the error has already been diagnosed.
834     return false;
835 
836   case tok::angle_string_literal:
837   case tok::string_literal: {
838     bool Invalid = false;
839     Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
840     if (Invalid)
841       return false;
842     break;
843   }
844 
845   case tok::less:
846     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
847     // case, glue the tokens together into FilenameBuffer and interpret those.
848     FilenameBuffer.push_back('<');
849     if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
850       return false;   // Found <eod> but no ">"?  Diagnostic already emitted.
851     Filename = FilenameBuffer.str();
852     break;
853   default:
854     PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
855     return false;
856   }
857 
858   // Get ')'.
859   PP.LexNonComment(Tok);
860 
861   // Ensure we have a trailing ).
862   if (Tok.isNot(tok::r_paren)) {
863     PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
864     PP.Diag(LParenLoc, diag::note_matching) << "(";
865     return false;
866   }
867 
868   bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
869   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
870   // error.
871   if (Filename.empty())
872     return false;
873 
874   // Search include directories.
875   const DirectoryLookup *CurDir;
876   const FileEntry *File =
877       PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
878 
879   // Get the result value.  A result of true means the file exists.
880   return File != 0;
881 }
882 
883 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
884 /// Returns true if successful.
885 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
886                                Preprocessor &PP) {
887   return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
888 }
889 
890 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
891 /// Returns true if successful.
892 static bool EvaluateHasIncludeNext(Token &Tok,
893                                    IdentifierInfo *II, Preprocessor &PP) {
894   // __has_include_next is like __has_include, except that we start
895   // searching after the current found directory.  If we can't do this,
896   // issue a diagnostic.
897   const DirectoryLookup *Lookup = PP.GetCurDirLookup();
898   if (PP.isInPrimaryFile()) {
899     Lookup = 0;
900     PP.Diag(Tok, diag::pp_include_next_in_primary);
901   } else if (Lookup == 0) {
902     PP.Diag(Tok, diag::pp_include_next_absolute_path);
903   } else {
904     // Start looking up in the next directory.
905     ++Lookup;
906   }
907 
908   return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
909 }
910 
911 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
912 /// as a builtin macro, handle it and return the next token as 'Tok'.
913 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
914   // Figure out which token this is.
915   IdentifierInfo *II = Tok.getIdentifierInfo();
916   assert(II && "Can't be a macro without id info!");
917 
918   // If this is an _Pragma or Microsoft __pragma directive, expand it,
919   // invoke the pragma handler, then lex the token after it.
920   if (II == Ident_Pragma)
921     return Handle_Pragma(Tok);
922   else if (II == Ident__pragma) // in non-MS mode this is null
923     return HandleMicrosoft__pragma(Tok);
924 
925   ++NumBuiltinMacroExpanded;
926 
927   SmallString<128> TmpBuffer;
928   llvm::raw_svector_ostream OS(TmpBuffer);
929 
930   // Set up the return result.
931   Tok.setIdentifierInfo(0);
932   Tok.clearFlag(Token::NeedsCleaning);
933 
934   if (II == Ident__LINE__) {
935     // C99 6.10.8: "__LINE__: The presumed line number (within the current
936     // source file) of the current source line (an integer constant)".  This can
937     // be affected by #line.
938     SourceLocation Loc = Tok.getLocation();
939 
940     // Advance to the location of the first _, this might not be the first byte
941     // of the token if it starts with an escaped newline.
942     Loc = AdvanceToTokenCharacter(Loc, 0);
943 
944     // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
945     // a macro expansion.  This doesn't matter for object-like macros, but
946     // can matter for a function-like macro that expands to contain __LINE__.
947     // Skip down through expansion points until we find a file loc for the
948     // end of the expansion history.
949     Loc = SourceMgr.getExpansionRange(Loc).second;
950     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
951 
952     // __LINE__ expands to a simple numeric value.
953     OS << (PLoc.isValid()? PLoc.getLine() : 1);
954     Tok.setKind(tok::numeric_constant);
955   } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
956     // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
957     // character string literal)". This can be affected by #line.
958     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
959 
960     // __BASE_FILE__ is a GNU extension that returns the top of the presumed
961     // #include stack instead of the current file.
962     if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
963       SourceLocation NextLoc = PLoc.getIncludeLoc();
964       while (NextLoc.isValid()) {
965         PLoc = SourceMgr.getPresumedLoc(NextLoc);
966         if (PLoc.isInvalid())
967           break;
968 
969         NextLoc = PLoc.getIncludeLoc();
970       }
971     }
972 
973     // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
974     SmallString<128> FN;
975     if (PLoc.isValid()) {
976       FN += PLoc.getFilename();
977       Lexer::Stringify(FN);
978       OS << '"' << FN.str() << '"';
979     }
980     Tok.setKind(tok::string_literal);
981   } else if (II == Ident__DATE__) {
982     if (!DATELoc.isValid())
983       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
984     Tok.setKind(tok::string_literal);
985     Tok.setLength(strlen("\"Mmm dd yyyy\""));
986     Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
987                                                  Tok.getLocation(),
988                                                  Tok.getLength()));
989     return;
990   } else if (II == Ident__TIME__) {
991     if (!TIMELoc.isValid())
992       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
993     Tok.setKind(tok::string_literal);
994     Tok.setLength(strlen("\"hh:mm:ss\""));
995     Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
996                                                  Tok.getLocation(),
997                                                  Tok.getLength()));
998     return;
999   } else if (II == Ident__INCLUDE_LEVEL__) {
1000     // Compute the presumed include depth of this token.  This can be affected
1001     // by GNU line markers.
1002     unsigned Depth = 0;
1003 
1004     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1005     if (PLoc.isValid()) {
1006       PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1007       for (; PLoc.isValid(); ++Depth)
1008         PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1009     }
1010 
1011     // __INCLUDE_LEVEL__ expands to a simple numeric value.
1012     OS << Depth;
1013     Tok.setKind(tok::numeric_constant);
1014   } else if (II == Ident__TIMESTAMP__) {
1015     // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
1016     // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1017 
1018     // Get the file that we are lexing out of.  If we're currently lexing from
1019     // a macro, dig into the include stack.
1020     const FileEntry *CurFile = 0;
1021     PreprocessorLexer *TheLexer = getCurrentFileLexer();
1022 
1023     if (TheLexer)
1024       CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1025 
1026     const char *Result;
1027     if (CurFile) {
1028       time_t TT = CurFile->getModificationTime();
1029       struct tm *TM = localtime(&TT);
1030       Result = asctime(TM);
1031     } else {
1032       Result = "??? ??? ?? ??:??:?? ????\n";
1033     }
1034     // Surround the string with " and strip the trailing newline.
1035     OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1036     Tok.setKind(tok::string_literal);
1037   } else if (II == Ident__COUNTER__) {
1038     // __COUNTER__ expands to a simple numeric value.
1039     OS << CounterValue++;
1040     Tok.setKind(tok::numeric_constant);
1041   } else if (II == Ident__has_feature   ||
1042              II == Ident__has_extension ||
1043              II == Ident__has_builtin   ||
1044              II == Ident__has_attribute) {
1045     // The argument to these builtins should be a parenthesized identifier.
1046     SourceLocation StartLoc = Tok.getLocation();
1047 
1048     bool IsValid = false;
1049     IdentifierInfo *FeatureII = 0;
1050 
1051     // Read the '('.
1052     Lex(Tok);
1053     if (Tok.is(tok::l_paren)) {
1054       // Read the identifier
1055       Lex(Tok);
1056       if (Tok.is(tok::identifier)) {
1057         FeatureII = Tok.getIdentifierInfo();
1058 
1059         // Read the ')'.
1060         Lex(Tok);
1061         if (Tok.is(tok::r_paren))
1062           IsValid = true;
1063       }
1064     }
1065 
1066     bool Value = false;
1067     if (!IsValid)
1068       Diag(StartLoc, diag::err_feature_check_malformed);
1069     else if (II == Ident__has_builtin) {
1070       // Check for a builtin is trivial.
1071       Value = FeatureII->getBuiltinID() != 0;
1072     } else if (II == Ident__has_attribute)
1073       Value = HasAttribute(FeatureII);
1074     else if (II == Ident__has_extension)
1075       Value = HasExtension(*this, FeatureII);
1076     else {
1077       assert(II == Ident__has_feature && "Must be feature check");
1078       Value = HasFeature(*this, FeatureII);
1079     }
1080 
1081     OS << (int)Value;
1082     if (IsValid)
1083       Tok.setKind(tok::numeric_constant);
1084   } else if (II == Ident__has_include ||
1085              II == Ident__has_include_next) {
1086     // The argument to these two builtins should be a parenthesized
1087     // file name string literal using angle brackets (<>) or
1088     // double-quotes ("").
1089     bool Value;
1090     if (II == Ident__has_include)
1091       Value = EvaluateHasInclude(Tok, II, *this);
1092     else
1093       Value = EvaluateHasIncludeNext(Tok, II, *this);
1094     OS << (int)Value;
1095     Tok.setKind(tok::numeric_constant);
1096   } else if (II == Ident__has_warning) {
1097     // The argument should be a parenthesized string literal.
1098     // The argument to these builtins should be a parenthesized identifier.
1099     SourceLocation StartLoc = Tok.getLocation();
1100     bool IsValid = false;
1101     bool Value = false;
1102     // Read the '('.
1103     Lex(Tok);
1104     do {
1105       if (Tok.is(tok::l_paren)) {
1106         // Read the string.
1107         Lex(Tok);
1108 
1109         // We need at least one string literal.
1110         if (!Tok.is(tok::string_literal)) {
1111           StartLoc = Tok.getLocation();
1112           IsValid = false;
1113           // Eat tokens until ')'.
1114           do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1115           break;
1116         }
1117 
1118         // String concatenation allows multiple strings, which can even come
1119         // from macro expansion.
1120         SmallVector<Token, 4> StrToks;
1121         while (Tok.is(tok::string_literal)) {
1122           // Complain about, and drop, any ud-suffix.
1123           if (Tok.hasUDSuffix())
1124             Diag(Tok, diag::err_invalid_string_udl);
1125           StrToks.push_back(Tok);
1126           LexUnexpandedToken(Tok);
1127         }
1128 
1129         // Is the end a ')'?
1130         if (!(IsValid = Tok.is(tok::r_paren)))
1131           break;
1132 
1133         // Concatenate and parse the strings.
1134         StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1135         assert(Literal.isAscii() && "Didn't allow wide strings in");
1136         if (Literal.hadError)
1137           break;
1138         if (Literal.Pascal) {
1139           Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1140           break;
1141         }
1142 
1143         StringRef WarningName(Literal.GetString());
1144 
1145         if (WarningName.size() < 3 || WarningName[0] != '-' ||
1146             WarningName[1] != 'W') {
1147           Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1148           break;
1149         }
1150 
1151         // Finally, check if the warning flags maps to a diagnostic group.
1152         // We construct a SmallVector here to talk to getDiagnosticIDs().
1153         // Although we don't use the result, this isn't a hot path, and not
1154         // worth special casing.
1155         llvm::SmallVector<diag::kind, 10> Diags;
1156         Value = !getDiagnostics().getDiagnosticIDs()->
1157           getDiagnosticsInGroup(WarningName.substr(2), Diags);
1158       }
1159     } while (false);
1160 
1161     if (!IsValid)
1162       Diag(StartLoc, diag::err_warning_check_malformed);
1163 
1164     OS << (int)Value;
1165     Tok.setKind(tok::numeric_constant);
1166   } else {
1167     llvm_unreachable("Unknown identifier!");
1168   }
1169   CreateString(OS.str().data(), OS.str().size(), Tok,
1170                Tok.getLocation(), Tok.getLocation());
1171 }
1172 
1173 void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1174   // If the 'used' status changed, and the macro requires 'unused' warning,
1175   // remove its SourceLocation from the warn-for-unused-macro locations.
1176   if (MI->isWarnIfUnused() && !MI->isUsed())
1177     WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1178   MI->setIsUsed(true);
1179 }
1180