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