clang API Documentation

PPMacroExpansion.cpp
Go to the documentation of this file.
00001 //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the top level handling of macro expasion for the
00011 // preprocessor.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Lex/Preprocessor.h"
00016 #include "MacroArgs.h"
00017 #include "clang/Lex/MacroInfo.h"
00018 #include "clang/Basic/SourceManager.h"
00019 #include "clang/Basic/FileManager.h"
00020 #include "clang/Basic/TargetInfo.h"
00021 #include "clang/Lex/LexDiagnostic.h"
00022 #include "clang/Lex/CodeCompletionHandler.h"
00023 #include "clang/Lex/ExternalPreprocessorSource.h"
00024 #include "clang/Lex/LiteralSupport.h"
00025 #include "llvm/ADT/StringSwitch.h"
00026 #include "llvm/ADT/STLExtras.h"
00027 #include "llvm/Config/llvm-config.h"
00028 #include "llvm/Support/raw_ostream.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include <cstdio>
00031 #include <ctime>
00032 using namespace clang;
00033 
00034 MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
00035   assert(II->hasMacroDefinition() && "Identifier is not a macro!");
00036   
00037   llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
00038     = Macros.find(II);
00039   if (Pos == Macros.end()) {
00040     // Load this macro from the external source.
00041     getExternalSource()->LoadMacroDefinition(II);
00042     Pos = Macros.find(II);
00043   }
00044   assert(Pos != Macros.end() && "Identifier macro info is missing!");
00045   return Pos->second;
00046 }
00047 
00048 /// setMacroInfo - Specify a macro for this identifier.
00049 ///
00050 void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
00051                                 bool LoadedFromAST) {
00052   if (MI) {
00053     Macros[II] = MI;
00054     II->setHasMacroDefinition(true);
00055     if (II->isFromAST() && !LoadedFromAST)
00056       II->setChangedSinceDeserialization();
00057   } else if (II->hasMacroDefinition()) {
00058     Macros.erase(II);
00059     II->setHasMacroDefinition(false);
00060     if (II->isFromAST() && !LoadedFromAST)
00061       II->setChangedSinceDeserialization();
00062   }
00063 }
00064 
00065 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
00066 /// table and mark it as a builtin macro to be expanded.
00067 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
00068   // Get the identifier.
00069   IdentifierInfo *Id = PP.getIdentifierInfo(Name);
00070 
00071   // Mark it as being a macro that is builtin.
00072   MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
00073   MI->setIsBuiltinMacro();
00074   PP.setMacroInfo(Id, MI);
00075   return Id;
00076 }
00077 
00078 
00079 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
00080 /// identifier table.
00081 void Preprocessor::RegisterBuiltinMacros() {
00082   Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
00083   Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
00084   Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
00085   Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
00086   Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
00087   Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
00088 
00089   // GCC Extensions.
00090   Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
00091   Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
00092   Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
00093 
00094   // Clang Extensions.
00095   Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
00096   Ident__has_extension    = RegisterBuiltinMacro(*this, "__has_extension");
00097   Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
00098   Ident__has_attribute    = RegisterBuiltinMacro(*this, "__has_attribute");
00099   Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
00100   Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
00101   Ident__has_warning      = RegisterBuiltinMacro(*this, "__has_warning");
00102 
00103   // Microsoft Extensions.
00104   if (LangOpts.MicrosoftExt) 
00105     Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
00106   else
00107     Ident__pragma = 0;
00108 }
00109 
00110 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
00111 /// in its expansion, currently expands to that token literally.
00112 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
00113                                           const IdentifierInfo *MacroIdent,
00114                                           Preprocessor &PP) {
00115   IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
00116 
00117   // If the token isn't an identifier, it's always literally expanded.
00118   if (II == 0) return true;
00119 
00120   // If the information about this identifier is out of date, update it from
00121   // the external source.
00122   if (II->isOutOfDate())
00123     PP.getExternalSource()->updateOutOfDateIdentifier(*II);
00124 
00125   // If the identifier is a macro, and if that macro is enabled, it may be
00126   // expanded so it's not a trivial expansion.
00127   if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
00128       // Fast expanding "#define X X" is ok, because X would be disabled.
00129       II != MacroIdent)
00130     return false;
00131 
00132   // If this is an object-like macro invocation, it is safe to trivially expand
00133   // it.
00134   if (MI->isObjectLike()) return true;
00135 
00136   // If this is a function-like macro invocation, it's safe to trivially expand
00137   // as long as the identifier is not a macro argument.
00138   for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
00139        I != E; ++I)
00140     if (*I == II)
00141       return false;   // Identifier is a macro argument.
00142 
00143   return true;
00144 }
00145 
00146 
00147 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
00148 /// lexed is a '('.  If so, consume the token and return true, if not, this
00149 /// method should have no observable side-effect on the lexed tokens.
00150 bool Preprocessor::isNextPPTokenLParen() {
00151   // Do some quick tests for rejection cases.
00152   unsigned Val;
00153   if (CurLexer)
00154     Val = CurLexer->isNextPPTokenLParen();
00155   else if (CurPTHLexer)
00156     Val = CurPTHLexer->isNextPPTokenLParen();
00157   else
00158     Val = CurTokenLexer->isNextTokenLParen();
00159 
00160   if (Val == 2) {
00161     // We have run off the end.  If it's a source file we don't
00162     // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
00163     // macro stack.
00164     if (CurPPLexer)
00165       return false;
00166     for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
00167       IncludeStackInfo &Entry = IncludeMacroStack[i-1];
00168       if (Entry.TheLexer)
00169         Val = Entry.TheLexer->isNextPPTokenLParen();
00170       else if (Entry.ThePTHLexer)
00171         Val = Entry.ThePTHLexer->isNextPPTokenLParen();
00172       else
00173         Val = Entry.TheTokenLexer->isNextTokenLParen();
00174 
00175       if (Val != 2)
00176         break;
00177 
00178       // Ran off the end of a source file?
00179       if (Entry.ThePPLexer)
00180         return false;
00181     }
00182   }
00183 
00184   // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
00185   // have found something that isn't a '(' or we found the end of the
00186   // translation unit.  In either case, return false.
00187   return Val == 1;
00188 }
00189 
00190 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
00191 /// expanded as a macro, handle it and return the next token as 'Identifier'.
00192 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
00193                                                  MacroInfo *MI) {
00194   // If this is a macro expansion in the "#if !defined(x)" line for the file,
00195   // then the macro could expand to different things in other contexts, we need
00196   // to disable the optimization in this case.
00197   if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
00198 
00199   // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
00200   if (MI->isBuiltinMacro()) {
00201     if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
00202                                            Identifier.getLocation());
00203     ExpandBuiltinMacro(Identifier);
00204     return false;
00205   }
00206 
00207   /// Args - If this is a function-like macro expansion, this contains,
00208   /// for each macro argument, the list of tokens that were provided to the
00209   /// invocation.
00210   MacroArgs *Args = 0;
00211 
00212   // Remember where the end of the expansion occurred.  For an object-like
00213   // macro, this is the identifier.  For a function-like macro, this is the ')'.
00214   SourceLocation ExpansionEnd = Identifier.getLocation();
00215 
00216   // If this is a function-like macro, read the arguments.
00217   if (MI->isFunctionLike()) {
00218     // C99 6.10.3p10: If the preprocessing token immediately after the the macro
00219     // name isn't a '(', this macro should not be expanded.
00220     if (!isNextPPTokenLParen())
00221       return true;
00222 
00223     // Remember that we are now parsing the arguments to a macro invocation.
00224     // Preprocessor directives used inside macro arguments are not portable, and
00225     // this enables the warning.
00226     InMacroArgs = true;
00227     Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
00228 
00229     // Finished parsing args.
00230     InMacroArgs = false;
00231 
00232     // If there was an error parsing the arguments, bail out.
00233     if (Args == 0) return false;
00234 
00235     ++NumFnMacroExpanded;
00236   } else {
00237     ++NumMacroExpanded;
00238   }
00239 
00240   // Notice that this macro has been used.
00241   markMacroAsUsed(MI);
00242 
00243   // Remember where the token is expanded.
00244   SourceLocation ExpandLoc = Identifier.getLocation();
00245   SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
00246 
00247   if (Callbacks) {
00248     if (InMacroArgs) {
00249       // We can have macro expansion inside a conditional directive while
00250       // reading the function macro arguments. To ensure, in that case, that
00251       // MacroExpands callbacks still happen in source order, queue this
00252       // callback to have it happen after the function macro callback.
00253       DelayedMacroExpandsCallbacks.push_back(
00254                               MacroExpandsInfo(Identifier, MI, ExpansionRange));
00255     } else {
00256       Callbacks->MacroExpands(Identifier, MI, ExpansionRange);
00257       if (!DelayedMacroExpandsCallbacks.empty()) {
00258         for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
00259           MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
00260           Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range);
00261         }
00262         DelayedMacroExpandsCallbacks.clear();
00263       }
00264     }
00265   }
00266   
00267   // If we started lexing a macro, enter the macro expansion body.
00268 
00269   // If this macro expands to no tokens, don't bother to push it onto the
00270   // expansion stack, only to take it right back off.
00271   if (MI->getNumTokens() == 0) {
00272     // No need for arg info.
00273     if (Args) Args->destroy(*this);
00274 
00275     // Ignore this macro use, just return the next token in the current
00276     // buffer.
00277     bool HadLeadingSpace = Identifier.hasLeadingSpace();
00278     bool IsAtStartOfLine = Identifier.isAtStartOfLine();
00279 
00280     Lex(Identifier);
00281 
00282     // If the identifier isn't on some OTHER line, inherit the leading
00283     // whitespace/first-on-a-line property of this token.  This handles
00284     // stuff like "! XX," -> "! ," and "   XX," -> "    ,", when XX is
00285     // empty.
00286     if (!Identifier.isAtStartOfLine()) {
00287       if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
00288       if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
00289     }
00290     Identifier.setFlag(Token::LeadingEmptyMacro);
00291     ++NumFastMacroExpanded;
00292     return false;
00293 
00294   } else if (MI->getNumTokens() == 1 &&
00295              isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
00296                                            *this)) {
00297     // Otherwise, if this macro expands into a single trivially-expanded
00298     // token: expand it now.  This handles common cases like
00299     // "#define VAL 42".
00300 
00301     // No need for arg info.
00302     if (Args) Args->destroy(*this);
00303 
00304     // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
00305     // identifier to the expanded token.
00306     bool isAtStartOfLine = Identifier.isAtStartOfLine();
00307     bool hasLeadingSpace = Identifier.hasLeadingSpace();
00308 
00309     // Replace the result token.
00310     Identifier = MI->getReplacementToken(0);
00311 
00312     // Restore the StartOfLine/LeadingSpace markers.
00313     Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
00314     Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
00315 
00316     // Update the tokens location to include both its expansion and physical
00317     // locations.
00318     SourceLocation Loc =
00319       SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
00320                                    ExpansionEnd,Identifier.getLength());
00321     Identifier.setLocation(Loc);
00322 
00323     // If this is a disabled macro or #define X X, we must mark the result as
00324     // unexpandable.
00325     if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
00326       if (MacroInfo *NewMI = getMacroInfo(NewII))
00327         if (!NewMI->isEnabled() || NewMI == MI) {
00328           Identifier.setFlag(Token::DisableExpand);
00329           Diag(Identifier, diag::pp_disabled_macro_expansion);
00330         }
00331     }
00332 
00333     // Since this is not an identifier token, it can't be macro expanded, so
00334     // we're done.
00335     ++NumFastMacroExpanded;
00336     return false;
00337   }
00338 
00339   // Start expanding the macro.
00340   EnterMacro(Identifier, ExpansionEnd, Args);
00341 
00342   // Now that the macro is at the top of the include stack, ask the
00343   // preprocessor to read the next token from it.
00344   Lex(Identifier);
00345   return false;
00346 }
00347 
00348 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
00349 /// token is the '(' of the macro, this method is invoked to read all of the
00350 /// actual arguments specified for the macro invocation.  This returns null on
00351 /// error.
00352 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
00353                                                    MacroInfo *MI,
00354                                                    SourceLocation &MacroEnd) {
00355   // The number of fixed arguments to parse.
00356   unsigned NumFixedArgsLeft = MI->getNumArgs();
00357   bool isVariadic = MI->isVariadic();
00358 
00359   // Outer loop, while there are more arguments, keep reading them.
00360   Token Tok;
00361 
00362   // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
00363   // an argument value in a macro could expand to ',' or '(' or ')'.
00364   LexUnexpandedToken(Tok);
00365   assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
00366 
00367   // ArgTokens - Build up a list of tokens that make up each argument.  Each
00368   // argument is separated by an EOF token.  Use a SmallVector so we can avoid
00369   // heap allocations in the common case.
00370   SmallVector<Token, 64> ArgTokens;
00371 
00372   unsigned NumActuals = 0;
00373   while (Tok.isNot(tok::r_paren)) {
00374     assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
00375            "only expect argument separators here");
00376 
00377     unsigned ArgTokenStart = ArgTokens.size();
00378     SourceLocation ArgStartLoc = Tok.getLocation();
00379 
00380     // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
00381     // that we already consumed the first one.
00382     unsigned NumParens = 0;
00383 
00384     while (1) {
00385       // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
00386       // an argument value in a macro could expand to ',' or '(' or ')'.
00387       LexUnexpandedToken(Tok);
00388 
00389       if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
00390         Diag(MacroName, diag::err_unterm_macro_invoc);
00391         // Do not lose the EOF/EOD.  Return it to the client.
00392         MacroName = Tok;
00393         return 0;
00394       } else if (Tok.is(tok::r_paren)) {
00395         // If we found the ) token, the macro arg list is done.
00396         if (NumParens-- == 0) {
00397           MacroEnd = Tok.getLocation();
00398           break;
00399         }
00400       } else if (Tok.is(tok::l_paren)) {
00401         ++NumParens;
00402       } else if (Tok.is(tok::comma) && NumParens == 0) {
00403         // Comma ends this argument if there are more fixed arguments expected.
00404         // However, if this is a variadic macro, and this is part of the
00405         // variadic part, then the comma is just an argument token.
00406         if (!isVariadic) break;
00407         if (NumFixedArgsLeft > 1)
00408           break;
00409       } else if (Tok.is(tok::comment) && !KeepMacroComments) {
00410         // If this is a comment token in the argument list and we're just in
00411         // -C mode (not -CC mode), discard the comment.
00412         continue;
00413       } else if (Tok.getIdentifierInfo() != 0) {
00414         // Reading macro arguments can cause macros that we are currently
00415         // expanding from to be popped off the expansion stack.  Doing so causes
00416         // them to be reenabled for expansion.  Here we record whether any
00417         // identifiers we lex as macro arguments correspond to disabled macros.
00418         // If so, we mark the token as noexpand.  This is a subtle aspect of
00419         // C99 6.10.3.4p2.
00420         if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
00421           if (!MI->isEnabled())
00422             Tok.setFlag(Token::DisableExpand);
00423       } else if (Tok.is(tok::code_completion)) {
00424         if (CodeComplete)
00425           CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
00426                                                   MI, NumActuals);
00427         // Don't mark that we reached the code-completion point because the
00428         // parser is going to handle the token and there will be another
00429         // code-completion callback.
00430       }
00431 
00432       ArgTokens.push_back(Tok);
00433     }
00434 
00435     // If this was an empty argument list foo(), don't add this as an empty
00436     // argument.
00437     if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
00438       break;
00439 
00440     // If this is not a variadic macro, and too many args were specified, emit
00441     // an error.
00442     if (!isVariadic && NumFixedArgsLeft == 0) {
00443       if (ArgTokens.size() != ArgTokenStart)
00444         ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
00445 
00446       // Emit the diagnostic at the macro name in case there is a missing ).
00447       // Emitting it at the , could be far away from the macro name.
00448       Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
00449       return 0;
00450     }
00451 
00452     // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
00453     // other modes.
00454     if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
00455       Diag(Tok, LangOpts.CPlusPlus0x ?
00456            diag::warn_cxx98_compat_empty_fnmacro_arg :
00457            diag::ext_empty_fnmacro_arg);
00458 
00459     // Add a marker EOF token to the end of the token list for this argument.
00460     Token EOFTok;
00461     EOFTok.startToken();
00462     EOFTok.setKind(tok::eof);
00463     EOFTok.setLocation(Tok.getLocation());
00464     EOFTok.setLength(0);
00465     ArgTokens.push_back(EOFTok);
00466     ++NumActuals;
00467     assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
00468     --NumFixedArgsLeft;
00469   }
00470 
00471   // Okay, we either found the r_paren.  Check to see if we parsed too few
00472   // arguments.
00473   unsigned MinArgsExpected = MI->getNumArgs();
00474 
00475   // See MacroArgs instance var for description of this.
00476   bool isVarargsElided = false;
00477 
00478   if (NumActuals < MinArgsExpected) {
00479     // There are several cases where too few arguments is ok, handle them now.
00480     if (NumActuals == 0 && MinArgsExpected == 1) {
00481       // #define A(X)  or  #define A(...)   ---> A()
00482 
00483       // If there is exactly one argument, and that argument is missing,
00484       // then we have an empty "()" argument empty list.  This is fine, even if
00485       // the macro expects one argument (the argument is just empty).
00486       isVarargsElided = MI->isVariadic();
00487     } else if (MI->isVariadic() &&
00488                (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
00489                 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
00490       // Varargs where the named vararg parameter is missing: ok as extension.
00491       // #define A(x, ...)
00492       // A("blah")
00493       Diag(Tok, diag::ext_missing_varargs_arg);
00494 
00495       // Remember this occurred, allowing us to elide the comma when used for
00496       // cases like:
00497       //   #define A(x, foo...) blah(a, ## foo)
00498       //   #define B(x, ...) blah(a, ## __VA_ARGS__)
00499       //   #define C(...) blah(a, ## __VA_ARGS__)
00500       //  A(x) B(x) C()
00501       isVarargsElided = true;
00502     } else {
00503       // Otherwise, emit the error.
00504       Diag(Tok, diag::err_too_few_args_in_macro_invoc);
00505       return 0;
00506     }
00507 
00508     // Add a marker EOF token to the end of the token list for this argument.
00509     SourceLocation EndLoc = Tok.getLocation();
00510     Tok.startToken();
00511     Tok.setKind(tok::eof);
00512     Tok.setLocation(EndLoc);
00513     Tok.setLength(0);
00514     ArgTokens.push_back(Tok);
00515 
00516     // If we expect two arguments, add both as empty.
00517     if (NumActuals == 0 && MinArgsExpected == 2)
00518       ArgTokens.push_back(Tok);
00519 
00520   } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
00521     // Emit the diagnostic at the macro name in case there is a missing ).
00522     // Emitting it at the , could be far away from the macro name.
00523     Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
00524     return 0;
00525   }
00526 
00527   return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
00528 }
00529 
00530 /// \brief Keeps macro expanded tokens for TokenLexers.
00531 //
00532 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
00533 /// going to lex in the cache and when it finishes the tokens are removed
00534 /// from the end of the cache.
00535 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
00536                                               ArrayRef<Token> tokens) {
00537   assert(tokLexer);
00538   if (tokens.empty())
00539     return 0;
00540 
00541   size_t newIndex = MacroExpandedTokens.size();
00542   bool cacheNeedsToGrow = tokens.size() >
00543                       MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); 
00544   MacroExpandedTokens.append(tokens.begin(), tokens.end());
00545 
00546   if (cacheNeedsToGrow) {
00547     // Go through all the TokenLexers whose 'Tokens' pointer points in the
00548     // buffer and update the pointers to the (potential) new buffer array.
00549     for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
00550       TokenLexer *prevLexer;
00551       size_t tokIndex;
00552       llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
00553       prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
00554     }
00555   }
00556 
00557   MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
00558   return MacroExpandedTokens.data() + newIndex;
00559 }
00560 
00561 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
00562   assert(!MacroExpandingLexersStack.empty());
00563   size_t tokIndex = MacroExpandingLexersStack.back().second;
00564   assert(tokIndex < MacroExpandedTokens.size());
00565   // Pop the cached macro expanded tokens from the end.
00566   MacroExpandedTokens.resize(tokIndex);
00567   MacroExpandingLexersStack.pop_back();
00568 }
00569 
00570 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
00571 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
00572 /// the identifier tokens inserted.
00573 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
00574                              Preprocessor &PP) {
00575   time_t TT = time(0);
00576   struct tm *TM = localtime(&TT);
00577 
00578   static const char * const Months[] = {
00579     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
00580   };
00581 
00582   char TmpBuffer[32];
00583 #ifdef LLVM_ON_WIN32
00584   sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
00585           TM->tm_year+1900);
00586 #else
00587   snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
00588           TM->tm_year+1900);
00589 #endif
00590 
00591   Token TmpTok;
00592   TmpTok.startToken();
00593   PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
00594   DATELoc = TmpTok.getLocation();
00595 
00596 #ifdef LLVM_ON_WIN32
00597   sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
00598 #else
00599   snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
00600 #endif
00601   PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
00602   TIMELoc = TmpTok.getLocation();
00603 }
00604 
00605 
00606 /// HasFeature - Return true if we recognize and implement the feature
00607 /// specified by the identifier as a standard language feature.
00608 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
00609   const LangOptions &LangOpts = PP.getLangOpts();
00610   StringRef Feature = II->getName();
00611 
00612   // Normalize the feature name, __foo__ becomes foo.
00613   if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
00614     Feature = Feature.substr(2, Feature.size() - 4);
00615 
00616   return llvm::StringSwitch<bool>(Feature)
00617            .Case("address_sanitizer", LangOpts.AddressSanitizer)
00618            .Case("attribute_analyzer_noreturn", true)
00619            .Case("attribute_availability", true)
00620            .Case("attribute_cf_returns_not_retained", true)
00621            .Case("attribute_cf_returns_retained", true)
00622            .Case("attribute_deprecated_with_message", true)
00623            .Case("attribute_ext_vector_type", true)
00624            .Case("attribute_ns_returns_not_retained", true)
00625            .Case("attribute_ns_returns_retained", true)
00626            .Case("attribute_ns_consumes_self", true)
00627            .Case("attribute_ns_consumed", true)
00628            .Case("attribute_cf_consumed", true)
00629            .Case("attribute_objc_ivar_unused", true)
00630            .Case("attribute_objc_method_family", true)
00631            .Case("attribute_overloadable", true)
00632            .Case("attribute_unavailable_with_message", true)
00633            .Case("blocks", LangOpts.Blocks)
00634            .Case("cxx_exceptions", LangOpts.Exceptions)
00635            .Case("cxx_rtti", LangOpts.RTTI)
00636            .Case("enumerator_attributes", true)
00637            // Objective-C features
00638            .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
00639            .Case("objc_arc", LangOpts.ObjCAutoRefCount)
00640            .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount && 
00641                  LangOpts.ObjCRuntimeHasWeak)
00642            .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
00643            .Case("objc_fixed_enum", LangOpts.ObjC2)
00644            .Case("objc_instancetype", LangOpts.ObjC2)
00645            .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
00646            .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
00647            .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
00648            .Case("ownership_holds", true)
00649            .Case("ownership_returns", true)
00650            .Case("ownership_takes", true)
00651            .Case("objc_bool", true)
00652            .Case("objc_subscripting", LangOpts.ObjCNonFragileABI)
00653            .Case("objc_array_literals", LangOpts.ObjC2)
00654            .Case("objc_dictionary_literals", LangOpts.ObjC2)
00655            .Case("objc_boxed_expressions", LangOpts.ObjC2)
00656            .Case("arc_cf_code_audited", true)
00657            // C11 features
00658            .Case("c_alignas", LangOpts.C11)
00659            .Case("c_atomic", LangOpts.C11)
00660            .Case("c_generic_selections", LangOpts.C11)
00661            .Case("c_static_assert", LangOpts.C11)
00662            // C++11 features
00663            .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
00664            .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
00665            .Case("cxx_alignas", LangOpts.CPlusPlus0x)
00666            .Case("cxx_atomic", LangOpts.CPlusPlus0x)
00667            .Case("cxx_attributes", LangOpts.CPlusPlus0x)
00668            .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
00669            .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
00670            .Case("cxx_decltype", LangOpts.CPlusPlus0x)
00671            .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus0x)
00672            .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
00673            .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
00674            .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
00675            .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
00676            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
00677            .Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
00678            .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
00679          //.Case("cxx_inheriting_constructors", false)
00680            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
00681            .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
00682            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus0x)
00683            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
00684            .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
00685            .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
00686            .Case("cxx_override_control", LangOpts.CPlusPlus0x)
00687            .Case("cxx_range_for", LangOpts.CPlusPlus0x)
00688            .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
00689            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
00690            .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
00691            .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
00692            .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
00693            .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
00694            .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
00695            .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus0x)
00696            .Case("cxx_user_literals", LangOpts.CPlusPlus0x)
00697            .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
00698            // Type traits
00699            .Case("has_nothrow_assign", LangOpts.CPlusPlus)
00700            .Case("has_nothrow_copy", LangOpts.CPlusPlus)
00701            .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
00702            .Case("has_trivial_assign", LangOpts.CPlusPlus)
00703            .Case("has_trivial_copy", LangOpts.CPlusPlus)
00704            .Case("has_trivial_constructor", LangOpts.CPlusPlus)
00705            .Case("has_trivial_destructor", LangOpts.CPlusPlus)
00706            .Case("has_virtual_destructor", LangOpts.CPlusPlus)
00707            .Case("is_abstract", LangOpts.CPlusPlus)
00708            .Case("is_base_of", LangOpts.CPlusPlus)
00709            .Case("is_class", LangOpts.CPlusPlus)
00710            .Case("is_convertible_to", LangOpts.CPlusPlus)
00711             // __is_empty is available only if the horrible
00712             // "struct __is_empty" parsing hack hasn't been needed in this
00713             // translation unit. If it has, __is_empty reverts to a normal
00714             // identifier and __has_feature(is_empty) evaluates false.
00715            .Case("is_empty", 
00716                  LangOpts.CPlusPlus && 
00717                  PP.getIdentifierInfo("__is_empty")->getTokenID()
00718                                                             != tok::identifier)
00719            .Case("is_enum", LangOpts.CPlusPlus)
00720            .Case("is_final", LangOpts.CPlusPlus)
00721            .Case("is_literal", LangOpts.CPlusPlus)
00722            .Case("is_standard_layout", LangOpts.CPlusPlus)
00723            // __is_pod is available only if the horrible
00724            // "struct __is_pod" parsing hack hasn't been needed in this
00725            // translation unit. If it has, __is_pod reverts to a normal
00726            // identifier and __has_feature(is_pod) evaluates false.
00727            .Case("is_pod", 
00728                  LangOpts.CPlusPlus && 
00729                  PP.getIdentifierInfo("__is_pod")->getTokenID()
00730                                                             != tok::identifier)
00731            .Case("is_polymorphic", LangOpts.CPlusPlus)
00732            .Case("is_trivial", LangOpts.CPlusPlus)
00733            .Case("is_trivially_assignable", LangOpts.CPlusPlus)
00734            .Case("is_trivially_constructible", LangOpts.CPlusPlus)
00735            .Case("is_trivially_copyable", LangOpts.CPlusPlus)
00736            .Case("is_union", LangOpts.CPlusPlus)
00737            .Case("modules", LangOpts.Modules)
00738            .Case("tls", PP.getTargetInfo().isTLSSupported())
00739            .Case("underlying_type", LangOpts.CPlusPlus)
00740            .Default(false);
00741 }
00742 
00743 /// HasExtension - Return true if we recognize and implement the feature
00744 /// specified by the identifier, either as an extension or a standard language
00745 /// feature.
00746 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
00747   if (HasFeature(PP, II))
00748     return true;
00749 
00750   // If the use of an extension results in an error diagnostic, extensions are
00751   // effectively unavailable, so just return false here.
00752   if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
00753       DiagnosticsEngine::Ext_Error)
00754     return false;
00755 
00756   const LangOptions &LangOpts = PP.getLangOpts();
00757   StringRef Extension = II->getName();
00758 
00759   // Normalize the extension name, __foo__ becomes foo.
00760   if (Extension.startswith("__") && Extension.endswith("__") &&
00761       Extension.size() >= 4)
00762     Extension = Extension.substr(2, Extension.size() - 4);
00763 
00764   // Because we inherit the feature list from HasFeature, this string switch
00765   // must be less restrictive than HasFeature's.
00766   return llvm::StringSwitch<bool>(Extension)
00767            // C11 features supported by other languages as extensions.
00768            .Case("c_alignas", true)
00769            .Case("c_atomic", true)
00770            .Case("c_generic_selections", true)
00771            .Case("c_static_assert", true)
00772            // C++0x features supported by other languages as extensions.
00773            .Case("cxx_atomic", LangOpts.CPlusPlus)
00774            .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
00775            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
00776            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
00777            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
00778            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
00779            .Case("cxx_override_control", LangOpts.CPlusPlus)
00780            .Case("cxx_range_for", LangOpts.CPlusPlus)
00781            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
00782            .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
00783            .Default(false);
00784 }
00785 
00786 /// HasAttribute -  Return true if we recognize and implement the attribute
00787 /// specified by the given identifier.
00788 static bool HasAttribute(const IdentifierInfo *II) {
00789   StringRef Name = II->getName();
00790   // Normalize the attribute name, __foo__ becomes foo.
00791   if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
00792     Name = Name.substr(2, Name.size() - 4);
00793 
00794   return llvm::StringSwitch<bool>(Name)
00795 #include "clang/Lex/AttrSpellings.inc"
00796         .Default(false);
00797 }
00798 
00799 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
00800 /// or '__has_include_next("path")' expression.
00801 /// Returns true if successful.
00802 static bool EvaluateHasIncludeCommon(Token &Tok,
00803                                      IdentifierInfo *II, Preprocessor &PP,
00804                                      const DirectoryLookup *LookupFrom) {
00805   SourceLocation LParenLoc;
00806 
00807   // Get '('.
00808   PP.LexNonComment(Tok);
00809 
00810   // Ensure we have a '('.
00811   if (Tok.isNot(tok::l_paren)) {
00812     PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
00813     return false;
00814   }
00815 
00816   // Save '(' location for possible missing ')' message.
00817   LParenLoc = Tok.getLocation();
00818 
00819   // Get the file name.
00820   PP.getCurrentLexer()->LexIncludeFilename(Tok);
00821 
00822   // Reserve a buffer to get the spelling.
00823   SmallString<128> FilenameBuffer;
00824   StringRef Filename;
00825   SourceLocation EndLoc;
00826   
00827   switch (Tok.getKind()) {
00828   case tok::eod:
00829     // If the token kind is EOD, the error has already been diagnosed.
00830     return false;
00831 
00832   case tok::angle_string_literal:
00833   case tok::string_literal: {
00834     bool Invalid = false;
00835     Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
00836     if (Invalid)
00837       return false;
00838     break;
00839   }
00840 
00841   case tok::less:
00842     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
00843     // case, glue the tokens together into FilenameBuffer and interpret those.
00844     FilenameBuffer.push_back('<');
00845     if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
00846       return false;   // Found <eod> but no ">"?  Diagnostic already emitted.
00847     Filename = FilenameBuffer.str();
00848     break;
00849   default:
00850     PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
00851     return false;
00852   }
00853 
00854   // Get ')'.
00855   PP.LexNonComment(Tok);
00856 
00857   // Ensure we have a trailing ).
00858   if (Tok.isNot(tok::r_paren)) {
00859     PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
00860     PP.Diag(LParenLoc, diag::note_matching) << "(";
00861     return false;
00862   }
00863 
00864   bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
00865   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
00866   // error.
00867   if (Filename.empty())
00868     return false;
00869 
00870   // Search include directories.
00871   const DirectoryLookup *CurDir;
00872   const FileEntry *File =
00873       PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
00874 
00875   // Get the result value.  A result of true means the file exists.
00876   return File != 0;
00877 }
00878 
00879 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
00880 /// Returns true if successful.
00881 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
00882                                Preprocessor &PP) {
00883   return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
00884 }
00885 
00886 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
00887 /// Returns true if successful.
00888 static bool EvaluateHasIncludeNext(Token &Tok,
00889                                    IdentifierInfo *II, Preprocessor &PP) {
00890   // __has_include_next is like __has_include, except that we start
00891   // searching after the current found directory.  If we can't do this,
00892   // issue a diagnostic.
00893   const DirectoryLookup *Lookup = PP.GetCurDirLookup();
00894   if (PP.isInPrimaryFile()) {
00895     Lookup = 0;
00896     PP.Diag(Tok, diag::pp_include_next_in_primary);
00897   } else if (Lookup == 0) {
00898     PP.Diag(Tok, diag::pp_include_next_absolute_path);
00899   } else {
00900     // Start looking up in the next directory.
00901     ++Lookup;
00902   }
00903 
00904   return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
00905 }
00906 
00907 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
00908 /// as a builtin macro, handle it and return the next token as 'Tok'.
00909 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
00910   // Figure out which token this is.
00911   IdentifierInfo *II = Tok.getIdentifierInfo();
00912   assert(II && "Can't be a macro without id info!");
00913 
00914   // If this is an _Pragma or Microsoft __pragma directive, expand it,
00915   // invoke the pragma handler, then lex the token after it.
00916   if (II == Ident_Pragma)
00917     return Handle_Pragma(Tok);
00918   else if (II == Ident__pragma) // in non-MS mode this is null
00919     return HandleMicrosoft__pragma(Tok);
00920 
00921   ++NumBuiltinMacroExpanded;
00922 
00923   SmallString<128> TmpBuffer;
00924   llvm::raw_svector_ostream OS(TmpBuffer);
00925 
00926   // Set up the return result.
00927   Tok.setIdentifierInfo(0);
00928   Tok.clearFlag(Token::NeedsCleaning);
00929 
00930   if (II == Ident__LINE__) {
00931     // C99 6.10.8: "__LINE__: The presumed line number (within the current
00932     // source file) of the current source line (an integer constant)".  This can
00933     // be affected by #line.
00934     SourceLocation Loc = Tok.getLocation();
00935 
00936     // Advance to the location of the first _, this might not be the first byte
00937     // of the token if it starts with an escaped newline.
00938     Loc = AdvanceToTokenCharacter(Loc, 0);
00939 
00940     // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
00941     // a macro expansion.  This doesn't matter for object-like macros, but
00942     // can matter for a function-like macro that expands to contain __LINE__.
00943     // Skip down through expansion points until we find a file loc for the
00944     // end of the expansion history.
00945     Loc = SourceMgr.getExpansionRange(Loc).second;
00946     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
00947 
00948     // __LINE__ expands to a simple numeric value.
00949     OS << (PLoc.isValid()? PLoc.getLine() : 1);
00950     Tok.setKind(tok::numeric_constant);
00951   } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
00952     // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
00953     // character string literal)". This can be affected by #line.
00954     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
00955 
00956     // __BASE_FILE__ is a GNU extension that returns the top of the presumed
00957     // #include stack instead of the current file.
00958     if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
00959       SourceLocation NextLoc = PLoc.getIncludeLoc();
00960       while (NextLoc.isValid()) {
00961         PLoc = SourceMgr.getPresumedLoc(NextLoc);
00962         if (PLoc.isInvalid())
00963           break;
00964         
00965         NextLoc = PLoc.getIncludeLoc();
00966       }
00967     }
00968 
00969     // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
00970     SmallString<128> FN;
00971     if (PLoc.isValid()) {
00972       FN += PLoc.getFilename();
00973       Lexer::Stringify(FN);
00974       OS << '"' << FN.str() << '"';
00975     }
00976     Tok.setKind(tok::string_literal);
00977   } else if (II == Ident__DATE__) {
00978     if (!DATELoc.isValid())
00979       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
00980     Tok.setKind(tok::string_literal);
00981     Tok.setLength(strlen("\"Mmm dd yyyy\""));
00982     Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
00983                                                  Tok.getLocation(),
00984                                                  Tok.getLength()));
00985     return;
00986   } else if (II == Ident__TIME__) {
00987     if (!TIMELoc.isValid())
00988       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
00989     Tok.setKind(tok::string_literal);
00990     Tok.setLength(strlen("\"hh:mm:ss\""));
00991     Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
00992                                                  Tok.getLocation(),
00993                                                  Tok.getLength()));
00994     return;
00995   } else if (II == Ident__INCLUDE_LEVEL__) {
00996     // Compute the presumed include depth of this token.  This can be affected
00997     // by GNU line markers.
00998     unsigned Depth = 0;
00999 
01000     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
01001     if (PLoc.isValid()) {
01002       PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
01003       for (; PLoc.isValid(); ++Depth)
01004         PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
01005     }
01006 
01007     // __INCLUDE_LEVEL__ expands to a simple numeric value.
01008     OS << Depth;
01009     Tok.setKind(tok::numeric_constant);
01010   } else if (II == Ident__TIMESTAMP__) {
01011     // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
01012     // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
01013 
01014     // Get the file that we are lexing out of.  If we're currently lexing from
01015     // a macro, dig into the include stack.
01016     const FileEntry *CurFile = 0;
01017     PreprocessorLexer *TheLexer = getCurrentFileLexer();
01018 
01019     if (TheLexer)
01020       CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
01021 
01022     const char *Result;
01023     if (CurFile) {
01024       time_t TT = CurFile->getModificationTime();
01025       struct tm *TM = localtime(&TT);
01026       Result = asctime(TM);
01027     } else {
01028       Result = "??? ??? ?? ??:??:?? ????\n";
01029     }
01030     // Surround the string with " and strip the trailing newline.
01031     OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
01032     Tok.setKind(tok::string_literal);
01033   } else if (II == Ident__COUNTER__) {
01034     // __COUNTER__ expands to a simple numeric value.
01035     OS << CounterValue++;
01036     Tok.setKind(tok::numeric_constant);
01037   } else if (II == Ident__has_feature   ||
01038              II == Ident__has_extension ||
01039              II == Ident__has_builtin   ||
01040              II == Ident__has_attribute) {
01041     // The argument to these builtins should be a parenthesized identifier.
01042     SourceLocation StartLoc = Tok.getLocation();
01043 
01044     bool IsValid = false;
01045     IdentifierInfo *FeatureII = 0;
01046 
01047     // Read the '('.
01048     Lex(Tok);
01049     if (Tok.is(tok::l_paren)) {
01050       // Read the identifier
01051       Lex(Tok);
01052       if (Tok.is(tok::identifier)) {
01053         FeatureII = Tok.getIdentifierInfo();
01054 
01055         // Read the ')'.
01056         Lex(Tok);
01057         if (Tok.is(tok::r_paren))
01058           IsValid = true;
01059       }
01060     }
01061 
01062     bool Value = false;
01063     if (!IsValid)
01064       Diag(StartLoc, diag::err_feature_check_malformed);
01065     else if (II == Ident__has_builtin) {
01066       // Check for a builtin is trivial.
01067       Value = FeatureII->getBuiltinID() != 0;
01068     } else if (II == Ident__has_attribute)
01069       Value = HasAttribute(FeatureII);
01070     else if (II == Ident__has_extension)
01071       Value = HasExtension(*this, FeatureII);
01072     else {
01073       assert(II == Ident__has_feature && "Must be feature check");
01074       Value = HasFeature(*this, FeatureII);
01075     }
01076 
01077     OS << (int)Value;
01078     if (IsValid)
01079       Tok.setKind(tok::numeric_constant);
01080   } else if (II == Ident__has_include ||
01081              II == Ident__has_include_next) {
01082     // The argument to these two builtins should be a parenthesized
01083     // file name string literal using angle brackets (<>) or
01084     // double-quotes ("").
01085     bool Value;
01086     if (II == Ident__has_include)
01087       Value = EvaluateHasInclude(Tok, II, *this);
01088     else
01089       Value = EvaluateHasIncludeNext(Tok, II, *this);
01090     OS << (int)Value;
01091     Tok.setKind(tok::numeric_constant);
01092   } else if (II == Ident__has_warning) {
01093     // The argument should be a parenthesized string literal.
01094     // The argument to these builtins should be a parenthesized identifier.
01095     SourceLocation StartLoc = Tok.getLocation();    
01096     bool IsValid = false;
01097     bool Value = false;
01098     // Read the '('.
01099     Lex(Tok);
01100     do {
01101       if (Tok.is(tok::l_paren)) {      
01102         // Read the string.
01103         Lex(Tok);
01104       
01105         // We need at least one string literal.
01106         if (!Tok.is(tok::string_literal)) {
01107           StartLoc = Tok.getLocation();
01108           IsValid = false;
01109           // Eat tokens until ')'.
01110           do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
01111           break;
01112         }
01113         
01114         // String concatenation allows multiple strings, which can even come
01115         // from macro expansion.
01116         SmallVector<Token, 4> StrToks;
01117         while (Tok.is(tok::string_literal)) {
01118           // Complain about, and drop, any ud-suffix.
01119           if (Tok.hasUDSuffix())
01120             Diag(Tok, diag::err_invalid_string_udl);
01121           StrToks.push_back(Tok);
01122           LexUnexpandedToken(Tok);
01123         }
01124         
01125         // Is the end a ')'?
01126         if (!(IsValid = Tok.is(tok::r_paren)))
01127           break;
01128         
01129         // Concatenate and parse the strings.
01130         StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
01131         assert(Literal.isAscii() && "Didn't allow wide strings in");
01132         if (Literal.hadError)
01133           break;
01134         if (Literal.Pascal) {
01135           Diag(Tok, diag::warn_pragma_diagnostic_invalid);
01136           break;
01137         }
01138         
01139         StringRef WarningName(Literal.GetString());
01140         
01141         if (WarningName.size() < 3 || WarningName[0] != '-' ||
01142             WarningName[1] != 'W') {
01143           Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
01144           break;
01145         }
01146         
01147         // Finally, check if the warning flags maps to a diagnostic group.
01148         // We construct a SmallVector here to talk to getDiagnosticIDs().
01149         // Although we don't use the result, this isn't a hot path, and not
01150         // worth special casing.
01151         llvm::SmallVector<diag::kind, 10> Diags;
01152         Value = !getDiagnostics().getDiagnosticIDs()->
01153           getDiagnosticsInGroup(WarningName.substr(2), Diags);
01154       }
01155     } while (false);
01156     
01157     if (!IsValid)
01158       Diag(StartLoc, diag::err_warning_check_malformed);
01159 
01160     OS << (int)Value;
01161     Tok.setKind(tok::numeric_constant);
01162   } else {
01163     llvm_unreachable("Unknown identifier!");
01164   }
01165   CreateString(OS.str().data(), OS.str().size(), Tok,
01166                Tok.getLocation(), Tok.getLocation());
01167 }
01168 
01169 void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
01170   // If the 'used' status changed, and the macro requires 'unused' warning,
01171   // remove its SourceLocation from the warn-for-unused-macro locations.
01172   if (MI->isWarnIfUnused() && !MI->isUsed())
01173     WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
01174   MI->setIsUsed(true);
01175 }