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