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