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