Home | History | Annotate | Download | only in Parse
      1 //===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
      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 Declaration portions of the Parser interfaces.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Parse/Parser.h"
     15 #include "clang/Parse/ParseDiagnostic.h"
     16 #include "clang/Basic/OpenCL.h"
     17 #include "clang/Sema/Scope.h"
     18 #include "clang/Sema/ParsedTemplate.h"
     19 #include "clang/Sema/PrettyDeclStackTrace.h"
     20 #include "RAIIObjectsForParser.h"
     21 #include "llvm/ADT/SmallSet.h"
     22 #include "llvm/ADT/StringSwitch.h"
     23 using namespace clang;
     24 
     25 //===----------------------------------------------------------------------===//
     26 // C99 6.7: Declarations.
     27 //===----------------------------------------------------------------------===//
     28 
     29 /// ParseTypeName
     30 ///       type-name: [C99 6.7.6]
     31 ///         specifier-qualifier-list abstract-declarator[opt]
     32 ///
     33 /// Called type-id in C++.
     34 TypeResult Parser::ParseTypeName(SourceRange *Range,
     35                                  Declarator::TheContext Context,
     36                                  AccessSpecifier AS,
     37                                  Decl **OwnedType) {
     38   // Parse the common declaration-specifiers piece.
     39   DeclSpec DS(AttrFactory);
     40   ParseSpecifierQualifierList(DS, AS);
     41   if (OwnedType)
     42     *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
     43 
     44   // Parse the abstract-declarator, if present.
     45   Declarator DeclaratorInfo(DS, Context);
     46   ParseDeclarator(DeclaratorInfo);
     47   if (Range)
     48     *Range = DeclaratorInfo.getSourceRange();
     49 
     50   if (DeclaratorInfo.isInvalidType())
     51     return true;
     52 
     53   return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
     54 }
     55 
     56 
     57 /// isAttributeLateParsed - Return true if the attribute has arguments that
     58 /// require late parsing.
     59 static bool isAttributeLateParsed(const IdentifierInfo &II) {
     60     return llvm::StringSwitch<bool>(II.getName())
     61 #include "clang/Parse/AttrLateParsed.inc"
     62         .Default(false);
     63 }
     64 
     65 
     66 /// ParseGNUAttributes - Parse a non-empty attributes list.
     67 ///
     68 /// [GNU] attributes:
     69 ///         attribute
     70 ///         attributes attribute
     71 ///
     72 /// [GNU]  attribute:
     73 ///          '__attribute__' '(' '(' attribute-list ')' ')'
     74 ///
     75 /// [GNU]  attribute-list:
     76 ///          attrib
     77 ///          attribute_list ',' attrib
     78 ///
     79 /// [GNU]  attrib:
     80 ///          empty
     81 ///          attrib-name
     82 ///          attrib-name '(' identifier ')'
     83 ///          attrib-name '(' identifier ',' nonempty-expr-list ')'
     84 ///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
     85 ///
     86 /// [GNU]  attrib-name:
     87 ///          identifier
     88 ///          typespec
     89 ///          typequal
     90 ///          storageclass
     91 ///
     92 /// FIXME: The GCC grammar/code for this construct implies we need two
     93 /// token lookahead. Comment from gcc: "If they start with an identifier
     94 /// which is followed by a comma or close parenthesis, then the arguments
     95 /// start with that identifier; otherwise they are an expression list."
     96 ///
     97 /// GCC does not require the ',' between attribs in an attribute-list.
     98 ///
     99 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
    100 /// any attributes that don't work (based on my limited testing). Most
    101 /// attributes are very simple in practice. Until we find a bug, I don't see
    102 /// a pressing need to implement the 2 token lookahead.
    103 
    104 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
    105                                 SourceLocation *endLoc,
    106                                 LateParsedAttrList *LateAttrs) {
    107   assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
    108 
    109   while (Tok.is(tok::kw___attribute)) {
    110     ConsumeToken();
    111     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
    112                          "attribute")) {
    113       SkipUntil(tok::r_paren, true); // skip until ) or ;
    114       return;
    115     }
    116     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
    117       SkipUntil(tok::r_paren, true); // skip until ) or ;
    118       return;
    119     }
    120     // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
    121     while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
    122            Tok.is(tok::comma)) {
    123       if (Tok.is(tok::comma)) {
    124         // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
    125         ConsumeToken();
    126         continue;
    127       }
    128       // we have an identifier or declaration specifier (const, int, etc.)
    129       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
    130       SourceLocation AttrNameLoc = ConsumeToken();
    131 
    132       if (Tok.is(tok::l_paren)) {
    133         // handle "parameterized" attributes
    134         if (LateAttrs && !ClassStack.empty() &&
    135             isAttributeLateParsed(*AttrName)) {
    136           // Delayed parsing is only available for attributes that occur
    137           // in certain locations within a class scope.
    138           LateParsedAttribute *LA =
    139             new LateParsedAttribute(this, *AttrName, AttrNameLoc);
    140           LateAttrs->push_back(LA);
    141           getCurrentClass().LateParsedDeclarations.push_back(LA);
    142 
    143           // consume everything up to and including the matching right parens
    144           ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
    145 
    146           Token Eof;
    147           Eof.startToken();
    148           Eof.setLocation(Tok.getLocation());
    149           LA->Toks.push_back(Eof);
    150         } else {
    151           ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc);
    152         }
    153       } else {
    154         attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
    155                      0, SourceLocation(), 0, 0);
    156       }
    157     }
    158     if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
    159       SkipUntil(tok::r_paren, false);
    160     SourceLocation Loc = Tok.getLocation();
    161     if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
    162       SkipUntil(tok::r_paren, false);
    163     }
    164     if (endLoc)
    165       *endLoc = Loc;
    166   }
    167 }
    168 
    169 
    170 /// Parse the arguments to a parameterized GNU attribute
    171 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
    172                                    SourceLocation AttrNameLoc,
    173                                    ParsedAttributes &Attrs,
    174                                    SourceLocation *EndLoc) {
    175 
    176   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
    177 
    178   // Availability attributes have their own grammar.
    179   if (AttrName->isStr("availability")) {
    180     ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
    181     return;
    182   }
    183   // Thread safety attributes fit into the FIXME case above, so we
    184   // just parse the arguments as a list of expressions
    185   if (IsThreadSafetyAttribute(AttrName->getName())) {
    186     ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
    187     return;
    188   }
    189 
    190   ConsumeParen(); // ignore the left paren loc for now
    191 
    192   IdentifierInfo *ParmName = 0;
    193   SourceLocation ParmLoc;
    194   bool BuiltinType = false;
    195 
    196   switch (Tok.getKind()) {
    197   case tok::kw_char:
    198   case tok::kw_wchar_t:
    199   case tok::kw_char16_t:
    200   case tok::kw_char32_t:
    201   case tok::kw_bool:
    202   case tok::kw_short:
    203   case tok::kw_int:
    204   case tok::kw_long:
    205   case tok::kw___int64:
    206   case tok::kw_signed:
    207   case tok::kw_unsigned:
    208   case tok::kw_float:
    209   case tok::kw_double:
    210   case tok::kw_void:
    211   case tok::kw_typeof:
    212     // __attribute__(( vec_type_hint(char) ))
    213     // FIXME: Don't just discard the builtin type token.
    214     ConsumeToken();
    215     BuiltinType = true;
    216     break;
    217 
    218   case tok::identifier:
    219     ParmName = Tok.getIdentifierInfo();
    220     ParmLoc = ConsumeToken();
    221     break;
    222 
    223   default:
    224     break;
    225   }
    226 
    227   ExprVector ArgExprs(Actions);
    228 
    229   if (!BuiltinType &&
    230       (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
    231     // Eat the comma.
    232     if (ParmLoc.isValid())
    233       ConsumeToken();
    234 
    235     // Parse the non-empty comma-separated list of expressions.
    236     while (1) {
    237       ExprResult ArgExpr(ParseAssignmentExpression());
    238       if (ArgExpr.isInvalid()) {
    239         SkipUntil(tok::r_paren);
    240         return;
    241       }
    242       ArgExprs.push_back(ArgExpr.release());
    243       if (Tok.isNot(tok::comma))
    244         break;
    245       ConsumeToken(); // Eat the comma, move to the next argument
    246     }
    247   }
    248   else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
    249     if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
    250                           tok::greater)) {
    251       while (Tok.is(tok::identifier)) {
    252         ConsumeToken();
    253         if (Tok.is(tok::greater))
    254           break;
    255         if (Tok.is(tok::comma)) {
    256           ConsumeToken();
    257           continue;
    258         }
    259       }
    260       if (Tok.isNot(tok::greater))
    261         Diag(Tok, diag::err_iboutletcollection_with_protocol);
    262       SkipUntil(tok::r_paren, false, true); // skip until ')'
    263     }
    264   }
    265 
    266   SourceLocation RParen = Tok.getLocation();
    267   if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
    268     AttributeList *attr =
    269       Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrNameLoc,
    270                    ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
    271     if (BuiltinType && attr->getKind() == AttributeList::AT_IBOutletCollection)
    272       Diag(Tok, diag::err_iboutletcollection_builtintype);
    273   }
    274 }
    275 
    276 
    277 /// ParseMicrosoftDeclSpec - Parse an __declspec construct
    278 ///
    279 /// [MS] decl-specifier:
    280 ///             __declspec ( extended-decl-modifier-seq )
    281 ///
    282 /// [MS] extended-decl-modifier-seq:
    283 ///             extended-decl-modifier[opt]
    284 ///             extended-decl-modifier extended-decl-modifier-seq
    285 
    286 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) {
    287   assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
    288 
    289   ConsumeToken();
    290   if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
    291                        "declspec")) {
    292     SkipUntil(tok::r_paren, true); // skip until ) or ;
    293     return;
    294   }
    295 
    296   while (Tok.getIdentifierInfo()) {
    297     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
    298     SourceLocation AttrNameLoc = ConsumeToken();
    299 
    300     // FIXME: Remove this when we have proper __declspec(property()) support.
    301     // Just skip everything inside property().
    302     if (AttrName->getName() == "property") {
    303       ConsumeParen();
    304       SkipUntil(tok::r_paren);
    305     }
    306     if (Tok.is(tok::l_paren)) {
    307       ConsumeParen();
    308       // FIXME: This doesn't parse __declspec(property(get=get_func_name))
    309       // correctly.
    310       ExprResult ArgExpr(ParseAssignmentExpression());
    311       if (!ArgExpr.isInvalid()) {
    312         Expr *ExprList = ArgExpr.take();
    313         attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
    314                      SourceLocation(), &ExprList, 1, true);
    315       }
    316       if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
    317         SkipUntil(tok::r_paren, false);
    318     } else {
    319       attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
    320                    0, SourceLocation(), 0, 0, true);
    321     }
    322   }
    323   if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
    324     SkipUntil(tok::r_paren, false);
    325   return;
    326 }
    327 
    328 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
    329   // Treat these like attributes
    330   // FIXME: Allow Sema to distinguish between these and real attributes!
    331   while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
    332          Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl)   ||
    333          Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
    334          Tok.is(tok::kw___ptr32) ||
    335          Tok.is(tok::kw___unaligned)) {
    336     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
    337     SourceLocation AttrNameLoc = ConsumeToken();
    338     if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
    339         Tok.is(tok::kw___ptr32))
    340       // FIXME: Support these properly!
    341       continue;
    342     attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
    343                  SourceLocation(), 0, 0, true);
    344   }
    345 }
    346 
    347 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
    348   // Treat these like attributes
    349   while (Tok.is(tok::kw___pascal)) {
    350     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
    351     SourceLocation AttrNameLoc = ConsumeToken();
    352     attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
    353                  SourceLocation(), 0, 0, true);
    354   }
    355 }
    356 
    357 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
    358   // Treat these like attributes
    359   while (Tok.is(tok::kw___kernel)) {
    360     SourceLocation AttrNameLoc = ConsumeToken();
    361     attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
    362                  AttrNameLoc, 0, AttrNameLoc, 0,
    363                  SourceLocation(), 0, 0, false);
    364   }
    365 }
    366 
    367 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
    368   SourceLocation Loc = Tok.getLocation();
    369   switch(Tok.getKind()) {
    370     // OpenCL qualifiers:
    371     case tok::kw___private:
    372     case tok::kw_private:
    373       DS.getAttributes().addNewInteger(
    374           Actions.getASTContext(),
    375           PP.getIdentifierInfo("address_space"), Loc, 0);
    376       break;
    377 
    378     case tok::kw___global:
    379       DS.getAttributes().addNewInteger(
    380           Actions.getASTContext(),
    381           PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
    382       break;
    383 
    384     case tok::kw___local:
    385       DS.getAttributes().addNewInteger(
    386           Actions.getASTContext(),
    387           PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
    388       break;
    389 
    390     case tok::kw___constant:
    391       DS.getAttributes().addNewInteger(
    392           Actions.getASTContext(),
    393           PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
    394       break;
    395 
    396     case tok::kw___read_only:
    397       DS.getAttributes().addNewInteger(
    398           Actions.getASTContext(),
    399           PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
    400       break;
    401 
    402     case tok::kw___write_only:
    403       DS.getAttributes().addNewInteger(
    404           Actions.getASTContext(),
    405           PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
    406       break;
    407 
    408     case tok::kw___read_write:
    409       DS.getAttributes().addNewInteger(
    410           Actions.getASTContext(),
    411           PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
    412       break;
    413     default: break;
    414   }
    415 }
    416 
    417 /// \brief Parse a version number.
    418 ///
    419 /// version:
    420 ///   simple-integer
    421 ///   simple-integer ',' simple-integer
    422 ///   simple-integer ',' simple-integer ',' simple-integer
    423 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
    424   Range = Tok.getLocation();
    425 
    426   if (!Tok.is(tok::numeric_constant)) {
    427     Diag(Tok, diag::err_expected_version);
    428     SkipUntil(tok::comma, tok::r_paren, true, true, true);
    429     return VersionTuple();
    430   }
    431 
    432   // Parse the major (and possibly minor and subminor) versions, which
    433   // are stored in the numeric constant. We utilize a quirk of the
    434   // lexer, which is that it handles something like 1.2.3 as a single
    435   // numeric constant, rather than two separate tokens.
    436   llvm::SmallString<512> Buffer;
    437   Buffer.resize(Tok.getLength()+1);
    438   const char *ThisTokBegin = &Buffer[0];
    439 
    440   // Get the spelling of the token, which eliminates trigraphs, etc.
    441   bool Invalid = false;
    442   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
    443   if (Invalid)
    444     return VersionTuple();
    445 
    446   // Parse the major version.
    447   unsigned AfterMajor = 0;
    448   unsigned Major = 0;
    449   while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
    450     Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
    451     ++AfterMajor;
    452   }
    453 
    454   if (AfterMajor == 0) {
    455     Diag(Tok, diag::err_expected_version);
    456     SkipUntil(tok::comma, tok::r_paren, true, true, true);
    457     return VersionTuple();
    458   }
    459 
    460   if (AfterMajor == ActualLength) {
    461     ConsumeToken();
    462 
    463     // We only had a single version component.
    464     if (Major == 0) {
    465       Diag(Tok, diag::err_zero_version);
    466       return VersionTuple();
    467     }
    468 
    469     return VersionTuple(Major);
    470   }
    471 
    472   if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
    473     Diag(Tok, diag::err_expected_version);
    474     SkipUntil(tok::comma, tok::r_paren, true, true, true);
    475     return VersionTuple();
    476   }
    477 
    478   // Parse the minor version.
    479   unsigned AfterMinor = AfterMajor + 1;
    480   unsigned Minor = 0;
    481   while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
    482     Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
    483     ++AfterMinor;
    484   }
    485 
    486   if (AfterMinor == ActualLength) {
    487     ConsumeToken();
    488 
    489     // We had major.minor.
    490     if (Major == 0 && Minor == 0) {
    491       Diag(Tok, diag::err_zero_version);
    492       return VersionTuple();
    493     }
    494 
    495     return VersionTuple(Major, Minor);
    496   }
    497 
    498   // If what follows is not a '.', we have a problem.
    499   if (ThisTokBegin[AfterMinor] != '.') {
    500     Diag(Tok, diag::err_expected_version);
    501     SkipUntil(tok::comma, tok::r_paren, true, true, true);
    502     return VersionTuple();
    503   }
    504 
    505   // Parse the subminor version.
    506   unsigned AfterSubminor = AfterMinor + 1;
    507   unsigned Subminor = 0;
    508   while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
    509     Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
    510     ++AfterSubminor;
    511   }
    512 
    513   if (AfterSubminor != ActualLength) {
    514     Diag(Tok, diag::err_expected_version);
    515     SkipUntil(tok::comma, tok::r_paren, true, true, true);
    516     return VersionTuple();
    517   }
    518   ConsumeToken();
    519   return VersionTuple(Major, Minor, Subminor);
    520 }
    521 
    522 /// \brief Parse the contents of the "availability" attribute.
    523 ///
    524 /// availability-attribute:
    525 ///   'availability' '(' platform ',' version-arg-list ')'
    526 ///
    527 /// platform:
    528 ///   identifier
    529 ///
    530 /// version-arg-list:
    531 ///   version-arg
    532 ///   version-arg ',' version-arg-list
    533 ///
    534 /// version-arg:
    535 ///   'introduced' '=' version
    536 ///   'deprecated' '=' version
    537 ///   'removed' = version
    538 ///   'unavailable'
    539 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
    540                                         SourceLocation AvailabilityLoc,
    541                                         ParsedAttributes &attrs,
    542                                         SourceLocation *endLoc) {
    543   SourceLocation PlatformLoc;
    544   IdentifierInfo *Platform = 0;
    545 
    546   enum { Introduced, Deprecated, Obsoleted, Unknown };
    547   AvailabilityChange Changes[Unknown];
    548 
    549   // Opening '('.
    550   BalancedDelimiterTracker T(*this, tok::l_paren);
    551   if (T.consumeOpen()) {
    552     Diag(Tok, diag::err_expected_lparen);
    553     return;
    554   }
    555 
    556   // Parse the platform name,
    557   if (Tok.isNot(tok::identifier)) {
    558     Diag(Tok, diag::err_availability_expected_platform);
    559     SkipUntil(tok::r_paren);
    560     return;
    561   }
    562   Platform = Tok.getIdentifierInfo();
    563   PlatformLoc = ConsumeToken();
    564 
    565   // Parse the ',' following the platform name.
    566   if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
    567     return;
    568 
    569   // If we haven't grabbed the pointers for the identifiers
    570   // "introduced", "deprecated", and "obsoleted", do so now.
    571   if (!Ident_introduced) {
    572     Ident_introduced = PP.getIdentifierInfo("introduced");
    573     Ident_deprecated = PP.getIdentifierInfo("deprecated");
    574     Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
    575     Ident_unavailable = PP.getIdentifierInfo("unavailable");
    576   }
    577 
    578   // Parse the set of introductions/deprecations/removals.
    579   SourceLocation UnavailableLoc;
    580   do {
    581     if (Tok.isNot(tok::identifier)) {
    582       Diag(Tok, diag::err_availability_expected_change);
    583       SkipUntil(tok::r_paren);
    584       return;
    585     }
    586     IdentifierInfo *Keyword = Tok.getIdentifierInfo();
    587     SourceLocation KeywordLoc = ConsumeToken();
    588 
    589     if (Keyword == Ident_unavailable) {
    590       if (UnavailableLoc.isValid()) {
    591         Diag(KeywordLoc, diag::err_availability_redundant)
    592           << Keyword << SourceRange(UnavailableLoc);
    593       }
    594       UnavailableLoc = KeywordLoc;
    595 
    596       if (Tok.isNot(tok::comma))
    597         break;
    598 
    599       ConsumeToken();
    600       continue;
    601     }
    602 
    603     if (Tok.isNot(tok::equal)) {
    604       Diag(Tok, diag::err_expected_equal_after)
    605         << Keyword;
    606       SkipUntil(tok::r_paren);
    607       return;
    608     }
    609     ConsumeToken();
    610 
    611     SourceRange VersionRange;
    612     VersionTuple Version = ParseVersionTuple(VersionRange);
    613 
    614     if (Version.empty()) {
    615       SkipUntil(tok::r_paren);
    616       return;
    617     }
    618 
    619     unsigned Index;
    620     if (Keyword == Ident_introduced)
    621       Index = Introduced;
    622     else if (Keyword == Ident_deprecated)
    623       Index = Deprecated;
    624     else if (Keyword == Ident_obsoleted)
    625       Index = Obsoleted;
    626     else
    627       Index = Unknown;
    628 
    629     if (Index < Unknown) {
    630       if (!Changes[Index].KeywordLoc.isInvalid()) {
    631         Diag(KeywordLoc, diag::err_availability_redundant)
    632           << Keyword
    633           << SourceRange(Changes[Index].KeywordLoc,
    634                          Changes[Index].VersionRange.getEnd());
    635       }
    636 
    637       Changes[Index].KeywordLoc = KeywordLoc;
    638       Changes[Index].Version = Version;
    639       Changes[Index].VersionRange = VersionRange;
    640     } else {
    641       Diag(KeywordLoc, diag::err_availability_unknown_change)
    642         << Keyword << VersionRange;
    643     }
    644 
    645     if (Tok.isNot(tok::comma))
    646       break;
    647 
    648     ConsumeToken();
    649   } while (true);
    650 
    651   // Closing ')'.
    652   if (T.consumeClose())
    653     return;
    654 
    655   if (endLoc)
    656     *endLoc = T.getCloseLocation();
    657 
    658   // The 'unavailable' availability cannot be combined with any other
    659   // availability changes. Make sure that hasn't happened.
    660   if (UnavailableLoc.isValid()) {
    661     bool Complained = false;
    662     for (unsigned Index = Introduced; Index != Unknown; ++Index) {
    663       if (Changes[Index].KeywordLoc.isValid()) {
    664         if (!Complained) {
    665           Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
    666             << SourceRange(Changes[Index].KeywordLoc,
    667                            Changes[Index].VersionRange.getEnd());
    668           Complained = true;
    669         }
    670 
    671         // Clear out the availability.
    672         Changes[Index] = AvailabilityChange();
    673       }
    674     }
    675   }
    676 
    677   // Record this attribute
    678   attrs.addNew(&Availability,
    679                SourceRange(AvailabilityLoc, T.getCloseLocation()),
    680                0, SourceLocation(),
    681                Platform, PlatformLoc,
    682                Changes[Introduced],
    683                Changes[Deprecated],
    684                Changes[Obsoleted],
    685                UnavailableLoc, false, false);
    686 }
    687 
    688 
    689 // Late Parsed Attributes:
    690 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
    691 
    692 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
    693 
    694 void Parser::LateParsedClass::ParseLexedAttributes() {
    695   Self->ParseLexedAttributes(*Class);
    696 }
    697 
    698 void Parser::LateParsedAttribute::ParseLexedAttributes() {
    699   Self->ParseLexedAttribute(*this);
    700 }
    701 
    702 /// Wrapper class which calls ParseLexedAttribute, after setting up the
    703 /// scope appropriately.
    704 void Parser::ParseLexedAttributes(ParsingClass &Class) {
    705   // Deal with templates
    706   // FIXME: Test cases to make sure this does the right thing for templates.
    707   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
    708   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
    709                                 HasTemplateScope);
    710   if (HasTemplateScope)
    711     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
    712 
    713   // Set or update the scope flags to include Scope::ThisScope.
    714   bool AlreadyHasClassScope = Class.TopLevelClass;
    715   unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope|Scope::ThisScope;
    716   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
    717   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
    718 
    719   for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i) {
    720     Class.LateParsedDeclarations[i]->ParseLexedAttributes();
    721   }
    722 }
    723 
    724 /// \brief Finish parsing an attribute for which parsing was delayed.
    725 /// This will be called at the end of parsing a class declaration
    726 /// for each LateParsedAttribute. We consume the saved tokens and
    727 /// create an attribute with the arguments filled in. We add this
    728 /// to the Attribute list for the decl.
    729 void Parser::ParseLexedAttribute(LateParsedAttribute &LA) {
    730   // Save the current token position.
    731   SourceLocation OrigLoc = Tok.getLocation();
    732 
    733   // Append the current token at the end of the new token stream so that it
    734   // doesn't get lost.
    735   LA.Toks.push_back(Tok);
    736   PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
    737   // Consume the previously pushed token.
    738   ConsumeAnyToken();
    739 
    740   ParsedAttributes Attrs(AttrFactory);
    741   SourceLocation endLoc;
    742 
    743   // If the Decl is templatized, add template parameters to scope.
    744   bool HasTemplateScope = LA.D && LA.D->isTemplateDecl();
    745   ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
    746   if (HasTemplateScope)
    747     Actions.ActOnReenterTemplateScope(Actions.CurScope, LA.D);
    748 
    749   // If the Decl is on a function, add function parameters to the scope.
    750   bool HasFunctionScope = LA.D && LA.D->isFunctionOrFunctionTemplate();
    751   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunctionScope);
    752   if (HasFunctionScope)
    753     Actions.ActOnReenterFunctionContext(Actions.CurScope, LA.D);
    754 
    755   ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
    756 
    757   if (HasFunctionScope) {
    758     Actions.ActOnExitFunctionContext();
    759     FnScope.Exit();  // Pop scope, and remove Decls from IdResolver
    760   }
    761   if (HasTemplateScope) {
    762     TempScope.Exit();
    763   }
    764 
    765   // Late parsed attributes must be attached to Decls by hand.  If the
    766   // LA.D is not set, then this was not done properly.
    767   assert(LA.D && "No decl attached to late parsed attribute");
    768   Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.D, Attrs);
    769 
    770   if (Tok.getLocation() != OrigLoc) {
    771     // Due to a parsing error, we either went over the cached tokens or
    772     // there are still cached tokens left, so we skip the leftover tokens.
    773     // Since this is an uncommon situation that should be avoided, use the
    774     // expensive isBeforeInTranslationUnit call.
    775     if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
    776                                                         OrigLoc))
    777     while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
    778         ConsumeAnyToken();
    779   }
    780 }
    781 
    782 /// \brief Wrapper around a case statement checking if AttrName is
    783 /// one of the thread safety attributes
    784 bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){
    785   return llvm::StringSwitch<bool>(AttrName)
    786       .Case("guarded_by", true)
    787       .Case("guarded_var", true)
    788       .Case("pt_guarded_by", true)
    789       .Case("pt_guarded_var", true)
    790       .Case("lockable", true)
    791       .Case("scoped_lockable", true)
    792       .Case("no_thread_safety_analysis", true)
    793       .Case("acquired_after", true)
    794       .Case("acquired_before", true)
    795       .Case("exclusive_lock_function", true)
    796       .Case("shared_lock_function", true)
    797       .Case("exclusive_trylock_function", true)
    798       .Case("shared_trylock_function", true)
    799       .Case("unlock_function", true)
    800       .Case("lock_returned", true)
    801       .Case("locks_excluded", true)
    802       .Case("exclusive_locks_required", true)
    803       .Case("shared_locks_required", true)
    804       .Default(false);
    805 }
    806 
    807 /// \brief Parse the contents of thread safety attributes. These
    808 /// should always be parsed as an expression list.
    809 ///
    810 /// We need to special case the parsing due to the fact that if the first token
    811 /// of the first argument is an identifier, the main parse loop will store
    812 /// that token as a "parameter" and the rest of
    813 /// the arguments will be added to a list of "arguments". However,
    814 /// subsequent tokens in the first argument are lost. We instead parse each
    815 /// argument as an expression and add all arguments to the list of "arguments".
    816 /// In future, we will take advantage of this special case to also
    817 /// deal with some argument scoping issues here (for example, referring to a
    818 /// function parameter in the attribute on that function).
    819 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
    820                                         SourceLocation AttrNameLoc,
    821                                         ParsedAttributes &Attrs,
    822                                         SourceLocation *EndLoc) {
    823   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
    824 
    825   BalancedDelimiterTracker T(*this, tok::l_paren);
    826   T.consumeOpen();
    827 
    828   ExprVector ArgExprs(Actions);
    829   bool ArgExprsOk = true;
    830 
    831   // now parse the list of expressions
    832   while (1) {
    833     ExprResult ArgExpr(ParseAssignmentExpression());
    834     if (ArgExpr.isInvalid()) {
    835       ArgExprsOk = false;
    836       T.consumeClose();
    837       break;
    838     } else {
    839       ArgExprs.push_back(ArgExpr.release());
    840     }
    841     if (Tok.isNot(tok::comma))
    842       break;
    843     ConsumeToken(); // Eat the comma, move to the next argument
    844   }
    845   // Match the ')'.
    846   if (ArgExprsOk && !T.consumeClose()) {
    847     Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
    848                  ArgExprs.take(), ArgExprs.size());
    849   }
    850   if (EndLoc)
    851     *EndLoc = T.getCloseLocation();
    852 }
    853 
    854 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
    855   Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
    856     << attrs.Range;
    857 }
    858 
    859 /// ParseDeclaration - Parse a full 'declaration', which consists of
    860 /// declaration-specifiers, some number of declarators, and a semicolon.
    861 /// 'Context' should be a Declarator::TheContext value.  This returns the
    862 /// location of the semicolon in DeclEnd.
    863 ///
    864 ///       declaration: [C99 6.7]
    865 ///         block-declaration ->
    866 ///           simple-declaration
    867 ///           others                   [FIXME]
    868 /// [C++]   template-declaration
    869 /// [C++]   namespace-definition
    870 /// [C++]   using-directive
    871 /// [C++]   using-declaration
    872 /// [C++0x/C1X] static_assert-declaration
    873 ///         others... [FIXME]
    874 ///
    875 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
    876                                                 unsigned Context,
    877                                                 SourceLocation &DeclEnd,
    878                                           ParsedAttributesWithRange &attrs) {
    879   ParenBraceBracketBalancer BalancerRAIIObj(*this);
    880   // Must temporarily exit the objective-c container scope for
    881   // parsing c none objective-c decls.
    882   ObjCDeclContextSwitch ObjCDC(*this);
    883 
    884   Decl *SingleDecl = 0;
    885   Decl *OwnedType = 0;
    886   switch (Tok.getKind()) {
    887   case tok::kw_template:
    888   case tok::kw_export:
    889     ProhibitAttributes(attrs);
    890     SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
    891     break;
    892   case tok::kw_inline:
    893     // Could be the start of an inline namespace. Allowed as an ext in C++03.
    894     if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) {
    895       ProhibitAttributes(attrs);
    896       SourceLocation InlineLoc = ConsumeToken();
    897       SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
    898       break;
    899     }
    900     return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
    901                                   true);
    902   case tok::kw_namespace:
    903     ProhibitAttributes(attrs);
    904     SingleDecl = ParseNamespace(Context, DeclEnd);
    905     break;
    906   case tok::kw_using:
    907     SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
    908                                                   DeclEnd, attrs, &OwnedType);
    909     break;
    910   case tok::kw_static_assert:
    911   case tok::kw__Static_assert:
    912     ProhibitAttributes(attrs);
    913     SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
    914     break;
    915   default:
    916     return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
    917   }
    918 
    919   // This routine returns a DeclGroup, if the thing we parsed only contains a
    920   // single decl, convert it now. Alias declarations can also declare a type;
    921   // include that too if it is present.
    922   return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
    923 }
    924 
    925 ///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
    926 ///         declaration-specifiers init-declarator-list[opt] ';'
    927 ///[C90/C++]init-declarator-list ';'                             [TODO]
    928 /// [OMP]   threadprivate-directive                              [TODO]
    929 ///
    930 ///       for-range-declaration: [C++0x 6.5p1: stmt.ranged]
    931 ///         attribute-specifier-seq[opt] type-specifier-seq declarator
    932 ///
    933 /// If RequireSemi is false, this does not check for a ';' at the end of the
    934 /// declaration.  If it is true, it checks for and eats it.
    935 ///
    936 /// If FRI is non-null, we might be parsing a for-range-declaration instead
    937 /// of a simple-declaration. If we find that we are, we also parse the
    938 /// for-range-initializer, and place it here.
    939 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts,
    940                                                       unsigned Context,
    941                                                       SourceLocation &DeclEnd,
    942                                                       ParsedAttributes &attrs,
    943                                                       bool RequireSemi,
    944                                                       ForRangeInit *FRI) {
    945   // Parse the common declaration-specifiers piece.
    946   ParsingDeclSpec DS(*this);
    947   DS.takeAttributesFrom(attrs);
    948 
    949   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
    950                              getDeclSpecContextFromDeclaratorContext(Context));
    951   StmtResult R = Actions.ActOnVlaStmt(DS);
    952   if (R.isUsable())
    953     Stmts.push_back(R.release());
    954 
    955   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
    956   // declaration-specifiers init-declarator-list[opt] ';'
    957   if (Tok.is(tok::semi)) {
    958     if (RequireSemi) ConsumeToken();
    959     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
    960                                                        DS);
    961     DS.complete(TheDecl);
    962     return Actions.ConvertDeclToDeclGroup(TheDecl);
    963   }
    964 
    965   return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
    966 }
    967 
    968 /// ParseDeclGroup - Having concluded that this is either a function
    969 /// definition or a group of object declarations, actually parse the
    970 /// result.
    971 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
    972                                               unsigned Context,
    973                                               bool AllowFunctionDefinitions,
    974                                               SourceLocation *DeclEnd,
    975                                               ForRangeInit *FRI) {
    976   // Parse the first declarator.
    977   ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
    978   ParseDeclarator(D);
    979 
    980   // Bail out if the first declarator didn't seem well-formed.
    981   if (!D.hasName() && !D.mayOmitIdentifier()) {
    982     // Skip until ; or }.
    983     SkipUntil(tok::r_brace, true, true);
    984     if (Tok.is(tok::semi))
    985       ConsumeToken();
    986     return DeclGroupPtrTy();
    987   }
    988 
    989   // Check to see if we have a function *definition* which must have a body.
    990   if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
    991       // Look at the next token to make sure that this isn't a function
    992       // declaration.  We have to check this because __attribute__ might be the
    993       // start of a function definition in GCC-extended K&R C.
    994       !isDeclarationAfterDeclarator()) {
    995 
    996     if (isStartOfFunctionDefinition(D)) {
    997       if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
    998         Diag(Tok, diag::err_function_declared_typedef);
    999 
   1000         // Recover by treating the 'typedef' as spurious.
   1001         DS.ClearStorageClassSpecs();
   1002       }
   1003 
   1004       Decl *TheDecl = ParseFunctionDefinition(D);
   1005       return Actions.ConvertDeclToDeclGroup(TheDecl);
   1006     }
   1007 
   1008     if (isDeclarationSpecifier()) {
   1009       // If there is an invalid declaration specifier right after the function
   1010       // prototype, then we must be in a missing semicolon case where this isn't
   1011       // actually a body.  Just fall through into the code that handles it as a
   1012       // prototype, and let the top-level code handle the erroneous declspec
   1013       // where it would otherwise expect a comma or semicolon.
   1014     } else {
   1015       Diag(Tok, diag::err_expected_fn_body);
   1016       SkipUntil(tok::semi);
   1017       return DeclGroupPtrTy();
   1018     }
   1019   }
   1020 
   1021   if (ParseAttributesAfterDeclarator(D))
   1022     return DeclGroupPtrTy();
   1023 
   1024   // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
   1025   // must parse and analyze the for-range-initializer before the declaration is
   1026   // analyzed.
   1027   if (FRI && Tok.is(tok::colon)) {
   1028     FRI->ColonLoc = ConsumeToken();
   1029     if (Tok.is(tok::l_brace))
   1030       FRI->RangeExpr = ParseBraceInitializer();
   1031     else
   1032       FRI->RangeExpr = ParseExpression();
   1033     Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
   1034     Actions.ActOnCXXForRangeDecl(ThisDecl);
   1035     Actions.FinalizeDeclaration(ThisDecl);
   1036     return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
   1037   }
   1038 
   1039   SmallVector<Decl *, 8> DeclsInGroup;
   1040   Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
   1041   D.complete(FirstDecl);
   1042   if (FirstDecl)
   1043     DeclsInGroup.push_back(FirstDecl);
   1044 
   1045   // If we don't have a comma, it is either the end of the list (a ';') or an
   1046   // error, bail out.
   1047   while (Tok.is(tok::comma)) {
   1048     // Consume the comma.
   1049     ConsumeToken();
   1050 
   1051     // Parse the next declarator.
   1052     D.clear();
   1053 
   1054     // Accept attributes in an init-declarator.  In the first declarator in a
   1055     // declaration, these would be part of the declspec.  In subsequent
   1056     // declarators, they become part of the declarator itself, so that they
   1057     // don't apply to declarators after *this* one.  Examples:
   1058     //    short __attribute__((common)) var;    -> declspec
   1059     //    short var __attribute__((common));    -> declarator
   1060     //    short x, __attribute__((common)) var;    -> declarator
   1061     MaybeParseGNUAttributes(D);
   1062 
   1063     ParseDeclarator(D);
   1064 
   1065     Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
   1066     D.complete(ThisDecl);
   1067     if (ThisDecl)
   1068       DeclsInGroup.push_back(ThisDecl);
   1069   }
   1070 
   1071   if (DeclEnd)
   1072     *DeclEnd = Tok.getLocation();
   1073 
   1074   if (Context != Declarator::ForContext &&
   1075       ExpectAndConsume(tok::semi,
   1076                        Context == Declarator::FileContext
   1077                          ? diag::err_invalid_token_after_toplevel_declarator
   1078                          : diag::err_expected_semi_declaration)) {
   1079     // Okay, there was no semicolon and one was expected.  If we see a
   1080     // declaration specifier, just assume it was missing and continue parsing.
   1081     // Otherwise things are very confused and we skip to recover.
   1082     if (!isDeclarationSpecifier()) {
   1083       SkipUntil(tok::r_brace, true, true);
   1084       if (Tok.is(tok::semi))
   1085         ConsumeToken();
   1086     }
   1087   }
   1088 
   1089   return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
   1090                                          DeclsInGroup.data(),
   1091                                          DeclsInGroup.size());
   1092 }
   1093 
   1094 /// Parse an optional simple-asm-expr and attributes, and attach them to a
   1095 /// declarator. Returns true on an error.
   1096 bool Parser::ParseAttributesAfterDeclarator(Declarator &D) {
   1097   // If a simple-asm-expr is present, parse it.
   1098   if (Tok.is(tok::kw_asm)) {
   1099     SourceLocation Loc;
   1100     ExprResult AsmLabel(ParseSimpleAsm(&Loc));
   1101     if (AsmLabel.isInvalid()) {
   1102       SkipUntil(tok::semi, true, true);
   1103       return true;
   1104     }
   1105 
   1106     D.setAsmLabel(AsmLabel.release());
   1107     D.SetRangeEnd(Loc);
   1108   }
   1109 
   1110   MaybeParseGNUAttributes(D);
   1111   return false;
   1112 }
   1113 
   1114 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
   1115 /// declarator'. This method parses the remainder of the declaration
   1116 /// (including any attributes or initializer, among other things) and
   1117 /// finalizes the declaration.
   1118 ///
   1119 ///       init-declarator: [C99 6.7]
   1120 ///         declarator
   1121 ///         declarator '=' initializer
   1122 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
   1123 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
   1124 /// [C++]   declarator initializer[opt]
   1125 ///
   1126 /// [C++] initializer:
   1127 /// [C++]   '=' initializer-clause
   1128 /// [C++]   '(' expression-list ')'
   1129 /// [C++0x] '=' 'default'                                                [TODO]
   1130 /// [C++0x] '=' 'delete'
   1131 /// [C++0x] braced-init-list
   1132 ///
   1133 /// According to the standard grammar, =default and =delete are function
   1134 /// definitions, but that definitely doesn't fit with the parser here.
   1135 ///
   1136 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
   1137                                      const ParsedTemplateInfo &TemplateInfo) {
   1138   if (ParseAttributesAfterDeclarator(D))
   1139     return 0;
   1140 
   1141   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
   1142 }
   1143 
   1144 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
   1145                                      const ParsedTemplateInfo &TemplateInfo) {
   1146   // Inform the current actions module that we just parsed this declarator.
   1147   Decl *ThisDecl = 0;
   1148   switch (TemplateInfo.Kind) {
   1149   case ParsedTemplateInfo::NonTemplate:
   1150     ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
   1151     break;
   1152 
   1153   case ParsedTemplateInfo::Template:
   1154   case ParsedTemplateInfo::ExplicitSpecialization:
   1155     ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
   1156                              MultiTemplateParamsArg(Actions,
   1157                                           TemplateInfo.TemplateParams->data(),
   1158                                           TemplateInfo.TemplateParams->size()),
   1159                                                D);
   1160     break;
   1161 
   1162   case ParsedTemplateInfo::ExplicitInstantiation: {
   1163     DeclResult ThisRes
   1164       = Actions.ActOnExplicitInstantiation(getCurScope(),
   1165                                            TemplateInfo.ExternLoc,
   1166                                            TemplateInfo.TemplateLoc,
   1167                                            D);
   1168     if (ThisRes.isInvalid()) {
   1169       SkipUntil(tok::semi, true, true);
   1170       return 0;
   1171     }
   1172 
   1173     ThisDecl = ThisRes.get();
   1174     break;
   1175     }
   1176   }
   1177 
   1178   bool TypeContainsAuto =
   1179     D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
   1180 
   1181   // Parse declarator '=' initializer.
   1182   if (isTokenEqualOrMistypedEqualEqual(
   1183                                diag::err_invalid_equalequal_after_declarator)) {
   1184     ConsumeToken();
   1185     if (Tok.is(tok::kw_delete)) {
   1186       if (D.isFunctionDeclarator())
   1187         Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
   1188           << 1 /* delete */;
   1189       else
   1190         Diag(ConsumeToken(), diag::err_deleted_non_function);
   1191     } else if (Tok.is(tok::kw_default)) {
   1192       if (D.isFunctionDeclarator())
   1193         Diag(Tok, diag::err_default_delete_in_multiple_declaration)
   1194           << 1 /* delete */;
   1195       else
   1196         Diag(ConsumeToken(), diag::err_default_special_members);
   1197     } else {
   1198       if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
   1199         EnterScope(0);
   1200         Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
   1201       }
   1202 
   1203       if (Tok.is(tok::code_completion)) {
   1204         Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
   1205         cutOffParsing();
   1206         return 0;
   1207       }
   1208 
   1209       ExprResult Init(ParseInitializer());
   1210 
   1211       if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
   1212         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
   1213         ExitScope();
   1214       }
   1215 
   1216       if (Init.isInvalid()) {
   1217         SkipUntil(tok::comma, true, true);
   1218         Actions.ActOnInitializerError(ThisDecl);
   1219       } else
   1220         Actions.AddInitializerToDecl(ThisDecl, Init.take(),
   1221                                      /*DirectInit=*/false, TypeContainsAuto);
   1222     }
   1223   } else if (Tok.is(tok::l_paren)) {
   1224     // Parse C++ direct initializer: '(' expression-list ')'
   1225     BalancedDelimiterTracker T(*this, tok::l_paren);
   1226     T.consumeOpen();
   1227 
   1228     ExprVector Exprs(Actions);
   1229     CommaLocsTy CommaLocs;
   1230 
   1231     if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
   1232       EnterScope(0);
   1233       Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
   1234     }
   1235 
   1236     if (ParseExpressionList(Exprs, CommaLocs)) {
   1237       SkipUntil(tok::r_paren);
   1238 
   1239       if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
   1240         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
   1241         ExitScope();
   1242       }
   1243     } else {
   1244       // Match the ')'.
   1245       T.consumeClose();
   1246 
   1247       assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
   1248              "Unexpected number of commas!");
   1249 
   1250       if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
   1251         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
   1252         ExitScope();
   1253       }
   1254 
   1255       Actions.AddCXXDirectInitializerToDecl(ThisDecl, T.getOpenLocation(),
   1256                                             move_arg(Exprs),
   1257                                             T.getCloseLocation(),
   1258                                             TypeContainsAuto);
   1259     }
   1260   } else if (getLang().CPlusPlus0x && Tok.is(tok::l_brace)) {
   1261     // Parse C++0x braced-init-list.
   1262     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
   1263 
   1264     if (D.getCXXScopeSpec().isSet()) {
   1265       EnterScope(0);
   1266       Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
   1267     }
   1268 
   1269     ExprResult Init(ParseBraceInitializer());
   1270 
   1271     if (D.getCXXScopeSpec().isSet()) {
   1272       Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
   1273       ExitScope();
   1274     }
   1275 
   1276     if (Init.isInvalid()) {
   1277       Actions.ActOnInitializerError(ThisDecl);
   1278     } else
   1279       Actions.AddInitializerToDecl(ThisDecl, Init.take(),
   1280                                    /*DirectInit=*/true, TypeContainsAuto);
   1281 
   1282   } else {
   1283     Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
   1284   }
   1285 
   1286   Actions.FinalizeDeclaration(ThisDecl);
   1287 
   1288   return ThisDecl;
   1289 }
   1290 
   1291 /// ParseSpecifierQualifierList
   1292 ///        specifier-qualifier-list:
   1293 ///          type-specifier specifier-qualifier-list[opt]
   1294 ///          type-qualifier specifier-qualifier-list[opt]
   1295 /// [GNU]    attributes     specifier-qualifier-list[opt]
   1296 ///
   1297 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS) {
   1298   /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
   1299   /// parse declaration-specifiers and complain about extra stuff.
   1300   /// TODO: diagnose attribute-specifiers and alignment-specifiers.
   1301   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS);
   1302 
   1303   // Validate declspec for type-name.
   1304   unsigned Specs = DS.getParsedSpecifiers();
   1305   if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
   1306       !DS.hasAttributes())
   1307     Diag(Tok, diag::err_typename_requires_specqual);
   1308 
   1309   // Issue diagnostic and remove storage class if present.
   1310   if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
   1311     if (DS.getStorageClassSpecLoc().isValid())
   1312       Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
   1313     else
   1314       Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
   1315     DS.ClearStorageClassSpecs();
   1316   }
   1317 
   1318   // Issue diagnostic and remove function specfier if present.
   1319   if (Specs & DeclSpec::PQ_FunctionSpecifier) {
   1320     if (DS.isInlineSpecified())
   1321       Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
   1322     if (DS.isVirtualSpecified())
   1323       Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
   1324     if (DS.isExplicitSpecified())
   1325       Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
   1326     DS.ClearFunctionSpecs();
   1327   }
   1328 }
   1329 
   1330 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
   1331 /// specified token is valid after the identifier in a declarator which
   1332 /// immediately follows the declspec.  For example, these things are valid:
   1333 ///
   1334 ///      int x   [             4];         // direct-declarator
   1335 ///      int x   (             int y);     // direct-declarator
   1336 ///  int(int x   )                         // direct-declarator
   1337 ///      int x   ;                         // simple-declaration
   1338 ///      int x   =             17;         // init-declarator-list
   1339 ///      int x   ,             y;          // init-declarator-list
   1340 ///      int x   __asm__       ("foo");    // init-declarator-list
   1341 ///      int x   :             4;          // struct-declarator
   1342 ///      int x   {             5};         // C++'0x unified initializers
   1343 ///
   1344 /// This is not, because 'x' does not immediately follow the declspec (though
   1345 /// ')' happens to be valid anyway).
   1346 ///    int (x)
   1347 ///
   1348 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
   1349   return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
   1350          T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
   1351          T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
   1352 }
   1353 
   1354 
   1355 /// ParseImplicitInt - This method is called when we have an non-typename
   1356 /// identifier in a declspec (which normally terminates the decl spec) when
   1357 /// the declspec has no type specifier.  In this case, the declspec is either
   1358 /// malformed or is "implicit int" (in K&R and C89).
   1359 ///
   1360 /// This method handles diagnosing this prettily and returns false if the
   1361 /// declspec is done being processed.  If it recovers and thinks there may be
   1362 /// other pieces of declspec after it, it returns true.
   1363 ///
   1364 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
   1365                               const ParsedTemplateInfo &TemplateInfo,
   1366                               AccessSpecifier AS) {
   1367   assert(Tok.is(tok::identifier) && "should have identifier");
   1368 
   1369   SourceLocation Loc = Tok.getLocation();
   1370   // If we see an identifier that is not a type name, we normally would
   1371   // parse it as the identifer being declared.  However, when a typename
   1372   // is typo'd or the definition is not included, this will incorrectly
   1373   // parse the typename as the identifier name and fall over misparsing
   1374   // later parts of the diagnostic.
   1375   //
   1376   // As such, we try to do some look-ahead in cases where this would
   1377   // otherwise be an "implicit-int" case to see if this is invalid.  For
   1378   // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
   1379   // an identifier with implicit int, we'd get a parse error because the
   1380   // next token is obviously invalid for a type.  Parse these as a case
   1381   // with an invalid type specifier.
   1382   assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
   1383 
   1384   // Since we know that this either implicit int (which is rare) or an
   1385   // error, we'd do lookahead to try to do better recovery.
   1386   if (isValidAfterIdentifierInDeclarator(NextToken())) {
   1387     // If this token is valid for implicit int, e.g. "static x = 4", then
   1388     // we just avoid eating the identifier, so it will be parsed as the
   1389     // identifier in the declarator.
   1390     return false;
   1391   }
   1392 
   1393   // Otherwise, if we don't consume this token, we are going to emit an
   1394   // error anyway.  Try to recover from various common problems.  Check
   1395   // to see if this was a reference to a tag name without a tag specified.
   1396   // This is a common problem in C (saying 'foo' instead of 'struct foo').
   1397   //
   1398   // C++ doesn't need this, and isTagName doesn't take SS.
   1399   if (SS == 0) {
   1400     const char *TagName = 0, *FixitTagName = 0;
   1401     tok::TokenKind TagKind = tok::unknown;
   1402 
   1403     switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
   1404       default: break;
   1405       case DeclSpec::TST_enum:
   1406         TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
   1407       case DeclSpec::TST_union:
   1408         TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
   1409       case DeclSpec::TST_struct:
   1410         TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
   1411       case DeclSpec::TST_class:
   1412         TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
   1413     }
   1414 
   1415     if (TagName) {
   1416       Diag(Loc, diag::err_use_of_tag_name_without_tag)
   1417         << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
   1418         << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName);
   1419 
   1420       // Parse this as a tag as if the missing tag were present.
   1421       if (TagKind == tok::kw_enum)
   1422         ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
   1423       else
   1424         ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
   1425       return true;
   1426     }
   1427   }
   1428 
   1429   // This is almost certainly an invalid type name. Let the action emit a
   1430   // diagnostic and attempt to recover.
   1431   ParsedType T;
   1432   if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
   1433                                       getCurScope(), SS, T)) {
   1434     // The action emitted a diagnostic, so we don't have to.
   1435     if (T) {
   1436       // The action has suggested that the type T could be used. Set that as
   1437       // the type in the declaration specifiers, consume the would-be type
   1438       // name token, and we're done.
   1439       const char *PrevSpec;
   1440       unsigned DiagID;
   1441       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
   1442       DS.SetRangeEnd(Tok.getLocation());
   1443       ConsumeToken();
   1444 
   1445       // There may be other declaration specifiers after this.
   1446       return true;
   1447     }
   1448 
   1449     // Fall through; the action had no suggestion for us.
   1450   } else {
   1451     // The action did not emit a diagnostic, so emit one now.
   1452     SourceRange R;
   1453     if (SS) R = SS->getRange();
   1454     Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
   1455   }
   1456 
   1457   // Mark this as an error.
   1458   const char *PrevSpec;
   1459   unsigned DiagID;
   1460   DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
   1461   DS.SetRangeEnd(Tok.getLocation());
   1462   ConsumeToken();
   1463 
   1464   // TODO: Could inject an invalid typedef decl in an enclosing scope to
   1465   // avoid rippling error messages on subsequent uses of the same type,
   1466   // could be useful if #include was forgotten.
   1467   return false;
   1468 }
   1469 
   1470 /// \brief Determine the declaration specifier context from the declarator
   1471 /// context.
   1472 ///
   1473 /// \param Context the declarator context, which is one of the
   1474 /// Declarator::TheContext enumerator values.
   1475 Parser::DeclSpecContext
   1476 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
   1477   if (Context == Declarator::MemberContext)
   1478     return DSC_class;
   1479   if (Context == Declarator::FileContext)
   1480     return DSC_top_level;
   1481   return DSC_normal;
   1482 }
   1483 
   1484 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
   1485 ///
   1486 /// FIXME: Simply returns an alignof() expression if the argument is a
   1487 /// type. Ideally, the type should be propagated directly into Sema.
   1488 ///
   1489 /// [C1X/C++0x] type-id
   1490 /// [C1X]       constant-expression
   1491 /// [C++0x]     assignment-expression
   1492 ExprResult Parser::ParseAlignArgument(SourceLocation Start) {
   1493   if (isTypeIdInParens()) {
   1494     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
   1495     SourceLocation TypeLoc = Tok.getLocation();
   1496     ParsedType Ty = ParseTypeName().get();
   1497     SourceRange TypeRange(Start, Tok.getLocation());
   1498     return Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
   1499                                                 Ty.getAsOpaquePtr(), TypeRange);
   1500   } else
   1501     return ParseConstantExpression();
   1502 }
   1503 
   1504 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
   1505 /// attribute to Attrs.
   1506 ///
   1507 /// alignment-specifier:
   1508 /// [C1X]   '_Alignas' '(' type-id ')'
   1509 /// [C1X]   '_Alignas' '(' constant-expression ')'
   1510 /// [C++0x] 'alignas' '(' type-id ')'
   1511 /// [C++0x] 'alignas' '(' assignment-expression ')'
   1512 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
   1513                                      SourceLocation *endLoc) {
   1514   assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
   1515          "Not an alignment-specifier!");
   1516 
   1517   SourceLocation KWLoc = Tok.getLocation();
   1518   ConsumeToken();
   1519 
   1520   BalancedDelimiterTracker T(*this, tok::l_paren);
   1521   if (T.expectAndConsume(diag::err_expected_lparen))
   1522     return;
   1523 
   1524   ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation());
   1525   if (ArgExpr.isInvalid()) {
   1526     SkipUntil(tok::r_paren);
   1527     return;
   1528   }
   1529 
   1530   T.consumeClose();
   1531   if (endLoc)
   1532     *endLoc = T.getCloseLocation();
   1533 
   1534   ExprVector ArgExprs(Actions);
   1535   ArgExprs.push_back(ArgExpr.release());
   1536   Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc,
   1537                0, T.getOpenLocation(), ArgExprs.take(), 1, false, true);
   1538 }
   1539 
   1540 /// ParseDeclarationSpecifiers
   1541 ///       declaration-specifiers: [C99 6.7]
   1542 ///         storage-class-specifier declaration-specifiers[opt]
   1543 ///         type-specifier declaration-specifiers[opt]
   1544 /// [C99]   function-specifier declaration-specifiers[opt]
   1545 /// [C1X]   alignment-specifier declaration-specifiers[opt]
   1546 /// [GNU]   attributes declaration-specifiers[opt]
   1547 /// [Clang] '__module_private__' declaration-specifiers[opt]
   1548 ///
   1549 ///       storage-class-specifier: [C99 6.7.1]
   1550 ///         'typedef'
   1551 ///         'extern'
   1552 ///         'static'
   1553 ///         'auto'
   1554 ///         'register'
   1555 /// [C++]   'mutable'
   1556 /// [GNU]   '__thread'
   1557 ///       function-specifier: [C99 6.7.4]
   1558 /// [C99]   'inline'
   1559 /// [C++]   'virtual'
   1560 /// [C++]   'explicit'
   1561 /// [OpenCL] '__kernel'
   1562 ///       'friend': [C++ dcl.friend]
   1563 ///       'constexpr': [C++0x dcl.constexpr]
   1564 
   1565 ///
   1566 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
   1567                                         const ParsedTemplateInfo &TemplateInfo,
   1568                                         AccessSpecifier AS,
   1569                                         DeclSpecContext DSContext) {
   1570   if (DS.getSourceRange().isInvalid()) {
   1571     DS.SetRangeStart(Tok.getLocation());
   1572     DS.SetRangeEnd(Tok.getLocation());
   1573   }
   1574 
   1575   while (1) {
   1576     bool isInvalid = false;
   1577     const char *PrevSpec = 0;
   1578     unsigned DiagID = 0;
   1579 
   1580     SourceLocation Loc = Tok.getLocation();
   1581 
   1582     switch (Tok.getKind()) {
   1583     default:
   1584     DoneWithDeclSpec:
   1585       // [C++0x] decl-specifier-seq: decl-specifier attribute-specifier-seq[opt]
   1586       MaybeParseCXX0XAttributes(DS.getAttributes());
   1587 
   1588       // If this is not a declaration specifier token, we're done reading decl
   1589       // specifiers.  First verify that DeclSpec's are consistent.
   1590       DS.Finish(Diags, PP);
   1591       return;
   1592 
   1593     case tok::code_completion: {
   1594       Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
   1595       if (DS.hasTypeSpecifier()) {
   1596         bool AllowNonIdentifiers
   1597           = (getCurScope()->getFlags() & (Scope::ControlScope |
   1598                                           Scope::BlockScope |
   1599                                           Scope::TemplateParamScope |
   1600                                           Scope::FunctionPrototypeScope |
   1601                                           Scope::AtCatchScope)) == 0;
   1602         bool AllowNestedNameSpecifiers
   1603           = DSContext == DSC_top_level ||
   1604             (DSContext == DSC_class && DS.isFriendSpecified());
   1605 
   1606         Actions.CodeCompleteDeclSpec(getCurScope(), DS,
   1607                                      AllowNonIdentifiers,
   1608                                      AllowNestedNameSpecifiers);
   1609         return cutOffParsing();
   1610       }
   1611 
   1612       if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
   1613         CCC = Sema::PCC_LocalDeclarationSpecifiers;
   1614       else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
   1615         CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
   1616                                     : Sema::PCC_Template;
   1617       else if (DSContext == DSC_class)
   1618         CCC = Sema::PCC_Class;
   1619       else if (ObjCImpDecl)
   1620         CCC = Sema::PCC_ObjCImplementation;
   1621 
   1622       Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
   1623       return cutOffParsing();
   1624     }
   1625 
   1626     case tok::coloncolon: // ::foo::bar
   1627       // C++ scope specifier.  Annotate and loop, or bail out on error.
   1628       if (TryAnnotateCXXScopeToken(true)) {
   1629         if (!DS.hasTypeSpecifier())
   1630           DS.SetTypeSpecError();
   1631         goto DoneWithDeclSpec;
   1632       }
   1633       if (Tok.is(tok::coloncolon)) // ::new or ::delete
   1634         goto DoneWithDeclSpec;
   1635       continue;
   1636 
   1637     case tok::annot_cxxscope: {
   1638       if (DS.hasTypeSpecifier())
   1639         goto DoneWithDeclSpec;
   1640 
   1641       CXXScopeSpec SS;
   1642       Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
   1643                                                    Tok.getAnnotationRange(),
   1644                                                    SS);
   1645 
   1646       // We are looking for a qualified typename.
   1647       Token Next = NextToken();
   1648       if (Next.is(tok::annot_template_id) &&
   1649           static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
   1650             ->Kind == TNK_Type_template) {
   1651         // We have a qualified template-id, e.g., N::A<int>
   1652 
   1653         // C++ [class.qual]p2:
   1654         //   In a lookup in which the constructor is an acceptable lookup
   1655         //   result and the nested-name-specifier nominates a class C:
   1656         //
   1657         //     - if the name specified after the
   1658         //       nested-name-specifier, when looked up in C, is the
   1659         //       injected-class-name of C (Clause 9), or
   1660         //
   1661         //     - if the name specified after the nested-name-specifier
   1662         //       is the same as the identifier or the
   1663         //       simple-template-id's template-name in the last
   1664         //       component of the nested-name-specifier,
   1665         //
   1666         //   the name is instead considered to name the constructor of
   1667         //   class C.
   1668         //
   1669         // Thus, if the template-name is actually the constructor
   1670         // name, then the code is ill-formed; this interpretation is
   1671         // reinforced by the NAD status of core issue 635.
   1672         TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
   1673         if ((DSContext == DSC_top_level ||
   1674              (DSContext == DSC_class && DS.isFriendSpecified())) &&
   1675             TemplateId->Name &&
   1676             Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
   1677           if (isConstructorDeclarator()) {
   1678             // The user meant this to be an out-of-line constructor
   1679             // definition, but template arguments are not allowed
   1680             // there.  Just allow this as a constructor; we'll
   1681             // complain about it later.
   1682             goto DoneWithDeclSpec;
   1683           }
   1684 
   1685           // The user meant this to name a type, but it actually names
   1686           // a constructor with some extraneous template
   1687           // arguments. Complain, then parse it as a type as the user
   1688           // intended.
   1689           Diag(TemplateId->TemplateNameLoc,
   1690                diag::err_out_of_line_template_id_names_constructor)
   1691             << TemplateId->Name;
   1692         }
   1693 
   1694         DS.getTypeSpecScope() = SS;
   1695         ConsumeToken(); // The C++ scope.
   1696         assert(Tok.is(tok::annot_template_id) &&
   1697                "ParseOptionalCXXScopeSpecifier not working");
   1698         AnnotateTemplateIdTokenAsType();
   1699         continue;
   1700       }
   1701 
   1702       if (Next.is(tok::annot_typename)) {
   1703         DS.getTypeSpecScope() = SS;
   1704         ConsumeToken(); // The C++ scope.
   1705         if (Tok.getAnnotationValue()) {
   1706           ParsedType T = getTypeAnnotation(Tok);
   1707           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
   1708                                          Tok.getAnnotationEndLoc(),
   1709                                          PrevSpec, DiagID, T);
   1710         }
   1711         else
   1712           DS.SetTypeSpecError();
   1713         DS.SetRangeEnd(Tok.getAnnotationEndLoc());
   1714         ConsumeToken(); // The typename
   1715       }
   1716 
   1717       if (Next.isNot(tok::identifier))
   1718         goto DoneWithDeclSpec;
   1719 
   1720       // If we're in a context where the identifier could be a class name,
   1721       // check whether this is a constructor declaration.
   1722       if ((DSContext == DSC_top_level ||
   1723            (DSContext == DSC_class && DS.isFriendSpecified())) &&
   1724           Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
   1725                                      &SS)) {
   1726         if (isConstructorDeclarator())
   1727           goto DoneWithDeclSpec;
   1728 
   1729         // As noted in C++ [class.qual]p2 (cited above), when the name
   1730         // of the class is qualified in a context where it could name
   1731         // a constructor, its a constructor name. However, we've
   1732         // looked at the declarator, and the user probably meant this
   1733         // to be a type. Complain that it isn't supposed to be treated
   1734         // as a type, then proceed to parse it as a type.
   1735         Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
   1736           << Next.getIdentifierInfo();
   1737       }
   1738 
   1739       ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
   1740                                                Next.getLocation(),
   1741                                                getCurScope(), &SS,
   1742                                                false, false, ParsedType(),
   1743                                                /*NonTrivialSourceInfo=*/true);
   1744 
   1745       // If the referenced identifier is not a type, then this declspec is
   1746       // erroneous: We already checked about that it has no type specifier, and
   1747       // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
   1748       // typename.
   1749       if (TypeRep == 0) {
   1750         ConsumeToken();   // Eat the scope spec so the identifier is current.
   1751         if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
   1752         goto DoneWithDeclSpec;
   1753       }
   1754 
   1755       DS.getTypeSpecScope() = SS;
   1756       ConsumeToken(); // The C++ scope.
   1757 
   1758       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
   1759                                      DiagID, TypeRep);
   1760       if (isInvalid)
   1761         break;
   1762 
   1763       DS.SetRangeEnd(Tok.getLocation());
   1764       ConsumeToken(); // The typename.
   1765 
   1766       continue;
   1767     }
   1768 
   1769     case tok::annot_typename: {
   1770       if (Tok.getAnnotationValue()) {
   1771         ParsedType T = getTypeAnnotation(Tok);
   1772         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
   1773                                        DiagID, T);
   1774       } else
   1775         DS.SetTypeSpecError();
   1776 
   1777       if (isInvalid)
   1778         break;
   1779 
   1780       DS.SetRangeEnd(Tok.getAnnotationEndLoc());
   1781       ConsumeToken(); // The typename
   1782 
   1783       // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
   1784       // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
   1785       // Objective-C interface.
   1786       if (Tok.is(tok::less) && getLang().ObjC1)
   1787         ParseObjCProtocolQualifiers(DS);
   1788 
   1789       continue;
   1790     }
   1791 
   1792     case tok::kw___is_signed:
   1793       // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
   1794       // typically treats it as a trait. If we see __is_signed as it appears
   1795       // in libstdc++, e.g.,
   1796       //
   1797       //   static const bool __is_signed;
   1798       //
   1799       // then treat __is_signed as an identifier rather than as a keyword.
   1800       if (DS.getTypeSpecType() == TST_bool &&
   1801           DS.getTypeQualifiers() == DeclSpec::TQ_const &&
   1802           DS.getStorageClassSpec() == DeclSpec::SCS_static) {
   1803         Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
   1804         Tok.setKind(tok::identifier);
   1805       }
   1806 
   1807       // We're done with the declaration-specifiers.
   1808       goto DoneWithDeclSpec;
   1809 
   1810       // typedef-name
   1811     case tok::identifier: {
   1812       // In C++, check to see if this is a scope specifier like foo::bar::, if
   1813       // so handle it as such.  This is important for ctor parsing.
   1814       if (getLang().CPlusPlus) {
   1815         if (TryAnnotateCXXScopeToken(true)) {
   1816           if (!DS.hasTypeSpecifier())
   1817             DS.SetTypeSpecError();
   1818           goto DoneWithDeclSpec;
   1819         }
   1820         if (!Tok.is(tok::identifier))
   1821           continue;
   1822       }
   1823 
   1824       // This identifier can only be a typedef name if we haven't already seen
   1825       // a type-specifier.  Without this check we misparse:
   1826       //  typedef int X; struct Y { short X; };  as 'short int'.
   1827       if (DS.hasTypeSpecifier())
   1828         goto DoneWithDeclSpec;
   1829 
   1830       // Check for need to substitute AltiVec keyword tokens.
   1831       if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
   1832         break;
   1833 
   1834       // It has to be available as a typedef too!
   1835       ParsedType TypeRep =
   1836         Actions.getTypeName(*Tok.getIdentifierInfo(),
   1837                             Tok.getLocation(), getCurScope());
   1838 
   1839       // If this is not a typedef name, don't parse it as part of the declspec,
   1840       // it must be an implicit int or an error.
   1841       if (!TypeRep) {
   1842         if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
   1843         goto DoneWithDeclSpec;
   1844       }
   1845 
   1846       // If we're in a context where the identifier could be a class name,
   1847       // check whether this is a constructor declaration.
   1848       if (getLang().CPlusPlus && DSContext == DSC_class &&
   1849           Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
   1850           isConstructorDeclarator())
   1851         goto DoneWithDeclSpec;
   1852 
   1853       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
   1854                                      DiagID, TypeRep);
   1855       if (isInvalid)
   1856         break;
   1857 
   1858       DS.SetRangeEnd(Tok.getLocation());
   1859       ConsumeToken(); // The identifier
   1860 
   1861       // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
   1862       // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
   1863       // Objective-C interface.
   1864       if (Tok.is(tok::less) && getLang().ObjC1)
   1865         ParseObjCProtocolQualifiers(DS);
   1866 
   1867       // Need to support trailing type qualifiers (e.g. "id<p> const").
   1868       // If a type specifier follows, it will be diagnosed elsewhere.
   1869       continue;
   1870     }
   1871 
   1872       // type-name
   1873     case tok::annot_template_id: {
   1874       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
   1875       if (TemplateId->Kind != TNK_Type_template) {
   1876         // This template-id does not refer to a type name, so we're
   1877         // done with the type-specifiers.
   1878         goto DoneWithDeclSpec;
   1879       }
   1880 
   1881       // If we're in a context where the template-id could be a
   1882       // constructor name or specialization, check whether this is a
   1883       // constructor declaration.
   1884       if (getLang().CPlusPlus && DSContext == DSC_class &&
   1885           Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
   1886           isConstructorDeclarator())
   1887         goto DoneWithDeclSpec;
   1888 
   1889       // Turn the template-id annotation token into a type annotation
   1890       // token, then try again to parse it as a type-specifier.
   1891       AnnotateTemplateIdTokenAsType();
   1892       continue;
   1893     }
   1894 
   1895     // GNU attributes support.
   1896     case tok::kw___attribute:
   1897       ParseGNUAttributes(DS.getAttributes());
   1898       continue;
   1899 
   1900     // Microsoft declspec support.
   1901     case tok::kw___declspec:
   1902       ParseMicrosoftDeclSpec(DS.getAttributes());
   1903       continue;
   1904 
   1905     // Microsoft single token adornments.
   1906     case tok::kw___forceinline:
   1907       // FIXME: Add handling here!
   1908       break;
   1909 
   1910     case tok::kw___ptr64:
   1911     case tok::kw___ptr32:
   1912     case tok::kw___w64:
   1913     case tok::kw___cdecl:
   1914     case tok::kw___stdcall:
   1915     case tok::kw___fastcall:
   1916     case tok::kw___thiscall:
   1917     case tok::kw___unaligned:
   1918       ParseMicrosoftTypeAttributes(DS.getAttributes());
   1919       continue;
   1920 
   1921     // Borland single token adornments.
   1922     case tok::kw___pascal:
   1923       ParseBorlandTypeAttributes(DS.getAttributes());
   1924       continue;
   1925 
   1926     // OpenCL single token adornments.
   1927     case tok::kw___kernel:
   1928       ParseOpenCLAttributes(DS.getAttributes());
   1929       continue;
   1930 
   1931     // storage-class-specifier
   1932     case tok::kw_typedef:
   1933       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
   1934                                          PrevSpec, DiagID);
   1935       break;
   1936     case tok::kw_extern:
   1937       if (DS.isThreadSpecified())
   1938         Diag(Tok, diag::ext_thread_before) << "extern";
   1939       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
   1940                                          PrevSpec, DiagID);
   1941       break;
   1942     case tok::kw___private_extern__:
   1943       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
   1944                                          Loc, PrevSpec, DiagID);
   1945       break;
   1946     case tok::kw_static:
   1947       if (DS.isThreadSpecified())
   1948         Diag(Tok, diag::ext_thread_before) << "static";
   1949       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
   1950                                          PrevSpec, DiagID);
   1951       break;
   1952     case tok::kw_auto:
   1953       if (getLang().CPlusPlus0x) {
   1954         if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
   1955           isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
   1956                                              PrevSpec, DiagID);
   1957           if (!isInvalid)
   1958             Diag(Tok, diag::ext_auto_storage_class)
   1959               << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
   1960         } else
   1961           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
   1962                                          DiagID);
   1963       } else
   1964         isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
   1965                                            PrevSpec, DiagID);
   1966       break;
   1967     case tok::kw_register:
   1968       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
   1969                                          PrevSpec, DiagID);
   1970       break;
   1971     case tok::kw_mutable:
   1972       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
   1973                                          PrevSpec, DiagID);
   1974       break;
   1975     case tok::kw___thread:
   1976       isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
   1977       break;
   1978 
   1979     // function-specifier
   1980     case tok::kw_inline:
   1981       isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
   1982       break;
   1983     case tok::kw_virtual:
   1984       isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
   1985       break;
   1986     case tok::kw_explicit:
   1987       isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
   1988       break;
   1989 
   1990     // alignment-specifier
   1991     case tok::kw__Alignas:
   1992       if (!getLang().C1X)
   1993         Diag(Tok, diag::ext_c1x_alignas);
   1994       ParseAlignmentSpecifier(DS.getAttributes());
   1995       continue;
   1996 
   1997     // friend
   1998     case tok::kw_friend:
   1999       if (DSContext == DSC_class)
   2000         isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
   2001       else {
   2002         PrevSpec = ""; // not actually used by the diagnostic
   2003         DiagID = diag::err_friend_invalid_in_context;
   2004         isInvalid = true;
   2005       }
   2006       break;
   2007 
   2008     // Modules
   2009     case tok::kw___module_private__:
   2010       isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
   2011       break;
   2012 
   2013     // constexpr
   2014     case tok::kw_constexpr:
   2015       isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
   2016       break;
   2017 
   2018     // type-specifier
   2019     case tok::kw_short:
   2020       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
   2021                                       DiagID);
   2022       break;
   2023     case tok::kw_long:
   2024       if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
   2025         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
   2026                                         DiagID);
   2027       else
   2028         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
   2029                                         DiagID);
   2030       break;
   2031     case tok::kw___int64:
   2032         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
   2033                                         DiagID);
   2034       break;
   2035     case tok::kw_signed:
   2036       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
   2037                                      DiagID);
   2038       break;
   2039     case tok::kw_unsigned:
   2040       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
   2041                                      DiagID);
   2042       break;
   2043     case tok::kw__Complex:
   2044       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
   2045                                         DiagID);
   2046       break;
   2047     case tok::kw__Imaginary:
   2048       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
   2049                                         DiagID);
   2050       break;
   2051     case tok::kw_void:
   2052       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
   2053                                      DiagID);
   2054       break;
   2055     case tok::kw_char:
   2056       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
   2057                                      DiagID);
   2058       break;
   2059     case tok::kw_int:
   2060       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
   2061                                      DiagID);
   2062       break;
   2063      case tok::kw_half:
   2064        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
   2065                                       DiagID);
   2066        break;
   2067     case tok::kw_float:
   2068       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
   2069                                      DiagID);
   2070       break;
   2071     case tok::kw_double:
   2072       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
   2073                                      DiagID);
   2074       break;
   2075     case tok::kw_wchar_t:
   2076       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
   2077                                      DiagID);
   2078       break;
   2079     case tok::kw_char16_t:
   2080       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
   2081                                      DiagID);
   2082       break;
   2083     case tok::kw_char32_t:
   2084       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
   2085                                      DiagID);
   2086       break;
   2087     case tok::kw_bool:
   2088     case tok::kw__Bool:
   2089       if (Tok.is(tok::kw_bool) &&
   2090           DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
   2091           DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
   2092         PrevSpec = ""; // Not used by the diagnostic.
   2093         DiagID = diag::err_bool_redeclaration;
   2094         // For better error recovery.
   2095         Tok.setKind(tok::identifier);
   2096         isInvalid = true;
   2097       } else {
   2098         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
   2099                                        DiagID);
   2100       }
   2101       break;
   2102     case tok::kw__Decimal32:
   2103       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
   2104                                      DiagID);
   2105       break;
   2106     case tok::kw__Decimal64:
   2107       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
   2108                                      DiagID);
   2109       break;
   2110     case tok::kw__Decimal128:
   2111       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
   2112                                      DiagID);
   2113       break;
   2114     case tok::kw___vector:
   2115       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
   2116       break;
   2117     case tok::kw___pixel:
   2118       isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
   2119       break;
   2120     case tok::kw___unknown_anytype:
   2121       isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
   2122                                      PrevSpec, DiagID);
   2123       break;
   2124 
   2125     // class-specifier:
   2126     case tok::kw_class:
   2127     case tok::kw_struct:
   2128     case tok::kw_union: {
   2129       tok::TokenKind Kind = Tok.getKind();
   2130       ConsumeToken();
   2131       ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
   2132       continue;
   2133     }
   2134 
   2135     // enum-specifier:
   2136     case tok::kw_enum:
   2137       ConsumeToken();
   2138       ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
   2139       continue;
   2140 
   2141     // cv-qualifier:
   2142     case tok::kw_const:
   2143       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
   2144                                  getLang());
   2145       break;
   2146     case tok::kw_volatile:
   2147       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
   2148                                  getLang());
   2149       break;
   2150     case tok::kw_restrict:
   2151       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
   2152                                  getLang());
   2153       break;
   2154 
   2155     // C++ typename-specifier:
   2156     case tok::kw_typename:
   2157       if (TryAnnotateTypeOrScopeToken()) {
   2158         DS.SetTypeSpecError();
   2159         goto DoneWithDeclSpec;
   2160       }
   2161       if (!Tok.is(tok::kw_typename))
   2162         continue;
   2163       break;
   2164 
   2165     // GNU typeof support.
   2166     case tok::kw_typeof:
   2167       ParseTypeofSpecifier(DS);
   2168       continue;
   2169 
   2170     case tok::kw_decltype:
   2171       ParseDecltypeSpecifier(DS);
   2172       continue;
   2173 
   2174     case tok::kw___underlying_type:
   2175       ParseUnderlyingTypeSpecifier(DS);
   2176       continue;
   2177 
   2178     case tok::kw__Atomic:
   2179       ParseAtomicSpecifier(DS);
   2180       continue;
   2181 
   2182     // OpenCL qualifiers:
   2183     case tok::kw_private:
   2184       if (!getLang().OpenCL)
   2185         goto DoneWithDeclSpec;
   2186     case tok::kw___private:
   2187     case tok::kw___global:
   2188     case tok::kw___local:
   2189     case tok::kw___constant:
   2190     case tok::kw___read_only:
   2191     case tok::kw___write_only:
   2192     case tok::kw___read_write:
   2193       ParseOpenCLQualifiers(DS);
   2194       break;
   2195 
   2196     case tok::less:
   2197       // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
   2198       // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
   2199       // but we support it.
   2200       if (DS.hasTypeSpecifier() || !getLang().ObjC1)
   2201         goto DoneWithDeclSpec;
   2202 
   2203       if (!ParseObjCProtocolQualifiers(DS))
   2204         Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
   2205           << FixItHint::CreateInsertion(Loc, "id")
   2206           << SourceRange(Loc, DS.getSourceRange().getEnd());
   2207 
   2208       // Need to support trailing type qualifiers (e.g. "id<p> const").
   2209       // If a type specifier follows, it will be diagnosed elsewhere.
   2210       continue;
   2211     }
   2212     // If the specifier wasn't legal, issue a diagnostic.
   2213     if (isInvalid) {
   2214       assert(PrevSpec && "Method did not return previous specifier!");
   2215       assert(DiagID);
   2216 
   2217       if (DiagID == diag::ext_duplicate_declspec)
   2218         Diag(Tok, DiagID)
   2219           << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
   2220       else
   2221         Diag(Tok, DiagID) << PrevSpec;
   2222     }
   2223 
   2224     DS.SetRangeEnd(Tok.getLocation());
   2225     if (DiagID != diag::err_bool_redeclaration)
   2226       ConsumeToken();
   2227   }
   2228 }
   2229 
   2230 /// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
   2231 /// primarily follow the C++ grammar with additions for C99 and GNU,
   2232 /// which together subsume the C grammar. Note that the C++
   2233 /// type-specifier also includes the C type-qualifier (for const,
   2234 /// volatile, and C99 restrict). Returns true if a type-specifier was
   2235 /// found (and parsed), false otherwise.
   2236 ///
   2237 ///       type-specifier: [C++ 7.1.5]
   2238 ///         simple-type-specifier
   2239 ///         class-specifier
   2240 ///         enum-specifier
   2241 ///         elaborated-type-specifier  [TODO]
   2242 ///         cv-qualifier
   2243 ///
   2244 ///       cv-qualifier: [C++ 7.1.5.1]
   2245 ///         'const'
   2246 ///         'volatile'
   2247 /// [C99]   'restrict'
   2248 ///
   2249 ///       simple-type-specifier: [ C++ 7.1.5.2]
   2250 ///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
   2251 ///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
   2252 ///         'char'
   2253 ///         'wchar_t'
   2254 ///         'bool'
   2255 ///         'short'
   2256 ///         'int'
   2257 ///         'long'
   2258 ///         'signed'
   2259 ///         'unsigned'
   2260 ///         'float'
   2261 ///         'double'
   2262 ///         'void'
   2263 /// [C99]   '_Bool'
   2264 /// [C99]   '_Complex'
   2265 /// [C99]   '_Imaginary'  // Removed in TC2?
   2266 /// [GNU]   '_Decimal32'
   2267 /// [GNU]   '_Decimal64'
   2268 /// [GNU]   '_Decimal128'
   2269 /// [GNU]   typeof-specifier
   2270 /// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
   2271 /// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
   2272 /// [C++0x] 'decltype' ( expression )
   2273 /// [AltiVec] '__vector'
   2274 bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
   2275                                         const char *&PrevSpec,
   2276                                         unsigned &DiagID,
   2277                                         const ParsedTemplateInfo &TemplateInfo,
   2278                                         bool SuppressDeclarations) {
   2279   SourceLocation Loc = Tok.getLocation();
   2280 
   2281   switch (Tok.getKind()) {
   2282   case tok::identifier:   // foo::bar
   2283     // If we already have a type specifier, this identifier is not a type.
   2284     if (DS.getTypeSpecType() != DeclSpec::TST_unspecified ||
   2285         DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
   2286         DS.getTypeSpecSign() != DeclSpec::TSS_unspecified)
   2287       return false;
   2288     // Check for need to substitute AltiVec keyword tokens.
   2289     if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
   2290       break;
   2291     // Fall through.
   2292   case tok::kw_typename:  // typename foo::bar
   2293     // Annotate typenames and C++ scope specifiers.  If we get one, just
   2294     // recurse to handle whatever we get.
   2295     if (TryAnnotateTypeOrScopeToken(/*EnteringContext=*/false,
   2296                                     /*NeedType=*/true))
   2297       return true;
   2298     if (Tok.is(tok::identifier))
   2299       return false;
   2300     return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
   2301                                       TemplateInfo, SuppressDeclarations);
   2302   case tok::coloncolon:   // ::foo::bar
   2303     if (NextToken().is(tok::kw_new) ||    // ::new
   2304         NextToken().is(tok::kw_delete))   // ::delete
   2305       return false;
   2306 
   2307     // Annotate typenames and C++ scope specifiers.  If we get one, just
   2308     // recurse to handle whatever we get.
   2309     if (TryAnnotateTypeOrScopeToken(/*EnteringContext=*/false,
   2310                                     /*NeedType=*/true))
   2311       return true;
   2312     return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
   2313                                       TemplateInfo, SuppressDeclarations);
   2314 
   2315   // simple-type-specifier:
   2316   case tok::annot_typename: {
   2317     if (ParsedType T = getTypeAnnotation(Tok)) {
   2318       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
   2319                                      Tok.getAnnotationEndLoc(), PrevSpec,
   2320                                      DiagID, T);
   2321     } else
   2322       DS.SetTypeSpecError();
   2323     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
   2324     ConsumeToken(); // The typename
   2325 
   2326     // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
   2327     // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
   2328     // Objective-C interface.  If we don't have Objective-C or a '<', this is
   2329     // just a normal reference to a typedef name.
   2330     if (Tok.is(tok::less) && getLang().ObjC1)
   2331       ParseObjCProtocolQualifiers(DS);
   2332 
   2333     return true;
   2334   }
   2335 
   2336   case tok::kw_short:
   2337     isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
   2338     break;
   2339   case tok::kw_long:
   2340     if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
   2341       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
   2342                                       DiagID);
   2343     else
   2344       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
   2345                                       DiagID);
   2346     break;
   2347   case tok::kw___int64:
   2348       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
   2349                                       DiagID);
   2350     break;
   2351   case tok::kw_signed:
   2352     isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
   2353     break;
   2354   case tok::kw_unsigned:
   2355     isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
   2356                                    DiagID);
   2357     break;
   2358   case tok::kw__Complex:
   2359     isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
   2360                                       DiagID);
   2361     break;
   2362   case tok::kw__Imaginary:
   2363     isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
   2364                                       DiagID);
   2365     break;
   2366   case tok::kw_void:
   2367     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
   2368     break;
   2369   case tok::kw_char:
   2370     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
   2371     break;
   2372   case tok::kw_int:
   2373     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
   2374     break;
   2375   case tok::kw_half:
   2376     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
   2377     break;
   2378   case tok::kw_float:
   2379     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
   2380     break;
   2381   case tok::kw_double:
   2382     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
   2383     break;
   2384   case tok::kw_wchar_t:
   2385     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
   2386     break;
   2387   case tok::kw_char16_t:
   2388     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
   2389     break;
   2390   case tok::kw_char32_t:
   2391     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
   2392     break;
   2393   case tok::kw_bool:
   2394   case tok::kw__Bool:
   2395     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
   2396     break;
   2397   case tok::kw__Decimal32:
   2398     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
   2399                                    DiagID);
   2400     break;
   2401   case tok::kw__Decimal64:
   2402     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
   2403                                    DiagID);
   2404     break;
   2405   case tok::kw__Decimal128:
   2406     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
   2407                                    DiagID);
   2408     break;
   2409   case tok::kw___vector:
   2410     isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
   2411     break;
   2412   case tok::kw___pixel:
   2413     isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
   2414     break;
   2415 
   2416   // class-specifier:
   2417   case tok::kw_class:
   2418   case tok::kw_struct:
   2419   case tok::kw_union: {
   2420     tok::TokenKind Kind = Tok.getKind();
   2421     ConsumeToken();
   2422     ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
   2423                         SuppressDeclarations);
   2424     return true;
   2425   }
   2426 
   2427   // enum-specifier:
   2428   case tok::kw_enum:
   2429     ConsumeToken();
   2430     ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
   2431     return true;
   2432 
   2433   // cv-qualifier:
   2434   case tok::kw_const:
   2435     isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
   2436                                DiagID, getLang());
   2437     break;
   2438   case tok::kw_volatile:
   2439     isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
   2440                                DiagID, getLang());
   2441     break;
   2442   case tok::kw_restrict:
   2443     isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
   2444                                DiagID, getLang());
   2445     break;
   2446 
   2447   // GNU typeof support.
   2448   case tok::kw_typeof:
   2449     ParseTypeofSpecifier(DS);
   2450     return true;
   2451 
   2452   // C++0x decltype support.
   2453   case tok::kw_decltype:
   2454     ParseDecltypeSpecifier(DS);
   2455     return true;
   2456 
   2457   // C++0x type traits support.
   2458   case tok::kw___underlying_type:
   2459     ParseUnderlyingTypeSpecifier(DS);
   2460     return true;
   2461 
   2462   case tok::kw__Atomic:
   2463     ParseAtomicSpecifier(DS);
   2464     return true;
   2465 
   2466   // OpenCL qualifiers:
   2467   case tok::kw_private:
   2468     if (!getLang().OpenCL)
   2469       return false;
   2470   case tok::kw___private:
   2471   case tok::kw___global:
   2472   case tok::kw___local:
   2473   case tok::kw___constant:
   2474   case tok::kw___read_only:
   2475   case tok::kw___write_only:
   2476   case tok::kw___read_write:
   2477     ParseOpenCLQualifiers(DS);
   2478     break;
   2479 
   2480   // C++0x auto support.
   2481   case tok::kw_auto:
   2482     // This is only called in situations where a storage-class specifier is
   2483     // illegal, so we can assume an auto type specifier was intended even in
   2484     // C++98. In C++98 mode, DeclSpec::Finish will produce an appropriate
   2485     // extension diagnostic.
   2486     if (!getLang().CPlusPlus)
   2487       return false;
   2488 
   2489     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
   2490     break;
   2491 
   2492   case tok::kw___ptr64:
   2493   case tok::kw___ptr32:
   2494   case tok::kw___w64:
   2495   case tok::kw___cdecl:
   2496   case tok::kw___stdcall:
   2497   case tok::kw___fastcall:
   2498   case tok::kw___thiscall:
   2499   case tok::kw___unaligned:
   2500     ParseMicrosoftTypeAttributes(DS.getAttributes());
   2501     return true;
   2502 
   2503   case tok::kw___pascal:
   2504     ParseBorlandTypeAttributes(DS.getAttributes());
   2505     return true;
   2506 
   2507   default:
   2508     // Not a type-specifier; do nothing.
   2509     return false;
   2510   }
   2511 
   2512   // If the specifier combination wasn't legal, issue a diagnostic.
   2513   if (isInvalid) {
   2514     assert(PrevSpec && "Method did not return previous specifier!");
   2515     // Pick between error or extwarn.
   2516     Diag(Tok, DiagID) << PrevSpec;
   2517   }
   2518   DS.SetRangeEnd(Tok.getLocation());
   2519   ConsumeToken(); // whatever we parsed above.
   2520   return true;
   2521 }
   2522 
   2523 /// ParseStructDeclaration - Parse a struct declaration without the terminating
   2524 /// semicolon.
   2525 ///
   2526 ///       struct-declaration:
   2527 ///         specifier-qualifier-list struct-declarator-list
   2528 /// [GNU]   __extension__ struct-declaration
   2529 /// [GNU]   specifier-qualifier-list
   2530 ///       struct-declarator-list:
   2531 ///         struct-declarator
   2532 ///         struct-declarator-list ',' struct-declarator
   2533 /// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
   2534 ///       struct-declarator:
   2535 ///         declarator
   2536 /// [GNU]   declarator attributes[opt]
   2537 ///         declarator[opt] ':' constant-expression
   2538 /// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
   2539 ///
   2540 void Parser::
   2541 ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
   2542 
   2543   if (Tok.is(tok::kw___extension__)) {
   2544     // __extension__ silences extension warnings in the subexpression.
   2545     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
   2546     ConsumeToken();
   2547     return ParseStructDeclaration(DS, Fields);
   2548   }
   2549 
   2550   // Parse the common specifier-qualifiers-list piece.
   2551   ParseSpecifierQualifierList(DS);
   2552 
   2553   // If there are no declarators, this is a free-standing declaration
   2554   // specifier. Let the actions module cope with it.
   2555   if (Tok.is(tok::semi)) {
   2556     Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
   2557     return;
   2558   }
   2559 
   2560   // Read struct-declarators until we find the semicolon.
   2561   bool FirstDeclarator = true;
   2562   while (1) {
   2563     ParsingDeclRAIIObject PD(*this);
   2564     FieldDeclarator DeclaratorInfo(DS);
   2565 
   2566     // Attributes are only allowed here on successive declarators.
   2567     if (!FirstDeclarator)
   2568       MaybeParseGNUAttributes(DeclaratorInfo.D);
   2569 
   2570     /// struct-declarator: declarator
   2571     /// struct-declarator: declarator[opt] ':' constant-expression
   2572     if (Tok.isNot(tok::colon)) {
   2573       // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
   2574       ColonProtectionRAIIObject X(*this);
   2575       ParseDeclarator(DeclaratorInfo.D);
   2576     }
   2577 
   2578     if (Tok.is(tok::colon)) {
   2579       ConsumeToken();
   2580       ExprResult Res(ParseConstantExpression());
   2581       if (Res.isInvalid())
   2582         SkipUntil(tok::semi, true, true);
   2583       else
   2584         DeclaratorInfo.BitfieldSize = Res.release();
   2585     }
   2586 
   2587     // If attributes exist after the declarator, parse them.
   2588     MaybeParseGNUAttributes(DeclaratorInfo.D);
   2589 
   2590     // We're done with this declarator;  invoke the callback.
   2591     Decl *D = Fields.invoke(DeclaratorInfo);
   2592     PD.complete(D);
   2593 
   2594     // If we don't have a comma, it is either the end of the list (a ';')
   2595     // or an error, bail out.
   2596     if (Tok.isNot(tok::comma))
   2597       return;
   2598 
   2599     // Consume the comma.
   2600     ConsumeToken();
   2601 
   2602     FirstDeclarator = false;
   2603   }
   2604 }
   2605 
   2606 /// ParseStructUnionBody
   2607 ///       struct-contents:
   2608 ///         struct-declaration-list
   2609 /// [EXT]   empty
   2610 /// [GNU]   "struct-declaration-list" without terminatoring ';'
   2611 ///       struct-declaration-list:
   2612 ///         struct-declaration
   2613 ///         struct-declaration-list struct-declaration
   2614 /// [OBC]   '@' 'defs' '(' class-name ')'
   2615 ///
   2616 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
   2617                                   unsigned TagType, Decl *TagDecl) {
   2618   PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
   2619                                       "parsing struct/union body");
   2620 
   2621   BalancedDelimiterTracker T(*this, tok::l_brace);
   2622   if (T.consumeOpen())
   2623     return;
   2624 
   2625   ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
   2626   Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
   2627 
   2628   // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
   2629   // C++.
   2630   if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
   2631     Diag(Tok, diag::ext_empty_struct_union)
   2632       << (TagType == TST_union);
   2633 
   2634   SmallVector<Decl *, 32> FieldDecls;
   2635 
   2636   // While we still have something to read, read the declarations in the struct.
   2637   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
   2638     // Each iteration of this loop reads one struct-declaration.
   2639 
   2640     // Check for extraneous top-level semicolon.
   2641     if (Tok.is(tok::semi)) {
   2642       Diag(Tok, diag::ext_extra_struct_semi)
   2643         << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
   2644         << FixItHint::CreateRemoval(Tok.getLocation());
   2645       ConsumeToken();
   2646       continue;
   2647     }
   2648 
   2649     // Parse all the comma separated declarators.
   2650     DeclSpec DS(AttrFactory);
   2651 
   2652     if (!Tok.is(tok::at)) {
   2653       struct CFieldCallback : FieldCallback {
   2654         Parser &P;
   2655         Decl *TagDecl;
   2656         SmallVectorImpl<Decl *> &FieldDecls;
   2657 
   2658         CFieldCallback(Parser &P, Decl *TagDecl,
   2659                        SmallVectorImpl<Decl *> &FieldDecls) :
   2660           P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
   2661 
   2662         virtual Decl *invoke(FieldDeclarator &FD) {
   2663           // Install the declarator into the current TagDecl.
   2664           Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
   2665                               FD.D.getDeclSpec().getSourceRange().getBegin(),
   2666                                                  FD.D, FD.BitfieldSize);
   2667           FieldDecls.push_back(Field);
   2668           return Field;
   2669         }
   2670       } Callback(*this, TagDecl, FieldDecls);
   2671 
   2672       ParseStructDeclaration(DS, Callback);
   2673     } else { // Handle @defs
   2674       ConsumeToken();
   2675       if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
   2676         Diag(Tok, diag::err_unexpected_at);
   2677         SkipUntil(tok::semi, true);
   2678         continue;
   2679       }
   2680       ConsumeToken();
   2681       ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
   2682       if (!Tok.is(tok::identifier)) {
   2683         Diag(Tok, diag::err_expected_ident);
   2684         SkipUntil(tok::semi, true);
   2685         continue;
   2686       }
   2687       SmallVector<Decl *, 16> Fields;
   2688       Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
   2689                         Tok.getIdentifierInfo(), Fields);
   2690       FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
   2691       ConsumeToken();
   2692       ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
   2693     }
   2694 
   2695     if (Tok.is(tok::semi)) {
   2696       ConsumeToken();
   2697     } else if (Tok.is(tok::r_brace)) {
   2698       ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
   2699       break;
   2700     } else {
   2701       ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
   2702       // Skip to end of block or statement to avoid ext-warning on extra ';'.
   2703       SkipUntil(tok::r_brace, true, true);
   2704       // If we stopped at a ';', eat it.
   2705       if (Tok.is(tok::semi)) ConsumeToken();
   2706     }
   2707   }
   2708 
   2709   T.consumeClose();
   2710 
   2711   ParsedAttributes attrs(AttrFactory);
   2712   // If attributes exist after struct contents, parse them.
   2713   MaybeParseGNUAttributes(attrs);
   2714 
   2715   Actions.ActOnFields(getCurScope(),
   2716                       RecordLoc, TagDecl, FieldDecls,
   2717                       T.getOpenLocation(), T.getCloseLocation(),
   2718                       attrs.getList());
   2719   StructScope.Exit();
   2720   Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
   2721                                    T.getCloseLocation());
   2722 }
   2723 
   2724 /// ParseEnumSpecifier
   2725 ///       enum-specifier: [C99 6.7.2.2]
   2726 ///         'enum' identifier[opt] '{' enumerator-list '}'
   2727 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
   2728 /// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
   2729 ///                                                 '}' attributes[opt]
   2730 ///         'enum' identifier
   2731 /// [GNU]   'enum' attributes[opt] identifier
   2732 ///
   2733 /// [C++0x] enum-head '{' enumerator-list[opt] '}'
   2734 /// [C++0x] enum-head '{' enumerator-list ','  '}'
   2735 ///
   2736 ///       enum-head: [C++0x]
   2737 ///         enum-key attributes[opt] identifier[opt] enum-base[opt]
   2738 ///         enum-key attributes[opt] nested-name-specifier identifier enum-base[opt]
   2739 ///
   2740 ///       enum-key: [C++0x]
   2741 ///         'enum'
   2742 ///         'enum' 'class'
   2743 ///         'enum' 'struct'
   2744 ///
   2745 ///       enum-base: [C++0x]
   2746 ///         ':' type-specifier-seq
   2747 ///
   2748 /// [C++] elaborated-type-specifier:
   2749 /// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
   2750 ///
   2751 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
   2752                                 const ParsedTemplateInfo &TemplateInfo,
   2753                                 AccessSpecifier AS) {
   2754   // Parse the tag portion of this.
   2755   if (Tok.is(tok::code_completion)) {
   2756     // Code completion for an enum name.
   2757     Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
   2758     return cutOffParsing();
   2759   }
   2760 
   2761   bool IsScopedEnum = false;
   2762   bool IsScopedUsingClassTag = false;
   2763 
   2764   if (getLang().CPlusPlus0x &&
   2765       (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
   2766     Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
   2767     IsScopedEnum = true;
   2768     IsScopedUsingClassTag = Tok.is(tok::kw_class);
   2769     ConsumeToken();
   2770   }
   2771 
   2772   // If attributes exist after tag, parse them.
   2773   ParsedAttributes attrs(AttrFactory);
   2774   MaybeParseGNUAttributes(attrs);
   2775 
   2776   bool AllowFixedUnderlyingType
   2777     = getLang().CPlusPlus0x || getLang().MicrosoftExt || getLang().ObjC2;
   2778 
   2779   CXXScopeSpec &SS = DS.getTypeSpecScope();
   2780   if (getLang().CPlusPlus) {
   2781     // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
   2782     // if a fixed underlying type is allowed.
   2783     ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
   2784 
   2785     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false))
   2786       return;
   2787 
   2788     if (SS.isSet() && Tok.isNot(tok::identifier)) {
   2789       Diag(Tok, diag::err_expected_ident);
   2790       if (Tok.isNot(tok::l_brace)) {
   2791         // Has no name and is not a definition.
   2792         // Skip the rest of this declarator, up until the comma or semicolon.
   2793         SkipUntil(tok::comma, true);
   2794         return;
   2795       }
   2796     }
   2797   }
   2798 
   2799   // Must have either 'enum name' or 'enum {...}'.
   2800   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
   2801       (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) {
   2802     Diag(Tok, diag::err_expected_ident_lbrace);
   2803 
   2804     // Skip the rest of this declarator, up until the comma or semicolon.
   2805     SkipUntil(tok::comma, true);
   2806     return;
   2807   }
   2808 
   2809   // If an identifier is present, consume and remember it.
   2810   IdentifierInfo *Name = 0;
   2811   SourceLocation NameLoc;
   2812   if (Tok.is(tok::identifier)) {
   2813     Name = Tok.getIdentifierInfo();
   2814     NameLoc = ConsumeToken();
   2815   }
   2816 
   2817   if (!Name && IsScopedEnum) {
   2818     // C++0x 7.2p2: The optional identifier shall not be omitted in the
   2819     // declaration of a scoped enumeration.
   2820     Diag(Tok, diag::err_scoped_enum_missing_identifier);
   2821     IsScopedEnum = false;
   2822     IsScopedUsingClassTag = false;
   2823   }
   2824 
   2825   TypeResult BaseType;
   2826 
   2827   // Parse the fixed underlying type.
   2828   if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
   2829     bool PossibleBitfield = false;
   2830     if (getCurScope()->getFlags() & Scope::ClassScope) {
   2831       // If we're in class scope, this can either be an enum declaration with
   2832       // an underlying type, or a declaration of a bitfield member. We try to
   2833       // use a simple disambiguation scheme first to catch the common cases
   2834       // (integer literal, sizeof); if it's still ambiguous, we then consider
   2835       // anything that's a simple-type-specifier followed by '(' as an
   2836       // expression. This suffices because function types are not valid
   2837       // underlying types anyway.
   2838       TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
   2839       // If the next token starts an expression, we know we're parsing a
   2840       // bit-field. This is the common case.
   2841       if (TPR == TPResult::True())
   2842         PossibleBitfield = true;
   2843       // If the next token starts a type-specifier-seq, it may be either a
   2844       // a fixed underlying type or the start of a function-style cast in C++;
   2845       // lookahead one more token to see if it's obvious that we have a
   2846       // fixed underlying type.
   2847       else if (TPR == TPResult::False() &&
   2848                GetLookAheadToken(2).getKind() == tok::semi) {
   2849         // Consume the ':'.
   2850         ConsumeToken();
   2851       } else {
   2852         // We have the start of a type-specifier-seq, so we have to perform
   2853         // tentative parsing to determine whether we have an expression or a
   2854         // type.
   2855         TentativeParsingAction TPA(*this);
   2856 
   2857         // Consume the ':'.
   2858         ConsumeToken();
   2859 
   2860         if ((getLang().CPlusPlus &&
   2861              isCXXDeclarationSpecifier() != TPResult::True()) ||
   2862             (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) {
   2863           // We'll parse this as a bitfield later.
   2864           PossibleBitfield = true;
   2865           TPA.Revert();
   2866         } else {
   2867           // We have a type-specifier-seq.
   2868           TPA.Commit();
   2869         }
   2870       }
   2871     } else {
   2872       // Consume the ':'.
   2873       ConsumeToken();
   2874     }
   2875 
   2876     if (!PossibleBitfield) {
   2877       SourceRange Range;
   2878       BaseType = ParseTypeName(&Range);
   2879 
   2880       if (!getLang().CPlusPlus0x && !getLang().ObjC2)
   2881         Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
   2882           << Range;
   2883       if (getLang().CPlusPlus0x)
   2884         Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
   2885     }
   2886   }
   2887 
   2888   // There are three options here.  If we have 'enum foo;', then this is a
   2889   // forward declaration.  If we have 'enum foo {...' then this is a
   2890   // definition. Otherwise we have something like 'enum foo xyz', a reference.
   2891   //
   2892   // This is needed to handle stuff like this right (C99 6.7.2.3p11):
   2893   // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
   2894   // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
   2895   //
   2896   Sema::TagUseKind TUK;
   2897   if (Tok.is(tok::l_brace))
   2898     TUK = Sema::TUK_Definition;
   2899   else if (Tok.is(tok::semi))
   2900     TUK = Sema::TUK_Declaration;
   2901   else
   2902     TUK = Sema::TUK_Reference;
   2903 
   2904   // enums cannot be templates, although they can be referenced from a
   2905   // template.
   2906   if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
   2907       TUK != Sema::TUK_Reference) {
   2908     Diag(Tok, diag::err_enum_template);
   2909 
   2910     // Skip the rest of this declarator, up until the comma or semicolon.
   2911     SkipUntil(tok::comma, true);
   2912     return;
   2913   }
   2914 
   2915   if (!Name && TUK != Sema::TUK_Definition) {
   2916     Diag(Tok, diag::err_enumerator_unnamed_no_def);
   2917 
   2918     // Skip the rest of this declarator, up until the comma or semicolon.
   2919     SkipUntil(tok::comma, true);
   2920     return;
   2921   }
   2922 
   2923   bool Owned = false;
   2924   bool IsDependent = false;
   2925   const char *PrevSpec = 0;
   2926   unsigned DiagID;
   2927   Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
   2928                                    StartLoc, SS, Name, NameLoc, attrs.getList(),
   2929                                    AS, DS.getModulePrivateSpecLoc(),
   2930                                    MultiTemplateParamsArg(Actions),
   2931                                    Owned, IsDependent, IsScopedEnum,
   2932                                    IsScopedUsingClassTag, BaseType);
   2933 
   2934   if (IsDependent) {
   2935     // This enum has a dependent nested-name-specifier. Handle it as a
   2936     // dependent tag.
   2937     if (!Name) {
   2938       DS.SetTypeSpecError();
   2939       Diag(Tok, diag::err_expected_type_name_after_typename);
   2940       return;
   2941     }
   2942 
   2943     TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
   2944                                                 TUK, SS, Name, StartLoc,
   2945                                                 NameLoc);
   2946     if (Type.isInvalid()) {
   2947       DS.SetTypeSpecError();
   2948       return;
   2949     }
   2950 
   2951     if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
   2952                            NameLoc.isValid() ? NameLoc : StartLoc,
   2953                            PrevSpec, DiagID, Type.get()))
   2954       Diag(StartLoc, DiagID) << PrevSpec;
   2955 
   2956     return;
   2957   }
   2958 
   2959   if (!TagDecl) {
   2960     // The action failed to produce an enumeration tag. If this is a
   2961     // definition, consume the entire definition.
   2962     if (Tok.is(tok::l_brace)) {
   2963       ConsumeBrace();
   2964       SkipUntil(tok::r_brace);
   2965     }
   2966 
   2967     DS.SetTypeSpecError();
   2968     return;
   2969   }
   2970 
   2971   if (Tok.is(tok::l_brace))
   2972     ParseEnumBody(StartLoc, TagDecl);
   2973 
   2974   if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
   2975                          NameLoc.isValid() ? NameLoc : StartLoc,
   2976                          PrevSpec, DiagID, TagDecl, Owned))
   2977     Diag(StartLoc, DiagID) << PrevSpec;
   2978 }
   2979 
   2980 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
   2981 ///       enumerator-list:
   2982 ///         enumerator
   2983 ///         enumerator-list ',' enumerator
   2984 ///       enumerator:
   2985 ///         enumeration-constant
   2986 ///         enumeration-constant '=' constant-expression
   2987 ///       enumeration-constant:
   2988 ///         identifier
   2989 ///
   2990 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
   2991   // Enter the scope of the enum body and start the definition.
   2992   ParseScope EnumScope(this, Scope::DeclScope);
   2993   Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
   2994 
   2995   BalancedDelimiterTracker T(*this, tok::l_brace);
   2996   T.consumeOpen();
   2997 
   2998   // C does not allow an empty enumerator-list, C++ does [dcl.enum].
   2999   if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
   3000     Diag(Tok, diag::error_empty_enum);
   3001 
   3002   SmallVector<Decl *, 32> EnumConstantDecls;
   3003 
   3004   Decl *LastEnumConstDecl = 0;
   3005 
   3006   // Parse the enumerator-list.
   3007   while (Tok.is(tok::identifier)) {
   3008     IdentifierInfo *Ident = Tok.getIdentifierInfo();
   3009     SourceLocation IdentLoc = ConsumeToken();
   3010 
   3011     // If attributes exist after the enumerator, parse them.
   3012     ParsedAttributes attrs(AttrFactory);
   3013     MaybeParseGNUAttributes(attrs);
   3014 
   3015     SourceLocation EqualLoc;
   3016     ExprResult AssignedVal;
   3017     if (Tok.is(tok::equal)) {
   3018       EqualLoc = ConsumeToken();
   3019       AssignedVal = ParseConstantExpression();
   3020       if (AssignedVal.isInvalid())
   3021         SkipUntil(tok::comma, tok::r_brace, true, true);
   3022     }
   3023 
   3024     // Install the enumerator constant into EnumDecl.
   3025     Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
   3026                                                     LastEnumConstDecl,
   3027                                                     IdentLoc, Ident,
   3028                                                     attrs.getList(), EqualLoc,
   3029                                                     AssignedVal.release());
   3030     EnumConstantDecls.push_back(EnumConstDecl);
   3031     LastEnumConstDecl = EnumConstDecl;
   3032 
   3033     if (Tok.is(tok::identifier)) {
   3034       // We're missing a comma between enumerators.
   3035       SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
   3036       Diag(Loc, diag::err_enumerator_list_missing_comma)
   3037         << FixItHint::CreateInsertion(Loc, ", ");
   3038       continue;
   3039     }
   3040 
   3041     if (Tok.isNot(tok::comma))
   3042       break;
   3043     SourceLocation CommaLoc = ConsumeToken();
   3044 
   3045     if (Tok.isNot(tok::identifier)) {
   3046       if (!getLang().C99 && !getLang().CPlusPlus0x)
   3047         Diag(CommaLoc, diag::ext_enumerator_list_comma)
   3048           << getLang().CPlusPlus
   3049           << FixItHint::CreateRemoval(CommaLoc);
   3050       else if (getLang().CPlusPlus0x)
   3051         Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
   3052           << FixItHint::CreateRemoval(CommaLoc);
   3053     }
   3054   }
   3055 
   3056   // Eat the }.
   3057   T.consumeClose();
   3058 
   3059   // If attributes exist after the identifier list, parse them.
   3060   ParsedAttributes attrs(AttrFactory);
   3061   MaybeParseGNUAttributes(attrs);
   3062 
   3063   Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
   3064                         EnumDecl, EnumConstantDecls.data(),
   3065                         EnumConstantDecls.size(), getCurScope(),
   3066                         attrs.getList());
   3067 
   3068   EnumScope.Exit();
   3069   Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
   3070                                    T.getCloseLocation());
   3071 }
   3072 
   3073 /// isTypeSpecifierQualifier - Return true if the current token could be the
   3074 /// start of a type-qualifier-list.
   3075 bool Parser::isTypeQualifier() const {
   3076   switch (Tok.getKind()) {
   3077   default: return false;
   3078 
   3079     // type-qualifier only in OpenCL
   3080   case tok::kw_private:
   3081     return getLang().OpenCL;
   3082 
   3083     // type-qualifier
   3084   case tok::kw_const:
   3085   case tok::kw_volatile:
   3086   case tok::kw_restrict:
   3087   case tok::kw___private:
   3088   case tok::kw___local:
   3089   case tok::kw___global:
   3090   case tok::kw___constant:
   3091   case tok::kw___read_only:
   3092   case tok::kw___read_write:
   3093   case tok::kw___write_only:
   3094     return true;
   3095   }
   3096 }
   3097 
   3098 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
   3099 /// is definitely a type-specifier.  Return false if it isn't part of a type
   3100 /// specifier or if we're not sure.
   3101 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
   3102   switch (Tok.getKind()) {
   3103   default: return false;
   3104     // type-specifiers
   3105   case tok::kw_short:
   3106   case tok::kw_long:
   3107   case tok::kw___int64:
   3108   case tok::kw_signed:
   3109   case tok::kw_unsigned:
   3110   case tok::kw__Complex:
   3111   case tok::kw__Imaginary:
   3112   case tok::kw_void:
   3113   case tok::kw_char:
   3114   case tok::kw_wchar_t:
   3115   case tok::kw_char16_t:
   3116   case tok::kw_char32_t:
   3117   case tok::kw_int:
   3118   case tok::kw_half:
   3119   case tok::kw_float:
   3120   case tok::kw_double:
   3121   case tok::kw_bool:
   3122   case tok::kw__Bool:
   3123   case tok::kw__Decimal32:
   3124   case tok::kw__Decimal64:
   3125   case tok::kw__Decimal128:
   3126   case tok::kw___vector:
   3127 
   3128     // struct-or-union-specifier (C99) or class-specifier (C++)
   3129   case tok::kw_class:
   3130   case tok::kw_struct:
   3131   case tok::kw_union:
   3132     // enum-specifier
   3133   case tok::kw_enum:
   3134 
   3135     // typedef-name
   3136   case tok::annot_typename:
   3137     return true;
   3138   }
   3139 }
   3140 
   3141 /// isTypeSpecifierQualifier - Return true if the current token could be the
   3142 /// start of a specifier-qualifier-list.
   3143 bool Parser::isTypeSpecifierQualifier() {
   3144   switch (Tok.getKind()) {
   3145   default: return false;
   3146 
   3147   case tok::identifier:   // foo::bar
   3148     if (TryAltiVecVectorToken())
   3149       return true;
   3150     // Fall through.
   3151   case tok::kw_typename:  // typename T::type
   3152     // Annotate typenames and C++ scope specifiers.  If we get one, just
   3153     // recurse to handle whatever we get.
   3154     if (TryAnnotateTypeOrScopeToken())
   3155       return true;
   3156     if (Tok.is(tok::identifier))
   3157       return false;
   3158     return isTypeSpecifierQualifier();
   3159 
   3160   case tok::coloncolon:   // ::foo::bar
   3161     if (NextToken().is(tok::kw_new) ||    // ::new
   3162         NextToken().is(tok::kw_delete))   // ::delete
   3163       return false;
   3164 
   3165     if (TryAnnotateTypeOrScopeToken())
   3166       return true;
   3167     return isTypeSpecifierQualifier();
   3168 
   3169     // GNU attributes support.
   3170   case tok::kw___attribute:
   3171     // GNU typeof support.
   3172   case tok::kw_typeof:
   3173 
   3174     // type-specifiers
   3175   case tok::kw_short:
   3176   case tok::kw_long:
   3177   case tok::kw___int64:
   3178   case tok::kw_signed:
   3179   case tok::kw_unsigned:
   3180   case tok::kw__Complex:
   3181   case tok::kw__Imaginary:
   3182   case tok::kw_void:
   3183   case tok::kw_char:
   3184   case tok::kw_wchar_t:
   3185   case tok::kw_char16_t:
   3186   case tok::kw_char32_t:
   3187   case tok::kw_int:
   3188   case tok::kw_half:
   3189   case tok::kw_float:
   3190   case tok::kw_double:
   3191   case tok::kw_bool:
   3192   case tok::kw__Bool:
   3193   case tok::kw__Decimal32:
   3194   case tok::kw__Decimal64:
   3195   case tok::kw__Decimal128:
   3196   case tok::kw___vector:
   3197 
   3198     // struct-or-union-specifier (C99) or class-specifier (C++)
   3199   case tok::kw_class:
   3200   case tok::kw_struct:
   3201   case tok::kw_union:
   3202     // enum-specifier
   3203   case tok::kw_enum:
   3204 
   3205     // type-qualifier
   3206   case tok::kw_const:
   3207   case tok::kw_volatile:
   3208   case tok::kw_restrict:
   3209 
   3210     // typedef-name
   3211   case tok::annot_typename:
   3212     return true;
   3213 
   3214     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
   3215   case tok::less:
   3216     return getLang().ObjC1;
   3217 
   3218   case tok::kw___cdecl:
   3219   case tok::kw___stdcall:
   3220   case tok::kw___fastcall:
   3221   case tok::kw___thiscall:
   3222   case tok::kw___w64:
   3223   case tok::kw___ptr64:
   3224   case tok::kw___ptr32:
   3225   case tok::kw___pascal:
   3226   case tok::kw___unaligned:
   3227 
   3228   case tok::kw___private:
   3229   case tok::kw___local:
   3230   case tok::kw___global:
   3231   case tok::kw___constant:
   3232   case tok::kw___read_only:
   3233   case tok::kw___read_write:
   3234   case tok::kw___write_only:
   3235 
   3236     return true;
   3237 
   3238   case tok::kw_private:
   3239     return getLang().OpenCL;
   3240 
   3241   // C1x _Atomic()
   3242   case tok::kw__Atomic:
   3243     return true;
   3244   }
   3245 }
   3246 
   3247 /// isDeclarationSpecifier() - Return true if the current token is part of a
   3248 /// declaration specifier.
   3249 ///
   3250 /// \param DisambiguatingWithExpression True to indicate that the purpose of
   3251 /// this check is to disambiguate between an expression and a declaration.
   3252 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
   3253   switch (Tok.getKind()) {
   3254   default: return false;
   3255 
   3256   case tok::kw_private:
   3257     return getLang().OpenCL;
   3258 
   3259   case tok::identifier:   // foo::bar
   3260     // Unfortunate hack to support "Class.factoryMethod" notation.
   3261     if (getLang().ObjC1 && NextToken().is(tok::period))
   3262       return false;
   3263     if (TryAltiVecVectorToken())
   3264       return true;
   3265     // Fall through.
   3266   case tok::kw_typename: // typename T::type
   3267     // Annotate typenames and C++ scope specifiers.  If we get one, just
   3268     // recurse to handle whatever we get.
   3269     if (TryAnnotateTypeOrScopeToken())
   3270       return true;
   3271     if (Tok.is(tok::identifier))
   3272       return false;
   3273 
   3274     // If we're in Objective-C and we have an Objective-C class type followed
   3275     // by an identifier and then either ':' or ']', in a place where an
   3276     // expression is permitted, then this is probably a class message send
   3277     // missing the initial '['. In this case, we won't consider this to be
   3278     // the start of a declaration.
   3279     if (DisambiguatingWithExpression &&
   3280         isStartOfObjCClassMessageMissingOpenBracket())
   3281       return false;
   3282 
   3283     return isDeclarationSpecifier();
   3284 
   3285   case tok::coloncolon:   // ::foo::bar
   3286     if (NextToken().is(tok::kw_new) ||    // ::new
   3287         NextToken().is(tok::kw_delete))   // ::delete
   3288       return false;
   3289 
   3290     // Annotate typenames and C++ scope specifiers.  If we get one, just
   3291     // recurse to handle whatever we get.
   3292     if (TryAnnotateTypeOrScopeToken())
   3293       return true;
   3294     return isDeclarationSpecifier();
   3295 
   3296     // storage-class-specifier
   3297   case tok::kw_typedef:
   3298   case tok::kw_extern:
   3299   case tok::kw___private_extern__:
   3300   case tok::kw_static:
   3301   case tok::kw_auto:
   3302   case tok::kw_register:
   3303   case tok::kw___thread:
   3304 
   3305     // Modules
   3306   case tok::kw___module_private__:
   3307 
   3308     // type-specifiers
   3309   case tok::kw_short:
   3310   case tok::kw_long:
   3311   case tok::kw___int64:
   3312   case tok::kw_signed:
   3313   case tok::kw_unsigned:
   3314   case tok::kw__Complex:
   3315   case tok::kw__Imaginary:
   3316   case tok::kw_void:
   3317   case tok::kw_char:
   3318   case tok::kw_wchar_t:
   3319   case tok::kw_char16_t:
   3320   case tok::kw_char32_t:
   3321 
   3322   case tok::kw_int:
   3323   case tok::kw_half:
   3324   case tok::kw_float:
   3325   case tok::kw_double:
   3326   case tok::kw_bool:
   3327   case tok::kw__Bool:
   3328   case tok::kw__Decimal32:
   3329   case tok::kw__Decimal64:
   3330   case tok::kw__Decimal128:
   3331   case tok::kw___vector:
   3332 
   3333     // struct-or-union-specifier (C99) or class-specifier (C++)
   3334   case tok::kw_class:
   3335   case tok::kw_struct:
   3336   case tok::kw_union:
   3337     // enum-specifier
   3338   case tok::kw_enum:
   3339 
   3340     // type-qualifier
   3341   case tok::kw_const:
   3342   case tok::kw_volatile:
   3343   case tok::kw_restrict:
   3344 
   3345     // function-specifier
   3346   case tok::kw_inline:
   3347   case tok::kw_virtual:
   3348   case tok::kw_explicit:
   3349 
   3350     // static_assert-declaration
   3351   case tok::kw__Static_assert:
   3352 
   3353     // GNU typeof support.
   3354   case tok::kw_typeof:
   3355 
   3356     // GNU attributes.
   3357   case tok::kw___attribute:
   3358     return true;
   3359 
   3360     // C++0x decltype.
   3361   case tok::kw_decltype:
   3362     return true;
   3363 
   3364     // C1x _Atomic()
   3365   case tok::kw__Atomic:
   3366     return true;
   3367 
   3368     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
   3369   case tok::less:
   3370     return getLang().ObjC1;
   3371 
   3372     // typedef-name
   3373   case tok::annot_typename:
   3374     return !DisambiguatingWithExpression ||
   3375            !isStartOfObjCClassMessageMissingOpenBracket();
   3376 
   3377   case tok::kw___declspec:
   3378   case tok::kw___cdecl:
   3379   case tok::kw___stdcall:
   3380   case tok::kw___fastcall:
   3381   case tok::kw___thiscall:
   3382   case tok::kw___w64:
   3383   case tok::kw___ptr64:
   3384   case tok::kw___ptr32:
   3385   case tok::kw___forceinline:
   3386   case tok::kw___pascal:
   3387   case tok::kw___unaligned:
   3388 
   3389   case tok::kw___private:
   3390   case tok::kw___local:
   3391   case tok::kw___global:
   3392   case tok::kw___constant:
   3393   case tok::kw___read_only:
   3394   case tok::kw___read_write:
   3395   case tok::kw___write_only:
   3396 
   3397     return true;
   3398   }
   3399 }
   3400 
   3401 bool Parser::isConstructorDeclarator() {
   3402   TentativeParsingAction TPA(*this);
   3403 
   3404   // Parse the C++ scope specifier.
   3405   CXXScopeSpec SS;
   3406   if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) {
   3407     TPA.Revert();
   3408     return false;
   3409   }
   3410 
   3411   // Parse the constructor name.
   3412   if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
   3413     // We already know that we have a constructor name; just consume
   3414     // the token.
   3415     ConsumeToken();
   3416   } else {
   3417     TPA.Revert();
   3418     return false;
   3419   }
   3420 
   3421   // Current class name must be followed by a left parentheses.
   3422   if (Tok.isNot(tok::l_paren)) {
   3423     TPA.Revert();
   3424     return false;
   3425   }
   3426   ConsumeParen();
   3427 
   3428   // A right parentheses or ellipsis signals that we have a constructor.
   3429   if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
   3430     TPA.Revert();
   3431     return true;
   3432   }
   3433 
   3434   // If we need to, enter the specified scope.
   3435   DeclaratorScopeObj DeclScopeObj(*this, SS);
   3436   if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
   3437     DeclScopeObj.EnterDeclaratorScope();
   3438 
   3439   // Optionally skip Microsoft attributes.
   3440   ParsedAttributes Attrs(AttrFactory);
   3441   MaybeParseMicrosoftAttributes(Attrs);
   3442 
   3443   // Check whether the next token(s) are part of a declaration
   3444   // specifier, in which case we have the start of a parameter and,
   3445   // therefore, we know that this is a constructor.
   3446   bool IsConstructor = isDeclarationSpecifier();
   3447   TPA.Revert();
   3448   return IsConstructor;
   3449 }
   3450 
   3451 /// ParseTypeQualifierListOpt
   3452 ///          type-qualifier-list: [C99 6.7.5]
   3453 ///            type-qualifier
   3454 /// [vendor]   attributes
   3455 ///              [ only if VendorAttributesAllowed=true ]
   3456 ///            type-qualifier-list type-qualifier
   3457 /// [vendor]   type-qualifier-list attributes
   3458 ///              [ only if VendorAttributesAllowed=true ]
   3459 /// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
   3460 ///              [ only if CXX0XAttributesAllowed=true ]
   3461 /// Note: vendor can be GNU, MS, etc.
   3462 ///
   3463 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
   3464                                        bool VendorAttributesAllowed,
   3465                                        bool CXX0XAttributesAllowed) {
   3466   if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
   3467     SourceLocation Loc = Tok.getLocation();
   3468     ParsedAttributesWithRange attrs(AttrFactory);
   3469     ParseCXX0XAttributes(attrs);
   3470     if (CXX0XAttributesAllowed)
   3471       DS.takeAttributesFrom(attrs);
   3472     else
   3473       Diag(Loc, diag::err_attributes_not_allowed);
   3474   }
   3475 
   3476   SourceLocation EndLoc;
   3477 
   3478   while (1) {
   3479     bool isInvalid = false;
   3480     const char *PrevSpec = 0;
   3481     unsigned DiagID = 0;
   3482     SourceLocation Loc = Tok.getLocation();
   3483 
   3484     switch (Tok.getKind()) {
   3485     case tok::code_completion:
   3486       Actions.CodeCompleteTypeQualifiers(DS);
   3487       return cutOffParsing();
   3488 
   3489     case tok::kw_const:
   3490       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
   3491                                  getLang());
   3492       break;
   3493     case tok::kw_volatile:
   3494       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
   3495                                  getLang());
   3496       break;
   3497     case tok::kw_restrict:
   3498       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
   3499                                  getLang());
   3500       break;
   3501 
   3502     // OpenCL qualifiers:
   3503     case tok::kw_private:
   3504       if (!getLang().OpenCL)
   3505         goto DoneWithTypeQuals;
   3506     case tok::kw___private:
   3507     case tok::kw___global:
   3508     case tok::kw___local:
   3509     case tok::kw___constant:
   3510     case tok::kw___read_only:
   3511     case tok::kw___write_only:
   3512     case tok::kw___read_write:
   3513       ParseOpenCLQualifiers(DS);
   3514       break;
   3515 
   3516     case tok::kw___w64:
   3517     case tok::kw___ptr64:
   3518     case tok::kw___ptr32:
   3519     case tok::kw___cdecl:
   3520     case tok::kw___stdcall:
   3521     case tok::kw___fastcall:
   3522     case tok::kw___thiscall:
   3523     case tok::kw___unaligned:
   3524       if (VendorAttributesAllowed) {
   3525         ParseMicrosoftTypeAttributes(DS.getAttributes());
   3526         continue;
   3527       }
   3528       goto DoneWithTypeQuals;
   3529     case tok::kw___pascal:
   3530       if (VendorAttributesAllowed) {
   3531         ParseBorlandTypeAttributes(DS.getAttributes());
   3532         continue;
   3533       }
   3534       goto DoneWithTypeQuals;
   3535     case tok::kw___attribute:
   3536       if (VendorAttributesAllowed) {
   3537         ParseGNUAttributes(DS.getAttributes());
   3538         continue; // do *not* consume the next token!
   3539       }
   3540       // otherwise, FALL THROUGH!
   3541     default:
   3542       DoneWithTypeQuals:
   3543       // If this is not a type-qualifier token, we're done reading type
   3544       // qualifiers.  First verify that DeclSpec's are consistent.
   3545       DS.Finish(Diags, PP);
   3546       if (EndLoc.isValid())
   3547         DS.SetRangeEnd(EndLoc);
   3548       return;
   3549     }
   3550 
   3551     // If the specifier combination wasn't legal, issue a diagnostic.
   3552     if (isInvalid) {
   3553       assert(PrevSpec && "Method did not return previous specifier!");
   3554       Diag(Tok, DiagID) << PrevSpec;
   3555     }
   3556     EndLoc = ConsumeToken();
   3557   }
   3558 }
   3559 
   3560 
   3561 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
   3562 ///
   3563 void Parser::ParseDeclarator(Declarator &D) {
   3564   /// This implements the 'declarator' production in the C grammar, then checks
   3565   /// for well-formedness and issues diagnostics.
   3566   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
   3567 }
   3568 
   3569 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
   3570 /// is parsed by the function passed to it. Pass null, and the direct-declarator
   3571 /// isn't parsed at all, making this function effectively parse the C++
   3572 /// ptr-operator production.
   3573 ///
   3574 ///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
   3575 /// [C]     pointer[opt] direct-declarator
   3576 /// [C++]   direct-declarator
   3577 /// [C++]   ptr-operator declarator
   3578 ///
   3579 ///       pointer: [C99 6.7.5]
   3580 ///         '*' type-qualifier-list[opt]
   3581 ///         '*' type-qualifier-list[opt] pointer
   3582 ///
   3583 ///       ptr-operator:
   3584 ///         '*' cv-qualifier-seq[opt]
   3585 ///         '&'
   3586 /// [C++0x] '&&'
   3587 /// [GNU]   '&' restrict[opt] attributes[opt]
   3588 /// [GNU?]  '&&' restrict[opt] attributes[opt]
   3589 ///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
   3590 void Parser::ParseDeclaratorInternal(Declarator &D,
   3591                                      DirectDeclParseFunction DirectDeclParser) {
   3592   if (Diags.hasAllExtensionsSilenced())
   3593     D.setExtension();
   3594 
   3595   // C++ member pointers start with a '::' or a nested-name.
   3596   // Member pointers get special handling, since there's no place for the
   3597   // scope spec in the generic path below.
   3598   if (getLang().CPlusPlus &&
   3599       (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
   3600        Tok.is(tok::annot_cxxscope))) {
   3601     CXXScopeSpec SS;
   3602     ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail
   3603 
   3604     if (SS.isNotEmpty()) {
   3605       if (Tok.isNot(tok::star)) {
   3606         // The scope spec really belongs to the direct-declarator.
   3607         D.getCXXScopeSpec() = SS;
   3608         if (DirectDeclParser)
   3609           (this->*DirectDeclParser)(D);
   3610         return;
   3611       }
   3612 
   3613       SourceLocation Loc = ConsumeToken();
   3614       D.SetRangeEnd(Loc);
   3615       DeclSpec DS(AttrFactory);
   3616       ParseTypeQualifierListOpt(DS);
   3617       D.ExtendWithDeclSpec(DS);
   3618 
   3619       // Recurse to parse whatever is left.
   3620       ParseDeclaratorInternal(D, DirectDeclParser);
   3621 
   3622       // Sema will have to catch (syntactically invalid) pointers into global
   3623       // scope. It has to catch pointers into namespace scope anyway.
   3624       D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
   3625                                                       Loc),
   3626                     DS.getAttributes(),
   3627                     /* Don't replace range end. */SourceLocation());
   3628       return;
   3629     }
   3630   }
   3631 
   3632   tok::TokenKind Kind = Tok.getKind();
   3633   // Not a pointer, C++ reference, or block.
   3634   if (Kind != tok::star && Kind != tok::caret &&
   3635       (Kind != tok::amp || !getLang().CPlusPlus) &&
   3636       // We parse rvalue refs in C++03, because otherwise the errors are scary.
   3637       (Kind != tok::ampamp || !getLang().CPlusPlus)) {
   3638     if (DirectDeclParser)
   3639       (this->*DirectDeclParser)(D);
   3640     return;
   3641   }
   3642 
   3643   // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
   3644   // '&&' -> rvalue reference
   3645   SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
   3646   D.SetRangeEnd(Loc);
   3647 
   3648   if (Kind == tok::star || Kind == tok::caret) {
   3649     // Is a pointer.
   3650     DeclSpec DS(AttrFactory);
   3651 
   3652     ParseTypeQualifierListOpt(DS);
   3653     D.ExtendWithDeclSpec(DS);
   3654 
   3655     // Recursively parse the declarator.
   3656     ParseDeclaratorInternal(D, DirectDeclParser);
   3657     if (Kind == tok::star)
   3658       // Remember that we parsed a pointer type, and remember the type-quals.
   3659       D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
   3660                                                 DS.getConstSpecLoc(),
   3661                                                 DS.getVolatileSpecLoc(),
   3662                                                 DS.getRestrictSpecLoc()),
   3663                     DS.getAttributes(),
   3664                     SourceLocation());
   3665     else
   3666       // Remember that we parsed a Block type, and remember the type-quals.
   3667       D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
   3668                                                      Loc),
   3669                     DS.getAttributes(),
   3670                     SourceLocation());
   3671   } else {
   3672     // Is a reference
   3673     DeclSpec DS(AttrFactory);
   3674 
   3675     // Complain about rvalue references in C++03, but then go on and build
   3676     // the declarator.
   3677     if (Kind == tok::ampamp)
   3678       Diag(Loc, getLang().CPlusPlus0x ?
   3679            diag::warn_cxx98_compat_rvalue_reference :
   3680            diag::ext_rvalue_reference);
   3681 
   3682     // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
   3683     // cv-qualifiers are introduced through the use of a typedef or of a
   3684     // template type argument, in which case the cv-qualifiers are ignored.
   3685     //
   3686     // [GNU] Retricted references are allowed.
   3687     // [GNU] Attributes on references are allowed.
   3688     // [C++0x] Attributes on references are not allowed.
   3689     ParseTypeQualifierListOpt(DS, true, false);
   3690     D.ExtendWithDeclSpec(DS);
   3691 
   3692     if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
   3693       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
   3694         Diag(DS.getConstSpecLoc(),
   3695              diag::err_invalid_reference_qualifier_application) << "const";
   3696       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
   3697         Diag(DS.getVolatileSpecLoc(),
   3698              diag::err_invalid_reference_qualifier_application) << "volatile";
   3699     }
   3700 
   3701     // Recursively parse the declarator.
   3702     ParseDeclaratorInternal(D, DirectDeclParser);
   3703 
   3704     if (D.getNumTypeObjects() > 0) {
   3705       // C++ [dcl.ref]p4: There shall be no references to references.
   3706       DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
   3707       if (InnerChunk.Kind == DeclaratorChunk::Reference) {
   3708         if (const IdentifierInfo *II = D.getIdentifier())
   3709           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
   3710            << II;
   3711         else
   3712           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
   3713             << "type name";
   3714 
   3715         // Once we've complained about the reference-to-reference, we
   3716         // can go ahead and build the (technically ill-formed)
   3717         // declarator: reference collapsing will take care of it.
   3718       }
   3719     }
   3720 
   3721     // Remember that we parsed a reference type. It doesn't have type-quals.
   3722     D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
   3723                                                 Kind == tok::amp),
   3724                   DS.getAttributes(),
   3725                   SourceLocation());
   3726   }
   3727 }
   3728 
   3729 /// ParseDirectDeclarator
   3730 ///       direct-declarator: [C99 6.7.5]
   3731 /// [C99]   identifier
   3732 ///         '(' declarator ')'
   3733 /// [GNU]   '(' attributes declarator ')'
   3734 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
   3735 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
   3736 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
   3737 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
   3738 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
   3739 ///         direct-declarator '(' parameter-type-list ')'
   3740 ///         direct-declarator '(' identifier-list[opt] ')'
   3741 /// [GNU]   direct-declarator '(' parameter-forward-declarations
   3742 ///                    parameter-type-list[opt] ')'
   3743 /// [C++]   direct-declarator '(' parameter-declaration-clause ')'
   3744 ///                    cv-qualifier-seq[opt] exception-specification[opt]
   3745 /// [C++]   declarator-id
   3746 ///
   3747 ///       declarator-id: [C++ 8]
   3748 ///         '...'[opt] id-expression
   3749 ///         '::'[opt] nested-name-specifier[opt] type-name
   3750 ///
   3751 ///       id-expression: [C++ 5.1]
   3752 ///         unqualified-id
   3753 ///         qualified-id
   3754 ///
   3755 ///       unqualified-id: [C++ 5.1]
   3756 ///         identifier
   3757 ///         operator-function-id
   3758 ///         conversion-function-id
   3759 ///          '~' class-name
   3760 ///         template-id
   3761 ///
   3762 void Parser::ParseDirectDeclarator(Declarator &D) {
   3763   DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
   3764 
   3765   if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
   3766     // ParseDeclaratorInternal might already have parsed the scope.
   3767     if (D.getCXXScopeSpec().isEmpty()) {
   3768       ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true);
   3769     }
   3770 
   3771     if (D.getCXXScopeSpec().isValid()) {
   3772       if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
   3773         // Change the declaration context for name lookup, until this function
   3774         // is exited (and the declarator has been parsed).
   3775         DeclScopeObj.EnterDeclaratorScope();
   3776     }
   3777 
   3778     // C++0x [dcl.fct]p14:
   3779     //   There is a syntactic ambiguity when an ellipsis occurs at the end
   3780     //   of a parameter-declaration-clause without a preceding comma. In
   3781     //   this case, the ellipsis is parsed as part of the
   3782     //   abstract-declarator if the type of the parameter names a template
   3783     //   parameter pack that has not been expanded; otherwise, it is parsed
   3784     //   as part of the parameter-declaration-clause.
   3785     if (Tok.is(tok::ellipsis) &&
   3786         !((D.getContext() == Declarator::PrototypeContext ||
   3787            D.getContext() == Declarator::BlockLiteralContext) &&
   3788           NextToken().is(tok::r_paren) &&
   3789           !Actions.containsUnexpandedParameterPacks(D)))
   3790       D.setEllipsisLoc(ConsumeToken());
   3791 
   3792     if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
   3793         Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
   3794       // We found something that indicates the start of an unqualified-id.
   3795       // Parse that unqualified-id.
   3796       bool AllowConstructorName;
   3797       if (D.getDeclSpec().hasTypeSpecifier())
   3798         AllowConstructorName = false;
   3799       else if (D.getCXXScopeSpec().isSet())
   3800         AllowConstructorName =
   3801           (D.getContext() == Declarator::FileContext ||
   3802            (D.getContext() == Declarator::MemberContext &&
   3803             D.getDeclSpec().isFriendSpecified()));
   3804       else
   3805         AllowConstructorName = (D.getContext() == Declarator::MemberContext);
   3806 
   3807       if (ParseUnqualifiedId(D.getCXXScopeSpec(),
   3808                              /*EnteringContext=*/true,
   3809                              /*AllowDestructorName=*/true,
   3810                              AllowConstructorName,
   3811                              ParsedType(),
   3812                              D.getName()) ||
   3813           // Once we're past the identifier, if the scope was bad, mark the
   3814           // whole declarator bad.
   3815           D.getCXXScopeSpec().isInvalid()) {
   3816         D.SetIdentifier(0, Tok.getLocation());
   3817         D.setInvalidType(true);
   3818       } else {
   3819         // Parsed the unqualified-id; update range information and move along.
   3820         if (D.getSourceRange().getBegin().isInvalid())
   3821           D.SetRangeBegin(D.getName().getSourceRange().getBegin());
   3822         D.SetRangeEnd(D.getName().getSourceRange().getEnd());
   3823       }
   3824       goto PastIdentifier;
   3825     }
   3826   } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
   3827     assert(!getLang().CPlusPlus &&
   3828            "There's a C++-specific check for tok::identifier above");
   3829     assert(Tok.getIdentifierInfo() && "Not an identifier?");
   3830     D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
   3831     ConsumeToken();
   3832     goto PastIdentifier;
   3833   }
   3834 
   3835   if (Tok.is(tok::l_paren)) {
   3836     // direct-declarator: '(' declarator ')'
   3837     // direct-declarator: '(' attributes declarator ')'
   3838     // Example: 'char (*X)'   or 'int (*XX)(void)'
   3839     ParseParenDeclarator(D);
   3840 
   3841     // If the declarator was parenthesized, we entered the declarator
   3842     // scope when parsing the parenthesized declarator, then exited
   3843     // the scope already. Re-enter the scope, if we need to.
   3844     if (D.getCXXScopeSpec().isSet()) {
   3845       // If there was an error parsing parenthesized declarator, declarator
   3846       // scope may have been enterred before. Don't do it again.
   3847       if (!D.isInvalidType() &&
   3848           Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
   3849         // Change the declaration context for name lookup, until this function
   3850         // is exited (and the declarator has been parsed).
   3851         DeclScopeObj.EnterDeclaratorScope();
   3852     }
   3853   } else if (D.mayOmitIdentifier()) {
   3854     // This could be something simple like "int" (in which case the declarator
   3855     // portion is empty), if an abstract-declarator is allowed.
   3856     D.SetIdentifier(0, Tok.getLocation());
   3857   } else {
   3858     if (D.getContext() == Declarator::MemberContext)
   3859       Diag(Tok, diag::err_expected_member_name_or_semi)
   3860         << D.getDeclSpec().getSourceRange();
   3861     else if (getLang().CPlusPlus)
   3862       Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
   3863     else
   3864       Diag(Tok, diag::err_expected_ident_lparen);
   3865     D.SetIdentifier(0, Tok.getLocation());
   3866     D.setInvalidType(true);
   3867   }
   3868 
   3869  PastIdentifier:
   3870   assert(D.isPastIdentifier() &&
   3871          "Haven't past the location of the identifier yet?");
   3872 
   3873   // Don't parse attributes unless we have an identifier.
   3874   if (D.getIdentifier())
   3875     MaybeParseCXX0XAttributes(D);
   3876 
   3877   while (1) {
   3878     if (Tok.is(tok::l_paren)) {
   3879       // The paren may be part of a C++ direct initializer, eg. "int x(1);".
   3880       // In such a case, check if we actually have a function declarator; if it
   3881       // is not, the declarator has been fully parsed.
   3882       if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
   3883         // When not in file scope, warn for ambiguous function declarators, just
   3884         // in case the author intended it as a variable definition.
   3885         bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
   3886         if (!isCXXFunctionDeclarator(warnIfAmbiguous))
   3887           break;
   3888       }
   3889       ParsedAttributes attrs(AttrFactory);
   3890       BalancedDelimiterTracker T(*this, tok::l_paren);
   3891       T.consumeOpen();
   3892       ParseFunctionDeclarator(D, attrs, T);
   3893     } else if (Tok.is(tok::l_square)) {
   3894       ParseBracketDeclarator(D);
   3895     } else {
   3896       break;
   3897     }
   3898   }
   3899 }
   3900 
   3901 /// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
   3902 /// only called before the identifier, so these are most likely just grouping
   3903 /// parens for precedence.  If we find that these are actually function
   3904 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
   3905 ///
   3906 ///       direct-declarator:
   3907 ///         '(' declarator ')'
   3908 /// [GNU]   '(' attributes declarator ')'
   3909 ///         direct-declarator '(' parameter-type-list ')'
   3910 ///         direct-declarator '(' identifier-list[opt] ')'
   3911 /// [GNU]   direct-declarator '(' parameter-forward-declarations
   3912 ///                    parameter-type-list[opt] ')'
   3913 ///
   3914 void Parser::ParseParenDeclarator(Declarator &D) {
   3915   BalancedDelimiterTracker T(*this, tok::l_paren);
   3916   T.consumeOpen();
   3917 
   3918   assert(!D.isPastIdentifier() && "Should be called before passing identifier");
   3919 
   3920   // Eat any attributes before we look at whether this is a grouping or function
   3921   // declarator paren.  If this is a grouping paren, the attribute applies to
   3922   // the type being built up, for example:
   3923   //     int (__attribute__(()) *x)(long y)
   3924   // If this ends up not being a grouping paren, the attribute applies to the
   3925   // first argument, for example:
   3926   //     int (__attribute__(()) int x)
   3927   // In either case, we need to eat any attributes to be able to determine what
   3928   // sort of paren this is.
   3929   //
   3930   ParsedAttributes attrs(AttrFactory);
   3931   bool RequiresArg = false;
   3932   if (Tok.is(tok::kw___attribute)) {
   3933     ParseGNUAttributes(attrs);
   3934 
   3935     // We require that the argument list (if this is a non-grouping paren) be
   3936     // present even if the attribute list was empty.
   3937     RequiresArg = true;
   3938   }
   3939   // Eat any Microsoft extensions.
   3940   if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
   3941        Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
   3942        Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) ||
   3943        Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
   3944     ParseMicrosoftTypeAttributes(attrs);
   3945   }
   3946   // Eat any Borland extensions.
   3947   if  (Tok.is(tok::kw___pascal))
   3948     ParseBorlandTypeAttributes(attrs);
   3949 
   3950   // If we haven't past the identifier yet (or where the identifier would be
   3951   // stored, if this is an abstract declarator), then this is probably just
   3952   // grouping parens. However, if this could be an abstract-declarator, then
   3953   // this could also be the start of function arguments (consider 'void()').
   3954   bool isGrouping;
   3955 
   3956   if (!D.mayOmitIdentifier()) {
   3957     // If this can't be an abstract-declarator, this *must* be a grouping
   3958     // paren, because we haven't seen the identifier yet.
   3959     isGrouping = true;
   3960   } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
   3961              (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
   3962              isDeclarationSpecifier()) {       // 'int(int)' is a function.
   3963     // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
   3964     // considered to be a type, not a K&R identifier-list.
   3965     isGrouping = false;
   3966   } else {
   3967     // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
   3968     isGrouping = true;
   3969   }
   3970 
   3971   // If this is a grouping paren, handle:
   3972   // direct-declarator: '(' declarator ')'
   3973   // direct-declarator: '(' attributes declarator ')'
   3974   if (isGrouping) {
   3975     bool hadGroupingParens = D.hasGroupingParens();
   3976     D.setGroupingParens(true);
   3977 
   3978     ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
   3979     // Match the ')'.
   3980     T.consumeClose();
   3981     D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
   3982                                             T.getCloseLocation()),
   3983                   attrs, T.getCloseLocation());
   3984 
   3985     D.setGroupingParens(hadGroupingParens);
   3986     return;
   3987   }
   3988 
   3989   // Okay, if this wasn't a grouping paren, it must be the start of a function
   3990   // argument list.  Recognize that this declarator will never have an
   3991   // identifier (and remember where it would have been), then call into
   3992   // ParseFunctionDeclarator to handle of argument list.
   3993   D.SetIdentifier(0, Tok.getLocation());
   3994 
   3995   ParseFunctionDeclarator(D, attrs, T, RequiresArg);
   3996 }
   3997 
   3998 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
   3999 /// declarator D up to a paren, which indicates that we are parsing function
   4000 /// arguments.
   4001 ///
   4002 /// If attrs is non-null, then the caller parsed those arguments immediately
   4003 /// after the open paren - they should be considered to be the first argument of
   4004 /// a parameter.  If RequiresArg is true, then the first argument of the
   4005 /// function is required to be present and required to not be an identifier
   4006 /// list.
   4007 ///
   4008 /// For C++, after the parameter-list, it also parses cv-qualifier-seq[opt],
   4009 /// (C++0x) ref-qualifier[opt], exception-specification[opt], and
   4010 /// (C++0x) trailing-return-type[opt].
   4011 ///
   4012 /// [C++0x] exception-specification:
   4013 ///           dynamic-exception-specification
   4014 ///           noexcept-specification
   4015 ///
   4016 void Parser::ParseFunctionDeclarator(Declarator &D,
   4017                                      ParsedAttributes &attrs,
   4018                                      BalancedDelimiterTracker &Tracker,
   4019                                      bool RequiresArg) {
   4020   // lparen is already consumed!
   4021   assert(D.isPastIdentifier() && "Should not call before identifier!");
   4022 
   4023   // This should be true when the function has typed arguments.
   4024   // Otherwise, it is treated as a K&R-style function.
   4025   bool HasProto = false;
   4026   // Build up an array of information about the parsed arguments.
   4027   SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
   4028   // Remember where we see an ellipsis, if any.
   4029   SourceLocation EllipsisLoc;
   4030 
   4031   DeclSpec DS(AttrFactory);
   4032   bool RefQualifierIsLValueRef = true;
   4033   SourceLocation RefQualifierLoc;
   4034   SourceLocation ConstQualifierLoc;
   4035   SourceLocation VolatileQualifierLoc;
   4036   ExceptionSpecificationType ESpecType = EST_None;
   4037   SourceRange ESpecRange;
   4038   SmallVector<ParsedType, 2> DynamicExceptions;
   4039   SmallVector<SourceRange, 2> DynamicExceptionRanges;
   4040   ExprResult NoexceptExpr;
   4041   ParsedType TrailingReturnType;
   4042 
   4043   SourceLocation EndLoc;
   4044   if (isFunctionDeclaratorIdentifierList()) {
   4045     if (RequiresArg)
   4046       Diag(Tok, diag::err_argument_required_after_attribute);
   4047 
   4048     ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
   4049 
   4050     Tracker.consumeClose();
   4051     EndLoc = Tracker.getCloseLocation();
   4052   } else {
   4053     // Enter function-declaration scope, limiting any declarators to the
   4054     // function prototype scope, including parameter declarators.
   4055     ParseScope PrototypeScope(this,
   4056                               Scope::FunctionPrototypeScope|Scope::DeclScope);
   4057 
   4058     if (Tok.isNot(tok::r_paren))
   4059       ParseParameterDeclarationClause(D, attrs, ParamInfo, EllipsisLoc);
   4060     else if (RequiresArg)
   4061       Diag(Tok, diag::err_argument_required_after_attribute);
   4062 
   4063     HasProto = ParamInfo.size() || getLang().CPlusPlus;
   4064 
   4065     // If we have the closing ')', eat it.
   4066     Tracker.consumeClose();
   4067     EndLoc = Tracker.getCloseLocation();
   4068 
   4069     if (getLang().CPlusPlus) {
   4070       MaybeParseCXX0XAttributes(attrs);
   4071 
   4072       // Parse cv-qualifier-seq[opt].
   4073       ParseTypeQualifierListOpt(DS, false /*no attributes*/);
   4074         if (!DS.getSourceRange().getEnd().isInvalid()) {
   4075           EndLoc = DS.getSourceRange().getEnd();
   4076           ConstQualifierLoc = DS.getConstSpecLoc();
   4077           VolatileQualifierLoc = DS.getVolatileSpecLoc();
   4078         }
   4079 
   4080       // Parse ref-qualifier[opt].
   4081       if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
   4082         Diag(Tok, getLang().CPlusPlus0x ?
   4083              diag::warn_cxx98_compat_ref_qualifier :
   4084              diag::ext_ref_qualifier);
   4085 
   4086         RefQualifierIsLValueRef = Tok.is(tok::amp);
   4087         RefQualifierLoc = ConsumeToken();
   4088         EndLoc = RefQualifierLoc;
   4089       }
   4090 
   4091       // Parse exception-specification[opt].
   4092       ESpecType = MaybeParseExceptionSpecification(ESpecRange,
   4093                                                    DynamicExceptions,
   4094                                                    DynamicExceptionRanges,
   4095                                                    NoexceptExpr);
   4096       if (ESpecType != EST_None)
   4097         EndLoc = ESpecRange.getEnd();
   4098 
   4099       // Parse trailing-return-type[opt].
   4100       if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
   4101         Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
   4102         SourceRange Range;
   4103         TrailingReturnType = ParseTrailingReturnType(Range).get();
   4104         if (Range.getEnd().isValid())
   4105           EndLoc = Range.getEnd();
   4106       }
   4107     }
   4108 
   4109     // Leave prototype scope.
   4110     PrototypeScope.Exit();
   4111   }
   4112 
   4113   // Remember that we parsed a function type, and remember the attributes.
   4114   D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
   4115                                              /*isVariadic=*/EllipsisLoc.isValid(),
   4116                                              EllipsisLoc,
   4117                                              ParamInfo.data(), ParamInfo.size(),
   4118                                              DS.getTypeQualifiers(),
   4119                                              RefQualifierIsLValueRef,
   4120                                              RefQualifierLoc, ConstQualifierLoc,
   4121                                              VolatileQualifierLoc,
   4122                                              /*MutableLoc=*/SourceLocation(),
   4123                                              ESpecType, ESpecRange.getBegin(),
   4124                                              DynamicExceptions.data(),
   4125                                              DynamicExceptionRanges.data(),
   4126                                              DynamicExceptions.size(),
   4127                                              NoexceptExpr.isUsable() ?
   4128                                                NoexceptExpr.get() : 0,
   4129                                              Tracker.getOpenLocation(),
   4130                                              EndLoc, D,
   4131                                              TrailingReturnType),
   4132                 attrs, EndLoc);
   4133 }
   4134 
   4135 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
   4136 /// identifier list form for a K&R-style function:  void foo(a,b,c)
   4137 ///
   4138 /// Note that identifier-lists are only allowed for normal declarators, not for
   4139 /// abstract-declarators.
   4140 bool Parser::isFunctionDeclaratorIdentifierList() {
   4141   return !getLang().CPlusPlus
   4142          && Tok.is(tok::identifier)
   4143          && !TryAltiVecVectorToken()
   4144          // K&R identifier lists can't have typedefs as identifiers, per C99
   4145          // 6.7.5.3p11.
   4146          && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
   4147          // Identifier lists follow a really simple grammar: the identifiers can
   4148          // be followed *only* by a ", identifier" or ")".  However, K&R
   4149          // identifier lists are really rare in the brave new modern world, and
   4150          // it is very common for someone to typo a type in a non-K&R style
   4151          // list.  If we are presented with something like: "void foo(intptr x,
   4152          // float y)", we don't want to start parsing the function declarator as
   4153          // though it is a K&R style declarator just because intptr is an
   4154          // invalid type.
   4155          //
   4156          // To handle this, we check to see if the token after the first
   4157          // identifier is a "," or ")".  Only then do we parse it as an
   4158          // identifier list.
   4159          && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
   4160 }
   4161 
   4162 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
   4163 /// we found a K&R-style identifier list instead of a typed parameter list.
   4164 ///
   4165 /// After returning, ParamInfo will hold the parsed parameters.
   4166 ///
   4167 ///       identifier-list: [C99 6.7.5]
   4168 ///         identifier
   4169 ///         identifier-list ',' identifier
   4170 ///
   4171 void Parser::ParseFunctionDeclaratorIdentifierList(
   4172        Declarator &D,
   4173        SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
   4174   // If there was no identifier specified for the declarator, either we are in
   4175   // an abstract-declarator, or we are in a parameter declarator which was found
   4176   // to be abstract.  In abstract-declarators, identifier lists are not valid:
   4177   // diagnose this.
   4178   if (!D.getIdentifier())
   4179     Diag(Tok, diag::ext_ident_list_in_param);
   4180 
   4181   // Maintain an efficient lookup of params we have seen so far.
   4182   llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
   4183 
   4184   while (1) {
   4185     // If this isn't an identifier, report the error and skip until ')'.
   4186     if (Tok.isNot(tok::identifier)) {
   4187       Diag(Tok, diag::err_expected_ident);
   4188       SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
   4189       // Forget we parsed anything.
   4190       ParamInfo.clear();
   4191       return;
   4192     }
   4193 
   4194     IdentifierInfo *ParmII = Tok.getIdentifierInfo();
   4195 
   4196     // Reject 'typedef int y; int test(x, y)', but continue parsing.
   4197     if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
   4198       Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
   4199 
   4200     // Verify that the argument identifier has not already been mentioned.
   4201     if (!ParamsSoFar.insert(ParmII)) {
   4202       Diag(Tok, diag::err_param_redefinition) << ParmII;
   4203     } else {
   4204       // Remember this identifier in ParamInfo.
   4205       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
   4206                                                      Tok.getLocation(),
   4207                                                      0));
   4208     }
   4209 
   4210     // Eat the identifier.
   4211     ConsumeToken();
   4212 
   4213     // The list continues if we see a comma.
   4214     if (Tok.isNot(tok::comma))
   4215       break;
   4216     ConsumeToken();
   4217   }
   4218 }
   4219 
   4220 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
   4221 /// after the opening parenthesis. This function will not parse a K&R-style
   4222 /// identifier list.
   4223 ///
   4224 /// D is the declarator being parsed.  If attrs is non-null, then the caller
   4225 /// parsed those arguments immediately after the open paren - they should be
   4226 /// considered to be the first argument of a parameter.
   4227 ///
   4228 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
   4229 /// be the location of the ellipsis, if any was parsed.
   4230 ///
   4231 ///       parameter-type-list: [C99 6.7.5]
   4232 ///         parameter-list
   4233 ///         parameter-list ',' '...'
   4234 /// [C++]   parameter-list '...'
   4235 ///
   4236 ///       parameter-list: [C99 6.7.5]
   4237 ///         parameter-declaration
   4238 ///         parameter-list ',' parameter-declaration
   4239 ///
   4240 ///       parameter-declaration: [C99 6.7.5]
   4241 ///         declaration-specifiers declarator
   4242 /// [C++]   declaration-specifiers declarator '=' assignment-expression
   4243 /// [GNU]   declaration-specifiers declarator attributes
   4244 ///         declaration-specifiers abstract-declarator[opt]
   4245 /// [C++]   declaration-specifiers abstract-declarator[opt]
   4246 ///           '=' assignment-expression
   4247 /// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
   4248 ///
   4249 void Parser::ParseParameterDeclarationClause(
   4250        Declarator &D,
   4251        ParsedAttributes &attrs,
   4252        SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
   4253        SourceLocation &EllipsisLoc) {
   4254 
   4255   while (1) {
   4256     if (Tok.is(tok::ellipsis)) {
   4257       EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
   4258       break;
   4259     }
   4260 
   4261     // Parse the declaration-specifiers.
   4262     // Just use the ParsingDeclaration "scope" of the declarator.
   4263     DeclSpec DS(AttrFactory);
   4264 
   4265     // Skip any Microsoft attributes before a param.
   4266     if (getLang().MicrosoftExt && Tok.is(tok::l_square))
   4267       ParseMicrosoftAttributes(DS.getAttributes());
   4268 
   4269     SourceLocation DSStart = Tok.getLocation();
   4270 
   4271     // If the caller parsed attributes for the first argument, add them now.
   4272     // Take them so that we only apply the attributes to the first parameter.
   4273     // FIXME: If we saw an ellipsis first, this code is not reached. Are the
   4274     // attributes lost? Should they even be allowed?
   4275     // FIXME: If we can leave the attributes in the token stream somehow, we can
   4276     // get rid of a parameter (attrs) and this statement. It might be too much
   4277     // hassle.
   4278     DS.takeAttributesFrom(attrs);
   4279 
   4280     ParseDeclarationSpecifiers(DS);
   4281 
   4282     // Parse the declarator.  This is "PrototypeContext", because we must
   4283     // accept either 'declarator' or 'abstract-declarator' here.
   4284     Declarator ParmDecl(DS, Declarator::PrototypeContext);
   4285     ParseDeclarator(ParmDecl);
   4286 
   4287     // Parse GNU attributes, if present.
   4288     MaybeParseGNUAttributes(ParmDecl);
   4289 
   4290     // Remember this parsed parameter in ParamInfo.
   4291     IdentifierInfo *ParmII = ParmDecl.getIdentifier();
   4292 
   4293     // DefArgToks is used when the parsing of default arguments needs
   4294     // to be delayed.
   4295     CachedTokens *DefArgToks = 0;
   4296 
   4297     // If no parameter was specified, verify that *something* was specified,
   4298     // otherwise we have a missing type and identifier.
   4299     if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
   4300         ParmDecl.getNumTypeObjects() == 0) {
   4301       // Completely missing, emit error.
   4302       Diag(DSStart, diag::err_missing_param);
   4303     } else {
   4304       // Otherwise, we have something.  Add it and let semantic analysis try
   4305       // to grok it and add the result to the ParamInfo we are building.
   4306 
   4307       // Inform the actions module about the parameter declarator, so it gets
   4308       // added to the current scope.
   4309       Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
   4310 
   4311       // Parse the default argument, if any. We parse the default
   4312       // arguments in all dialects; the semantic analysis in
   4313       // ActOnParamDefaultArgument will reject the default argument in
   4314       // C.
   4315       if (Tok.is(tok::equal)) {
   4316         SourceLocation EqualLoc = Tok.getLocation();
   4317 
   4318         // Parse the default argument
   4319         if (D.getContext() == Declarator::MemberContext) {
   4320           // If we're inside a class definition, cache the tokens
   4321           // corresponding to the default argument. We'll actually parse
   4322           // them when we see the end of the class definition.
   4323           // FIXME: Templates will require something similar.
   4324           // FIXME: Can we use a smart pointer for Toks?
   4325           DefArgToks = new CachedTokens;
   4326 
   4327           if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
   4328                                     /*StopAtSemi=*/true,
   4329                                     /*ConsumeFinalToken=*/false)) {
   4330             delete DefArgToks;
   4331             DefArgToks = 0;
   4332             Actions.ActOnParamDefaultArgumentError(Param);
   4333           } else {
   4334             // Mark the end of the default argument so that we know when to
   4335             // stop when we parse it later on.
   4336             Token DefArgEnd;
   4337             DefArgEnd.startToken();
   4338             DefArgEnd.setKind(tok::cxx_defaultarg_end);
   4339             DefArgEnd.setLocation(Tok.getLocation());
   4340             DefArgToks->push_back(DefArgEnd);
   4341             Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
   4342                                                 (*DefArgToks)[1].getLocation());
   4343           }
   4344         } else {
   4345           // Consume the '='.
   4346           ConsumeToken();
   4347 
   4348           // The argument isn't actually potentially evaluated unless it is
   4349           // used.
   4350           EnterExpressionEvaluationContext Eval(Actions,
   4351                                               Sema::PotentiallyEvaluatedIfUsed);
   4352 
   4353           ExprResult DefArgResult(ParseAssignmentExpression());
   4354           if (DefArgResult.isInvalid()) {
   4355             Actions.ActOnParamDefaultArgumentError(Param);
   4356             SkipUntil(tok::comma, tok::r_paren, true, true);
   4357           } else {
   4358             // Inform the actions module about the default argument
   4359             Actions.ActOnParamDefaultArgument(Param, EqualLoc,
   4360                                               DefArgResult.take());
   4361           }
   4362         }
   4363       }
   4364 
   4365       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
   4366                                           ParmDecl.getIdentifierLoc(), Param,
   4367                                           DefArgToks));
   4368     }
   4369 
   4370     // If the next token is a comma, consume it and keep reading arguments.
   4371     if (Tok.isNot(tok::comma)) {
   4372       if (Tok.is(tok::ellipsis)) {
   4373         EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
   4374 
   4375         if (!getLang().CPlusPlus) {
   4376           // We have ellipsis without a preceding ',', which is ill-formed
   4377           // in C. Complain and provide the fix.
   4378           Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
   4379             << FixItHint::CreateInsertion(EllipsisLoc, ", ");
   4380         }
   4381       }
   4382 
   4383       break;
   4384     }
   4385 
   4386     // Consume the comma.
   4387     ConsumeToken();
   4388   }
   4389 
   4390 }
   4391 
   4392 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
   4393 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
   4394 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
   4395 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
   4396 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
   4397 void Parser::ParseBracketDeclarator(Declarator &D) {
   4398   BalancedDelimiterTracker T(*this, tok::l_square);
   4399   T.consumeOpen();
   4400 
   4401   // C array syntax has many features, but by-far the most common is [] and [4].
   4402   // This code does a fast path to handle some of the most obvious cases.
   4403   if (Tok.getKind() == tok::r_square) {
   4404     T.consumeClose();
   4405     ParsedAttributes attrs(AttrFactory);
   4406     MaybeParseCXX0XAttributes(attrs);
   4407 
   4408     // Remember that we parsed the empty array type.
   4409     ExprResult NumElements;
   4410     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
   4411                                             T.getOpenLocation(),
   4412                                             T.getCloseLocation()),
   4413                   attrs, T.getCloseLocation());
   4414     return;
   4415   } else if (Tok.getKind() == tok::numeric_constant &&
   4416              GetLookAheadToken(1).is(tok::r_square)) {
   4417     // [4] is very common.  Parse the numeric constant expression.
   4418     ExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
   4419     ConsumeToken();
   4420 
   4421     T.consumeClose();
   4422     ParsedAttributes attrs(AttrFactory);
   4423     MaybeParseCXX0XAttributes(attrs);
   4424 
   4425     // Remember that we parsed a array type, and remember its features.
   4426     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
   4427                                             ExprRes.release(),
   4428                                             T.getOpenLocation(),
   4429                                             T.getCloseLocation()),
   4430                   attrs, T.getCloseLocation());
   4431     return;
   4432   }
   4433 
   4434   // If valid, this location is the position where we read the 'static' keyword.
   4435   SourceLocation StaticLoc;
   4436   if (Tok.is(tok::kw_static))
   4437     StaticLoc = ConsumeToken();
   4438 
   4439   // If there is a type-qualifier-list, read it now.
   4440   // Type qualifiers in an array subscript are a C99 feature.
   4441   DeclSpec DS(AttrFactory);
   4442   ParseTypeQualifierListOpt(DS, false /*no attributes*/);
   4443 
   4444   // If we haven't already read 'static', check to see if there is one after the
   4445   // type-qualifier-list.
   4446   if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
   4447     StaticLoc = ConsumeToken();
   4448 
   4449   // Handle "direct-declarator [ type-qual-list[opt] * ]".
   4450   bool isStar = false;
   4451   ExprResult NumElements;
   4452 
   4453   // Handle the case where we have '[*]' as the array size.  However, a leading
   4454   // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
   4455   // the the token after the star is a ']'.  Since stars in arrays are
   4456   // infrequent, use of lookahead is not costly here.
   4457   if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
   4458     ConsumeToken();  // Eat the '*'.
   4459 
   4460     if (StaticLoc.isValid()) {
   4461       Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
   4462       StaticLoc = SourceLocation();  // Drop the static.
   4463     }
   4464     isStar = true;
   4465   } else if (Tok.isNot(tok::r_square)) {
   4466     // Note, in C89, this production uses the constant-expr production instead
   4467     // of assignment-expr.  The only difference is that assignment-expr allows
   4468     // things like '=' and '*='.  Sema rejects these in C89 mode because they
   4469     // are not i-c-e's, so we don't need to distinguish between the two here.
   4470 
   4471     // Parse the constant-expression or assignment-expression now (depending
   4472     // on dialect).
   4473     if (getLang().CPlusPlus)
   4474       NumElements = ParseConstantExpression();
   4475     else
   4476       NumElements = ParseAssignmentExpression();
   4477   }
   4478 
   4479   // If there was an error parsing the assignment-expression, recover.
   4480   if (NumElements.isInvalid()) {
   4481     D.setInvalidType(true);
   4482     // If the expression was invalid, skip it.
   4483     SkipUntil(tok::r_square);
   4484     return;
   4485   }
   4486 
   4487   T.consumeClose();
   4488 
   4489   ParsedAttributes attrs(AttrFactory);
   4490   MaybeParseCXX0XAttributes(attrs);
   4491 
   4492   // Remember that we parsed a array type, and remember its features.
   4493   D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
   4494                                           StaticLoc.isValid(), isStar,
   4495                                           NumElements.release(),
   4496                                           T.getOpenLocation(),
   4497                                           T.getCloseLocation()),
   4498                 attrs, T.getCloseLocation());
   4499 }
   4500 
   4501 /// [GNU]   typeof-specifier:
   4502 ///           typeof ( expressions )
   4503 ///           typeof ( type-name )
   4504 /// [GNU/C++] typeof unary-expression
   4505 ///
   4506 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
   4507   assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
   4508   Token OpTok = Tok;
   4509   SourceLocation StartLoc = ConsumeToken();
   4510 
   4511   const bool hasParens = Tok.is(tok::l_paren);
   4512 
   4513   bool isCastExpr;
   4514   ParsedType CastTy;
   4515   SourceRange CastRange;
   4516   ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
   4517                                                           CastTy, CastRange);
   4518   if (hasParens)
   4519     DS.setTypeofParensRange(CastRange);
   4520 
   4521   if (CastRange.getEnd().isInvalid())
   4522     // FIXME: Not accurate, the range gets one token more than it should.
   4523     DS.SetRangeEnd(Tok.getLocation());
   4524   else
   4525     DS.SetRangeEnd(CastRange.getEnd());
   4526 
   4527   if (isCastExpr) {
   4528     if (!CastTy) {
   4529       DS.SetTypeSpecError();
   4530       return;
   4531     }
   4532 
   4533     const char *PrevSpec = 0;
   4534     unsigned DiagID;
   4535     // Check for duplicate type specifiers (e.g. "int typeof(int)").
   4536     if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
   4537                            DiagID, CastTy))
   4538       Diag(StartLoc, DiagID) << PrevSpec;
   4539     return;
   4540   }
   4541 
   4542   // If we get here, the operand to the typeof was an expresion.
   4543   if (Operand.isInvalid()) {
   4544     DS.SetTypeSpecError();
   4545     return;
   4546   }
   4547 
   4548   const char *PrevSpec = 0;
   4549   unsigned DiagID;
   4550   // Check for duplicate type specifiers (e.g. "int typeof(int)").
   4551   if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
   4552                          DiagID, Operand.get()))
   4553     Diag(StartLoc, DiagID) << PrevSpec;
   4554 }
   4555 
   4556 /// [C1X]   atomic-specifier:
   4557 ///           _Atomic ( type-name )
   4558 ///
   4559 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
   4560   assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier");
   4561 
   4562   SourceLocation StartLoc = ConsumeToken();
   4563   BalancedDelimiterTracker T(*this, tok::l_paren);
   4564   if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) {
   4565     SkipUntil(tok::r_paren);
   4566     return;
   4567   }
   4568 
   4569   TypeResult Result = ParseTypeName();
   4570   if (Result.isInvalid()) {
   4571     SkipUntil(tok::r_paren);
   4572     return;
   4573   }
   4574 
   4575   // Match the ')'
   4576   T.consumeClose();
   4577 
   4578   if (T.getCloseLocation().isInvalid())
   4579     return;
   4580 
   4581   DS.setTypeofParensRange(T.getRange());
   4582   DS.SetRangeEnd(T.getCloseLocation());
   4583 
   4584   const char *PrevSpec = 0;
   4585   unsigned DiagID;
   4586   if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
   4587                          DiagID, Result.release()))
   4588     Diag(StartLoc, DiagID) << PrevSpec;
   4589 }
   4590 
   4591 
   4592 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
   4593 /// from TryAltiVecVectorToken.
   4594 bool Parser::TryAltiVecVectorTokenOutOfLine() {
   4595   Token Next = NextToken();
   4596   switch (Next.getKind()) {
   4597   default: return false;
   4598   case tok::kw_short:
   4599   case tok::kw_long:
   4600   case tok::kw_signed:
   4601   case tok::kw_unsigned:
   4602   case tok::kw_void:
   4603   case tok::kw_char:
   4604   case tok::kw_int:
   4605   case tok::kw_float:
   4606   case tok::kw_double:
   4607   case tok::kw_bool:
   4608   case tok::kw___pixel:
   4609     Tok.setKind(tok::kw___vector);
   4610     return true;
   4611   case tok::identifier:
   4612     if (Next.getIdentifierInfo() == Ident_pixel) {
   4613       Tok.setKind(tok::kw___vector);
   4614       return true;
   4615     }
   4616     return false;
   4617   }
   4618 }
   4619 
   4620 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
   4621                                       const char *&PrevSpec, unsigned &DiagID,
   4622                                       bool &isInvalid) {
   4623   if (Tok.getIdentifierInfo() == Ident_vector) {
   4624     Token Next = NextToken();
   4625     switch (Next.getKind()) {
   4626     case tok::kw_short:
   4627     case tok::kw_long:
   4628     case tok::kw_signed:
   4629     case tok::kw_unsigned:
   4630     case tok::kw_void:
   4631     case tok::kw_char:
   4632     case tok::kw_int:
   4633     case tok::kw_float:
   4634     case tok::kw_double:
   4635     case tok::kw_bool:
   4636     case tok::kw___pixel:
   4637       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
   4638       return true;
   4639     case tok::identifier:
   4640       if (Next.getIdentifierInfo() == Ident_pixel) {
   4641         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
   4642         return true;
   4643       }
   4644       break;
   4645     default:
   4646       break;
   4647     }
   4648   } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
   4649              DS.isTypeAltiVecVector()) {
   4650     isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
   4651     return true;
   4652   }
   4653   return false;
   4654 }
   4655