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