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