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