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 expansion for the
00011 // preprocessor.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Lex/Preprocessor.h"
00016 #include "clang/Basic/Attributes.h"
00017 #include "clang/Basic/FileManager.h"
00018 #include "clang/Basic/SourceManager.h"
00019 #include "clang/Basic/TargetInfo.h"
00020 #include "clang/Lex/CodeCompletionHandler.h"
00021 #include "clang/Lex/ExternalPreprocessorSource.h"
00022 #include "clang/Lex/LexDiagnostic.h"
00023 #include "clang/Lex/MacroArgs.h"
00024 #include "clang/Lex/MacroInfo.h"
00025 #include "llvm/ADT/STLExtras.h"
00026 #include "llvm/ADT/SmallString.h"
00027 #include "llvm/ADT/StringSwitch.h"
00028 #include "llvm/Config/llvm-config.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include "llvm/Support/Format.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 #include <cstdio>
00033 #include <ctime>
00034 using namespace clang;
00035 
00036 MacroDirective *
00037 Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
00038   assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
00039 
00040   macro_iterator Pos = Macros.find(II);
00041   assert(Pos != Macros.end() && "Identifier macro info is missing!");
00042   return Pos->second;
00043 }
00044 
00045 void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
00046   assert(MD && "MacroDirective should be non-zero!");
00047   assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
00048 
00049   MacroDirective *&StoredMD = Macros[II];
00050   MD->setPrevious(StoredMD);
00051   StoredMD = MD;
00052   // Setup the identifier as having associated macro history.
00053   II->setHasMacroDefinition(true);
00054   if (!MD->isDefined())
00055     II->setHasMacroDefinition(false);
00056   bool isImportedMacro = isa<DefMacroDirective>(MD) &&
00057                          cast<DefMacroDirective>(MD)->isImported();
00058   if (II->isFromAST() && !isImportedMacro)
00059     II->setChangedSinceDeserialization();
00060 }
00061 
00062 void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
00063                                            MacroDirective *MD) {
00064   assert(II && MD);
00065   MacroDirective *&StoredMD = Macros[II];
00066   assert(!StoredMD &&
00067          "the macro history was modified before initializing it from a pch");
00068   StoredMD = MD;
00069   // Setup the identifier as having associated macro history.
00070   II->setHasMacroDefinition(true);
00071   if (!MD->isDefined())
00072     II->setHasMacroDefinition(false);
00073 }
00074 
00075 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
00076 /// table and mark it as a builtin macro to be expanded.
00077 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
00078   // Get the identifier.
00079   IdentifierInfo *Id = PP.getIdentifierInfo(Name);
00080 
00081   // Mark it as being a macro that is builtin.
00082   MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
00083   MI->setIsBuiltinMacro();
00084   PP.appendDefMacroDirective(Id, MI);
00085   return Id;
00086 }
00087 
00088 
00089 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
00090 /// identifier table.
00091 void Preprocessor::RegisterBuiltinMacros() {
00092   Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
00093   Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
00094   Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
00095   Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
00096   Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
00097   Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
00098 
00099   // C++ Standing Document Extensions.
00100   Ident__has_cpp_attribute = RegisterBuiltinMacro(*this, "__has_cpp_attribute");
00101 
00102   // GCC Extensions.
00103   Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
00104   Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
00105   Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
00106 
00107   // Microsoft Extensions.
00108   if (LangOpts.MicrosoftExt) {
00109     Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
00110     Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
00111   } else {
00112     Ident__identifier = nullptr;
00113     Ident__pragma = nullptr;
00114   }
00115 
00116   // Clang Extensions.
00117   Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
00118   Ident__has_extension    = RegisterBuiltinMacro(*this, "__has_extension");
00119   Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
00120   Ident__has_attribute    = RegisterBuiltinMacro(*this, "__has_attribute");
00121   Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
00122   Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
00123   Ident__has_warning      = RegisterBuiltinMacro(*this, "__has_warning");
00124   Ident__is_identifier    = RegisterBuiltinMacro(*this, "__is_identifier");
00125 
00126   // Modules.
00127   if (LangOpts.Modules) {
00128     Ident__building_module  = RegisterBuiltinMacro(*this, "__building_module");
00129 
00130     // __MODULE__
00131     if (!LangOpts.CurrentModule.empty())
00132       Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
00133     else
00134       Ident__MODULE__ = nullptr;
00135   } else {
00136     Ident__building_module = nullptr;
00137     Ident__MODULE__ = nullptr;
00138   }
00139 }
00140 
00141 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
00142 /// in its expansion, currently expands to that token literally.
00143 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
00144                                           const IdentifierInfo *MacroIdent,
00145                                           Preprocessor &PP) {
00146   IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
00147 
00148   // If the token isn't an identifier, it's always literally expanded.
00149   if (!II) return true;
00150 
00151   // If the information about this identifier is out of date, update it from
00152   // the external source.
00153   if (II->isOutOfDate())
00154     PP.getExternalSource()->updateOutOfDateIdentifier(*II);
00155 
00156   // If the identifier is a macro, and if that macro is enabled, it may be
00157   // expanded so it's not a trivial expansion.
00158   if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
00159       // Fast expanding "#define X X" is ok, because X would be disabled.
00160       II != MacroIdent)
00161     return false;
00162 
00163   // If this is an object-like macro invocation, it is safe to trivially expand
00164   // it.
00165   if (MI->isObjectLike()) return true;
00166 
00167   // If this is a function-like macro invocation, it's safe to trivially expand
00168   // as long as the identifier is not a macro argument.
00169   for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
00170        I != E; ++I)
00171     if (*I == II)
00172       return false;   // Identifier is a macro argument.
00173 
00174   return true;
00175 }
00176 
00177 
00178 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
00179 /// lexed is a '('.  If so, consume the token and return true, if not, this
00180 /// method should have no observable side-effect on the lexed tokens.
00181 bool Preprocessor::isNextPPTokenLParen() {
00182   // Do some quick tests for rejection cases.
00183   unsigned Val;
00184   if (CurLexer)
00185     Val = CurLexer->isNextPPTokenLParen();
00186   else if (CurPTHLexer)
00187     Val = CurPTHLexer->isNextPPTokenLParen();
00188   else
00189     Val = CurTokenLexer->isNextTokenLParen();
00190 
00191   if (Val == 2) {
00192     // We have run off the end.  If it's a source file we don't
00193     // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
00194     // macro stack.
00195     if (CurPPLexer)
00196       return false;
00197     for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
00198       IncludeStackInfo &Entry = IncludeMacroStack[i-1];
00199       if (Entry.TheLexer)
00200         Val = Entry.TheLexer->isNextPPTokenLParen();
00201       else if (Entry.ThePTHLexer)
00202         Val = Entry.ThePTHLexer->isNextPPTokenLParen();
00203       else
00204         Val = Entry.TheTokenLexer->isNextTokenLParen();
00205 
00206       if (Val != 2)
00207         break;
00208 
00209       // Ran off the end of a source file?
00210       if (Entry.ThePPLexer)
00211         return false;
00212     }
00213   }
00214 
00215   // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
00216   // have found something that isn't a '(' or we found the end of the
00217   // translation unit.  In either case, return false.
00218   return Val == 1;
00219 }
00220 
00221 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
00222 /// expanded as a macro, handle it and return the next token as 'Identifier'.
00223 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
00224                                                  MacroDirective *MD) {
00225   MacroDirective::DefInfo Def = MD->getDefinition();
00226   assert(Def.isValid());
00227   MacroInfo *MI = Def.getMacroInfo();
00228 
00229   // If this is a macro expansion in the "#if !defined(x)" line for the file,
00230   // then the macro could expand to different things in other contexts, we need
00231   // to disable the optimization in this case.
00232   if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
00233 
00234   // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
00235   if (MI->isBuiltinMacro()) {
00236     if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
00237                                            Identifier.getLocation(),
00238                                            /*Args=*/nullptr);
00239     ExpandBuiltinMacro(Identifier);
00240     return true;
00241   }
00242 
00243   /// Args - If this is a function-like macro expansion, this contains,
00244   /// for each macro argument, the list of tokens that were provided to the
00245   /// invocation.
00246   MacroArgs *Args = nullptr;
00247 
00248   // Remember where the end of the expansion occurred.  For an object-like
00249   // macro, this is the identifier.  For a function-like macro, this is the ')'.
00250   SourceLocation ExpansionEnd = Identifier.getLocation();
00251 
00252   // If this is a function-like macro, read the arguments.
00253   if (MI->isFunctionLike()) {
00254     // Remember that we are now parsing the arguments to a macro invocation.
00255     // Preprocessor directives used inside macro arguments are not portable, and
00256     // this enables the warning.
00257     InMacroArgs = true;
00258     Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
00259 
00260     // Finished parsing args.
00261     InMacroArgs = false;
00262 
00263     // If there was an error parsing the arguments, bail out.
00264     if (!Args) return true;
00265 
00266     ++NumFnMacroExpanded;
00267   } else {
00268     ++NumMacroExpanded;
00269   }
00270 
00271   // Notice that this macro has been used.
00272   markMacroAsUsed(MI);
00273 
00274   // Remember where the token is expanded.
00275   SourceLocation ExpandLoc = Identifier.getLocation();
00276   SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
00277 
00278   if (Callbacks) {
00279     if (InMacroArgs) {
00280       // We can have macro expansion inside a conditional directive while
00281       // reading the function macro arguments. To ensure, in that case, that
00282       // MacroExpands callbacks still happen in source order, queue this
00283       // callback to have it happen after the function macro callback.
00284       DelayedMacroExpandsCallbacks.push_back(
00285                               MacroExpandsInfo(Identifier, MD, ExpansionRange));
00286     } else {
00287       Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
00288       if (!DelayedMacroExpandsCallbacks.empty()) {
00289         for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
00290           MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
00291           // FIXME: We lose macro args info with delayed callback.
00292           Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
00293                                   /*Args=*/nullptr);
00294         }
00295         DelayedMacroExpandsCallbacks.clear();
00296       }
00297     }
00298   }
00299 
00300   // If the macro definition is ambiguous, complain.
00301   if (Def.getDirective()->isAmbiguous()) {
00302     Diag(Identifier, diag::warn_pp_ambiguous_macro)
00303       << Identifier.getIdentifierInfo();
00304     Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
00305       << Identifier.getIdentifierInfo();
00306     for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
00307          PrevDef && !PrevDef.isUndefined();
00308          PrevDef = PrevDef.getPreviousDefinition()) {
00309       Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
00310            diag::note_pp_ambiguous_macro_other)
00311         << Identifier.getIdentifierInfo();
00312       if (!PrevDef.getDirective()->isAmbiguous())
00313         break;
00314     }
00315   }
00316 
00317   // If we started lexing a macro, enter the macro expansion body.
00318 
00319   // If this macro expands to no tokens, don't bother to push it onto the
00320   // expansion stack, only to take it right back off.
00321   if (MI->getNumTokens() == 0) {
00322     // No need for arg info.
00323     if (Args) Args->destroy(*this);
00324 
00325     // Propagate whitespace info as if we had pushed, then popped,
00326     // a macro context.
00327     Identifier.setFlag(Token::LeadingEmptyMacro);
00328     PropagateLineStartLeadingSpaceInfo(Identifier);
00329     ++NumFastMacroExpanded;
00330     return false;
00331   } else if (MI->getNumTokens() == 1 &&
00332              isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
00333                                            *this)) {
00334     // Otherwise, if this macro expands into a single trivially-expanded
00335     // token: expand it now.  This handles common cases like
00336     // "#define VAL 42".
00337 
00338     // No need for arg info.
00339     if (Args) Args->destroy(*this);
00340 
00341     // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
00342     // identifier to the expanded token.
00343     bool isAtStartOfLine = Identifier.isAtStartOfLine();
00344     bool hasLeadingSpace = Identifier.hasLeadingSpace();
00345 
00346     // Replace the result token.
00347     Identifier = MI->getReplacementToken(0);
00348 
00349     // Restore the StartOfLine/LeadingSpace markers.
00350     Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
00351     Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
00352 
00353     // Update the tokens location to include both its expansion and physical
00354     // locations.
00355     SourceLocation Loc =
00356       SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
00357                                    ExpansionEnd,Identifier.getLength());
00358     Identifier.setLocation(Loc);
00359 
00360     // If this is a disabled macro or #define X X, we must mark the result as
00361     // unexpandable.
00362     if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
00363       if (MacroInfo *NewMI = getMacroInfo(NewII))
00364         if (!NewMI->isEnabled() || NewMI == MI) {
00365           Identifier.setFlag(Token::DisableExpand);
00366           // Don't warn for "#define X X" like "#define bool bool" from
00367           // stdbool.h.
00368           if (NewMI != MI || MI->isFunctionLike())
00369             Diag(Identifier, diag::pp_disabled_macro_expansion);
00370         }
00371     }
00372 
00373     // Since this is not an identifier token, it can't be macro expanded, so
00374     // we're done.
00375     ++NumFastMacroExpanded;
00376     return true;
00377   }
00378 
00379   // Start expanding the macro.
00380   EnterMacro(Identifier, ExpansionEnd, MI, Args);
00381   return false;
00382 }
00383 
00384 enum Bracket {
00385   Brace,
00386   Paren
00387 };
00388 
00389 /// CheckMatchedBrackets - Returns true if the braces and parentheses in the
00390 /// token vector are properly nested.
00391 static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
00392   SmallVector<Bracket, 8> Brackets;
00393   for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
00394                                               E = Tokens.end();
00395        I != E; ++I) {
00396     if (I->is(tok::l_paren)) {
00397       Brackets.push_back(Paren);
00398     } else if (I->is(tok::r_paren)) {
00399       if (Brackets.empty() || Brackets.back() == Brace)
00400         return false;
00401       Brackets.pop_back();
00402     } else if (I->is(tok::l_brace)) {
00403       Brackets.push_back(Brace);
00404     } else if (I->is(tok::r_brace)) {
00405       if (Brackets.empty() || Brackets.back() == Paren)
00406         return false;
00407       Brackets.pop_back();
00408     }
00409   }
00410   if (!Brackets.empty())
00411     return false;
00412   return true;
00413 }
00414 
00415 /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
00416 /// vector of tokens in NewTokens.  The new number of arguments will be placed
00417 /// in NumArgs and the ranges which need to surrounded in parentheses will be
00418 /// in ParenHints.
00419 /// Returns false if the token stream cannot be changed.  If this is because
00420 /// of an initializer list starting a macro argument, the range of those
00421 /// initializer lists will be place in InitLists.
00422 static bool GenerateNewArgTokens(Preprocessor &PP,
00423                                  SmallVectorImpl<Token> &OldTokens,
00424                                  SmallVectorImpl<Token> &NewTokens,
00425                                  unsigned &NumArgs,
00426                                  SmallVectorImpl<SourceRange> &ParenHints,
00427                                  SmallVectorImpl<SourceRange> &InitLists) {
00428   if (!CheckMatchedBrackets(OldTokens))
00429     return false;
00430 
00431   // Once it is known that the brackets are matched, only a simple count of the
00432   // braces is needed.
00433   unsigned Braces = 0;
00434 
00435   // First token of a new macro argument.
00436   SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
00437 
00438   // First closing brace in a new macro argument.  Used to generate
00439   // SourceRanges for InitLists.
00440   SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
00441   NumArgs = 0;
00442   Token TempToken;
00443   // Set to true when a macro separator token is found inside a braced list.
00444   // If true, the fixed argument spans multiple old arguments and ParenHints
00445   // will be updated.
00446   bool FoundSeparatorToken = false;
00447   for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
00448                                         E = OldTokens.end();
00449        I != E; ++I) {
00450     if (I->is(tok::l_brace)) {
00451       ++Braces;
00452     } else if (I->is(tok::r_brace)) {
00453       --Braces;
00454       if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
00455         ClosingBrace = I;
00456     } else if (I->is(tok::eof)) {
00457       // EOF token is used to separate macro arguments
00458       if (Braces != 0) {
00459         // Assume comma separator is actually braced list separator and change
00460         // it back to a comma.
00461         FoundSeparatorToken = true;
00462         I->setKind(tok::comma);
00463         I->setLength(1);
00464       } else { // Braces == 0
00465         // Separator token still separates arguments.
00466         ++NumArgs;
00467 
00468         // If the argument starts with a brace, it can't be fixed with
00469         // parentheses.  A different diagnostic will be given.
00470         if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
00471           InitLists.push_back(
00472               SourceRange(ArgStartIterator->getLocation(),
00473                           PP.getLocForEndOfToken(ClosingBrace->getLocation())));
00474           ClosingBrace = E;
00475         }
00476 
00477         // Add left paren
00478         if (FoundSeparatorToken) {
00479           TempToken.startToken();
00480           TempToken.setKind(tok::l_paren);
00481           TempToken.setLocation(ArgStartIterator->getLocation());
00482           TempToken.setLength(0);
00483           NewTokens.push_back(TempToken);
00484         }
00485 
00486         // Copy over argument tokens
00487         NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
00488 
00489         // Add right paren and store the paren locations in ParenHints
00490         if (FoundSeparatorToken) {
00491           SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
00492           TempToken.startToken();
00493           TempToken.setKind(tok::r_paren);
00494           TempToken.setLocation(Loc);
00495           TempToken.setLength(0);
00496           NewTokens.push_back(TempToken);
00497           ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
00498                                            Loc));
00499         }
00500 
00501         // Copy separator token
00502         NewTokens.push_back(*I);
00503 
00504         // Reset values
00505         ArgStartIterator = I + 1;
00506         FoundSeparatorToken = false;
00507       }
00508     }
00509   }
00510 
00511   return !ParenHints.empty() && InitLists.empty();
00512 }
00513 
00514 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
00515 /// token is the '(' of the macro, this method is invoked to read all of the
00516 /// actual arguments specified for the macro invocation.  This returns null on
00517 /// error.
00518 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
00519                                                    MacroInfo *MI,
00520                                                    SourceLocation &MacroEnd) {
00521   // The number of fixed arguments to parse.
00522   unsigned NumFixedArgsLeft = MI->getNumArgs();
00523   bool isVariadic = MI->isVariadic();
00524 
00525   // Outer loop, while there are more arguments, keep reading them.
00526   Token Tok;
00527 
00528   // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
00529   // an argument value in a macro could expand to ',' or '(' or ')'.
00530   LexUnexpandedToken(Tok);
00531   assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
00532 
00533   // ArgTokens - Build up a list of tokens that make up each argument.  Each
00534   // argument is separated by an EOF token.  Use a SmallVector so we can avoid
00535   // heap allocations in the common case.
00536   SmallVector<Token, 64> ArgTokens;
00537   bool ContainsCodeCompletionTok = false;
00538 
00539   SourceLocation TooManyArgsLoc;
00540 
00541   unsigned NumActuals = 0;
00542   while (Tok.isNot(tok::r_paren)) {
00543     if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
00544       break;
00545 
00546     assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
00547            "only expect argument separators here");
00548 
00549     unsigned ArgTokenStart = ArgTokens.size();
00550     SourceLocation ArgStartLoc = Tok.getLocation();
00551 
00552     // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
00553     // that we already consumed the first one.
00554     unsigned NumParens = 0;
00555 
00556     while (1) {
00557       // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
00558       // an argument value in a macro could expand to ',' or '(' or ')'.
00559       LexUnexpandedToken(Tok);
00560 
00561       if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
00562         if (!ContainsCodeCompletionTok) {
00563           Diag(MacroName, diag::err_unterm_macro_invoc);
00564           Diag(MI->getDefinitionLoc(), diag::note_macro_here)
00565             << MacroName.getIdentifierInfo();
00566           // Do not lose the EOF/EOD.  Return it to the client.
00567           MacroName = Tok;
00568           return nullptr;
00569         } else {
00570           // Do not lose the EOF/EOD.
00571           Token *Toks = new Token[1];
00572           Toks[0] = Tok;
00573           EnterTokenStream(Toks, 1, true, true);
00574           break;
00575         }
00576       } else if (Tok.is(tok::r_paren)) {
00577         // If we found the ) token, the macro arg list is done.
00578         if (NumParens-- == 0) {
00579           MacroEnd = Tok.getLocation();
00580           break;
00581         }
00582       } else if (Tok.is(tok::l_paren)) {
00583         ++NumParens;
00584       } else if (Tok.is(tok::comma) && NumParens == 0 &&
00585                  !(Tok.getFlags() & Token::IgnoredComma)) {
00586         // In Microsoft-compatibility mode, single commas from nested macro
00587         // expansions should not be considered as argument separators. We test
00588         // for this with the IgnoredComma token flag above.
00589 
00590         // Comma ends this argument if there are more fixed arguments expected.
00591         // However, if this is a variadic macro, and this is part of the
00592         // variadic part, then the comma is just an argument token.
00593         if (!isVariadic) break;
00594         if (NumFixedArgsLeft > 1)
00595           break;
00596       } else if (Tok.is(tok::comment) && !KeepMacroComments) {
00597         // If this is a comment token in the argument list and we're just in
00598         // -C mode (not -CC mode), discard the comment.
00599         continue;
00600       } else if (Tok.getIdentifierInfo() != nullptr) {
00601         // Reading macro arguments can cause macros that we are currently
00602         // expanding from to be popped off the expansion stack.  Doing so causes
00603         // them to be reenabled for expansion.  Here we record whether any
00604         // identifiers we lex as macro arguments correspond to disabled macros.
00605         // If so, we mark the token as noexpand.  This is a subtle aspect of
00606         // C99 6.10.3.4p2.
00607         if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
00608           if (!MI->isEnabled())
00609             Tok.setFlag(Token::DisableExpand);
00610       } else if (Tok.is(tok::code_completion)) {
00611         ContainsCodeCompletionTok = true;
00612         if (CodeComplete)
00613           CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
00614                                                   MI, NumActuals);
00615         // Don't mark that we reached the code-completion point because the
00616         // parser is going to handle the token and there will be another
00617         // code-completion callback.
00618       }
00619 
00620       ArgTokens.push_back(Tok);
00621     }
00622 
00623     // If this was an empty argument list foo(), don't add this as an empty
00624     // argument.
00625     if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
00626       break;
00627 
00628     // If this is not a variadic macro, and too many args were specified, emit
00629     // an error.
00630     if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
00631       if (ArgTokens.size() != ArgTokenStart)
00632         TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
00633       else
00634         TooManyArgsLoc = ArgStartLoc;
00635     }
00636 
00637     // Empty arguments are standard in C99 and C++0x, and are supported as an
00638     // extension in other modes.
00639     if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
00640       Diag(Tok, LangOpts.CPlusPlus11 ?
00641            diag::warn_cxx98_compat_empty_fnmacro_arg :
00642            diag::ext_empty_fnmacro_arg);
00643 
00644     // Add a marker EOF token to the end of the token list for this argument.
00645     Token EOFTok;
00646     EOFTok.startToken();
00647     EOFTok.setKind(tok::eof);
00648     EOFTok.setLocation(Tok.getLocation());
00649     EOFTok.setLength(0);
00650     ArgTokens.push_back(EOFTok);
00651     ++NumActuals;
00652     if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
00653       --NumFixedArgsLeft;
00654   }
00655 
00656   // Okay, we either found the r_paren.  Check to see if we parsed too few
00657   // arguments.
00658   unsigned MinArgsExpected = MI->getNumArgs();
00659 
00660   // If this is not a variadic macro, and too many args were specified, emit
00661   // an error.
00662   if (!isVariadic && NumActuals > MinArgsExpected &&
00663       !ContainsCodeCompletionTok) {
00664     // Emit the diagnostic at the macro name in case there is a missing ).
00665     // Emitting it at the , could be far away from the macro name.
00666     Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
00667     Diag(MI->getDefinitionLoc(), diag::note_macro_here)
00668       << MacroName.getIdentifierInfo();
00669 
00670     // Commas from braced initializer lists will be treated as argument
00671     // separators inside macros.  Attempt to correct for this with parentheses.
00672     // TODO: See if this can be generalized to angle brackets for templates
00673     // inside macro arguments.
00674 
00675     SmallVector<Token, 4> FixedArgTokens;
00676     unsigned FixedNumArgs = 0;
00677     SmallVector<SourceRange, 4> ParenHints, InitLists;
00678     if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
00679                               ParenHints, InitLists)) {
00680       if (!InitLists.empty()) {
00681         DiagnosticBuilder DB =
00682             Diag(MacroName,
00683                  diag::note_init_list_at_beginning_of_macro_argument);
00684         for (const SourceRange &Range : InitLists)
00685           DB << Range;
00686       }
00687       return nullptr;
00688     }
00689     if (FixedNumArgs != MinArgsExpected)
00690       return nullptr;
00691 
00692     DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
00693     for (const SourceRange &ParenLocation : ParenHints) {
00694       DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
00695       DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
00696     }
00697     ArgTokens.swap(FixedArgTokens);
00698     NumActuals = FixedNumArgs;
00699   }
00700 
00701   // See MacroArgs instance var for description of this.
00702   bool isVarargsElided = false;
00703 
00704   if (ContainsCodeCompletionTok) {
00705     // Recover from not-fully-formed macro invocation during code-completion.
00706     Token EOFTok;
00707     EOFTok.startToken();
00708     EOFTok.setKind(tok::eof);
00709     EOFTok.setLocation(Tok.getLocation());
00710     EOFTok.setLength(0);
00711     for (; NumActuals < MinArgsExpected; ++NumActuals)
00712       ArgTokens.push_back(EOFTok);
00713   }
00714 
00715   if (NumActuals < MinArgsExpected) {
00716     // There are several cases where too few arguments is ok, handle them now.
00717     if (NumActuals == 0 && MinArgsExpected == 1) {
00718       // #define A(X)  or  #define A(...)   ---> A()
00719 
00720       // If there is exactly one argument, and that argument is missing,
00721       // then we have an empty "()" argument empty list.  This is fine, even if
00722       // the macro expects one argument (the argument is just empty).
00723       isVarargsElided = MI->isVariadic();
00724     } else if (MI->isVariadic() &&
00725                (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
00726                 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
00727       // Varargs where the named vararg parameter is missing: OK as extension.
00728       //   #define A(x, ...)
00729       //   A("blah")
00730       //
00731       // If the macro contains the comma pasting extension, the diagnostic
00732       // is suppressed; we know we'll get another diagnostic later.
00733       if (!MI->hasCommaPasting()) {
00734         Diag(Tok, diag::ext_missing_varargs_arg);
00735         Diag(MI->getDefinitionLoc(), diag::note_macro_here)
00736           << MacroName.getIdentifierInfo();
00737       }
00738 
00739       // Remember this occurred, allowing us to elide the comma when used for
00740       // cases like:
00741       //   #define A(x, foo...) blah(a, ## foo)
00742       //   #define B(x, ...) blah(a, ## __VA_ARGS__)
00743       //   #define C(...) blah(a, ## __VA_ARGS__)
00744       //  A(x) B(x) C()
00745       isVarargsElided = true;
00746     } else if (!ContainsCodeCompletionTok) {
00747       // Otherwise, emit the error.
00748       Diag(Tok, diag::err_too_few_args_in_macro_invoc);
00749       Diag(MI->getDefinitionLoc(), diag::note_macro_here)
00750         << MacroName.getIdentifierInfo();
00751       return nullptr;
00752     }
00753 
00754     // Add a marker EOF token to the end of the token list for this argument.
00755     SourceLocation EndLoc = Tok.getLocation();
00756     Tok.startToken();
00757     Tok.setKind(tok::eof);
00758     Tok.setLocation(EndLoc);
00759     Tok.setLength(0);
00760     ArgTokens.push_back(Tok);
00761 
00762     // If we expect two arguments, add both as empty.
00763     if (NumActuals == 0 && MinArgsExpected == 2)
00764       ArgTokens.push_back(Tok);
00765 
00766   } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
00767              !ContainsCodeCompletionTok) {
00768     // Emit the diagnostic at the macro name in case there is a missing ).
00769     // Emitting it at the , could be far away from the macro name.
00770     Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
00771     Diag(MI->getDefinitionLoc(), diag::note_macro_here)
00772       << MacroName.getIdentifierInfo();
00773     return nullptr;
00774   }
00775 
00776   return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
00777 }
00778 
00779 /// \brief Keeps macro expanded tokens for TokenLexers.
00780 //
00781 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
00782 /// going to lex in the cache and when it finishes the tokens are removed
00783 /// from the end of the cache.
00784 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
00785                                               ArrayRef<Token> tokens) {
00786   assert(tokLexer);
00787   if (tokens.empty())
00788     return nullptr;
00789 
00790   size_t newIndex = MacroExpandedTokens.size();
00791   bool cacheNeedsToGrow = tokens.size() >
00792                       MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); 
00793   MacroExpandedTokens.append(tokens.begin(), tokens.end());
00794 
00795   if (cacheNeedsToGrow) {
00796     // Go through all the TokenLexers whose 'Tokens' pointer points in the
00797     // buffer and update the pointers to the (potential) new buffer array.
00798     for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
00799       TokenLexer *prevLexer;
00800       size_t tokIndex;
00801       std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
00802       prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
00803     }
00804   }
00805 
00806   MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
00807   return MacroExpandedTokens.data() + newIndex;
00808 }
00809 
00810 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
00811   assert(!MacroExpandingLexersStack.empty());
00812   size_t tokIndex = MacroExpandingLexersStack.back().second;
00813   assert(tokIndex < MacroExpandedTokens.size());
00814   // Pop the cached macro expanded tokens from the end.
00815   MacroExpandedTokens.resize(tokIndex);
00816   MacroExpandingLexersStack.pop_back();
00817 }
00818 
00819 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
00820 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
00821 /// the identifier tokens inserted.
00822 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
00823                              Preprocessor &PP) {
00824   time_t TT = time(nullptr);
00825   struct tm *TM = localtime(&TT);
00826 
00827   static const char * const Months[] = {
00828     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
00829   };
00830 
00831   {
00832     SmallString<32> TmpBuffer;
00833     llvm::raw_svector_ostream TmpStream(TmpBuffer);
00834     TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
00835                               TM->tm_mday, TM->tm_year + 1900);
00836     Token TmpTok;
00837     TmpTok.startToken();
00838     PP.CreateString(TmpStream.str(), TmpTok);
00839     DATELoc = TmpTok.getLocation();
00840   }
00841 
00842   {
00843     SmallString<32> TmpBuffer;
00844     llvm::raw_svector_ostream TmpStream(TmpBuffer);
00845     TmpStream << llvm::format("\"%02d:%02d:%02d\"",
00846                               TM->tm_hour, TM->tm_min, TM->tm_sec);
00847     Token TmpTok;
00848     TmpTok.startToken();
00849     PP.CreateString(TmpStream.str(), TmpTok);
00850     TIMELoc = TmpTok.getLocation();
00851   }
00852 }
00853 
00854 
00855 /// HasFeature - Return true if we recognize and implement the feature
00856 /// specified by the identifier as a standard language feature.
00857 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
00858   const LangOptions &LangOpts = PP.getLangOpts();
00859   StringRef Feature = II->getName();
00860 
00861   // Normalize the feature name, __foo__ becomes foo.
00862   if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
00863     Feature = Feature.substr(2, Feature.size() - 4);
00864 
00865   return llvm::StringSwitch<bool>(Feature)
00866       .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
00867       .Case("attribute_analyzer_noreturn", true)
00868       .Case("attribute_availability", true)
00869       .Case("attribute_availability_with_message", true)
00870       .Case("attribute_cf_returns_not_retained", true)
00871       .Case("attribute_cf_returns_retained", true)
00872       .Case("attribute_deprecated_with_message", true)
00873       .Case("attribute_ext_vector_type", true)
00874       .Case("attribute_ns_returns_not_retained", true)
00875       .Case("attribute_ns_returns_retained", true)
00876       .Case("attribute_ns_consumes_self", true)
00877       .Case("attribute_ns_consumed", true)
00878       .Case("attribute_cf_consumed", true)
00879       .Case("attribute_objc_ivar_unused", true)
00880       .Case("attribute_objc_method_family", true)
00881       .Case("attribute_overloadable", true)
00882       .Case("attribute_unavailable_with_message", true)
00883       .Case("attribute_unused_on_fields", true)
00884       .Case("blocks", LangOpts.Blocks)
00885       .Case("c_thread_safety_attributes", true)
00886       .Case("cxx_exceptions", LangOpts.CXXExceptions)
00887       .Case("cxx_rtti", LangOpts.RTTI)
00888       .Case("enumerator_attributes", true)
00889       .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
00890       .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
00891       .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
00892       // Objective-C features
00893       .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
00894       .Case("objc_arc", LangOpts.ObjCAutoRefCount)
00895       .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
00896       .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
00897       .Case("objc_fixed_enum", LangOpts.ObjC2)
00898       .Case("objc_instancetype", LangOpts.ObjC2)
00899       .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
00900       .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
00901       .Case("objc_property_explicit_atomic",
00902             true) // Does clang support explicit "atomic" keyword?
00903       .Case("objc_protocol_qualifier_mangling", true)
00904       .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
00905       .Case("ownership_holds", true)
00906       .Case("ownership_returns", true)
00907       .Case("ownership_takes", true)
00908       .Case("objc_bool", true)
00909       .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
00910       .Case("objc_array_literals", LangOpts.ObjC2)
00911       .Case("objc_dictionary_literals", LangOpts.ObjC2)
00912       .Case("objc_boxed_expressions", LangOpts.ObjC2)
00913       .Case("arc_cf_code_audited", true)
00914       // C11 features
00915       .Case("c_alignas", LangOpts.C11)
00916       .Case("c_atomic", LangOpts.C11)
00917       .Case("c_generic_selections", LangOpts.C11)
00918       .Case("c_static_assert", LangOpts.C11)
00919       .Case("c_thread_local",
00920             LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
00921       // C++11 features
00922       .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
00923       .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
00924       .Case("cxx_alignas", LangOpts.CPlusPlus11)
00925       .Case("cxx_atomic", LangOpts.CPlusPlus11)
00926       .Case("cxx_attributes", LangOpts.CPlusPlus11)
00927       .Case("cxx_auto_type", LangOpts.CPlusPlus11)
00928       .Case("cxx_constexpr", LangOpts.CPlusPlus11)
00929       .Case("cxx_decltype", LangOpts.CPlusPlus11)
00930       .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
00931       .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
00932       .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
00933       .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
00934       .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
00935       .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
00936       .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
00937       .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
00938       .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
00939       .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
00940       .Case("cxx_lambdas", LangOpts.CPlusPlus11)
00941       .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
00942       .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
00943       .Case("cxx_noexcept", LangOpts.CPlusPlus11)
00944       .Case("cxx_nullptr", LangOpts.CPlusPlus11)
00945       .Case("cxx_override_control", LangOpts.CPlusPlus11)
00946       .Case("cxx_range_for", LangOpts.CPlusPlus11)
00947       .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
00948       .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
00949       .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
00950       .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
00951       .Case("cxx_static_assert", LangOpts.CPlusPlus11)
00952       .Case("cxx_thread_local",
00953             LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
00954       .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
00955       .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
00956       .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
00957       .Case("cxx_user_literals", LangOpts.CPlusPlus11)
00958       .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
00959       // C++1y features
00960       .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
00961       .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
00962       .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
00963       .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
00964       .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
00965       .Case("cxx_init_captures", LangOpts.CPlusPlus14)
00966       .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
00967       .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
00968       .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
00969       // C++ TSes
00970       //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
00971       //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
00972       // FIXME: Should this be __has_feature or __has_extension?
00973       //.Case("raw_invocation_type", LangOpts.CPlusPlus)
00974       // Type traits
00975       .Case("has_nothrow_assign", LangOpts.CPlusPlus)
00976       .Case("has_nothrow_copy", LangOpts.CPlusPlus)
00977       .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
00978       .Case("has_trivial_assign", LangOpts.CPlusPlus)
00979       .Case("has_trivial_copy", LangOpts.CPlusPlus)
00980       .Case("has_trivial_constructor", LangOpts.CPlusPlus)
00981       .Case("has_trivial_destructor", LangOpts.CPlusPlus)
00982       .Case("has_virtual_destructor", LangOpts.CPlusPlus)
00983       .Case("is_abstract", LangOpts.CPlusPlus)
00984       .Case("is_base_of", LangOpts.CPlusPlus)
00985       .Case("is_class", LangOpts.CPlusPlus)
00986       .Case("is_constructible", LangOpts.CPlusPlus)
00987       .Case("is_convertible_to", LangOpts.CPlusPlus)
00988       .Case("is_empty", LangOpts.CPlusPlus)
00989       .Case("is_enum", LangOpts.CPlusPlus)
00990       .Case("is_final", LangOpts.CPlusPlus)
00991       .Case("is_literal", LangOpts.CPlusPlus)
00992       .Case("is_standard_layout", LangOpts.CPlusPlus)
00993       .Case("is_pod", LangOpts.CPlusPlus)
00994       .Case("is_polymorphic", LangOpts.CPlusPlus)
00995       .Case("is_sealed", LangOpts.MicrosoftExt)
00996       .Case("is_trivial", LangOpts.CPlusPlus)
00997       .Case("is_trivially_assignable", LangOpts.CPlusPlus)
00998       .Case("is_trivially_constructible", LangOpts.CPlusPlus)
00999       .Case("is_trivially_copyable", LangOpts.CPlusPlus)
01000       .Case("is_union", LangOpts.CPlusPlus)
01001       .Case("modules", LangOpts.Modules)
01002       .Case("tls", PP.getTargetInfo().isTLSSupported())
01003       .Case("underlying_type", LangOpts.CPlusPlus)
01004       .Default(false);
01005 }
01006 
01007 /// HasExtension - Return true if we recognize and implement the feature
01008 /// specified by the identifier, either as an extension or a standard language
01009 /// feature.
01010 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
01011   if (HasFeature(PP, II))
01012     return true;
01013 
01014   // If the use of an extension results in an error diagnostic, extensions are
01015   // effectively unavailable, so just return false here.
01016   if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
01017       diag::Severity::Error)
01018     return false;
01019 
01020   const LangOptions &LangOpts = PP.getLangOpts();
01021   StringRef Extension = II->getName();
01022 
01023   // Normalize the extension name, __foo__ becomes foo.
01024   if (Extension.startswith("__") && Extension.endswith("__") &&
01025       Extension.size() >= 4)
01026     Extension = Extension.substr(2, Extension.size() - 4);
01027 
01028   // Because we inherit the feature list from HasFeature, this string switch
01029   // must be less restrictive than HasFeature's.
01030   return llvm::StringSwitch<bool>(Extension)
01031            // C11 features supported by other languages as extensions.
01032            .Case("c_alignas", true)
01033            .Case("c_atomic", true)
01034            .Case("c_generic_selections", true)
01035            .Case("c_static_assert", true)
01036            .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
01037            // C++11 features supported by other languages as extensions.
01038            .Case("cxx_atomic", LangOpts.CPlusPlus)
01039            .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
01040            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
01041            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
01042            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
01043            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
01044            .Case("cxx_override_control", LangOpts.CPlusPlus)
01045            .Case("cxx_range_for", LangOpts.CPlusPlus)
01046            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
01047            .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
01048            // C++1y features supported by other languages as extensions.
01049            .Case("cxx_binary_literals", true)
01050            .Case("cxx_init_captures", LangOpts.CPlusPlus11)
01051            .Case("cxx_variable_templates", LangOpts.CPlusPlus)
01052            .Default(false);
01053 }
01054 
01055 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
01056 /// or '__has_include_next("path")' expression.
01057 /// Returns true if successful.
01058 static bool EvaluateHasIncludeCommon(Token &Tok,
01059                                      IdentifierInfo *II, Preprocessor &PP,
01060                                      const DirectoryLookup *LookupFrom,
01061                                      const FileEntry *LookupFromFile) {
01062   // Save the location of the current token.  If a '(' is later found, use
01063   // that location.  If not, use the end of this location instead.
01064   SourceLocation LParenLoc = Tok.getLocation();
01065 
01066   // These expressions are only allowed within a preprocessor directive.
01067   if (!PP.isParsingIfOrElifDirective()) {
01068     PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
01069     return false;
01070   }
01071 
01072   // Get '('.
01073   PP.LexNonComment(Tok);
01074 
01075   // Ensure we have a '('.
01076   if (Tok.isNot(tok::l_paren)) {
01077     // No '(', use end of last token.
01078     LParenLoc = PP.getLocForEndOfToken(LParenLoc);
01079     PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
01080     // If the next token looks like a filename or the start of one,
01081     // assume it is and process it as such.
01082     if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
01083         !Tok.is(tok::less))
01084       return false;
01085   } else {
01086     // Save '(' location for possible missing ')' message.
01087     LParenLoc = Tok.getLocation();
01088 
01089     if (PP.getCurrentLexer()) {
01090       // Get the file name.
01091       PP.getCurrentLexer()->LexIncludeFilename(Tok);
01092     } else {
01093       // We're in a macro, so we can't use LexIncludeFilename; just
01094       // grab the next token.
01095       PP.Lex(Tok);
01096     }
01097   }
01098 
01099   // Reserve a buffer to get the spelling.
01100   SmallString<128> FilenameBuffer;
01101   StringRef Filename;
01102   SourceLocation EndLoc;
01103   
01104   switch (Tok.getKind()) {
01105   case tok::eod:
01106     // If the token kind is EOD, the error has already been diagnosed.
01107     return false;
01108 
01109   case tok::angle_string_literal:
01110   case tok::string_literal: {
01111     bool Invalid = false;
01112     Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
01113     if (Invalid)
01114       return false;
01115     break;
01116   }
01117 
01118   case tok::less:
01119     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
01120     // case, glue the tokens together into FilenameBuffer and interpret those.
01121     FilenameBuffer.push_back('<');
01122     if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
01123       // Let the caller know a <eod> was found by changing the Token kind.
01124       Tok.setKind(tok::eod);
01125       return false;   // Found <eod> but no ">"?  Diagnostic already emitted.
01126     }
01127     Filename = FilenameBuffer.str();
01128     break;
01129   default:
01130     PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
01131     return false;
01132   }
01133 
01134   SourceLocation FilenameLoc = Tok.getLocation();
01135 
01136   // Get ')'.
01137   PP.LexNonComment(Tok);
01138 
01139   // Ensure we have a trailing ).
01140   if (Tok.isNot(tok::r_paren)) {
01141     PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
01142         << II << tok::r_paren;
01143     PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
01144     return false;
01145   }
01146 
01147   bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
01148   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
01149   // error.
01150   if (Filename.empty())
01151     return false;
01152 
01153   // Search include directories.
01154   const DirectoryLookup *CurDir;
01155   const FileEntry *File =
01156       PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
01157                     CurDir, nullptr, nullptr, nullptr);
01158 
01159   // Get the result value.  A result of true means the file exists.
01160   return File != nullptr;
01161 }
01162 
01163 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
01164 /// Returns true if successful.
01165 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
01166                                Preprocessor &PP) {
01167   return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
01168 }
01169 
01170 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
01171 /// Returns true if successful.
01172 static bool EvaluateHasIncludeNext(Token &Tok,
01173                                    IdentifierInfo *II, Preprocessor &PP) {
01174   // __has_include_next is like __has_include, except that we start
01175   // searching after the current found directory.  If we can't do this,
01176   // issue a diagnostic.
01177   // FIXME: Factor out duplication wiht
01178   // Preprocessor::HandleIncludeNextDirective.
01179   const DirectoryLookup *Lookup = PP.GetCurDirLookup();
01180   const FileEntry *LookupFromFile = nullptr;
01181   if (PP.isInPrimaryFile()) {
01182     Lookup = nullptr;
01183     PP.Diag(Tok, diag::pp_include_next_in_primary);
01184   } else if (PP.getCurrentSubmodule()) {
01185     // Start looking up in the directory *after* the one in which the current
01186     // file would be found, if any.
01187     assert(PP.getCurrentLexer() && "#include_next directive in macro?");
01188     LookupFromFile = PP.getCurrentLexer()->getFileEntry();
01189     Lookup = nullptr;
01190   } else if (!Lookup) {
01191     PP.Diag(Tok, diag::pp_include_next_absolute_path);
01192   } else {
01193     // Start looking up in the next directory.
01194     ++Lookup;
01195   }
01196 
01197   return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
01198 }
01199 
01200 /// \brief Process __building_module(identifier) expression.
01201 /// \returns true if we are building the named module, false otherwise.
01202 static bool EvaluateBuildingModule(Token &Tok,
01203                                    IdentifierInfo *II, Preprocessor &PP) {
01204   // Get '('.
01205   PP.LexNonComment(Tok);
01206 
01207   // Ensure we have a '('.
01208   if (Tok.isNot(tok::l_paren)) {
01209     PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
01210                                                             << tok::l_paren;
01211     return false;
01212   }
01213 
01214   // Save '(' location for possible missing ')' message.
01215   SourceLocation LParenLoc = Tok.getLocation();
01216 
01217   // Get the module name.
01218   PP.LexNonComment(Tok);
01219 
01220   // Ensure that we have an identifier.
01221   if (Tok.isNot(tok::identifier)) {
01222     PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
01223     return false;
01224   }
01225 
01226   bool Result
01227     = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
01228 
01229   // Get ')'.
01230   PP.LexNonComment(Tok);
01231 
01232   // Ensure we have a trailing ).
01233   if (Tok.isNot(tok::r_paren)) {
01234     PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
01235                                                             << tok::r_paren;
01236     PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
01237     return false;
01238   }
01239 
01240   return Result;
01241 }
01242 
01243 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
01244 /// as a builtin macro, handle it and return the next token as 'Tok'.
01245 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
01246   // Figure out which token this is.
01247   IdentifierInfo *II = Tok.getIdentifierInfo();
01248   assert(II && "Can't be a macro without id info!");
01249 
01250   // If this is an _Pragma or Microsoft __pragma directive, expand it,
01251   // invoke the pragma handler, then lex the token after it.
01252   if (II == Ident_Pragma)
01253     return Handle_Pragma(Tok);
01254   else if (II == Ident__pragma) // in non-MS mode this is null
01255     return HandleMicrosoft__pragma(Tok);
01256 
01257   ++NumBuiltinMacroExpanded;
01258 
01259   SmallString<128> TmpBuffer;
01260   llvm::raw_svector_ostream OS(TmpBuffer);
01261 
01262   // Set up the return result.
01263   Tok.setIdentifierInfo(nullptr);
01264   Tok.clearFlag(Token::NeedsCleaning);
01265 
01266   if (II == Ident__LINE__) {
01267     // C99 6.10.8: "__LINE__: The presumed line number (within the current
01268     // source file) of the current source line (an integer constant)".  This can
01269     // be affected by #line.
01270     SourceLocation Loc = Tok.getLocation();
01271 
01272     // Advance to the location of the first _, this might not be the first byte
01273     // of the token if it starts with an escaped newline.
01274     Loc = AdvanceToTokenCharacter(Loc, 0);
01275 
01276     // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
01277     // a macro expansion.  This doesn't matter for object-like macros, but
01278     // can matter for a function-like macro that expands to contain __LINE__.
01279     // Skip down through expansion points until we find a file loc for the
01280     // end of the expansion history.
01281     Loc = SourceMgr.getExpansionRange(Loc).second;
01282     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
01283 
01284     // __LINE__ expands to a simple numeric value.
01285     OS << (PLoc.isValid()? PLoc.getLine() : 1);
01286     Tok.setKind(tok::numeric_constant);
01287   } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
01288     // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
01289     // character string literal)". This can be affected by #line.
01290     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
01291 
01292     // __BASE_FILE__ is a GNU extension that returns the top of the presumed
01293     // #include stack instead of the current file.
01294     if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
01295       SourceLocation NextLoc = PLoc.getIncludeLoc();
01296       while (NextLoc.isValid()) {
01297         PLoc = SourceMgr.getPresumedLoc(NextLoc);
01298         if (PLoc.isInvalid())
01299           break;
01300         
01301         NextLoc = PLoc.getIncludeLoc();
01302       }
01303     }
01304 
01305     // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
01306     SmallString<128> FN;
01307     if (PLoc.isValid()) {
01308       FN += PLoc.getFilename();
01309       Lexer::Stringify(FN);
01310       OS << '"' << FN.str() << '"';
01311     }
01312     Tok.setKind(tok::string_literal);
01313   } else if (II == Ident__DATE__) {
01314     Diag(Tok.getLocation(), diag::warn_pp_date_time);
01315     if (!DATELoc.isValid())
01316       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
01317     Tok.setKind(tok::string_literal);
01318     Tok.setLength(strlen("\"Mmm dd yyyy\""));
01319     Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
01320                                                  Tok.getLocation(),
01321                                                  Tok.getLength()));
01322     return;
01323   } else if (II == Ident__TIME__) {
01324     Diag(Tok.getLocation(), diag::warn_pp_date_time);
01325     if (!TIMELoc.isValid())
01326       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
01327     Tok.setKind(tok::string_literal);
01328     Tok.setLength(strlen("\"hh:mm:ss\""));
01329     Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
01330                                                  Tok.getLocation(),
01331                                                  Tok.getLength()));
01332     return;
01333   } else if (II == Ident__INCLUDE_LEVEL__) {
01334     // Compute the presumed include depth of this token.  This can be affected
01335     // by GNU line markers.
01336     unsigned Depth = 0;
01337 
01338     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
01339     if (PLoc.isValid()) {
01340       PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
01341       for (; PLoc.isValid(); ++Depth)
01342         PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
01343     }
01344 
01345     // __INCLUDE_LEVEL__ expands to a simple numeric value.
01346     OS << Depth;
01347     Tok.setKind(tok::numeric_constant);
01348   } else if (II == Ident__TIMESTAMP__) {
01349     Diag(Tok.getLocation(), diag::warn_pp_date_time);
01350     // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
01351     // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
01352 
01353     // Get the file that we are lexing out of.  If we're currently lexing from
01354     // a macro, dig into the include stack.
01355     const FileEntry *CurFile = nullptr;
01356     PreprocessorLexer *TheLexer = getCurrentFileLexer();
01357 
01358     if (TheLexer)
01359       CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
01360 
01361     const char *Result;
01362     if (CurFile) {
01363       time_t TT = CurFile->getModificationTime();
01364       struct tm *TM = localtime(&TT);
01365       Result = asctime(TM);
01366     } else {
01367       Result = "??? ??? ?? ??:??:?? ????\n";
01368     }
01369     // Surround the string with " and strip the trailing newline.
01370     OS << '"' << StringRef(Result).drop_back() << '"';
01371     Tok.setKind(tok::string_literal);
01372   } else if (II == Ident__COUNTER__) {
01373     // __COUNTER__ expands to a simple numeric value.
01374     OS << CounterValue++;
01375     Tok.setKind(tok::numeric_constant);
01376   } else if (II == Ident__has_feature   ||
01377              II == Ident__has_extension ||
01378              II == Ident__has_builtin   ||
01379              II == Ident__is_identifier ||
01380              II == Ident__has_attribute ||
01381              II == Ident__has_cpp_attribute) {
01382     // The argument to these builtins should be a parenthesized identifier.
01383     SourceLocation StartLoc = Tok.getLocation();
01384 
01385     bool IsValid = false;
01386     IdentifierInfo *FeatureII = nullptr;
01387     IdentifierInfo *ScopeII = nullptr;
01388 
01389     // Read the '('.
01390     LexUnexpandedToken(Tok);
01391     if (Tok.is(tok::l_paren)) {
01392       // Read the identifier
01393       LexUnexpandedToken(Tok);
01394       if ((FeatureII = Tok.getIdentifierInfo())) {
01395         // If we're checking __has_cpp_attribute, it is possible to receive a
01396         // scope token. Read the "::", if it's available.
01397         LexUnexpandedToken(Tok);
01398         bool IsScopeValid = true;
01399         if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
01400           LexUnexpandedToken(Tok);
01401           // The first thing we read was not the feature, it was the scope.
01402           ScopeII = FeatureII;
01403           if ((FeatureII = Tok.getIdentifierInfo()))
01404             LexUnexpandedToken(Tok);
01405           else
01406             IsScopeValid = false;          
01407         }
01408         // Read the closing paren.
01409         if (IsScopeValid && Tok.is(tok::r_paren))
01410           IsValid = true;
01411       }
01412     }
01413 
01414     int Value = 0;
01415     if (!IsValid)
01416       Diag(StartLoc, diag::err_feature_check_malformed);
01417     else if (II == Ident__is_identifier)
01418       Value = FeatureII->getTokenID() == tok::identifier;
01419     else if (II == Ident__has_builtin) {
01420       // Check for a builtin is trivial.
01421       Value = FeatureII->getBuiltinID() != 0;
01422     } else if (II == Ident__has_attribute)
01423       Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII,
01424                            getTargetInfo().getTriple(), getLangOpts());
01425     else if (II == Ident__has_cpp_attribute)
01426       Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
01427                            getTargetInfo().getTriple(), getLangOpts());
01428     else if (II == Ident__has_extension)
01429       Value = HasExtension(*this, FeatureII);
01430     else {
01431       assert(II == Ident__has_feature && "Must be feature check");
01432       Value = HasFeature(*this, FeatureII);
01433     }
01434 
01435     OS << Value;
01436     if (IsValid)
01437       Tok.setKind(tok::numeric_constant);
01438   } else if (II == Ident__has_include ||
01439              II == Ident__has_include_next) {
01440     // The argument to these two builtins should be a parenthesized
01441     // file name string literal using angle brackets (<>) or
01442     // double-quotes ("").
01443     bool Value;
01444     if (II == Ident__has_include)
01445       Value = EvaluateHasInclude(Tok, II, *this);
01446     else
01447       Value = EvaluateHasIncludeNext(Tok, II, *this);
01448     OS << (int)Value;
01449     if (Tok.is(tok::r_paren))
01450       Tok.setKind(tok::numeric_constant);
01451   } else if (II == Ident__has_warning) {
01452     // The argument should be a parenthesized string literal.
01453     // The argument to these builtins should be a parenthesized identifier.
01454     SourceLocation StartLoc = Tok.getLocation();    
01455     bool IsValid = false;
01456     bool Value = false;
01457     // Read the '('.
01458     LexUnexpandedToken(Tok);
01459     do {
01460       if (Tok.isNot(tok::l_paren)) {
01461         Diag(StartLoc, diag::err_warning_check_malformed);
01462         break;
01463       }
01464 
01465       LexUnexpandedToken(Tok);
01466       std::string WarningName;
01467       SourceLocation StrStartLoc = Tok.getLocation();
01468       if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
01469                                   /*MacroExpansion=*/false)) {
01470         // Eat tokens until ')'.
01471         while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
01472                Tok.isNot(tok::eof))
01473           LexUnexpandedToken(Tok);
01474         break;
01475       }
01476 
01477       // Is the end a ')'?
01478       if (!(IsValid = Tok.is(tok::r_paren))) {
01479         Diag(StartLoc, diag::err_warning_check_malformed);
01480         break;
01481       }
01482 
01483       // FIXME: Should we accept "-R..." flags here, or should that be handled
01484       // by a separate __has_remark?
01485       if (WarningName.size() < 3 || WarningName[0] != '-' ||
01486           WarningName[1] != 'W') {
01487         Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
01488         break;
01489       }
01490 
01491       // Finally, check if the warning flags maps to a diagnostic group.
01492       // We construct a SmallVector here to talk to getDiagnosticIDs().
01493       // Although we don't use the result, this isn't a hot path, and not
01494       // worth special casing.
01495       SmallVector<diag::kind, 10> Diags;
01496       Value = !getDiagnostics().getDiagnosticIDs()->
01497         getDiagnosticsInGroup(diag::Flavor::WarningOrError,
01498                               WarningName.substr(2), Diags);
01499     } while (false);
01500 
01501     OS << (int)Value;
01502     if (IsValid)
01503       Tok.setKind(tok::numeric_constant);
01504   } else if (II == Ident__building_module) {
01505     // The argument to this builtin should be an identifier. The
01506     // builtin evaluates to 1 when that identifier names the module we are
01507     // currently building.
01508     OS << (int)EvaluateBuildingModule(Tok, II, *this);
01509     Tok.setKind(tok::numeric_constant);
01510   } else if (II == Ident__MODULE__) {
01511     // The current module as an identifier.
01512     OS << getLangOpts().CurrentModule;
01513     IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
01514     Tok.setIdentifierInfo(ModuleII);
01515     Tok.setKind(ModuleII->getTokenID());
01516   } else if (II == Ident__identifier) {
01517     SourceLocation Loc = Tok.getLocation();
01518 
01519     // We're expecting '__identifier' '(' identifier ')'. Try to recover
01520     // if the parens are missing.
01521     LexNonComment(Tok);
01522     if (Tok.isNot(tok::l_paren)) {
01523       // No '(', use end of last token.
01524       Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
01525         << II << tok::l_paren;
01526       // If the next token isn't valid as our argument, we can't recover.
01527       if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
01528         Tok.setKind(tok::identifier);
01529       return;
01530     }
01531 
01532     SourceLocation LParenLoc = Tok.getLocation();
01533     LexNonComment(Tok);
01534 
01535     if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
01536       Tok.setKind(tok::identifier);
01537     else {
01538       Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
01539         << Tok.getKind();
01540       // Don't walk past anything that's not a real token.
01541       if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
01542         return;
01543     }
01544 
01545     // Discard the ')', preserving 'Tok' as our result.
01546     Token RParen;
01547     LexNonComment(RParen);
01548     if (RParen.isNot(tok::r_paren)) {
01549       Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
01550         << Tok.getKind() << tok::r_paren;
01551       Diag(LParenLoc, diag::note_matching) << tok::l_paren;
01552     }
01553     return;
01554   } else {
01555     llvm_unreachable("Unknown identifier!");
01556   }
01557   CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
01558 }
01559 
01560 void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
01561   // If the 'used' status changed, and the macro requires 'unused' warning,
01562   // remove its SourceLocation from the warn-for-unused-macro locations.
01563   if (MI->isWarnIfUnused() && !MI->isUsed())
01564     WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
01565   MI->setIsUsed(true);
01566 }