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