zcov: / lib/Lex/PPMacroExpansion.cpp


Files: 1 Branches Taken: 78.4% 185 / 236
Generated: 2010-02-10 01:31 Branches Executed: 93.2% 220 / 236
Line Coverage: 85.8% 290 / 338


Programs: 2 Runs 3018


       1                 : //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
       2                 : //
       3                 : //                     The LLVM Compiler Infrastructure
       4                 : //
       5                 : // This file is distributed under the University of Illinois Open Source
       6                 : // License. See LICENSE.TXT for details.
       7                 : //
       8                 : //===----------------------------------------------------------------------===//
       9                 : //
      10                 : // This file implements the top level handling of macro expasion for the
      11                 : // preprocessor.
      12                 : //
      13                 : //===----------------------------------------------------------------------===//
      14                 : 
      15                 : #include "clang/Lex/Preprocessor.h"
      16                 : #include "MacroArgs.h"
      17                 : #include "clang/Lex/MacroInfo.h"
      18                 : #include "clang/Basic/SourceManager.h"
      19                 : #include "clang/Basic/FileManager.h"
      20                 : #include "clang/Lex/LexDiagnostic.h"
      21                 : #include "llvm/ADT/StringSwitch.h"
      22                 : #include "llvm/Support/raw_ostream.h"
      23                 : #include <cstdio>
      24                 : #include <ctime>
      25                 : using namespace clang;
      26                 : 
      27                 : /// setMacroInfo - Specify a macro for this identifier.
      28                 : ///
      29           303350: void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
                   303194: branch 0 taken
                      156: branch 1 taken
      30           303350:   if (MI) {
      31           303194:     Macros[II] = MI;
      32           303194:     II->setHasMacroDefinition(true);
                      156: branch 1 taken
                        0: branch 2 not taken
      33              156:   } else if (II->hasMacroDefinition()) {
      34              156:     Macros.erase(II);
      35              156:     II->setHasMacroDefinition(false);
      36                 :   }
      37           303350: }
      38                 : 
      39                 : /// RegisterBuiltinMacro - Register the specified identifier in the identifier
      40                 : /// table and mark it as a builtin macro to be expanded.
      41            32929: static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
      42                 :   // Get the identifier.
      43            32929:   IdentifierInfo *Id = PP.getIdentifierInfo(Name);
      44                 : 
      45                 :   // Mark it as being a macro that is builtin.
      46            32929:   MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
      47            32929:   MI->setIsBuiltinMacro();
      48            32929:   PP.setMacroInfo(Id, MI);
      49            32929:   return Id;
      50                 : }
      51                 : 
      52                 : 
      53                 : /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
      54                 : /// identifier table.
      55             2533: void Preprocessor::RegisterBuiltinMacros() {
      56             2533:   Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
      57             2533:   Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
      58             2533:   Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
      59             2533:   Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
      60             2533:   Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
      61             2533:   Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
      62                 : 
      63                 :   // GCC Extensions.
      64             2533:   Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
      65             2533:   Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
      66             2533:   Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
      67                 : 
      68                 :   // Clang Extensions.
      69             2533:   Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
      70             2533:   Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
      71             2533:   Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
      72             2533:   Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
      73             2533: }
      74                 : 
      75                 : /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
      76                 : /// in its expansion, currently expands to that token literally.
      77                 : static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
      78                 :                                           const IdentifierInfo *MacroIdent,
      79             4668:                                           Preprocessor &PP) {
      80             4668:   IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
      81                 : 
      82                 :   // If the token isn't an identifier, it's always literally expanded.
                     2389: branch 0 taken
                     2279: branch 1 taken
      83             4668:   if (II == 0) return true;
      84                 : 
      85                 :   // If the identifier is a macro, and if that macro is enabled, it may be
      86                 :   // expanded so it's not a trivial expansion.
                     1133: branch 1 taken
                     1146: branch 2 taken
                     1131: branch 5 taken
                        2: branch 6 taken
                     1131: branch 7 taken
                        0: branch 8 not taken
                     1131: branch 9 taken
                     1148: branch 10 taken
      87             2279:   if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
      88                 :       // Fast expanding "#define X X" is ok, because X would be disabled.
      89                 :       II != MacroIdent)
      90             1131:     return false;
      91                 : 
      92                 :   // If this is an object-like macro invocation, it is safe to trivially expand
      93                 :   // it.
                      765: branch 1 taken
                      383: branch 2 taken
      94             1148:   if (MI->isObjectLike()) return true;
      95                 : 
      96                 :   // If this is a function-like macro invocation, it's safe to trivially expand
      97                 :   // as long as the identifier is not a macro argument.
                      378: branch 2 taken
                        9: branch 3 taken
      98              387:   for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
      99                 :        I != E; ++I)
                      374: branch 0 taken
                        4: branch 1 taken
     100              378:     if (*I == II)
     101              374:       return false;   // Identifier is a macro argument.
     102                 : 
     103                9:   return true;
     104                 : }
     105                 : 
     106                 : 
     107                 : /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
     108                 : /// lexed is a '('.  If so, consume the token and return true, if not, this
     109                 : /// method should have no observable side-effect on the lexed tokens.
     110             4020: bool Preprocessor::isNextPPTokenLParen() {
     111                 :   // Do some quick tests for rejection cases.
     112                 :   unsigned Val;
                     2095: branch 1 taken
                     1925: branch 2 taken
     113             4020:   if (CurLexer)
     114             2095:     Val = CurLexer->isNextPPTokenLParen();
                        0: branch 1 not taken
                     1925: branch 2 taken
     115             1925:   else if (CurPTHLexer)
     116                0:     Val = CurPTHLexer->isNextPPTokenLParen();
     117                 :   else
     118             1925:     Val = CurTokenLexer->isNextTokenLParen();
     119                 : 
                       43: branch 0 taken
                     3977: branch 1 taken
     120             4020:   if (Val == 2) {
     121                 :     // We have run off the end.  If it's a source file we don't
     122                 :     // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
     123                 :     // macro stack.
                        1: branch 0 taken
                       42: branch 1 taken
     124               43:     if (CurPPLexer)
     125                1:       return false;
                       42: branch 1 taken
                        0: branch 2 not taken
     126               42:     for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
     127               42:       IncludeStackInfo &Entry = IncludeMacroStack[i-1];
                       31: branch 0 taken
                       11: branch 1 taken
     128               42:       if (Entry.TheLexer)
     129               31:         Val = Entry.TheLexer->isNextPPTokenLParen();
                        0: branch 0 not taken
                       11: branch 1 taken
     130               11:       else if (Entry.ThePTHLexer)
     131                0:         Val = Entry.ThePTHLexer->isNextPPTokenLParen();
     132                 :       else
     133               11:         Val = Entry.TheTokenLexer->isNextTokenLParen();
     134                 : 
                       42: branch 0 taken
                        0: branch 1 not taken
     135               42:       if (Val != 2)
     136               42:         break;
     137                 : 
     138                 :       // Ran off the end of a source file?
                        0: branch 0 not taken
                        0: branch 1 not taken
     139                0:       if (Entry.ThePPLexer)
     140                0:         return false;
     141                 :     }
     142                 :   }
     143                 : 
     144                 :   // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
     145                 :   // have found something that isn't a '(' or we found the end of the
     146                 :   // translation unit.  In either case, return false.
     147             4019:   return Val == 1;
     148                 : }
     149                 : 
     150                 : /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
     151                 : /// expanded as a macro, handle it and return the next token as 'Identifier'.
     152                 : bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
     153            11808:                                                  MacroInfo *MI) {
                     5323: branch 0 taken
                     6485: branch 1 taken
     154            11808:   if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
     155                 : 
     156                 :   // If this is a macro expansion in the "#if !defined(x)" line for the file,
     157                 :   // then the macro could expand to different things in other contexts, we need
     158                 :   // to disable the optimization in this case.
                     6809: branch 0 taken
                     4999: branch 1 taken
     159            11808:   if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
     160                 : 
     161                 :   // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
                      234: branch 1 taken
                    11574: branch 2 taken
     162            11808:   if (MI->isBuiltinMacro()) {
     163              234:     ExpandBuiltinMacro(Identifier);
     164              234:     return false;
     165                 :   }
     166                 : 
     167                 :   /// Args - If this is a function-like macro expansion, this contains,
     168                 :   /// for each macro argument, the list of tokens that were provided to the
     169                 :   /// invocation.
     170            11574:   MacroArgs *Args = 0;
     171                 : 
     172                 :   // Remember where the end of the instantiation occurred.  For an object-like
     173                 :   // macro, this is the identifier.  For a function-like macro, this is the ')'.
     174            11574:   SourceLocation InstantiationEnd = Identifier.getLocation();
     175                 : 
     176                 :   // If this is a function-like macro, read the arguments.
                     4020: branch 1 taken
                     7554: branch 2 taken
     177            11574:   if (MI->isFunctionLike()) {
     178                 :     // C99 6.10.3p10: If the preprocessing token immediately after the the macro
     179                 :     // name isn't a '(', this macro should not be expanded.
                       38: branch 1 taken
                     3982: branch 2 taken
     180             4020:     if (!isNextPPTokenLParen())
     181               38:       return true;
     182                 : 
     183                 :     // Remember that we are now parsing the arguments to a macro invocation.
     184                 :     // Preprocessor directives used inside macro arguments are not portable, and
     185                 :     // this enables the warning.
     186             3982:     InMacroArgs = true;
     187             3982:     Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
     188                 : 
     189                 :     // Finished parsing args.
     190             3982:     InMacroArgs = false;
     191                 : 
     192                 :     // If there was an error parsing the arguments, bail out.
                       10: branch 0 taken
                     3972: branch 1 taken
     193             3982:     if (Args == 0) return false;
     194                 : 
     195             3972:     ++NumFnMacroExpanded;
     196                 :   } else {
     197             7554:     ++NumMacroExpanded;
     198                 :   }
     199                 : 
     200                 :   // Notice that this macro has been used.
     201            11526:   MI->setIsUsed(true);
     202                 : 
     203                 :   // If we started lexing a macro, enter the macro expansion body.
     204                 : 
     205                 :   // If this macro expands to no tokens, don't bother to push it onto the
     206                 :   // expansion stack, only to take it right back off.
                      848: branch 1 taken
                    10678: branch 2 taken
     207            11526:   if (MI->getNumTokens() == 0) {
     208                 :     // No need for arg info.
                       19: branch 0 taken
                      829: branch 1 taken
     209              848:     if (Args) Args->destroy(*this);
     210                 : 
     211                 :     // Ignore this macro use, just return the next token in the current
     212                 :     // buffer.
     213              848:     bool HadLeadingSpace = Identifier.hasLeadingSpace();
     214              848:     bool IsAtStartOfLine = Identifier.isAtStartOfLine();
     215                 : 
     216              848:     Lex(Identifier);
     217                 : 
     218                 :     // If the identifier isn't on some OTHER line, inherit the leading
     219                 :     // whitespace/first-on-a-line property of this token.  This handles
     220                 :     // stuff like "! XX," -> "! ," and "   XX," -> "    ,", when XX is
     221                 :     // empty.
                      420: branch 1 taken
                      428: branch 2 taken
     222              848:     if (!Identifier.isAtStartOfLine()) {
                        7: branch 0 taken
                      413: branch 1 taken
     223              420:       if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
                      396: branch 0 taken
                       24: branch 1 taken
     224              420:       if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
     225                 :     }
     226              848:     ++NumFastMacroExpanded;
     227              848:     return false;
     228                 : 
                     4668: branch 1 taken
                     6010: branch 2 taken
                     3163: branch 5 taken
                     1505: branch 6 taken
                     3163: branch 7 taken
                     7515: branch 8 taken
     229            10678:   } else if (MI->getNumTokens() == 1 &&
     230                 :              isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
     231                 :                                            *this)) {
     232                 :     // Otherwise, if this macro expands into a single trivially-expanded
     233                 :     // token: expand it now.  This handles common cases like
     234                 :     // "#define VAL 42".
     235                 : 
     236                 :     // No need for arg info.
                       19: branch 0 taken
                     3144: branch 1 taken
     237             3163:     if (Args) Args->destroy(*this);
     238                 : 
     239                 :     // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
     240                 :     // identifier to the expanded token.
     241             3163:     bool isAtStartOfLine = Identifier.isAtStartOfLine();
     242             3163:     bool hasLeadingSpace = Identifier.hasLeadingSpace();
     243                 : 
     244                 :     // Remember where the token is instantiated.
     245             3163:     SourceLocation InstantiateLoc = Identifier.getLocation();
     246                 : 
     247                 :     // Replace the result token.
     248             3163:     Identifier = MI->getReplacementToken(0);
     249                 : 
     250                 :     // Restore the StartOfLine/LeadingSpace markers.
     251             3163:     Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
     252             3163:     Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
     253                 : 
     254                 :     // Update the tokens location to include both its instantiation and physical
     255                 :     // locations.
     256                 :     SourceLocation Loc =
     257                 :       SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
     258             3163:                                        InstantiationEnd,Identifier.getLength());
     259             3163:     Identifier.setLocation(Loc);
     260                 : 
     261                 :     // If this is #define X X, we must mark the result as unexpandible.
                      774: branch 1 taken
                     2389: branch 2 taken
     262             3163:     if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
                        0: branch 1 not taken
                      774: branch 2 taken
     263              774:       if (getMacroInfo(NewII) == MI)
     264                0:         Identifier.setFlag(Token::DisableExpand);
     265                 : 
     266                 :     // Since this is not an identifier token, it can't be macro expanded, so
     267                 :     // we're done.
     268             3163:     ++NumFastMacroExpanded;
     269             3163:     return false;
     270                 :   }
     271                 : 
     272                 :   // Start expanding the macro.
     273             7515:   EnterMacro(Identifier, InstantiationEnd, Args);
     274                 : 
     275                 :   // Now that the macro is at the top of the include stack, ask the
     276                 :   // preprocessor to read the next token from it.
     277             7515:   Lex(Identifier);
     278             7515:   return false;
     279                 : }
     280                 : 
     281                 : /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
     282                 : /// token is the '(' of the macro, this method is invoked to read all of the
     283                 : /// actual arguments specified for the macro invocation.  This returns null on
     284                 : /// error.
     285                 : MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
     286                 :                                                    MacroInfo *MI,
     287             3982:                                                    SourceLocation &MacroEnd) {
     288                 :   // The number of fixed arguments to parse.
     289             3982:   unsigned NumFixedArgsLeft = MI->getNumArgs();
     290             3982:   bool isVariadic = MI->isVariadic();
     291                 : 
     292                 :   // Outer loop, while there are more arguments, keep reading them.
     293             3982:   Token Tok;
     294                 : 
     295                 :   // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
     296                 :   // an argument value in a macro could expand to ',' or '(' or ')'.
     297             3982:   LexUnexpandedToken(Tok);
                     3982: branch 1 taken
                        0: branch 2 not taken
     298             3982:   assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
     299                 : 
     300                 :   // ArgTokens - Build up a list of tokens that make up each argument.  Each
     301                 :   // argument is separated by an EOF token.  Use a SmallVector so we can avoid
     302                 :   // heap allocations in the common case.
     303             3982:   llvm::SmallVector<Token, 64> ArgTokens;
     304                 : 
     305             3982:   unsigned NumActuals = 0;
                     6164: branch 1 taken
                     3895: branch 2 taken
     306            14041:   while (Tok.isNot(tok::r_paren)) {
     307                 :     assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
                     2182: branch 1 taken
                     3982: branch 2 taken
                     2182: branch 4 taken
                        0: branch 5 not taken
     308             6164:            "only expect argument separators here");
     309                 : 
     310             6164:     unsigned ArgTokenStart = ArgTokens.size();
     311             6164:     SourceLocation ArgStartLoc = Tok.getLocation();
     312                 : 
     313                 :     // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
     314                 :     // that we already consumed the first one.
     315             6164:     unsigned NumParens = 0;
     316                 : 
     317            12083:     while (1) {
     318                 :       // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
     319                 :       // an argument value in a macro could expand to ',' or '(' or ')'.
     320            18247:       LexUnexpandedToken(Tok);
     321                 : 
                    18247: branch 1 taken
                        0: branch 2 not taken
                        1: branch 4 taken
                    18246: branch 5 taken
                        1: branch 6 taken
                    18246: branch 7 taken
     322            18247:       if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
     323                1:         Diag(MacroName, diag::err_unterm_macro_invoc);
     324                 :         // Do not lose the EOF/EOM.  Return it to the client.
     325                1:         MacroName = Tok;
     326                1:         return 0;
                     5013: branch 1 taken
                    13233: branch 2 taken
     327            18246:       } else if (Tok.is(tok::r_paren)) {
     328                 :         // If we found the ) token, the macro arg list is done.
                     3980: branch 0 taken
                     1033: branch 1 taken
     329             5013:         if (NumParens-- == 0) {
     330             3980:           MacroEnd = Tok.getLocation();
     331             3980:           break;
     332                 :         }
                     1033: branch 1 taken
                    12200: branch 2 taken
     333            13233:       } else if (Tok.is(tok::l_paren)) {
     334             1033:         ++NumParens;
                     2523: branch 1 taken
                     9677: branch 2 taken
                     2232: branch 3 taken
                      291: branch 4 taken
                     2232: branch 5 taken
                     9968: branch 6 taken
     335            12200:       } else if (Tok.is(tok::comma) && NumParens == 0) {
     336                 :         // Comma ends this argument if there are more fixed arguments expected.
     337                 :         // However, if this is a variadic macro, and this is part of the
     338                 :         // variadic part, then the comma is just an argument token.
                       88: branch 0 taken
                     2144: branch 1 taken
     339             2232:         if (!isVariadic) break;
                       39: branch 0 taken
                       49: branch 1 taken
     340               88:         if (NumFixedArgsLeft > 1)
     341               39:           break;
                        0: branch 1 not taken
                     9968: branch 2 taken
                     9968: branch 3 taken
                     9968: branch 4 taken
                        0: branch 5 not taken
                     9968: branch 6 taken
     342             9968:       } else if (Tok.is(tok::comment) && !KeepMacroComments) {
     343                 :         // If this is a comment token in the argument list and we're just in
     344                 :         // -C mode (not -CC mode), discard the comment.
     345                0:         continue;
                     3365: branch 1 taken
                     6603: branch 2 taken
     346             9968:       } else if (Tok.getIdentifierInfo() != 0) {
     347                 :         // Reading macro arguments can cause macros that we are currently
     348                 :         // expanding from to be popped off the expansion stack.  Doing so causes
     349                 :         // them to be reenabled for expansion.  Here we record whether any
     350                 :         // identifiers we lex as macro arguments correspond to disabled macros.
     351                 :         // If so, we mark the token as noexpand.  This is a subtle aspect of
     352                 :         // C99 6.10.3.4p2.
                      644: branch 2 taken
                     2721: branch 3 taken
     353             3365:         if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
                        7: branch 1 taken
                      637: branch 2 taken
     354              644:           if (!MI->isEnabled())
     355                7:             Tok.setFlag(Token::DisableExpand);
     356                 :       }
     357            12083:       ArgTokens.push_back(Tok);
     358                 :     }
     359                 : 
     360                 :     // If this was an empty argument list foo(), don't add this as an empty
     361                 :     // argument.
                       89: branch 1 taken
                     6074: branch 2 taken
                       80: branch 4 taken
                        9: branch 5 taken
                       80: branch 6 taken
                     6083: branch 7 taken
     362             6163:     if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
     363               80:       break;
     364                 : 
     365                 :     // If this is not a variadic macro, and too many args were specified, emit
     366                 :     // an error.
                     5981: branch 0 taken
                      102: branch 1 taken
                        6: branch 2 taken
                     5975: branch 3 taken
     367             6083:     if (!isVariadic && NumFixedArgsLeft == 0) {
                        4: branch 1 taken
                        2: branch 2 taken
     368                6:       if (ArgTokens.size() != ArgTokenStart)
     369                4:         ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
     370                 : 
     371                 :       // Emit the diagnostic at the macro name in case there is a missing ).
     372                 :       // Emitting it at the , could be far away from the macro name.
     373                6:       Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
     374                6:       return 0;
     375                 :     }
     376                 : 
     377                 :     // Empty arguments are standard in C99 and supported as an extension in
     378                 :     // other modes.
                       33: branch 1 taken
                     6044: branch 2 taken
                        5: branch 3 taken
                       28: branch 4 taken
                        5: branch 5 taken
                     6072: branch 6 taken
     379             6077:     if (ArgTokens.size() == ArgTokenStart && !Features.C99)
     380                5:       Diag(Tok, diag::ext_empty_fnmacro_arg);
     381                 : 
     382                 :     // Add a marker EOF token to the end of the token list for this argument.
     383             6077:     Token EOFTok;
     384             6077:     EOFTok.startToken();
     385             6077:     EOFTok.setKind(tok::eof);
     386             6077:     EOFTok.setLocation(Tok.getLocation());
     387             6077:     EOFTok.setLength(0);
     388             6077:     ArgTokens.push_back(EOFTok);
     389             6077:     ++NumActuals;
                        0: branch 0 not taken
                     6077: branch 1 taken
     390             6077:     assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
     391             6077:     --NumFixedArgsLeft;
     392                 :   }
     393                 : 
     394                 :   // Okay, we either found the r_paren.  Check to see if we parsed too few
     395                 :   // arguments.
     396             3975:   unsigned MinArgsExpected = MI->getNumArgs();
     397                 : 
     398                 :   // See MacroArgs instance var for description of this.
     399             3975:   bool isVarargsElided = false;
     400                 : 
                       69: branch 0 taken
                     3906: branch 1 taken
     401             3975:   if (NumActuals < MinArgsExpected) {
     402                 :     // There are several cases where too few arguments is ok, handle them now.
                       51: branch 0 taken
                       18: branch 1 taken
                       46: branch 2 taken
                        5: branch 3 taken
     403              115:     if (NumActuals == 0 && MinArgsExpected == 1) {
     404                 :       // #define A(X)  or  #define A(...)   ---> A()
     405                 : 
     406                 :       // If there is exactly one argument, and that argument is missing,
     407                 :       // then we have an empty "()" argument empty list.  This is fine, even if
     408                 :       // the macro expects one argument (the argument is just empty).
     409               46:       isVarargsElided = MI->isVariadic();
                       20: branch 1 taken
                        3: branch 2 taken
                        4: branch 3 taken
                       16: branch 4 taken
                        4: branch 5 taken
                        0: branch 6 not taken
                        4: branch 7 taken
                        0: branch 8 not taken
                       20: branch 9 taken
                        3: branch 10 taken
     410               23:     } else if (MI->isVariadic() &&
     411                 :                (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
     412                 :                 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
     413                 :       // Varargs where the named vararg parameter is missing: ok as extension.
     414                 :       // #define A(x, ...)
     415                 :       // A("blah")
     416               20:       Diag(Tok, diag::ext_missing_varargs_arg);
     417                 : 
     418                 :       // Remember this occurred, allowing us to elide the comma when used for
     419                 :       // cases like:
     420                 :       //   #define A(x, foo...) blah(a, ## foo)
     421                 :       //   #define B(x, ...) blah(a, ## __VA_ARGS__)
     422                 :       //   #define C(...) blah(a, ## __VA_ARGS__)
     423                 :       //  A(x) B(x) C()
     424               20:       isVarargsElided = true;
     425                 :     } else {
     426                 :       // Otherwise, emit the error.
     427                3:       Diag(Tok, diag::err_too_few_args_in_macro_invoc);
     428                3:       return 0;
     429                 :     }
     430                 : 
     431                 :     // Add a marker EOF token to the end of the token list for this argument.
     432               66:     SourceLocation EndLoc = Tok.getLocation();
     433               66:     Tok.startToken();
     434               66:     Tok.setKind(tok::eof);
     435               66:     Tok.setLocation(EndLoc);
     436               66:     Tok.setLength(0);
     437               66:     ArgTokens.push_back(Tok);
     438                 : 
     439                 :     // If we expect two arguments, add both as empty.
                       50: branch 0 taken
                       16: branch 1 taken
                        4: branch 2 taken
                       46: branch 3 taken
     440               66:     if (NumActuals == 0 && MinArgsExpected == 2)
     441                4:       ArgTokens.push_back(Tok);
     442                 : 
                        0: branch 0 not taken
                     3906: branch 1 taken
                        0: branch 3 not taken
                        0: branch 4 not taken
                        0: branch 5 not taken
                     3906: branch 6 taken
     443             3906:   } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
     444                 :     // Emit the diagnostic at the macro name in case there is a missing ).
     445                 :     // Emitting it at the , could be far away from the macro name.
     446                0:     Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
     447                0:     return 0;
     448                 :   }
     449                 : 
     450                 :   return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
     451             3972:                            isVarargsElided, *this);
     452                 : }
     453                 : 
     454                 : /// ComputeDATE_TIME - Compute the current time, enter it into the specified
     455                 : /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
     456                 : /// the identifier tokens inserted.
     457                 : static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
     458                1:                              Preprocessor &PP) {
     459                1:   time_t TT = time(0);
     460                1:   struct tm *TM = localtime(&TT);
     461                 : 
     462                 :   static const char * const Months[] = {
     463                 :     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
     464                 :   };
     465                 : 
     466                 :   char TmpBuffer[100];
     467                 :   sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
     468                1:           TM->tm_year+1900);
     469                 : 
     470                1:   Token TmpTok;
     471                1:   TmpTok.startToken();
     472                1:   PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
     473                1:   DATELoc = TmpTok.getLocation();
     474                 : 
     475                1:   sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
     476                1:   PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
     477                1:   TIMELoc = TmpTok.getLocation();
     478                1: }
     479                 : 
     480                 : 
     481                 : /// HasFeature - Return true if we recognize and implement the specified feature
     482                 : /// specified by the identifier.
     483               36: static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
     484               36:   const LangOptions &LangOpts = PP.getLangOptions();
     485                 : 
     486                 :   return llvm::StringSwitch<bool>(II->getName())
     487                 :            .Case("blocks", LangOpts.Blocks)
     488                 :            .Case("cxx_rtti", LangOpts.RTTI)
     489                 :          //.Case("cxx_lambdas", false)
     490                 :          //.Case("cxx_nullptr", false)
     491                 :          //.Case("cxx_concepts", false)
     492                 :            .Case("cxx_decltype", LangOpts.CPlusPlus0x)
     493                 :            .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
     494                 :            .Case("cxx_exceptions", LangOpts.Exceptions)
     495                 :            .Case("cxx_attributes", LangOpts.CPlusPlus0x)
     496                 :            .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
     497                 :            .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
     498                 :            .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
     499                 :          //.Case("cxx_rvalue_references", false)
     500                 :            .Case("attribute_overloadable", true)
     501                 :          //.Case("cxx_variadic_templates", false)
     502                 :            .Case("attribute_ext_vector_type", true)
     503                 :            .Case("attribute_analyzer_noreturn", true)
     504                 :            .Case("attribute_ns_returns_retained", true)
     505                 :            .Case("attribute_cf_returns_retained", true)
     506               36:            .Default(false);
     507                 : }
     508                 : 
     509                 : /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
     510                 : /// or '__has_include_next("path")' expression.
     511                 : /// Returns true if successful.
     512                 : static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
     513                 :         IdentifierInfo *II, Preprocessor &PP,
     514               38:         const DirectoryLookup *LookupFrom) {
     515               38:   SourceLocation LParenLoc;
     516                 : 
     517                 :   // Get '('.
     518               38:   PP.LexNonComment(Tok);
     519                 : 
     520                 :   // Ensure we have a '('.
                        0: branch 1 not taken
                       38: branch 2 taken
     521               38:   if (Tok.isNot(tok::l_paren)) {
     522                0:     PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
     523                0:     return false;
     524                 :   }
     525                 : 
     526                 :   // Save '(' location for possible missing ')' message.
     527               38:   LParenLoc = Tok.getLocation();
     528                 : 
     529                 :   // Get the file name.
     530               38:   PP.getCurrentLexer()->LexIncludeFilename(Tok);
     531                 : 
     532                 :   // Reserve a buffer to get the spelling.
     533               38:   llvm::SmallString<128> FilenameBuffer;
     534               38:   llvm::StringRef Filename;
     535                 : 
                        0: branch 1 not taken
                       38: branch 2 taken
                        0: branch 3 not taken
                        0: branch 4 not taken
     536               38:   switch (Tok.getKind()) {
     537                 :   case tok::eom:
     538                 :     // If the token kind is EOM, the error has already been diagnosed.
     539                0:     return false;
     540                 : 
     541                 :   case tok::angle_string_literal:
     542                 :   case tok::string_literal: {
     543               38:     FilenameBuffer.resize(Tok.getLength());
     544               38:     const char *FilenameStart = &FilenameBuffer[0];
     545               38:     unsigned Len = PP.getSpelling(Tok, FilenameStart);
     546               38:     Filename = llvm::StringRef(FilenameStart, Len);
     547               38:     break;
     548                 :   }
     549                 : 
     550                 :   case tok::less:
     551                 :     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
     552                 :     // case, glue the tokens together into FilenameBuffer and interpret those.
     553                0:     FilenameBuffer.push_back('<');
                        0: branch 1 not taken
                        0: branch 2 not taken
     554                0:     if (PP.ConcatenateIncludeName(FilenameBuffer))
     555                0:       return false;   // Found <eom> but no ">"?  Diagnostic already emitted.
     556                0:     Filename = FilenameBuffer.str();
     557                0:     break;
     558                 :   default:
     559                0:     PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
     560                0:     return false;
     561                 :   }
     562                 : 
     563               38:   bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
     564                 :   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
     565                 :   // error.
                        0: branch 1 not taken
                       38: branch 2 taken
     566               38:   if (Filename.empty())
     567                0:     return false;
     568                 : 
     569                 :   // Search include directories.
     570                 :   const DirectoryLookup *CurDir;
     571               38:   const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
     572                 : 
     573                 :   // Get the result value.  Result = true means the file exists.
     574               38:   Result = File != 0;
     575                 : 
     576                 :   // Get ')'.
     577               38:   PP.LexNonComment(Tok);
     578                 : 
     579                 :   // Ensure we have a trailing ).
                        0: branch 1 not taken
                       38: branch 2 taken
     580               38:   if (Tok.isNot(tok::r_paren)) {
     581                0:     PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
     582                0:     PP.Diag(LParenLoc, diag::note_matching) << "(";
     583                0:     return false;
     584                 :   }
     585                 : 
     586               38:   return true;
     587                 : }
     588                 : 
     589                 : /// EvaluateHasInclude - Process a '__has_include("path")' expression.
     590                 : /// Returns true if successful.
     591                 : static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
     592                7:                                Preprocessor &PP) {
     593                7:   return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
     594                 : }
     595                 : 
     596                 : /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
     597                 : /// Returns true if successful.
     598                 : static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
     599               31:                                    IdentifierInfo *II, Preprocessor &PP) {
     600                 :   // __has_include_next is like __has_include, except that we start
     601                 :   // searching after the current found directory.  If we can't do this,
     602                 :   // issue a diagnostic.
     603               31:   const DirectoryLookup *Lookup = PP.GetCurDirLookup();
                        5: branch 1 taken
                       26: branch 2 taken
     604               31:   if (PP.isInPrimaryFile()) {
     605                5:     Lookup = 0;
     606                5:     PP.Diag(Tok, diag::pp_include_next_in_primary);
                        0: branch 0 not taken
                       26: branch 1 taken
     607               26:   } else if (Lookup == 0) {
     608                0:     PP.Diag(Tok, diag::pp_include_next_absolute_path);
     609                 :   } else {
     610                 :     // Start looking up in the next directory.
     611               26:     ++Lookup;
     612                 :   }
     613                 : 
     614               31:   return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
     615                 : }
     616                 : 
     617                 : /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
     618                 : /// as a builtin macro, handle it and return the next token as 'Tok'.
     619              234: void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
     620                 :   // Figure out which token this is.
     621              234:   IdentifierInfo *II = Tok.getIdentifierInfo();
                        0: branch 0 not taken
                      234: branch 1 taken
     622              234:   assert(II && "Can't be a macro without id info!");
     623                 : 
     624                 :   // If this is an _Pragma directive, expand it, invoke the pragma handler, then
     625                 :   // lex the token after it.
                       16: branch 0 taken
                      218: branch 1 taken
     626              234:   if (II == Ident_Pragma)
     627               16:     return Handle_Pragma(Tok);
     628                 : 
     629              218:   ++NumBuiltinMacroExpanded;
     630                 : 
     631              218:   llvm::SmallString<128> TmpBuffer;
     632              218:   llvm::raw_svector_ostream OS(TmpBuffer);
     633                 : 
     634                 :   // Set up the return result.
     635              218:   Tok.setIdentifierInfo(0);
     636              218:   Tok.clearFlag(Token::NeedsCleaning);
     637                 : 
                       89: branch 0 taken
                      129: branch 1 taken
     638              218:   if (II == Ident__LINE__) {
     639                 :     // C99 6.10.8: "__LINE__: The presumed line number (within the current
     640                 :     // source file) of the current source line (an integer constant)".  This can
     641                 :     // be affected by #line.
     642               89:     SourceLocation Loc = Tok.getLocation();
     643                 : 
     644                 :     // Advance to the location of the first _, this might not be the first byte
     645                 :     // of the token if it starts with an escaped newline.
     646               89:     Loc = AdvanceToTokenCharacter(Loc, 0);
     647                 : 
     648                 :     // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
     649                 :     // a macro instantiation.  This doesn't matter for object-like macros, but
     650                 :     // can matter for a function-like macro that expands to contain __LINE__.
     651                 :     // Skip down through instantiation points until we find a file loc for the
     652                 :     // end of the instantiation history.
     653               89:     Loc = SourceMgr.getInstantiationRange(Loc).second;
     654               89:     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
     655                 : 
     656                 :     // __LINE__ expands to a simple numeric value.
     657               89:     OS << PLoc.getLine();
     658               89:     Tok.setKind(tok::numeric_constant);
                      100: branch 0 taken
                       29: branch 1 taken
                        0: branch 2 not taken
                      100: branch 3 taken
     659              158:   } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
     660                 :     // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
     661                 :     // character string literal)". This can be affected by #line.
     662               29:     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
     663                 : 
     664                 :     // __BASE_FILE__ is a GNU extension that returns the top of the presumed
     665                 :     // #include stack instead of the current file.
                        0: branch 0 not taken
                       29: branch 1 taken
     666               29:     if (II == Ident__BASE_FILE__) {
     667                0:       SourceLocation NextLoc = PLoc.getIncludeLoc();
                        0: branch 1 not taken
                        0: branch 2 not taken
     668                0:       while (NextLoc.isValid()) {
     669                0:         PLoc = SourceMgr.getPresumedLoc(NextLoc);
     670                0:         NextLoc = PLoc.getIncludeLoc();
     671                 :       }
     672                 :     }
     673                 : 
     674                 :     // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
     675               29:     llvm::SmallString<128> FN;
     676               29:     FN += PLoc.getFilename();
     677               29:     Lexer::Stringify(FN);
     678               29:     OS << '"' << FN.str() << '"';
     679               29:     Tok.setKind(tok::string_literal);
                        1: branch 0 taken
                       99: branch 1 taken
     680              100:   } else if (II == Ident__DATE__) {
                        1: branch 1 taken
                        0: branch 2 not taken
     681                1:     if (!DATELoc.isValid())
     682                1:       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
     683                1:     Tok.setKind(tok::string_literal);
     684                1:     Tok.setLength(strlen("\"Mmm dd yyyy\""));
     685                 :     Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
     686                 :                                                      Tok.getLocation(),
     687                1:                                                      Tok.getLength()));
     688                2:     return;
                        1: branch 0 taken
                       98: branch 1 taken
     689               99:   } else if (II == Ident__TIME__) {
                        0: branch 1 not taken
                        1: branch 2 taken
     690                1:     if (!TIMELoc.isValid())
     691                0:       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
     692                1:     Tok.setKind(tok::string_literal);
     693                1:     Tok.setLength(strlen("\"hh:mm:ss\""));
     694                 :     Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
     695                 :                                                      Tok.getLocation(),
     696                1:                                                      Tok.getLength()));
     697                 :     return;
                        0: branch 0 not taken
                       98: branch 1 taken
     698               98:   } else if (II == Ident__INCLUDE_LEVEL__) {
     699                 :     // Compute the presumed include depth of this token.  This can be affected
     700                 :     // by GNU line markers.
     701                0:     unsigned Depth = 0;
     702                 : 
     703                0:     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
     704                0:     PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
                        0: branch 1 not taken
                        0: branch 2 not taken
     705                0:     for (; PLoc.isValid(); ++Depth)
     706                0:       PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
     707                 : 
     708                 :     // __INCLUDE_LEVEL__ expands to a simple numeric value.
     709                0:     OS << Depth;
     710                0:     Tok.setKind(tok::numeric_constant);
                        0: branch 0 not taken
                       98: branch 1 taken
     711               98:   } else if (II == Ident__TIMESTAMP__) {
     712                 :     // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
     713                 :     // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
     714                 : 
     715                 :     // Get the file that we are lexing out of.  If we're currently lexing from
     716                 :     // a macro, dig into the include stack.
     717                0:     const FileEntry *CurFile = 0;
     718                0:     PreprocessorLexer *TheLexer = getCurrentFileLexer();
     719                 : 
                        0: branch 0 not taken
                        0: branch 1 not taken
     720                0:     if (TheLexer)
     721                0:       CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
     722                 : 
     723                 :     const char *Result;
                        0: branch 0 not taken
                        0: branch 1 not taken
     724                0:     if (CurFile) {
     725                0:       time_t TT = CurFile->getModificationTime();
     726                0:       struct tm *TM = localtime(&TT);
     727                0:       Result = asctime(TM);
     728                 :     } else {
     729                0:       Result = "??? ??? ?? ??:??:?? ????\n";
     730                 :     }
     731                 :     // Surround the string with " and strip the trailing newline.
     732                0:     OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
     733                0:     Tok.setKind(tok::string_literal);
                       12: branch 0 taken
                       86: branch 1 taken
     734               98:   } else if (II == Ident__COUNTER__) {
     735                 :     // __COUNTER__ expands to a simple numeric value.
     736               12:     OS << CounterValue++;
     737               12:     Tok.setKind(tok::numeric_constant);
                       50: branch 0 taken
                       36: branch 1 taken
                       12: branch 2 taken
                       38: branch 3 taken
     738              134:   } else if (II == Ident__has_feature ||
     739                 :              II == Ident__has_builtin) {
     740                 :     // The argument to these two builtins should be a parenthesized identifier.
     741               48:     SourceLocation StartLoc = Tok.getLocation();
     742                 : 
     743               48:     bool IsValid = false;
     744               48:     IdentifierInfo *FeatureII = 0;
     745                 : 
     746                 :     // Read the '('.
     747               48:     Lex(Tok);
                       48: branch 1 taken
                        0: branch 2 not taken
     748               48:     if (Tok.is(tok::l_paren)) {
     749                 :       // Read the identifier
     750               48:       Lex(Tok);
                       48: branch 1 taken
                        0: branch 2 not taken
     751               48:       if (Tok.is(tok::identifier)) {
     752               48:         FeatureII = Tok.getIdentifierInfo();
     753                 : 
     754                 :         // Read the ')'.
     755               48:         Lex(Tok);
                       48: branch 1 taken
                        0: branch 2 not taken
     756               48:         if (Tok.is(tok::r_paren))
     757               48:           IsValid = true;
     758                 :       }
     759                 :     }
     760                 : 
     761               48:     bool Value = false;
                        0: branch 0 not taken
                       48: branch 1 taken
     762               48:     if (!IsValid)
     763                0:       Diag(StartLoc, diag::err_feature_check_malformed);
                       12: branch 0 taken
                       36: branch 1 taken
     764               48:     else if (II == Ident__has_builtin) {
     765                 :       // Check for a builtin is trivial.
     766               12:       Value = FeatureII->getBuiltinID() != 0;
     767                 :     } else {
                        0: branch 0 not taken
                       36: branch 1 taken
     768               36:       assert(II == Ident__has_feature && "Must be feature check");
     769               36:       Value = HasFeature(*this, FeatureII);
     770                 :     }
     771                 : 
     772               48:     OS << (int)Value;
     773               48:     Tok.setKind(tok::numeric_constant);
                       31: branch 0 taken
                        7: branch 1 taken
                       31: branch 2 taken
                        0: branch 3 not taken
     774               76:   } else if (II == Ident__has_include ||
     775                 :              II == Ident__has_include_next) {
     776                 :     // The argument to these two builtins should be a parenthesized
     777                 :     // file name string literal using angle brackets (<>) or
     778                 :     // double-quotes ("").
     779               38:     bool Value = false;
     780                 :     bool IsValid;
                        7: branch 0 taken
                       31: branch 1 taken
     781               38:     if (II == Ident__has_include)
     782                7:       IsValid = EvaluateHasInclude(Value, Tok, II, *this);
     783                 :     else
     784               31:       IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
     785               38:     OS << (int)Value;
     786               38:     Tok.setKind(tok::numeric_constant);
     787                 :   } else {
     788                0:     assert(0 && "Unknown identifier!");
     789                 :   }
                      216: branch 7 taken
                        2: branch 8 taken
                      216: branch 10 taken
                        2: branch 11 taken
     790              216:   CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
     791                 : }

Generated: 2010-02-10 01:31 by zcov