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