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