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