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