xref: /freebsd/contrib/llvm-project/clang/lib/Parse/ParseDecl.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
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           ThisVarDecl->getType()->getCanonicalTypeInternal(),
2423           ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2424           /*Braced=*/false);
2425       CalledSignatureHelp = true;
2426       return PreferredType;
2427     };
2428     auto SetPreferredType = [&] {
2429       PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2430     };
2431 
2432     llvm::function_ref<void()> ExpressionStarts;
2433     if (ThisVarDecl) {
2434       // ParseExpressionList can sometimes succeed even when ThisDecl is not
2435       // VarDecl. This is an error and it is reported in a call to
2436       // Actions.ActOnInitializerError(). However, we call
2437       // ProduceConstructorSignatureHelp only on VarDecls.
2438       ExpressionStarts = SetPreferredType;
2439     }
2440     if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2441       if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2442         Actions.ProduceConstructorSignatureHelp(
2443             ThisVarDecl->getType()->getCanonicalTypeInternal(),
2444             ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2445             /*Braced=*/false);
2446         CalledSignatureHelp = true;
2447       }
2448       Actions.ActOnInitializerError(ThisDecl);
2449       SkipUntil(tok::r_paren, StopAtSemi);
2450     } else {
2451       // Match the ')'.
2452       T.consumeClose();
2453 
2454       assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2455              "Unexpected number of commas!");
2456 
2457       InitScope.pop();
2458 
2459       ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2460                                                           T.getCloseLocation(),
2461                                                           Exprs);
2462       Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2463                                    /*DirectInit=*/true);
2464     }
2465     break;
2466   }
2467   case InitKind::CXXBraced: {
2468     // Parse C++0x braced-init-list.
2469     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2470 
2471     InitializerScopeRAII InitScope(*this, D, ThisDecl);
2472 
2473     PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2474     ExprResult Init(ParseBraceInitializer());
2475 
2476     InitScope.pop();
2477 
2478     if (Init.isInvalid()) {
2479       Actions.ActOnInitializerError(ThisDecl);
2480     } else
2481       Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2482     break;
2483   }
2484   case InitKind::Uninitialized: {
2485     Actions.ActOnUninitializedDecl(ThisDecl);
2486     break;
2487   }
2488   }
2489 
2490   Actions.FinalizeDeclaration(ThisDecl);
2491   return OuterDecl ? OuterDecl : ThisDecl;
2492 }
2493 
2494 /// ParseSpecifierQualifierList
2495 ///        specifier-qualifier-list:
2496 ///          type-specifier specifier-qualifier-list[opt]
2497 ///          type-qualifier specifier-qualifier-list[opt]
2498 /// [GNU]    attributes     specifier-qualifier-list[opt]
2499 ///
2500 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2501                                          DeclSpecContext DSC) {
2502   /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
2503   /// parse declaration-specifiers and complain about extra stuff.
2504   /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2505   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2506 
2507   // Validate declspec for type-name.
2508   unsigned Specs = DS.getParsedSpecifiers();
2509   if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2510     Diag(Tok, diag::err_expected_type);
2511     DS.SetTypeSpecError();
2512   } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2513     Diag(Tok, diag::err_typename_requires_specqual);
2514     if (!DS.hasTypeSpecifier())
2515       DS.SetTypeSpecError();
2516   }
2517 
2518   // Issue diagnostic and remove storage class if present.
2519   if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2520     if (DS.getStorageClassSpecLoc().isValid())
2521       Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2522     else
2523       Diag(DS.getThreadStorageClassSpecLoc(),
2524            diag::err_typename_invalid_storageclass);
2525     DS.ClearStorageClassSpecs();
2526   }
2527 
2528   // Issue diagnostic and remove function specifier if present.
2529   if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2530     if (DS.isInlineSpecified())
2531       Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2532     if (DS.isVirtualSpecified())
2533       Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2534     if (DS.hasExplicitSpecifier())
2535       Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2536     DS.ClearFunctionSpecs();
2537   }
2538 
2539   // Issue diagnostic and remove constexpr specifier if present.
2540   if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2541     Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2542         << static_cast<int>(DS.getConstexprSpecifier());
2543     DS.ClearConstexprSpec();
2544   }
2545 }
2546 
2547 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2548 /// specified token is valid after the identifier in a declarator which
2549 /// immediately follows the declspec.  For example, these things are valid:
2550 ///
2551 ///      int x   [             4];         // direct-declarator
2552 ///      int x   (             int y);     // direct-declarator
2553 ///  int(int x   )                         // direct-declarator
2554 ///      int x   ;                         // simple-declaration
2555 ///      int x   =             17;         // init-declarator-list
2556 ///      int x   ,             y;          // init-declarator-list
2557 ///      int x   __asm__       ("foo");    // init-declarator-list
2558 ///      int x   :             4;          // struct-declarator
2559 ///      int x   {             5};         // C++'0x unified initializers
2560 ///
2561 /// This is not, because 'x' does not immediately follow the declspec (though
2562 /// ')' happens to be valid anyway).
2563 ///    int (x)
2564 ///
2565 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2566   return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2567                    tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2568                    tok::colon);
2569 }
2570 
2571 /// ParseImplicitInt - This method is called when we have an non-typename
2572 /// identifier in a declspec (which normally terminates the decl spec) when
2573 /// the declspec has no type specifier.  In this case, the declspec is either
2574 /// malformed or is "implicit int" (in K&R and C89).
2575 ///
2576 /// This method handles diagnosing this prettily and returns false if the
2577 /// declspec is done being processed.  If it recovers and thinks there may be
2578 /// other pieces of declspec after it, it returns true.
2579 ///
2580 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2581                               const ParsedTemplateInfo &TemplateInfo,
2582                               AccessSpecifier AS, DeclSpecContext DSC,
2583                               ParsedAttributesWithRange &Attrs) {
2584   assert(Tok.is(tok::identifier) && "should have identifier");
2585 
2586   SourceLocation Loc = Tok.getLocation();
2587   // If we see an identifier that is not a type name, we normally would
2588   // parse it as the identifier being declared.  However, when a typename
2589   // is typo'd or the definition is not included, this will incorrectly
2590   // parse the typename as the identifier name and fall over misparsing
2591   // later parts of the diagnostic.
2592   //
2593   // As such, we try to do some look-ahead in cases where this would
2594   // otherwise be an "implicit-int" case to see if this is invalid.  For
2595   // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
2596   // an identifier with implicit int, we'd get a parse error because the
2597   // next token is obviously invalid for a type.  Parse these as a case
2598   // with an invalid type specifier.
2599   assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2600 
2601   // Since we know that this either implicit int (which is rare) or an
2602   // error, do lookahead to try to do better recovery. This never applies
2603   // within a type specifier. Outside of C++, we allow this even if the
2604   // language doesn't "officially" support implicit int -- we support
2605   // implicit int as an extension in C99 and C11.
2606   if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2607       isValidAfterIdentifierInDeclarator(NextToken())) {
2608     // If this token is valid for implicit int, e.g. "static x = 4", then
2609     // we just avoid eating the identifier, so it will be parsed as the
2610     // identifier in the declarator.
2611     return false;
2612   }
2613 
2614   // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2615   // for incomplete declarations such as `pipe p`.
2616   if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2617     return false;
2618 
2619   if (getLangOpts().CPlusPlus &&
2620       DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2621     // Don't require a type specifier if we have the 'auto' storage class
2622     // specifier in C++98 -- we'll promote it to a type specifier.
2623     if (SS)
2624       AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2625     return false;
2626   }
2627 
2628   if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2629       getLangOpts().MSVCCompat) {
2630     // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2631     // Give Sema a chance to recover if we are in a template with dependent base
2632     // classes.
2633     if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2634             *Tok.getIdentifierInfo(), Tok.getLocation(),
2635             DSC == DeclSpecContext::DSC_template_type_arg)) {
2636       const char *PrevSpec;
2637       unsigned DiagID;
2638       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2639                          Actions.getASTContext().getPrintingPolicy());
2640       DS.SetRangeEnd(Tok.getLocation());
2641       ConsumeToken();
2642       return false;
2643     }
2644   }
2645 
2646   // Otherwise, if we don't consume this token, we are going to emit an
2647   // error anyway.  Try to recover from various common problems.  Check
2648   // to see if this was a reference to a tag name without a tag specified.
2649   // This is a common problem in C (saying 'foo' instead of 'struct foo').
2650   //
2651   // C++ doesn't need this, and isTagName doesn't take SS.
2652   if (SS == nullptr) {
2653     const char *TagName = nullptr, *FixitTagName = nullptr;
2654     tok::TokenKind TagKind = tok::unknown;
2655 
2656     switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2657       default: break;
2658       case DeclSpec::TST_enum:
2659         TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
2660       case DeclSpec::TST_union:
2661         TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2662       case DeclSpec::TST_struct:
2663         TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2664       case DeclSpec::TST_interface:
2665         TagName="__interface"; FixitTagName = "__interface ";
2666         TagKind=tok::kw___interface;break;
2667       case DeclSpec::TST_class:
2668         TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2669     }
2670 
2671     if (TagName) {
2672       IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2673       LookupResult R(Actions, TokenName, SourceLocation(),
2674                      Sema::LookupOrdinaryName);
2675 
2676       Diag(Loc, diag::err_use_of_tag_name_without_tag)
2677         << TokenName << TagName << getLangOpts().CPlusPlus
2678         << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2679 
2680       if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2681         for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2682              I != IEnd; ++I)
2683           Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2684             << TokenName << TagName;
2685       }
2686 
2687       // Parse this as a tag as if the missing tag were present.
2688       if (TagKind == tok::kw_enum)
2689         ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2690                            DeclSpecContext::DSC_normal);
2691       else
2692         ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2693                             /*EnteringContext*/ false,
2694                             DeclSpecContext::DSC_normal, Attrs);
2695       return true;
2696     }
2697   }
2698 
2699   // Determine whether this identifier could plausibly be the name of something
2700   // being declared (with a missing type).
2701   if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2702                                 DSC == DeclSpecContext::DSC_class)) {
2703     // Look ahead to the next token to try to figure out what this declaration
2704     // was supposed to be.
2705     switch (NextToken().getKind()) {
2706     case tok::l_paren: {
2707       // static x(4); // 'x' is not a type
2708       // x(int n);    // 'x' is not a type
2709       // x (*p)[];    // 'x' is a type
2710       //
2711       // Since we're in an error case, we can afford to perform a tentative
2712       // parse to determine which case we're in.
2713       TentativeParsingAction PA(*this);
2714       ConsumeToken();
2715       TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2716       PA.Revert();
2717 
2718       if (TPR != TPResult::False) {
2719         // The identifier is followed by a parenthesized declarator.
2720         // It's supposed to be a type.
2721         break;
2722       }
2723 
2724       // If we're in a context where we could be declaring a constructor,
2725       // check whether this is a constructor declaration with a bogus name.
2726       if (DSC == DeclSpecContext::DSC_class ||
2727           (DSC == DeclSpecContext::DSC_top_level && SS)) {
2728         IdentifierInfo *II = Tok.getIdentifierInfo();
2729         if (Actions.isCurrentClassNameTypo(II, SS)) {
2730           Diag(Loc, diag::err_constructor_bad_name)
2731             << Tok.getIdentifierInfo() << II
2732             << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2733           Tok.setIdentifierInfo(II);
2734         }
2735       }
2736       // Fall through.
2737       LLVM_FALLTHROUGH;
2738     }
2739     case tok::comma:
2740     case tok::equal:
2741     case tok::kw_asm:
2742     case tok::l_brace:
2743     case tok::l_square:
2744     case tok::semi:
2745       // This looks like a variable or function declaration. The type is
2746       // probably missing. We're done parsing decl-specifiers.
2747       // But only if we are not in a function prototype scope.
2748       if (getCurScope()->isFunctionPrototypeScope())
2749         break;
2750       if (SS)
2751         AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2752       return false;
2753 
2754     default:
2755       // This is probably supposed to be a type. This includes cases like:
2756       //   int f(itn);
2757       //   struct S { unsigned : 4; };
2758       break;
2759     }
2760   }
2761 
2762   // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2763   // and attempt to recover.
2764   ParsedType T;
2765   IdentifierInfo *II = Tok.getIdentifierInfo();
2766   bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2767   Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2768                                   IsTemplateName);
2769   if (T) {
2770     // The action has suggested that the type T could be used. Set that as
2771     // the type in the declaration specifiers, consume the would-be type
2772     // name token, and we're done.
2773     const char *PrevSpec;
2774     unsigned DiagID;
2775     DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2776                        Actions.getASTContext().getPrintingPolicy());
2777     DS.SetRangeEnd(Tok.getLocation());
2778     ConsumeToken();
2779     // There may be other declaration specifiers after this.
2780     return true;
2781   } else if (II != Tok.getIdentifierInfo()) {
2782     // If no type was suggested, the correction is to a keyword
2783     Tok.setKind(II->getTokenID());
2784     // There may be other declaration specifiers after this.
2785     return true;
2786   }
2787 
2788   // Otherwise, the action had no suggestion for us.  Mark this as an error.
2789   DS.SetTypeSpecError();
2790   DS.SetRangeEnd(Tok.getLocation());
2791   ConsumeToken();
2792 
2793   // Eat any following template arguments.
2794   if (IsTemplateName) {
2795     SourceLocation LAngle, RAngle;
2796     TemplateArgList Args;
2797     ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2798   }
2799 
2800   // TODO: Could inject an invalid typedef decl in an enclosing scope to
2801   // avoid rippling error messages on subsequent uses of the same type,
2802   // could be useful if #include was forgotten.
2803   return true;
2804 }
2805 
2806 /// Determine the declaration specifier context from the declarator
2807 /// context.
2808 ///
2809 /// \param Context the declarator context, which is one of the
2810 /// DeclaratorContext enumerator values.
2811 Parser::DeclSpecContext
2812 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2813   if (Context == DeclaratorContext::Member)
2814     return DeclSpecContext::DSC_class;
2815   if (Context == DeclaratorContext::File)
2816     return DeclSpecContext::DSC_top_level;
2817   if (Context == DeclaratorContext::TemplateParam)
2818     return DeclSpecContext::DSC_template_param;
2819   if (Context == DeclaratorContext::TemplateArg ||
2820       Context == DeclaratorContext::TemplateTypeArg)
2821     return DeclSpecContext::DSC_template_type_arg;
2822   if (Context == DeclaratorContext::TrailingReturn ||
2823       Context == DeclaratorContext::TrailingReturnVar)
2824     return DeclSpecContext::DSC_trailing;
2825   if (Context == DeclaratorContext::AliasDecl ||
2826       Context == DeclaratorContext::AliasTemplate)
2827     return DeclSpecContext::DSC_alias_declaration;
2828   return DeclSpecContext::DSC_normal;
2829 }
2830 
2831 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2832 ///
2833 /// FIXME: Simply returns an alignof() expression if the argument is a
2834 /// type. Ideally, the type should be propagated directly into Sema.
2835 ///
2836 /// [C11]   type-id
2837 /// [C11]   constant-expression
2838 /// [C++0x] type-id ...[opt]
2839 /// [C++0x] assignment-expression ...[opt]
2840 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2841                                       SourceLocation &EllipsisLoc) {
2842   ExprResult ER;
2843   if (isTypeIdInParens()) {
2844     SourceLocation TypeLoc = Tok.getLocation();
2845     ParsedType Ty = ParseTypeName().get();
2846     SourceRange TypeRange(Start, Tok.getLocation());
2847     ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2848                                                Ty.getAsOpaquePtr(), TypeRange);
2849   } else
2850     ER = ParseConstantExpression();
2851 
2852   if (getLangOpts().CPlusPlus11)
2853     TryConsumeToken(tok::ellipsis, EllipsisLoc);
2854 
2855   return ER;
2856 }
2857 
2858 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2859 /// attribute to Attrs.
2860 ///
2861 /// alignment-specifier:
2862 /// [C11]   '_Alignas' '(' type-id ')'
2863 /// [C11]   '_Alignas' '(' constant-expression ')'
2864 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2865 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2866 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2867                                      SourceLocation *EndLoc) {
2868   assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2869          "Not an alignment-specifier!");
2870 
2871   IdentifierInfo *KWName = Tok.getIdentifierInfo();
2872   SourceLocation KWLoc = ConsumeToken();
2873 
2874   BalancedDelimiterTracker T(*this, tok::l_paren);
2875   if (T.expectAndConsume())
2876     return;
2877 
2878   SourceLocation EllipsisLoc;
2879   ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2880   if (ArgExpr.isInvalid()) {
2881     T.skipToEnd();
2882     return;
2883   }
2884 
2885   T.consumeClose();
2886   if (EndLoc)
2887     *EndLoc = T.getCloseLocation();
2888 
2889   ArgsVector ArgExprs;
2890   ArgExprs.push_back(ArgExpr.get());
2891   Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2892                ParsedAttr::AS_Keyword, EllipsisLoc);
2893 }
2894 
2895 ExprResult Parser::ParseExtIntegerArgument() {
2896   assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
2897          "Not an extended int type");
2898   ConsumeToken();
2899 
2900   BalancedDelimiterTracker T(*this, tok::l_paren);
2901   if (T.expectAndConsume())
2902     return ExprError();
2903 
2904   ExprResult ER = ParseConstantExpression();
2905   if (ER.isInvalid()) {
2906     T.skipToEnd();
2907     return ExprError();
2908   }
2909 
2910   if(T.consumeClose())
2911     return ExprError();
2912   return ER;
2913 }
2914 
2915 /// Determine whether we're looking at something that might be a declarator
2916 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2917 /// diagnose a missing semicolon after a prior tag definition in the decl
2918 /// specifier.
2919 ///
2920 /// \return \c true if an error occurred and this can't be any kind of
2921 /// declaration.
2922 bool
2923 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2924                                               DeclSpecContext DSContext,
2925                                               LateParsedAttrList *LateAttrs) {
2926   assert(DS.hasTagDefinition() && "shouldn't call this");
2927 
2928   bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2929                           DSContext == DeclSpecContext::DSC_top_level);
2930 
2931   if (getLangOpts().CPlusPlus &&
2932       Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2933                   tok::annot_template_id) &&
2934       TryAnnotateCXXScopeToken(EnteringContext)) {
2935     SkipMalformedDecl();
2936     return true;
2937   }
2938 
2939   bool HasScope = Tok.is(tok::annot_cxxscope);
2940   // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2941   Token AfterScope = HasScope ? NextToken() : Tok;
2942 
2943   // Determine whether the following tokens could possibly be a
2944   // declarator.
2945   bool MightBeDeclarator = true;
2946   if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2947     // A declarator-id can't start with 'typename'.
2948     MightBeDeclarator = false;
2949   } else if (AfterScope.is(tok::annot_template_id)) {
2950     // If we have a type expressed as a template-id, this cannot be a
2951     // declarator-id (such a type cannot be redeclared in a simple-declaration).
2952     TemplateIdAnnotation *Annot =
2953         static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2954     if (Annot->Kind == TNK_Type_template)
2955       MightBeDeclarator = false;
2956   } else if (AfterScope.is(tok::identifier)) {
2957     const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2958 
2959     // These tokens cannot come after the declarator-id in a
2960     // simple-declaration, and are likely to come after a type-specifier.
2961     if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2962                      tok::annot_cxxscope, tok::coloncolon)) {
2963       // Missing a semicolon.
2964       MightBeDeclarator = false;
2965     } else if (HasScope) {
2966       // If the declarator-id has a scope specifier, it must redeclare a
2967       // previously-declared entity. If that's a type (and this is not a
2968       // typedef), that's an error.
2969       CXXScopeSpec SS;
2970       Actions.RestoreNestedNameSpecifierAnnotation(
2971           Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2972       IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2973       Sema::NameClassification Classification = Actions.ClassifyName(
2974           getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2975           /*CCC=*/nullptr);
2976       switch (Classification.getKind()) {
2977       case Sema::NC_Error:
2978         SkipMalformedDecl();
2979         return true;
2980 
2981       case Sema::NC_Keyword:
2982         llvm_unreachable("typo correction is not possible here");
2983 
2984       case Sema::NC_Type:
2985       case Sema::NC_TypeTemplate:
2986       case Sema::NC_UndeclaredNonType:
2987       case Sema::NC_UndeclaredTemplate:
2988         // Not a previously-declared non-type entity.
2989         MightBeDeclarator = false;
2990         break;
2991 
2992       case Sema::NC_Unknown:
2993       case Sema::NC_NonType:
2994       case Sema::NC_DependentNonType:
2995       case Sema::NC_OverloadSet:
2996       case Sema::NC_VarTemplate:
2997       case Sema::NC_FunctionTemplate:
2998       case Sema::NC_Concept:
2999         // Might be a redeclaration of a prior entity.
3000         break;
3001       }
3002     }
3003   }
3004 
3005   if (MightBeDeclarator)
3006     return false;
3007 
3008   const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3009   Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
3010        diag::err_expected_after)
3011       << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3012 
3013   // Try to recover from the typo, by dropping the tag definition and parsing
3014   // the problematic tokens as a type.
3015   //
3016   // FIXME: Split the DeclSpec into pieces for the standalone
3017   // declaration and pieces for the following declaration, instead
3018   // of assuming that all the other pieces attach to new declaration,
3019   // and call ParsedFreeStandingDeclSpec as appropriate.
3020   DS.ClearTypeSpecType();
3021   ParsedTemplateInfo NotATemplate;
3022   ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3023   return false;
3024 }
3025 
3026 // Choose the apprpriate diagnostic error for why fixed point types are
3027 // disabled, set the previous specifier, and mark as invalid.
3028 static void SetupFixedPointError(const LangOptions &LangOpts,
3029                                  const char *&PrevSpec, unsigned &DiagID,
3030                                  bool &isInvalid) {
3031   assert(!LangOpts.FixedPoint);
3032   DiagID = diag::err_fixed_point_not_enabled;
3033   PrevSpec = "";  // Not used by diagnostic
3034   isInvalid = true;
3035 }
3036 
3037 /// ParseDeclarationSpecifiers
3038 ///       declaration-specifiers: [C99 6.7]
3039 ///         storage-class-specifier declaration-specifiers[opt]
3040 ///         type-specifier declaration-specifiers[opt]
3041 /// [C99]   function-specifier declaration-specifiers[opt]
3042 /// [C11]   alignment-specifier declaration-specifiers[opt]
3043 /// [GNU]   attributes declaration-specifiers[opt]
3044 /// [Clang] '__module_private__' declaration-specifiers[opt]
3045 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3046 ///
3047 ///       storage-class-specifier: [C99 6.7.1]
3048 ///         'typedef'
3049 ///         'extern'
3050 ///         'static'
3051 ///         'auto'
3052 ///         'register'
3053 /// [C++]   'mutable'
3054 /// [C++11] 'thread_local'
3055 /// [C11]   '_Thread_local'
3056 /// [GNU]   '__thread'
3057 ///       function-specifier: [C99 6.7.4]
3058 /// [C99]   'inline'
3059 /// [C++]   'virtual'
3060 /// [C++]   'explicit'
3061 /// [OpenCL] '__kernel'
3062 ///       'friend': [C++ dcl.friend]
3063 ///       'constexpr': [C++0x dcl.constexpr]
3064 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
3065                                         const ParsedTemplateInfo &TemplateInfo,
3066                                         AccessSpecifier AS,
3067                                         DeclSpecContext DSContext,
3068                                         LateParsedAttrList *LateAttrs) {
3069   if (DS.getSourceRange().isInvalid()) {
3070     // Start the range at the current token but make the end of the range
3071     // invalid.  This will make the entire range invalid unless we successfully
3072     // consume a token.
3073     DS.SetRangeStart(Tok.getLocation());
3074     DS.SetRangeEnd(SourceLocation());
3075   }
3076 
3077   bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3078                           DSContext == DeclSpecContext::DSC_top_level);
3079   bool AttrsLastTime = false;
3080   ParsedAttributesWithRange attrs(AttrFactory);
3081   // We use Sema's policy to get bool macros right.
3082   PrintingPolicy Policy = Actions.getPrintingPolicy();
3083   while (true) {
3084     bool isInvalid = false;
3085     bool isStorageClass = false;
3086     const char *PrevSpec = nullptr;
3087     unsigned DiagID = 0;
3088 
3089     // This value needs to be set to the location of the last token if the last
3090     // token of the specifier is already consumed.
3091     SourceLocation ConsumedEnd;
3092 
3093     // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3094     // implementation for VS2013 uses _Atomic as an identifier for one of the
3095     // classes in <atomic>.
3096     //
3097     // A typedef declaration containing _Atomic<...> is among the places where
3098     // the class is used.  If we are currently parsing such a declaration, treat
3099     // the token as an identifier.
3100     if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3101         DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3102         !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3103       Tok.setKind(tok::identifier);
3104 
3105     SourceLocation Loc = Tok.getLocation();
3106 
3107     // Helper for image types in OpenCL.
3108     auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3109       // Check if the image type is supported and otherwise turn the keyword into an identifier
3110       // because image types from extensions are not reserved identifiers.
3111       if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3112         Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3113         Tok.setKind(tok::identifier);
3114         return false;
3115       }
3116       isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3117       return true;
3118     };
3119 
3120     // Turn off usual access checking for template specializations and
3121     // instantiations.
3122     bool IsTemplateSpecOrInst =
3123         (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3124          TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3125 
3126     switch (Tok.getKind()) {
3127     default:
3128     DoneWithDeclSpec:
3129       if (!AttrsLastTime)
3130         ProhibitAttributes(attrs);
3131       else {
3132         // Reject C++11 attributes that appertain to decl specifiers as
3133         // we don't support any C++11 attributes that appertain to decl
3134         // specifiers. This also conforms to what g++ 4.8 is doing.
3135         ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3136 
3137         DS.takeAttributesFrom(attrs);
3138       }
3139 
3140       // If this is not a declaration specifier token, we're done reading decl
3141       // specifiers.  First verify that DeclSpec's are consistent.
3142       DS.Finish(Actions, Policy);
3143       return;
3144 
3145     case tok::l_square:
3146     case tok::kw_alignas:
3147       if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3148         goto DoneWithDeclSpec;
3149 
3150       ProhibitAttributes(attrs);
3151       // FIXME: It would be good to recover by accepting the attributes,
3152       //        but attempting to do that now would cause serious
3153       //        madness in terms of diagnostics.
3154       attrs.clear();
3155       attrs.Range = SourceRange();
3156 
3157       ParseCXX11Attributes(attrs);
3158       AttrsLastTime = true;
3159       continue;
3160 
3161     case tok::code_completion: {
3162       Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3163       if (DS.hasTypeSpecifier()) {
3164         bool AllowNonIdentifiers
3165           = (getCurScope()->getFlags() & (Scope::ControlScope |
3166                                           Scope::BlockScope |
3167                                           Scope::TemplateParamScope |
3168                                           Scope::FunctionPrototypeScope |
3169                                           Scope::AtCatchScope)) == 0;
3170         bool AllowNestedNameSpecifiers
3171           = DSContext == DeclSpecContext::DSC_top_level ||
3172             (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3173 
3174         cutOffParsing();
3175         Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3176                                      AllowNonIdentifiers,
3177                                      AllowNestedNameSpecifiers);
3178         return;
3179       }
3180 
3181       if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3182         CCC = Sema::PCC_LocalDeclarationSpecifiers;
3183       else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3184         CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3185                                                       : Sema::PCC_Template;
3186       else if (DSContext == DeclSpecContext::DSC_class)
3187         CCC = Sema::PCC_Class;
3188       else if (CurParsedObjCImpl)
3189         CCC = Sema::PCC_ObjCImplementation;
3190 
3191       cutOffParsing();
3192       Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3193       return;
3194     }
3195 
3196     case tok::coloncolon: // ::foo::bar
3197       // C++ scope specifier.  Annotate and loop, or bail out on error.
3198       if (TryAnnotateCXXScopeToken(EnteringContext)) {
3199         if (!DS.hasTypeSpecifier())
3200           DS.SetTypeSpecError();
3201         goto DoneWithDeclSpec;
3202       }
3203       if (Tok.is(tok::coloncolon)) // ::new or ::delete
3204         goto DoneWithDeclSpec;
3205       continue;
3206 
3207     case tok::annot_cxxscope: {
3208       if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3209         goto DoneWithDeclSpec;
3210 
3211       CXXScopeSpec SS;
3212       Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3213                                                    Tok.getAnnotationRange(),
3214                                                    SS);
3215 
3216       // We are looking for a qualified typename.
3217       Token Next = NextToken();
3218 
3219       TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3220                                              ? takeTemplateIdAnnotation(Next)
3221                                              : nullptr;
3222       if (TemplateId && TemplateId->hasInvalidName()) {
3223         // We found something like 'T::U<Args> x', but U is not a template.
3224         // Assume it was supposed to be a type.
3225         DS.SetTypeSpecError();
3226         ConsumeAnnotationToken();
3227         break;
3228       }
3229 
3230       if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3231         // We have a qualified template-id, e.g., N::A<int>
3232 
3233         // If this would be a valid constructor declaration with template
3234         // arguments, we will reject the attempt to form an invalid type-id
3235         // referring to the injected-class-name when we annotate the token,
3236         // per C++ [class.qual]p2.
3237         //
3238         // To improve diagnostics for this case, parse the declaration as a
3239         // constructor (and reject the extra template arguments later).
3240         if ((DSContext == DeclSpecContext::DSC_top_level ||
3241              DSContext == DeclSpecContext::DSC_class) &&
3242             TemplateId->Name &&
3243             Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3244             isConstructorDeclarator(/*Unqualified=*/false)) {
3245           // The user meant this to be an out-of-line constructor
3246           // definition, but template arguments are not allowed
3247           // there.  Just allow this as a constructor; we'll
3248           // complain about it later.
3249           goto DoneWithDeclSpec;
3250         }
3251 
3252         DS.getTypeSpecScope() = SS;
3253         ConsumeAnnotationToken(); // The C++ scope.
3254         assert(Tok.is(tok::annot_template_id) &&
3255                "ParseOptionalCXXScopeSpecifier not working");
3256         AnnotateTemplateIdTokenAsType(SS);
3257         continue;
3258       }
3259 
3260       if (TemplateId && TemplateId->Kind == TNK_Concept_template &&
3261           GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3262         DS.getTypeSpecScope() = SS;
3263         // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3264         // Consume the scope annotation and continue to consume the template-id
3265         // as a placeholder-specifier.
3266         ConsumeAnnotationToken();
3267         continue;
3268       }
3269 
3270       if (Next.is(tok::annot_typename)) {
3271         DS.getTypeSpecScope() = SS;
3272         ConsumeAnnotationToken(); // The C++ scope.
3273         TypeResult T = getTypeAnnotation(Tok);
3274         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3275                                        Tok.getAnnotationEndLoc(),
3276                                        PrevSpec, DiagID, T, Policy);
3277         if (isInvalid)
3278           break;
3279         DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3280         ConsumeAnnotationToken(); // The typename
3281       }
3282 
3283       if (Next.isNot(tok::identifier))
3284         goto DoneWithDeclSpec;
3285 
3286       // Check whether this is a constructor declaration. If we're in a
3287       // context where the identifier could be a class name, and it has the
3288       // shape of a constructor declaration, process it as one.
3289       if ((DSContext == DeclSpecContext::DSC_top_level ||
3290            DSContext == DeclSpecContext::DSC_class) &&
3291           Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3292                                      &SS) &&
3293           isConstructorDeclarator(/*Unqualified*/ false))
3294         goto DoneWithDeclSpec;
3295 
3296       // C++20 [temp.spec] 13.9/6.
3297       // This disables the access checking rules for function template explicit
3298       // instantiation and explicit specialization:
3299       // - `return type`.
3300       SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3301 
3302       ParsedType TypeRep =
3303           Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3304                               getCurScope(), &SS, false, false, nullptr,
3305                               /*IsCtorOrDtorName=*/false,
3306                               /*WantNontrivialTypeSourceInfo=*/true,
3307                               isClassTemplateDeductionContext(DSContext));
3308 
3309       if (IsTemplateSpecOrInst)
3310         SAC.done();
3311 
3312       // If the referenced identifier is not a type, then this declspec is
3313       // erroneous: We already checked about that it has no type specifier, and
3314       // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
3315       // typename.
3316       if (!TypeRep) {
3317         if (TryAnnotateTypeConstraint())
3318           goto DoneWithDeclSpec;
3319         if (Tok.isNot(tok::annot_cxxscope) ||
3320             NextToken().isNot(tok::identifier))
3321           continue;
3322         // Eat the scope spec so the identifier is current.
3323         ConsumeAnnotationToken();
3324         ParsedAttributesWithRange Attrs(AttrFactory);
3325         if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3326           if (!Attrs.empty()) {
3327             AttrsLastTime = true;
3328             attrs.takeAllFrom(Attrs);
3329           }
3330           continue;
3331         }
3332         goto DoneWithDeclSpec;
3333       }
3334 
3335       DS.getTypeSpecScope() = SS;
3336       ConsumeAnnotationToken(); // The C++ scope.
3337 
3338       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3339                                      DiagID, TypeRep, Policy);
3340       if (isInvalid)
3341         break;
3342 
3343       DS.SetRangeEnd(Tok.getLocation());
3344       ConsumeToken(); // The typename.
3345 
3346       continue;
3347     }
3348 
3349     case tok::annot_typename: {
3350       // If we've previously seen a tag definition, we were almost surely
3351       // missing a semicolon after it.
3352       if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3353         goto DoneWithDeclSpec;
3354 
3355       TypeResult T = getTypeAnnotation(Tok);
3356       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3357                                      DiagID, T, Policy);
3358       if (isInvalid)
3359         break;
3360 
3361       DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3362       ConsumeAnnotationToken(); // The typename
3363 
3364       continue;
3365     }
3366 
3367     case tok::kw___is_signed:
3368       // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3369       // typically treats it as a trait. If we see __is_signed as it appears
3370       // in libstdc++, e.g.,
3371       //
3372       //   static const bool __is_signed;
3373       //
3374       // then treat __is_signed as an identifier rather than as a keyword.
3375       if (DS.getTypeSpecType() == TST_bool &&
3376           DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3377           DS.getStorageClassSpec() == DeclSpec::SCS_static)
3378         TryKeywordIdentFallback(true);
3379 
3380       // We're done with the declaration-specifiers.
3381       goto DoneWithDeclSpec;
3382 
3383       // typedef-name
3384     case tok::kw___super:
3385     case tok::kw_decltype:
3386     case tok::identifier: {
3387       // This identifier can only be a typedef name if we haven't already seen
3388       // a type-specifier.  Without this check we misparse:
3389       //  typedef int X; struct Y { short X; };  as 'short int'.
3390       if (DS.hasTypeSpecifier())
3391         goto DoneWithDeclSpec;
3392 
3393       // If the token is an identifier named "__declspec" and Microsoft
3394       // extensions are not enabled, it is likely that there will be cascading
3395       // parse errors if this really is a __declspec attribute. Attempt to
3396       // recognize that scenario and recover gracefully.
3397       if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3398           Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3399         Diag(Loc, diag::err_ms_attributes_not_enabled);
3400 
3401         // The next token should be an open paren. If it is, eat the entire
3402         // attribute declaration and continue.
3403         if (NextToken().is(tok::l_paren)) {
3404           // Consume the __declspec identifier.
3405           ConsumeToken();
3406 
3407           // Eat the parens and everything between them.
3408           BalancedDelimiterTracker T(*this, tok::l_paren);
3409           if (T.consumeOpen()) {
3410             assert(false && "Not a left paren?");
3411             return;
3412           }
3413           T.skipToEnd();
3414           continue;
3415         }
3416       }
3417 
3418       // In C++, check to see if this is a scope specifier like foo::bar::, if
3419       // so handle it as such.  This is important for ctor parsing.
3420       if (getLangOpts().CPlusPlus) {
3421         // C++20 [temp.spec] 13.9/6.
3422         // This disables the access checking rules for function template
3423         // explicit instantiation and explicit specialization:
3424         // - `return type`.
3425         SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3426 
3427         const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3428 
3429         if (IsTemplateSpecOrInst)
3430           SAC.done();
3431 
3432         if (Success) {
3433           if (IsTemplateSpecOrInst)
3434             SAC.redelay();
3435           DS.SetTypeSpecError();
3436           goto DoneWithDeclSpec;
3437         }
3438 
3439         if (!Tok.is(tok::identifier))
3440           continue;
3441       }
3442 
3443       // Check for need to substitute AltiVec keyword tokens.
3444       if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3445         break;
3446 
3447       // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3448       //                allow the use of a typedef name as a type specifier.
3449       if (DS.isTypeAltiVecVector())
3450         goto DoneWithDeclSpec;
3451 
3452       if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3453           isObjCInstancetype()) {
3454         ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3455         assert(TypeRep);
3456         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3457                                        DiagID, TypeRep, Policy);
3458         if (isInvalid)
3459           break;
3460 
3461         DS.SetRangeEnd(Loc);
3462         ConsumeToken();
3463         continue;
3464       }
3465 
3466       // If we're in a context where the identifier could be a class name,
3467       // check whether this is a constructor declaration.
3468       if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3469           Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3470           isConstructorDeclarator(/*Unqualified*/true))
3471         goto DoneWithDeclSpec;
3472 
3473       ParsedType TypeRep = Actions.getTypeName(
3474           *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3475           false, false, nullptr, false, false,
3476           isClassTemplateDeductionContext(DSContext));
3477 
3478       // If this is not a typedef name, don't parse it as part of the declspec,
3479       // it must be an implicit int or an error.
3480       if (!TypeRep) {
3481         if (TryAnnotateTypeConstraint())
3482           goto DoneWithDeclSpec;
3483         if (Tok.isNot(tok::identifier))
3484           continue;
3485         ParsedAttributesWithRange Attrs(AttrFactory);
3486         if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3487           if (!Attrs.empty()) {
3488             AttrsLastTime = true;
3489             attrs.takeAllFrom(Attrs);
3490           }
3491           continue;
3492         }
3493         goto DoneWithDeclSpec;
3494       }
3495 
3496       // Likewise, if this is a context where the identifier could be a template
3497       // name, check whether this is a deduction guide declaration.
3498       if (getLangOpts().CPlusPlus17 &&
3499           (DSContext == DeclSpecContext::DSC_class ||
3500            DSContext == DeclSpecContext::DSC_top_level) &&
3501           Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3502                                        Tok.getLocation()) &&
3503           isConstructorDeclarator(/*Unqualified*/ true,
3504                                   /*DeductionGuide*/ true))
3505         goto DoneWithDeclSpec;
3506 
3507       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3508                                      DiagID, TypeRep, Policy);
3509       if (isInvalid)
3510         break;
3511 
3512       DS.SetRangeEnd(Tok.getLocation());
3513       ConsumeToken(); // The identifier
3514 
3515       // Objective-C supports type arguments and protocol references
3516       // following an Objective-C object or object pointer
3517       // type. Handle either one of them.
3518       if (Tok.is(tok::less) && getLangOpts().ObjC) {
3519         SourceLocation NewEndLoc;
3520         TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3521                                   Loc, TypeRep, /*consumeLastToken=*/true,
3522                                   NewEndLoc);
3523         if (NewTypeRep.isUsable()) {
3524           DS.UpdateTypeRep(NewTypeRep.get());
3525           DS.SetRangeEnd(NewEndLoc);
3526         }
3527       }
3528 
3529       // Need to support trailing type qualifiers (e.g. "id<p> const").
3530       // If a type specifier follows, it will be diagnosed elsewhere.
3531       continue;
3532     }
3533 
3534       // type-name or placeholder-specifier
3535     case tok::annot_template_id: {
3536       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3537 
3538       if (TemplateId->hasInvalidName()) {
3539         DS.SetTypeSpecError();
3540         break;
3541       }
3542 
3543       if (TemplateId->Kind == TNK_Concept_template) {
3544         // If we've already diagnosed that this type-constraint has invalid
3545         // arguemnts, drop it and just form 'auto' or 'decltype(auto)'.
3546         if (TemplateId->hasInvalidArgs())
3547           TemplateId = nullptr;
3548 
3549         if (NextToken().is(tok::identifier)) {
3550           Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3551               << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3552           // Attempt to continue as if 'auto' was placed here.
3553           isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3554                                          TemplateId, Policy);
3555           break;
3556         }
3557         if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3558             goto DoneWithDeclSpec;
3559         ConsumeAnnotationToken();
3560         SourceLocation AutoLoc = Tok.getLocation();
3561         if (TryConsumeToken(tok::kw_decltype)) {
3562           BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3563           if (Tracker.consumeOpen()) {
3564             // Something like `void foo(Iterator decltype i)`
3565             Diag(Tok, diag::err_expected) << tok::l_paren;
3566           } else {
3567             if (!TryConsumeToken(tok::kw_auto)) {
3568               // Something like `void foo(Iterator decltype(int) i)`
3569               Tracker.skipToEnd();
3570               Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3571                 << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3572                                                             Tok.getLocation()),
3573                                                 "auto");
3574             } else {
3575               Tracker.consumeClose();
3576             }
3577           }
3578           ConsumedEnd = Tok.getLocation();
3579           DS.setTypeofParensRange(Tracker.getRange());
3580           // Even if something went wrong above, continue as if we've seen
3581           // `decltype(auto)`.
3582           isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3583                                          DiagID, TemplateId, Policy);
3584         } else {
3585           isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
3586                                          TemplateId, Policy);
3587         }
3588         break;
3589       }
3590 
3591       if (TemplateId->Kind != TNK_Type_template &&
3592           TemplateId->Kind != TNK_Undeclared_template) {
3593         // This template-id does not refer to a type name, so we're
3594         // done with the type-specifiers.
3595         goto DoneWithDeclSpec;
3596       }
3597 
3598       // If we're in a context where the template-id could be a
3599       // constructor name or specialization, check whether this is a
3600       // constructor declaration.
3601       if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3602           Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3603           isConstructorDeclarator(/*Unqualified=*/true))
3604         goto DoneWithDeclSpec;
3605 
3606       // Turn the template-id annotation token into a type annotation
3607       // token, then try again to parse it as a type-specifier.
3608       CXXScopeSpec SS;
3609       AnnotateTemplateIdTokenAsType(SS);
3610       continue;
3611     }
3612 
3613     // Attributes support.
3614     case tok::kw___attribute:
3615     case tok::kw___declspec:
3616       ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), nullptr,
3617                       LateAttrs);
3618       continue;
3619 
3620     // Microsoft single token adornments.
3621     case tok::kw___forceinline: {
3622       isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3623       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3624       SourceLocation AttrNameLoc = Tok.getLocation();
3625       DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3626                                 nullptr, 0, ParsedAttr::AS_Keyword);
3627       break;
3628     }
3629 
3630     case tok::kw___unaligned:
3631       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3632                                  getLangOpts());
3633       break;
3634 
3635     case tok::kw___sptr:
3636     case tok::kw___uptr:
3637     case tok::kw___ptr64:
3638     case tok::kw___ptr32:
3639     case tok::kw___w64:
3640     case tok::kw___cdecl:
3641     case tok::kw___stdcall:
3642     case tok::kw___fastcall:
3643     case tok::kw___thiscall:
3644     case tok::kw___regcall:
3645     case tok::kw___vectorcall:
3646       ParseMicrosoftTypeAttributes(DS.getAttributes());
3647       continue;
3648 
3649     // Borland single token adornments.
3650     case tok::kw___pascal:
3651       ParseBorlandTypeAttributes(DS.getAttributes());
3652       continue;
3653 
3654     // OpenCL single token adornments.
3655     case tok::kw___kernel:
3656       ParseOpenCLKernelAttributes(DS.getAttributes());
3657       continue;
3658 
3659     // Nullability type specifiers.
3660     case tok::kw__Nonnull:
3661     case tok::kw__Nullable:
3662     case tok::kw__Nullable_result:
3663     case tok::kw__Null_unspecified:
3664       ParseNullabilityTypeSpecifiers(DS.getAttributes());
3665       continue;
3666 
3667     // Objective-C 'kindof' types.
3668     case tok::kw___kindof:
3669       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3670                                 nullptr, 0, ParsedAttr::AS_Keyword);
3671       (void)ConsumeToken();
3672       continue;
3673 
3674     // storage-class-specifier
3675     case tok::kw_typedef:
3676       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3677                                          PrevSpec, DiagID, Policy);
3678       isStorageClass = true;
3679       break;
3680     case tok::kw_extern:
3681       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3682         Diag(Tok, diag::ext_thread_before) << "extern";
3683       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3684                                          PrevSpec, DiagID, Policy);
3685       isStorageClass = true;
3686       break;
3687     case tok::kw___private_extern__:
3688       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3689                                          Loc, PrevSpec, DiagID, Policy);
3690       isStorageClass = true;
3691       break;
3692     case tok::kw_static:
3693       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3694         Diag(Tok, diag::ext_thread_before) << "static";
3695       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3696                                          PrevSpec, DiagID, Policy);
3697       isStorageClass = true;
3698       break;
3699     case tok::kw_auto:
3700       if (getLangOpts().CPlusPlus11) {
3701         if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3702           isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3703                                              PrevSpec, DiagID, Policy);
3704           if (!isInvalid)
3705             Diag(Tok, diag::ext_auto_storage_class)
3706               << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3707         } else
3708           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3709                                          DiagID, Policy);
3710       } else
3711         isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3712                                            PrevSpec, DiagID, Policy);
3713       isStorageClass = true;
3714       break;
3715     case tok::kw___auto_type:
3716       Diag(Tok, diag::ext_auto_type);
3717       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3718                                      DiagID, Policy);
3719       break;
3720     case tok::kw_register:
3721       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3722                                          PrevSpec, DiagID, Policy);
3723       isStorageClass = true;
3724       break;
3725     case tok::kw_mutable:
3726       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3727                                          PrevSpec, DiagID, Policy);
3728       isStorageClass = true;
3729       break;
3730     case tok::kw___thread:
3731       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3732                                                PrevSpec, DiagID);
3733       isStorageClass = true;
3734       break;
3735     case tok::kw_thread_local:
3736       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3737                                                PrevSpec, DiagID);
3738       isStorageClass = true;
3739       break;
3740     case tok::kw__Thread_local:
3741       if (!getLangOpts().C11)
3742         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3743       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3744                                                Loc, PrevSpec, DiagID);
3745       isStorageClass = true;
3746       break;
3747 
3748     // function-specifier
3749     case tok::kw_inline:
3750       isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3751       break;
3752     case tok::kw_virtual:
3753       // C++ for OpenCL does not allow virtual function qualifier, to avoid
3754       // function pointers restricted in OpenCL v2.0 s6.9.a.
3755       if (getLangOpts().OpenCLCPlusPlus &&
3756           !getActions().getOpenCLOptions().isAvailableOption(
3757               "__cl_clang_function_pointers", getLangOpts())) {
3758         DiagID = diag::err_openclcxx_virtual_function;
3759         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3760         isInvalid = true;
3761       } else {
3762         isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3763       }
3764       break;
3765     case tok::kw_explicit: {
3766       SourceLocation ExplicitLoc = Loc;
3767       SourceLocation CloseParenLoc;
3768       ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3769       ConsumedEnd = ExplicitLoc;
3770       ConsumeToken(); // kw_explicit
3771       if (Tok.is(tok::l_paren)) {
3772         if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
3773           Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
3774                                       ? diag::warn_cxx17_compat_explicit_bool
3775                                       : diag::ext_explicit_bool);
3776 
3777           ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3778           BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3779           Tracker.consumeOpen();
3780           ExplicitExpr = ParseConstantExpression();
3781           ConsumedEnd = Tok.getLocation();
3782           if (ExplicitExpr.isUsable()) {
3783             CloseParenLoc = Tok.getLocation();
3784             Tracker.consumeClose();
3785             ExplicitSpec =
3786                 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3787           } else
3788             Tracker.skipToEnd();
3789         } else {
3790           Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
3791         }
3792       }
3793       isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3794                                              ExplicitSpec, CloseParenLoc);
3795       break;
3796     }
3797     case tok::kw__Noreturn:
3798       if (!getLangOpts().C11)
3799         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3800       isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3801       break;
3802 
3803     // alignment-specifier
3804     case tok::kw__Alignas:
3805       if (!getLangOpts().C11)
3806         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3807       ParseAlignmentSpecifier(DS.getAttributes());
3808       continue;
3809 
3810     // friend
3811     case tok::kw_friend:
3812       if (DSContext == DeclSpecContext::DSC_class)
3813         isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3814       else {
3815         PrevSpec = ""; // not actually used by the diagnostic
3816         DiagID = diag::err_friend_invalid_in_context;
3817         isInvalid = true;
3818       }
3819       break;
3820 
3821     // Modules
3822     case tok::kw___module_private__:
3823       isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3824       break;
3825 
3826     // constexpr, consteval, constinit specifiers
3827     case tok::kw_constexpr:
3828       isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
3829                                       PrevSpec, DiagID);
3830       break;
3831     case tok::kw_consteval:
3832       isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
3833                                       PrevSpec, DiagID);
3834       break;
3835     case tok::kw_constinit:
3836       isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constinit, Loc,
3837                                       PrevSpec, DiagID);
3838       break;
3839 
3840     // type-specifier
3841     case tok::kw_short:
3842       isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec,
3843                                       DiagID, Policy);
3844       break;
3845     case tok::kw_long:
3846       if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
3847         isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec,
3848                                         DiagID, Policy);
3849       else
3850         isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
3851                                         PrevSpec, DiagID, Policy);
3852       break;
3853     case tok::kw___int64:
3854       isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
3855                                       PrevSpec, DiagID, Policy);
3856       break;
3857     case tok::kw_signed:
3858       isInvalid =
3859           DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
3860       break;
3861     case tok::kw_unsigned:
3862       isInvalid = DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec,
3863                                      DiagID);
3864       break;
3865     case tok::kw__Complex:
3866       if (!getLangOpts().C99)
3867         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3868       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3869                                         DiagID);
3870       break;
3871     case tok::kw__Imaginary:
3872       if (!getLangOpts().C99)
3873         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3874       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3875                                         DiagID);
3876       break;
3877     case tok::kw_void:
3878       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3879                                      DiagID, Policy);
3880       break;
3881     case tok::kw_char:
3882       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3883                                      DiagID, Policy);
3884       break;
3885     case tok::kw_int:
3886       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3887                                      DiagID, Policy);
3888       break;
3889     case tok::kw__ExtInt:
3890     case tok::kw__BitInt: {
3891       DiagnoseBitIntUse(Tok);
3892       ExprResult ER = ParseExtIntegerArgument();
3893       if (ER.isInvalid())
3894         continue;
3895       isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
3896       ConsumedEnd = PrevTokLocation;
3897       break;
3898     }
3899     case tok::kw___int128:
3900       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3901                                      DiagID, Policy);
3902       break;
3903     case tok::kw_half:
3904       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3905                                      DiagID, Policy);
3906       break;
3907     case tok::kw___bf16:
3908       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
3909                                      DiagID, Policy);
3910       break;
3911     case tok::kw_float:
3912       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3913                                      DiagID, Policy);
3914       break;
3915     case tok::kw_double:
3916       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3917                                      DiagID, Policy);
3918       break;
3919     case tok::kw__Float16:
3920       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3921                                      DiagID, Policy);
3922       break;
3923     case tok::kw__Accum:
3924       if (!getLangOpts().FixedPoint) {
3925         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3926       } else {
3927         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3928                                        DiagID, Policy);
3929       }
3930       break;
3931     case tok::kw__Fract:
3932       if (!getLangOpts().FixedPoint) {
3933         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3934       } else {
3935         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3936                                        DiagID, Policy);
3937       }
3938       break;
3939     case tok::kw__Sat:
3940       if (!getLangOpts().FixedPoint) {
3941         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3942       } else {
3943         isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3944       }
3945       break;
3946     case tok::kw___float128:
3947       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3948                                      DiagID, Policy);
3949       break;
3950     case tok::kw___ibm128:
3951       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec,
3952                                      DiagID, Policy);
3953       break;
3954     case tok::kw_wchar_t:
3955       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3956                                      DiagID, Policy);
3957       break;
3958     case tok::kw_char8_t:
3959       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3960                                      DiagID, Policy);
3961       break;
3962     case tok::kw_char16_t:
3963       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3964                                      DiagID, Policy);
3965       break;
3966     case tok::kw_char32_t:
3967       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3968                                      DiagID, Policy);
3969       break;
3970     case tok::kw_bool:
3971     case tok::kw__Bool:
3972       if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
3973         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3974 
3975       if (Tok.is(tok::kw_bool) &&
3976           DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3977           DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3978         PrevSpec = ""; // Not used by the diagnostic.
3979         DiagID = diag::err_bool_redeclaration;
3980         // For better error recovery.
3981         Tok.setKind(tok::identifier);
3982         isInvalid = true;
3983       } else {
3984         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3985                                        DiagID, Policy);
3986       }
3987       break;
3988     case tok::kw__Decimal32:
3989       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3990                                      DiagID, Policy);
3991       break;
3992     case tok::kw__Decimal64:
3993       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3994                                      DiagID, Policy);
3995       break;
3996     case tok::kw__Decimal128:
3997       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3998                                      DiagID, Policy);
3999       break;
4000     case tok::kw___vector:
4001       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4002       break;
4003     case tok::kw___pixel:
4004       isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4005       break;
4006     case tok::kw___bool:
4007       isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4008       break;
4009     case tok::kw_pipe:
4010       if (!getLangOpts().OpenCL ||
4011           getLangOpts().getOpenCLCompatibleVersion() < 200) {
4012         // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4013         // should support the "pipe" word as identifier.
4014         Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
4015         Tok.setKind(tok::identifier);
4016         goto DoneWithDeclSpec;
4017       } else if (!getLangOpts().OpenCLPipes) {
4018         DiagID = diag::err_opencl_unknown_type_specifier;
4019         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4020         isInvalid = true;
4021       } else
4022         isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4023       break;
4024 // We only need to enumerate each image type once.
4025 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4026 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
4027 #define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4028     case tok::kw_##ImgType##_t: \
4029       if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4030         goto DoneWithDeclSpec; \
4031       break;
4032 #include "clang/Basic/OpenCLImageTypes.def"
4033     case tok::kw___unknown_anytype:
4034       isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
4035                                      PrevSpec, DiagID, Policy);
4036       break;
4037 
4038     // class-specifier:
4039     case tok::kw_class:
4040     case tok::kw_struct:
4041     case tok::kw___interface:
4042     case tok::kw_union: {
4043       tok::TokenKind Kind = Tok.getKind();
4044       ConsumeToken();
4045 
4046       // These are attributes following class specifiers.
4047       // To produce better diagnostic, we parse them when
4048       // parsing class specifier.
4049       ParsedAttributesWithRange Attributes(AttrFactory);
4050       ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4051                           EnteringContext, DSContext, Attributes);
4052 
4053       // If there are attributes following class specifier,
4054       // take them over and handle them here.
4055       if (!Attributes.empty()) {
4056         AttrsLastTime = true;
4057         attrs.takeAllFrom(Attributes);
4058       }
4059       continue;
4060     }
4061 
4062     // enum-specifier:
4063     case tok::kw_enum:
4064       ConsumeToken();
4065       ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4066       continue;
4067 
4068     // cv-qualifier:
4069     case tok::kw_const:
4070       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4071                                  getLangOpts());
4072       break;
4073     case tok::kw_volatile:
4074       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4075                                  getLangOpts());
4076       break;
4077     case tok::kw_restrict:
4078       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4079                                  getLangOpts());
4080       break;
4081 
4082     // C++ typename-specifier:
4083     case tok::kw_typename:
4084       if (TryAnnotateTypeOrScopeToken()) {
4085         DS.SetTypeSpecError();
4086         goto DoneWithDeclSpec;
4087       }
4088       if (!Tok.is(tok::kw_typename))
4089         continue;
4090       break;
4091 
4092     // GNU typeof support.
4093     case tok::kw_typeof:
4094       ParseTypeofSpecifier(DS);
4095       continue;
4096 
4097     case tok::annot_decltype:
4098       ParseDecltypeSpecifier(DS);
4099       continue;
4100 
4101     case tok::annot_pragma_pack:
4102       HandlePragmaPack();
4103       continue;
4104 
4105     case tok::annot_pragma_ms_pragma:
4106       HandlePragmaMSPragma();
4107       continue;
4108 
4109     case tok::annot_pragma_ms_vtordisp:
4110       HandlePragmaMSVtorDisp();
4111       continue;
4112 
4113     case tok::annot_pragma_ms_pointers_to_members:
4114       HandlePragmaMSPointersToMembers();
4115       continue;
4116 
4117     case tok::kw___underlying_type:
4118       ParseUnderlyingTypeSpecifier(DS);
4119       continue;
4120 
4121     case tok::kw__Atomic:
4122       // C11 6.7.2.4/4:
4123       //   If the _Atomic keyword is immediately followed by a left parenthesis,
4124       //   it is interpreted as a type specifier (with a type name), not as a
4125       //   type qualifier.
4126       if (!getLangOpts().C11)
4127         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4128 
4129       if (NextToken().is(tok::l_paren)) {
4130         ParseAtomicSpecifier(DS);
4131         continue;
4132       }
4133       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4134                                  getLangOpts());
4135       break;
4136 
4137     // OpenCL address space qualifiers:
4138     case tok::kw___generic:
4139       // generic address space is introduced only in OpenCL v2.0
4140       // see OpenCL C Spec v2.0 s6.5.5
4141       // OpenCL v3.0 introduces __opencl_c_generic_address_space
4142       // feature macro to indicate if generic address space is supported
4143       if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4144         DiagID = diag::err_opencl_unknown_type_specifier;
4145         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4146         isInvalid = true;
4147         break;
4148       }
4149       LLVM_FALLTHROUGH;
4150     case tok::kw_private:
4151       // It's fine (but redundant) to check this for __generic on the
4152       // fallthrough path; we only form the __generic token in OpenCL mode.
4153       if (!getLangOpts().OpenCL)
4154         goto DoneWithDeclSpec;
4155       LLVM_FALLTHROUGH;
4156     case tok::kw___private:
4157     case tok::kw___global:
4158     case tok::kw___local:
4159     case tok::kw___constant:
4160     // OpenCL access qualifiers:
4161     case tok::kw___read_only:
4162     case tok::kw___write_only:
4163     case tok::kw___read_write:
4164       ParseOpenCLQualifiers(DS.getAttributes());
4165       break;
4166 
4167     case tok::less:
4168       // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4169       // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
4170       // but we support it.
4171       if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4172         goto DoneWithDeclSpec;
4173 
4174       SourceLocation StartLoc = Tok.getLocation();
4175       SourceLocation EndLoc;
4176       TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4177       if (Type.isUsable()) {
4178         if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4179                                PrevSpec, DiagID, Type.get(),
4180                                Actions.getASTContext().getPrintingPolicy()))
4181           Diag(StartLoc, DiagID) << PrevSpec;
4182 
4183         DS.SetRangeEnd(EndLoc);
4184       } else {
4185         DS.SetTypeSpecError();
4186       }
4187 
4188       // Need to support trailing type qualifiers (e.g. "id<p> const").
4189       // If a type specifier follows, it will be diagnosed elsewhere.
4190       continue;
4191     }
4192 
4193     DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4194 
4195     // If the specifier wasn't legal, issue a diagnostic.
4196     if (isInvalid) {
4197       assert(PrevSpec && "Method did not return previous specifier!");
4198       assert(DiagID);
4199 
4200       if (DiagID == diag::ext_duplicate_declspec ||
4201           DiagID == diag::ext_warn_duplicate_declspec ||
4202           DiagID == diag::err_duplicate_declspec)
4203         Diag(Loc, DiagID) << PrevSpec
4204                           << FixItHint::CreateRemoval(
4205                                  SourceRange(Loc, DS.getEndLoc()));
4206       else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4207         Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4208                           << isStorageClass;
4209       } else
4210         Diag(Loc, DiagID) << PrevSpec;
4211     }
4212 
4213     if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4214       // After an error the next token can be an annotation token.
4215       ConsumeAnyToken();
4216 
4217     AttrsLastTime = false;
4218   }
4219 }
4220 
4221 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4222 /// semicolon.
4223 ///
4224 /// Note that a struct declaration refers to a declaration in a struct,
4225 /// not to the declaration of a struct.
4226 ///
4227 ///       struct-declaration:
4228 /// [C2x]   attributes-specifier-seq[opt]
4229 ///           specifier-qualifier-list struct-declarator-list
4230 /// [GNU]   __extension__ struct-declaration
4231 /// [GNU]   specifier-qualifier-list
4232 ///       struct-declarator-list:
4233 ///         struct-declarator
4234 ///         struct-declarator-list ',' struct-declarator
4235 /// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
4236 ///       struct-declarator:
4237 ///         declarator
4238 /// [GNU]   declarator attributes[opt]
4239 ///         declarator[opt] ':' constant-expression
4240 /// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
4241 ///
4242 void Parser::ParseStructDeclaration(
4243     ParsingDeclSpec &DS,
4244     llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4245 
4246   if (Tok.is(tok::kw___extension__)) {
4247     // __extension__ silences extension warnings in the subexpression.
4248     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
4249     ConsumeToken();
4250     return ParseStructDeclaration(DS, FieldsCallback);
4251   }
4252 
4253   // Parse leading attributes.
4254   ParsedAttributesWithRange Attrs(AttrFactory);
4255   MaybeParseCXX11Attributes(Attrs);
4256   DS.takeAttributesFrom(Attrs);
4257 
4258   // Parse the common specifier-qualifiers-list piece.
4259   ParseSpecifierQualifierList(DS);
4260 
4261   // If there are no declarators, this is a free-standing declaration
4262   // specifier. Let the actions module cope with it.
4263   if (Tok.is(tok::semi)) {
4264     RecordDecl *AnonRecord = nullptr;
4265     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4266                                                        DS, AnonRecord);
4267     assert(!AnonRecord && "Did not expect anonymous struct or union here");
4268     DS.complete(TheDecl);
4269     return;
4270   }
4271 
4272   // Read struct-declarators until we find the semicolon.
4273   bool FirstDeclarator = true;
4274   SourceLocation CommaLoc;
4275   while (true) {
4276     ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4277     DeclaratorInfo.D.setCommaLoc(CommaLoc);
4278 
4279     // Attributes are only allowed here on successive declarators.
4280     if (!FirstDeclarator) {
4281       // However, this does not apply for [[]] attributes (which could show up
4282       // before or after the __attribute__ attributes).
4283       DiagnoseAndSkipCXX11Attributes();
4284       MaybeParseGNUAttributes(DeclaratorInfo.D);
4285       DiagnoseAndSkipCXX11Attributes();
4286     }
4287 
4288     /// struct-declarator: declarator
4289     /// struct-declarator: declarator[opt] ':' constant-expression
4290     if (Tok.isNot(tok::colon)) {
4291       // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4292       ColonProtectionRAIIObject X(*this);
4293       ParseDeclarator(DeclaratorInfo.D);
4294     } else
4295       DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4296 
4297     if (TryConsumeToken(tok::colon)) {
4298       ExprResult Res(ParseConstantExpression());
4299       if (Res.isInvalid())
4300         SkipUntil(tok::semi, StopBeforeMatch);
4301       else
4302         DeclaratorInfo.BitfieldSize = Res.get();
4303     }
4304 
4305     // If attributes exist after the declarator, parse them.
4306     MaybeParseGNUAttributes(DeclaratorInfo.D);
4307 
4308     // We're done with this declarator;  invoke the callback.
4309     FieldsCallback(DeclaratorInfo);
4310 
4311     // If we don't have a comma, it is either the end of the list (a ';')
4312     // or an error, bail out.
4313     if (!TryConsumeToken(tok::comma, CommaLoc))
4314       return;
4315 
4316     FirstDeclarator = false;
4317   }
4318 }
4319 
4320 /// ParseStructUnionBody
4321 ///       struct-contents:
4322 ///         struct-declaration-list
4323 /// [EXT]   empty
4324 /// [GNU]   "struct-declaration-list" without terminating ';'
4325 ///       struct-declaration-list:
4326 ///         struct-declaration
4327 ///         struct-declaration-list struct-declaration
4328 /// [OBC]   '@' 'defs' '(' class-name ')'
4329 ///
4330 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4331                                   DeclSpec::TST TagType, RecordDecl *TagDecl) {
4332   PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4333                                       "parsing struct/union body");
4334   assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4335 
4336   BalancedDelimiterTracker T(*this, tok::l_brace);
4337   if (T.consumeOpen())
4338     return;
4339 
4340   ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4341   Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4342 
4343   // While we still have something to read, read the declarations in the struct.
4344   while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4345          Tok.isNot(tok::eof)) {
4346     // Each iteration of this loop reads one struct-declaration.
4347 
4348     // Check for extraneous top-level semicolon.
4349     if (Tok.is(tok::semi)) {
4350       ConsumeExtraSemi(InsideStruct, TagType);
4351       continue;
4352     }
4353 
4354     // Parse _Static_assert declaration.
4355     if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4356       SourceLocation DeclEnd;
4357       ParseStaticAssertDeclaration(DeclEnd);
4358       continue;
4359     }
4360 
4361     if (Tok.is(tok::annot_pragma_pack)) {
4362       HandlePragmaPack();
4363       continue;
4364     }
4365 
4366     if (Tok.is(tok::annot_pragma_align)) {
4367       HandlePragmaAlign();
4368       continue;
4369     }
4370 
4371     if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4372       // Result can be ignored, because it must be always empty.
4373       AccessSpecifier AS = AS_none;
4374       ParsedAttributesWithRange Attrs(AttrFactory);
4375       (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4376       continue;
4377     }
4378 
4379     if (tok::isPragmaAnnotation(Tok.getKind())) {
4380       Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4381           << DeclSpec::getSpecifierName(
4382                  TagType, Actions.getASTContext().getPrintingPolicy());
4383       ConsumeAnnotationToken();
4384       continue;
4385     }
4386 
4387     if (!Tok.is(tok::at)) {
4388       auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4389         // Install the declarator into the current TagDecl.
4390         Decl *Field =
4391             Actions.ActOnField(getCurScope(), TagDecl,
4392                                FD.D.getDeclSpec().getSourceRange().getBegin(),
4393                                FD.D, FD.BitfieldSize);
4394         FD.complete(Field);
4395       };
4396 
4397       // Parse all the comma separated declarators.
4398       ParsingDeclSpec DS(*this);
4399       ParseStructDeclaration(DS, CFieldCallback);
4400     } else { // Handle @defs
4401       ConsumeToken();
4402       if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4403         Diag(Tok, diag::err_unexpected_at);
4404         SkipUntil(tok::semi);
4405         continue;
4406       }
4407       ConsumeToken();
4408       ExpectAndConsume(tok::l_paren);
4409       if (!Tok.is(tok::identifier)) {
4410         Diag(Tok, diag::err_expected) << tok::identifier;
4411         SkipUntil(tok::semi);
4412         continue;
4413       }
4414       SmallVector<Decl *, 16> Fields;
4415       Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4416                         Tok.getIdentifierInfo(), Fields);
4417       ConsumeToken();
4418       ExpectAndConsume(tok::r_paren);
4419     }
4420 
4421     if (TryConsumeToken(tok::semi))
4422       continue;
4423 
4424     if (Tok.is(tok::r_brace)) {
4425       ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4426       break;
4427     }
4428 
4429     ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4430     // Skip to end of block or statement to avoid ext-warning on extra ';'.
4431     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4432     // If we stopped at a ';', eat it.
4433     TryConsumeToken(tok::semi);
4434   }
4435 
4436   T.consumeClose();
4437 
4438   ParsedAttributes attrs(AttrFactory);
4439   // If attributes exist after struct contents, parse them.
4440   MaybeParseGNUAttributes(attrs);
4441 
4442   SmallVector<Decl *, 32> FieldDecls(TagDecl->field_begin(),
4443                                      TagDecl->field_end());
4444 
4445   Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4446                       T.getOpenLocation(), T.getCloseLocation(), attrs);
4447   StructScope.Exit();
4448   Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4449 }
4450 
4451 /// ParseEnumSpecifier
4452 ///       enum-specifier: [C99 6.7.2.2]
4453 ///         'enum' identifier[opt] '{' enumerator-list '}'
4454 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4455 /// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4456 ///                                                 '}' attributes[opt]
4457 /// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4458 ///                                                 '}'
4459 ///         'enum' identifier
4460 /// [GNU]   'enum' attributes[opt] identifier
4461 ///
4462 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4463 /// [C++11] enum-head '{' enumerator-list ','  '}'
4464 ///
4465 ///       enum-head: [C++11]
4466 ///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4467 ///         enum-key attribute-specifier-seq[opt] nested-name-specifier
4468 ///             identifier enum-base[opt]
4469 ///
4470 ///       enum-key: [C++11]
4471 ///         'enum'
4472 ///         'enum' 'class'
4473 ///         'enum' 'struct'
4474 ///
4475 ///       enum-base: [C++11]
4476 ///         ':' type-specifier-seq
4477 ///
4478 /// [C++] elaborated-type-specifier:
4479 /// [C++]   'enum' nested-name-specifier[opt] identifier
4480 ///
4481 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4482                                 const ParsedTemplateInfo &TemplateInfo,
4483                                 AccessSpecifier AS, DeclSpecContext DSC) {
4484   // Parse the tag portion of this.
4485   if (Tok.is(tok::code_completion)) {
4486     // Code completion for an enum name.
4487     cutOffParsing();
4488     Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4489     return;
4490   }
4491 
4492   // If attributes exist after tag, parse them.
4493   ParsedAttributesWithRange attrs(AttrFactory);
4494   MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4495 
4496   SourceLocation ScopedEnumKWLoc;
4497   bool IsScopedUsingClassTag = false;
4498 
4499   // In C++11, recognize 'enum class' and 'enum struct'.
4500   if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4501     Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4502                                         : diag::ext_scoped_enum);
4503     IsScopedUsingClassTag = Tok.is(tok::kw_class);
4504     ScopedEnumKWLoc = ConsumeToken();
4505 
4506     // Attributes are not allowed between these keywords.  Diagnose,
4507     // but then just treat them like they appeared in the right place.
4508     ProhibitAttributes(attrs);
4509 
4510     // They are allowed afterwards, though.
4511     MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4512   }
4513 
4514   // C++11 [temp.explicit]p12:
4515   //   The usual access controls do not apply to names used to specify
4516   //   explicit instantiations.
4517   // We extend this to also cover explicit specializations.  Note that
4518   // we don't suppress if this turns out to be an elaborated type
4519   // specifier.
4520   bool shouldDelayDiagsInTag =
4521     (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4522      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4523   SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4524 
4525   // Determine whether this declaration is permitted to have an enum-base.
4526   AllowDefiningTypeSpec AllowEnumSpecifier =
4527       isDefiningTypeSpecifierContext(DSC);
4528   bool CanBeOpaqueEnumDeclaration =
4529       DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
4530   bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
4531                           getLangOpts().MicrosoftExt) &&
4532                          (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4533                           CanBeOpaqueEnumDeclaration);
4534 
4535   CXXScopeSpec &SS = DS.getTypeSpecScope();
4536   if (getLangOpts().CPlusPlus) {
4537     // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4538     ColonProtectionRAIIObject X(*this);
4539 
4540     CXXScopeSpec Spec;
4541     if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4542                                        /*ObjectHasErrors=*/false,
4543                                        /*EnteringContext=*/true))
4544       return;
4545 
4546     if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4547       Diag(Tok, diag::err_expected) << tok::identifier;
4548       if (Tok.isNot(tok::l_brace)) {
4549         // Has no name and is not a definition.
4550         // Skip the rest of this declarator, up until the comma or semicolon.
4551         SkipUntil(tok::comma, StopAtSemi);
4552         return;
4553       }
4554     }
4555 
4556     SS = Spec;
4557   }
4558 
4559   // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4560   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4561       Tok.isNot(tok::colon)) {
4562     Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4563 
4564     // Skip the rest of this declarator, up until the comma or semicolon.
4565     SkipUntil(tok::comma, StopAtSemi);
4566     return;
4567   }
4568 
4569   // If an identifier is present, consume and remember it.
4570   IdentifierInfo *Name = nullptr;
4571   SourceLocation NameLoc;
4572   if (Tok.is(tok::identifier)) {
4573     Name = Tok.getIdentifierInfo();
4574     NameLoc = ConsumeToken();
4575   }
4576 
4577   if (!Name && ScopedEnumKWLoc.isValid()) {
4578     // C++0x 7.2p2: The optional identifier shall not be omitted in the
4579     // declaration of a scoped enumeration.
4580     Diag(Tok, diag::err_scoped_enum_missing_identifier);
4581     ScopedEnumKWLoc = SourceLocation();
4582     IsScopedUsingClassTag = false;
4583   }
4584 
4585   // Okay, end the suppression area.  We'll decide whether to emit the
4586   // diagnostics in a second.
4587   if (shouldDelayDiagsInTag)
4588     diagsFromTag.done();
4589 
4590   TypeResult BaseType;
4591   SourceRange BaseRange;
4592 
4593   bool CanBeBitfield = (getCurScope()->getFlags() & Scope::ClassScope) &&
4594                        ScopedEnumKWLoc.isInvalid() && Name;
4595 
4596   // Parse the fixed underlying type.
4597   if (Tok.is(tok::colon)) {
4598     // This might be an enum-base or part of some unrelated enclosing context.
4599     //
4600     // 'enum E : base' is permitted in two circumstances:
4601     //
4602     // 1) As a defining-type-specifier, when followed by '{'.
4603     // 2) As the sole constituent of a complete declaration -- when DS is empty
4604     //    and the next token is ';'.
4605     //
4606     // The restriction to defining-type-specifiers is important to allow parsing
4607     //   a ? new enum E : int{}
4608     //   _Generic(a, enum E : int{})
4609     // properly.
4610     //
4611     // One additional consideration applies:
4612     //
4613     // C++ [dcl.enum]p1:
4614     //   A ':' following "enum nested-name-specifier[opt] identifier" within
4615     //   the decl-specifier-seq of a member-declaration is parsed as part of
4616     //   an enum-base.
4617     //
4618     // Other language modes supporting enumerations with fixed underlying types
4619     // do not have clear rules on this, so we disambiguate to determine whether
4620     // the tokens form a bit-field width or an enum-base.
4621 
4622     if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
4623       // Outside C++11, do not interpret the tokens as an enum-base if they do
4624       // not make sense as one. In C++11, it's an error if this happens.
4625       if (getLangOpts().CPlusPlus11)
4626         Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4627     } else if (CanHaveEnumBase || !ColonIsSacred) {
4628       SourceLocation ColonLoc = ConsumeToken();
4629 
4630       // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4631       // because under -fms-extensions,
4632       //   enum E : int *p;
4633       // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4634       DeclSpec DS(AttrFactory);
4635       ParseSpecifierQualifierList(DS, AS, DeclSpecContext::DSC_type_specifier);
4636       Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
4637       BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4638 
4639       BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4640 
4641       if (!getLangOpts().ObjC) {
4642         if (getLangOpts().CPlusPlus11)
4643           Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4644               << BaseRange;
4645         else if (getLangOpts().CPlusPlus)
4646           Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4647               << BaseRange;
4648         else if (getLangOpts().MicrosoftExt)
4649           Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4650               << BaseRange;
4651         else
4652           Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4653               << BaseRange;
4654       }
4655     }
4656   }
4657 
4658   // There are four options here.  If we have 'friend enum foo;' then this is a
4659   // friend declaration, and cannot have an accompanying definition. If we have
4660   // 'enum foo;', then this is a forward declaration.  If we have
4661   // 'enum foo {...' then this is a definition. Otherwise we have something
4662   // like 'enum foo xyz', a reference.
4663   //
4664   // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4665   // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
4666   // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
4667   //
4668   Sema::TagUseKind TUK;
4669   if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4670     TUK = Sema::TUK_Reference;
4671   else if (Tok.is(tok::l_brace)) {
4672     if (DS.isFriendSpecified()) {
4673       Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4674         << SourceRange(DS.getFriendSpecLoc());
4675       ConsumeBrace();
4676       SkipUntil(tok::r_brace, StopAtSemi);
4677       // Discard any other definition-only pieces.
4678       attrs.clear();
4679       ScopedEnumKWLoc = SourceLocation();
4680       IsScopedUsingClassTag = false;
4681       BaseType = TypeResult();
4682       TUK = Sema::TUK_Friend;
4683     } else {
4684       TUK = Sema::TUK_Definition;
4685     }
4686   } else if (!isTypeSpecifier(DSC) &&
4687              (Tok.is(tok::semi) ||
4688               (Tok.isAtStartOfLine() &&
4689                !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4690     // An opaque-enum-declaration is required to be standalone (no preceding or
4691     // following tokens in the declaration). Sema enforces this separately by
4692     // diagnosing anything else in the DeclSpec.
4693     TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4694     if (Tok.isNot(tok::semi)) {
4695       // A semicolon was missing after this declaration. Diagnose and recover.
4696       ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4697       PP.EnterToken(Tok, /*IsReinject=*/true);
4698       Tok.setKind(tok::semi);
4699     }
4700   } else {
4701     TUK = Sema::TUK_Reference;
4702   }
4703 
4704   bool IsElaboratedTypeSpecifier =
4705       TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
4706 
4707   // If this is an elaborated type specifier nested in a larger declaration,
4708   // and we delayed diagnostics before, just merge them into the current pool.
4709   if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4710     diagsFromTag.redelay();
4711   }
4712 
4713   MultiTemplateParamsArg TParams;
4714   if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4715       TUK != Sema::TUK_Reference) {
4716     if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4717       // Skip the rest of this declarator, up until the comma or semicolon.
4718       Diag(Tok, diag::err_enum_template);
4719       SkipUntil(tok::comma, StopAtSemi);
4720       return;
4721     }
4722 
4723     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4724       // Enumerations can't be explicitly instantiated.
4725       DS.SetTypeSpecError();
4726       Diag(StartLoc, diag::err_explicit_instantiation_enum);
4727       return;
4728     }
4729 
4730     assert(TemplateInfo.TemplateParams && "no template parameters");
4731     TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4732                                      TemplateInfo.TemplateParams->size());
4733   }
4734 
4735   if (!Name && TUK != Sema::TUK_Definition) {
4736     Diag(Tok, diag::err_enumerator_unnamed_no_def);
4737 
4738     // Skip the rest of this declarator, up until the comma or semicolon.
4739     SkipUntil(tok::comma, StopAtSemi);
4740     return;
4741   }
4742 
4743   // An elaborated-type-specifier has a much more constrained grammar:
4744   //
4745   //   'enum' nested-name-specifier[opt] identifier
4746   //
4747   // If we parsed any other bits, reject them now.
4748   //
4749   // MSVC and (for now at least) Objective-C permit a full enum-specifier
4750   // or opaque-enum-declaration anywhere.
4751   if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
4752       !getLangOpts().ObjC) {
4753     ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
4754                             /*DiagnoseEmptyAttrs=*/true);
4755     if (BaseType.isUsable())
4756       Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
4757           << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
4758     else if (ScopedEnumKWLoc.isValid())
4759       Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
4760         << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
4761   }
4762 
4763   stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4764 
4765   Sema::SkipBodyInfo SkipBody;
4766   if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4767       NextToken().is(tok::identifier))
4768     SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4769                                               NextToken().getIdentifierInfo(),
4770                                               NextToken().getLocation());
4771 
4772   bool Owned = false;
4773   bool IsDependent = false;
4774   const char *PrevSpec = nullptr;
4775   unsigned DiagID;
4776   Decl *TagDecl = Actions.ActOnTag(
4777       getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4778       attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4779       ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4780       DSC == DeclSpecContext::DSC_type_specifier,
4781       DSC == DeclSpecContext::DSC_template_param ||
4782           DSC == DeclSpecContext::DSC_template_type_arg,
4783       &SkipBody);
4784 
4785   if (SkipBody.ShouldSkip) {
4786     assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4787 
4788     BalancedDelimiterTracker T(*this, tok::l_brace);
4789     T.consumeOpen();
4790     T.skipToEnd();
4791 
4792     if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4793                            NameLoc.isValid() ? NameLoc : StartLoc,
4794                            PrevSpec, DiagID, TagDecl, Owned,
4795                            Actions.getASTContext().getPrintingPolicy()))
4796       Diag(StartLoc, DiagID) << PrevSpec;
4797     return;
4798   }
4799 
4800   if (IsDependent) {
4801     // This enum has a dependent nested-name-specifier. Handle it as a
4802     // dependent tag.
4803     if (!Name) {
4804       DS.SetTypeSpecError();
4805       Diag(Tok, diag::err_expected_type_name_after_typename);
4806       return;
4807     }
4808 
4809     TypeResult Type = Actions.ActOnDependentTag(
4810         getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4811     if (Type.isInvalid()) {
4812       DS.SetTypeSpecError();
4813       return;
4814     }
4815 
4816     if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4817                            NameLoc.isValid() ? NameLoc : StartLoc,
4818                            PrevSpec, DiagID, Type.get(),
4819                            Actions.getASTContext().getPrintingPolicy()))
4820       Diag(StartLoc, DiagID) << PrevSpec;
4821 
4822     return;
4823   }
4824 
4825   if (!TagDecl) {
4826     // The action failed to produce an enumeration tag. If this is a
4827     // definition, consume the entire definition.
4828     if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4829       ConsumeBrace();
4830       SkipUntil(tok::r_brace, StopAtSemi);
4831     }
4832 
4833     DS.SetTypeSpecError();
4834     return;
4835   }
4836 
4837   if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
4838     Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4839     ParseEnumBody(StartLoc, D);
4840     if (SkipBody.CheckSameAsPrevious &&
4841         !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4842       DS.SetTypeSpecError();
4843       return;
4844     }
4845   }
4846 
4847   if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4848                          NameLoc.isValid() ? NameLoc : StartLoc,
4849                          PrevSpec, DiagID, TagDecl, Owned,
4850                          Actions.getASTContext().getPrintingPolicy()))
4851     Diag(StartLoc, DiagID) << PrevSpec;
4852 }
4853 
4854 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4855 ///       enumerator-list:
4856 ///         enumerator
4857 ///         enumerator-list ',' enumerator
4858 ///       enumerator:
4859 ///         enumeration-constant attributes[opt]
4860 ///         enumeration-constant attributes[opt] '=' constant-expression
4861 ///       enumeration-constant:
4862 ///         identifier
4863 ///
4864 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4865   // Enter the scope of the enum body and start the definition.
4866   ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4867   Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4868 
4869   BalancedDelimiterTracker T(*this, tok::l_brace);
4870   T.consumeOpen();
4871 
4872   // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4873   if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4874     Diag(Tok, diag::err_empty_enum);
4875 
4876   SmallVector<Decl *, 32> EnumConstantDecls;
4877   SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4878 
4879   Decl *LastEnumConstDecl = nullptr;
4880 
4881   // Parse the enumerator-list.
4882   while (Tok.isNot(tok::r_brace)) {
4883     // Parse enumerator. If failed, try skipping till the start of the next
4884     // enumerator definition.
4885     if (Tok.isNot(tok::identifier)) {
4886       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4887       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4888           TryConsumeToken(tok::comma))
4889         continue;
4890       break;
4891     }
4892     IdentifierInfo *Ident = Tok.getIdentifierInfo();
4893     SourceLocation IdentLoc = ConsumeToken();
4894 
4895     // If attributes exist after the enumerator, parse them.
4896     ParsedAttributesWithRange attrs(AttrFactory);
4897     MaybeParseGNUAttributes(attrs);
4898     if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4899       if (getLangOpts().CPlusPlus)
4900         Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4901                                     ? diag::warn_cxx14_compat_ns_enum_attribute
4902                                     : diag::ext_ns_enum_attribute)
4903             << 1 /*enumerator*/;
4904       ParseCXX11Attributes(attrs);
4905     }
4906 
4907     SourceLocation EqualLoc;
4908     ExprResult AssignedVal;
4909     EnumAvailabilityDiags.emplace_back(*this);
4910 
4911     EnterExpressionEvaluationContext ConstantEvaluated(
4912         Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4913     if (TryConsumeToken(tok::equal, EqualLoc)) {
4914       AssignedVal = ParseConstantExpressionInExprEvalContext();
4915       if (AssignedVal.isInvalid())
4916         SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4917     }
4918 
4919     // Install the enumerator constant into EnumDecl.
4920     Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4921         getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4922         EqualLoc, AssignedVal.get());
4923     EnumAvailabilityDiags.back().done();
4924 
4925     EnumConstantDecls.push_back(EnumConstDecl);
4926     LastEnumConstDecl = EnumConstDecl;
4927 
4928     if (Tok.is(tok::identifier)) {
4929       // We're missing a comma between enumerators.
4930       SourceLocation Loc = getEndOfPreviousToken();
4931       Diag(Loc, diag::err_enumerator_list_missing_comma)
4932         << FixItHint::CreateInsertion(Loc, ", ");
4933       continue;
4934     }
4935 
4936     // Emumerator definition must be finished, only comma or r_brace are
4937     // allowed here.
4938     SourceLocation CommaLoc;
4939     if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4940       if (EqualLoc.isValid())
4941         Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4942                                                            << tok::comma;
4943       else
4944         Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4945       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4946         if (TryConsumeToken(tok::comma, CommaLoc))
4947           continue;
4948       } else {
4949         break;
4950       }
4951     }
4952 
4953     // If comma is followed by r_brace, emit appropriate warning.
4954     if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4955       if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4956         Diag(CommaLoc, getLangOpts().CPlusPlus ?
4957                diag::ext_enumerator_list_comma_cxx :
4958                diag::ext_enumerator_list_comma_c)
4959           << FixItHint::CreateRemoval(CommaLoc);
4960       else if (getLangOpts().CPlusPlus11)
4961         Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4962           << FixItHint::CreateRemoval(CommaLoc);
4963       break;
4964     }
4965   }
4966 
4967   // Eat the }.
4968   T.consumeClose();
4969 
4970   // If attributes exist after the identifier list, parse them.
4971   ParsedAttributes attrs(AttrFactory);
4972   MaybeParseGNUAttributes(attrs);
4973 
4974   Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4975                         getCurScope(), attrs);
4976 
4977   // Now handle enum constant availability diagnostics.
4978   assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4979   for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4980     ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4981     EnumAvailabilityDiags[i].redelay();
4982     PD.complete(EnumConstantDecls[i]);
4983   }
4984 
4985   EnumScope.Exit();
4986   Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4987 
4988   // The next token must be valid after an enum definition. If not, a ';'
4989   // was probably forgotten.
4990   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4991   if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4992     ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4993     // Push this token back into the preprocessor and change our current token
4994     // to ';' so that the rest of the code recovers as though there were an
4995     // ';' after the definition.
4996     PP.EnterToken(Tok, /*IsReinject=*/true);
4997     Tok.setKind(tok::semi);
4998   }
4999 }
5000 
5001 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5002 /// is definitely a type-specifier.  Return false if it isn't part of a type
5003 /// specifier or if we're not sure.
5004 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5005   switch (Tok.getKind()) {
5006   default: return false;
5007     // type-specifiers
5008   case tok::kw_short:
5009   case tok::kw_long:
5010   case tok::kw___int64:
5011   case tok::kw___int128:
5012   case tok::kw_signed:
5013   case tok::kw_unsigned:
5014   case tok::kw__Complex:
5015   case tok::kw__Imaginary:
5016   case tok::kw_void:
5017   case tok::kw_char:
5018   case tok::kw_wchar_t:
5019   case tok::kw_char8_t:
5020   case tok::kw_char16_t:
5021   case tok::kw_char32_t:
5022   case tok::kw_int:
5023   case tok::kw__ExtInt:
5024   case tok::kw__BitInt:
5025   case tok::kw___bf16:
5026   case tok::kw_half:
5027   case tok::kw_float:
5028   case tok::kw_double:
5029   case tok::kw__Accum:
5030   case tok::kw__Fract:
5031   case tok::kw__Float16:
5032   case tok::kw___float128:
5033   case tok::kw___ibm128:
5034   case tok::kw_bool:
5035   case tok::kw__Bool:
5036   case tok::kw__Decimal32:
5037   case tok::kw__Decimal64:
5038   case tok::kw__Decimal128:
5039   case tok::kw___vector:
5040 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5041 #include "clang/Basic/OpenCLImageTypes.def"
5042 
5043     // struct-or-union-specifier (C99) or class-specifier (C++)
5044   case tok::kw_class:
5045   case tok::kw_struct:
5046   case tok::kw___interface:
5047   case tok::kw_union:
5048     // enum-specifier
5049   case tok::kw_enum:
5050 
5051     // typedef-name
5052   case tok::annot_typename:
5053     return true;
5054   }
5055 }
5056 
5057 /// isTypeSpecifierQualifier - Return true if the current token could be the
5058 /// start of a specifier-qualifier-list.
5059 bool Parser::isTypeSpecifierQualifier() {
5060   switch (Tok.getKind()) {
5061   default: return false;
5062 
5063   case tok::identifier:   // foo::bar
5064     if (TryAltiVecVectorToken())
5065       return true;
5066     LLVM_FALLTHROUGH;
5067   case tok::kw_typename:  // typename T::type
5068     // Annotate typenames and C++ scope specifiers.  If we get one, just
5069     // recurse to handle whatever we get.
5070     if (TryAnnotateTypeOrScopeToken())
5071       return true;
5072     if (Tok.is(tok::identifier))
5073       return false;
5074     return isTypeSpecifierQualifier();
5075 
5076   case tok::coloncolon:   // ::foo::bar
5077     if (NextToken().is(tok::kw_new) ||    // ::new
5078         NextToken().is(tok::kw_delete))   // ::delete
5079       return false;
5080 
5081     if (TryAnnotateTypeOrScopeToken())
5082       return true;
5083     return isTypeSpecifierQualifier();
5084 
5085     // GNU attributes support.
5086   case tok::kw___attribute:
5087     // GNU typeof support.
5088   case tok::kw_typeof:
5089 
5090     // type-specifiers
5091   case tok::kw_short:
5092   case tok::kw_long:
5093   case tok::kw___int64:
5094   case tok::kw___int128:
5095   case tok::kw_signed:
5096   case tok::kw_unsigned:
5097   case tok::kw__Complex:
5098   case tok::kw__Imaginary:
5099   case tok::kw_void:
5100   case tok::kw_char:
5101   case tok::kw_wchar_t:
5102   case tok::kw_char8_t:
5103   case tok::kw_char16_t:
5104   case tok::kw_char32_t:
5105   case tok::kw_int:
5106   case tok::kw__ExtInt:
5107   case tok::kw__BitInt:
5108   case tok::kw_half:
5109   case tok::kw___bf16:
5110   case tok::kw_float:
5111   case tok::kw_double:
5112   case tok::kw__Accum:
5113   case tok::kw__Fract:
5114   case tok::kw__Float16:
5115   case tok::kw___float128:
5116   case tok::kw___ibm128:
5117   case tok::kw_bool:
5118   case tok::kw__Bool:
5119   case tok::kw__Decimal32:
5120   case tok::kw__Decimal64:
5121   case tok::kw__Decimal128:
5122   case tok::kw___vector:
5123 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5124 #include "clang/Basic/OpenCLImageTypes.def"
5125 
5126     // struct-or-union-specifier (C99) or class-specifier (C++)
5127   case tok::kw_class:
5128   case tok::kw_struct:
5129   case tok::kw___interface:
5130   case tok::kw_union:
5131     // enum-specifier
5132   case tok::kw_enum:
5133 
5134     // type-qualifier
5135   case tok::kw_const:
5136   case tok::kw_volatile:
5137   case tok::kw_restrict:
5138   case tok::kw__Sat:
5139 
5140     // Debugger support.
5141   case tok::kw___unknown_anytype:
5142 
5143     // typedef-name
5144   case tok::annot_typename:
5145     return true;
5146 
5147     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5148   case tok::less:
5149     return getLangOpts().ObjC;
5150 
5151   case tok::kw___cdecl:
5152   case tok::kw___stdcall:
5153   case tok::kw___fastcall:
5154   case tok::kw___thiscall:
5155   case tok::kw___regcall:
5156   case tok::kw___vectorcall:
5157   case tok::kw___w64:
5158   case tok::kw___ptr64:
5159   case tok::kw___ptr32:
5160   case tok::kw___pascal:
5161   case tok::kw___unaligned:
5162 
5163   case tok::kw__Nonnull:
5164   case tok::kw__Nullable:
5165   case tok::kw__Nullable_result:
5166   case tok::kw__Null_unspecified:
5167 
5168   case tok::kw___kindof:
5169 
5170   case tok::kw___private:
5171   case tok::kw___local:
5172   case tok::kw___global:
5173   case tok::kw___constant:
5174   case tok::kw___generic:
5175   case tok::kw___read_only:
5176   case tok::kw___read_write:
5177   case tok::kw___write_only:
5178     return true;
5179 
5180   case tok::kw_private:
5181     return getLangOpts().OpenCL;
5182 
5183   // C11 _Atomic
5184   case tok::kw__Atomic:
5185     return true;
5186   }
5187 }
5188 
5189 /// isDeclarationSpecifier() - Return true if the current token is part of a
5190 /// declaration specifier.
5191 ///
5192 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5193 /// this check is to disambiguate between an expression and a declaration.
5194 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
5195   switch (Tok.getKind()) {
5196   default: return false;
5197 
5198   // OpenCL 2.0 and later define this keyword.
5199   case tok::kw_pipe:
5200     return getLangOpts().OpenCL &&
5201            getLangOpts().getOpenCLCompatibleVersion() >= 200;
5202 
5203   case tok::identifier:   // foo::bar
5204     // Unfortunate hack to support "Class.factoryMethod" notation.
5205     if (getLangOpts().ObjC && NextToken().is(tok::period))
5206       return false;
5207     if (TryAltiVecVectorToken())
5208       return true;
5209     LLVM_FALLTHROUGH;
5210   case tok::kw_decltype: // decltype(T())::type
5211   case tok::kw_typename: // typename T::type
5212     // Annotate typenames and C++ scope specifiers.  If we get one, just
5213     // recurse to handle whatever we get.
5214     if (TryAnnotateTypeOrScopeToken())
5215       return true;
5216     if (TryAnnotateTypeConstraint())
5217       return true;
5218     if (Tok.is(tok::identifier))
5219       return false;
5220 
5221     // If we're in Objective-C and we have an Objective-C class type followed
5222     // by an identifier and then either ':' or ']', in a place where an
5223     // expression is permitted, then this is probably a class message send
5224     // missing the initial '['. In this case, we won't consider this to be
5225     // the start of a declaration.
5226     if (DisambiguatingWithExpression &&
5227         isStartOfObjCClassMessageMissingOpenBracket())
5228       return false;
5229 
5230     return isDeclarationSpecifier();
5231 
5232   case tok::coloncolon:   // ::foo::bar
5233     if (NextToken().is(tok::kw_new) ||    // ::new
5234         NextToken().is(tok::kw_delete))   // ::delete
5235       return false;
5236 
5237     // Annotate typenames and C++ scope specifiers.  If we get one, just
5238     // recurse to handle whatever we get.
5239     if (TryAnnotateTypeOrScopeToken())
5240       return true;
5241     return isDeclarationSpecifier();
5242 
5243     // storage-class-specifier
5244   case tok::kw_typedef:
5245   case tok::kw_extern:
5246   case tok::kw___private_extern__:
5247   case tok::kw_static:
5248   case tok::kw_auto:
5249   case tok::kw___auto_type:
5250   case tok::kw_register:
5251   case tok::kw___thread:
5252   case tok::kw_thread_local:
5253   case tok::kw__Thread_local:
5254 
5255     // Modules
5256   case tok::kw___module_private__:
5257 
5258     // Debugger support
5259   case tok::kw___unknown_anytype:
5260 
5261     // type-specifiers
5262   case tok::kw_short:
5263   case tok::kw_long:
5264   case tok::kw___int64:
5265   case tok::kw___int128:
5266   case tok::kw_signed:
5267   case tok::kw_unsigned:
5268   case tok::kw__Complex:
5269   case tok::kw__Imaginary:
5270   case tok::kw_void:
5271   case tok::kw_char:
5272   case tok::kw_wchar_t:
5273   case tok::kw_char8_t:
5274   case tok::kw_char16_t:
5275   case tok::kw_char32_t:
5276 
5277   case tok::kw_int:
5278   case tok::kw__ExtInt:
5279   case tok::kw__BitInt:
5280   case tok::kw_half:
5281   case tok::kw___bf16:
5282   case tok::kw_float:
5283   case tok::kw_double:
5284   case tok::kw__Accum:
5285   case tok::kw__Fract:
5286   case tok::kw__Float16:
5287   case tok::kw___float128:
5288   case tok::kw___ibm128:
5289   case tok::kw_bool:
5290   case tok::kw__Bool:
5291   case tok::kw__Decimal32:
5292   case tok::kw__Decimal64:
5293   case tok::kw__Decimal128:
5294   case tok::kw___vector:
5295 
5296     // struct-or-union-specifier (C99) or class-specifier (C++)
5297   case tok::kw_class:
5298   case tok::kw_struct:
5299   case tok::kw_union:
5300   case tok::kw___interface:
5301     // enum-specifier
5302   case tok::kw_enum:
5303 
5304     // type-qualifier
5305   case tok::kw_const:
5306   case tok::kw_volatile:
5307   case tok::kw_restrict:
5308   case tok::kw__Sat:
5309 
5310     // function-specifier
5311   case tok::kw_inline:
5312   case tok::kw_virtual:
5313   case tok::kw_explicit:
5314   case tok::kw__Noreturn:
5315 
5316     // alignment-specifier
5317   case tok::kw__Alignas:
5318 
5319     // friend keyword.
5320   case tok::kw_friend:
5321 
5322     // static_assert-declaration
5323   case tok::kw_static_assert:
5324   case tok::kw__Static_assert:
5325 
5326     // GNU typeof support.
5327   case tok::kw_typeof:
5328 
5329     // GNU attributes.
5330   case tok::kw___attribute:
5331 
5332     // C++11 decltype and constexpr.
5333   case tok::annot_decltype:
5334   case tok::kw_constexpr:
5335 
5336     // C++20 consteval and constinit.
5337   case tok::kw_consteval:
5338   case tok::kw_constinit:
5339 
5340     // C11 _Atomic
5341   case tok::kw__Atomic:
5342     return true;
5343 
5344     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5345   case tok::less:
5346     return getLangOpts().ObjC;
5347 
5348     // typedef-name
5349   case tok::annot_typename:
5350     return !DisambiguatingWithExpression ||
5351            !isStartOfObjCClassMessageMissingOpenBracket();
5352 
5353     // placeholder-type-specifier
5354   case tok::annot_template_id: {
5355     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5356     if (TemplateId->hasInvalidName())
5357       return true;
5358     // FIXME: What about type templates that have only been annotated as
5359     // annot_template_id, not as annot_typename?
5360     return isTypeConstraintAnnotation() &&
5361            (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5362   }
5363 
5364   case tok::annot_cxxscope: {
5365     TemplateIdAnnotation *TemplateId =
5366         NextToken().is(tok::annot_template_id)
5367             ? takeTemplateIdAnnotation(NextToken())
5368             : nullptr;
5369     if (TemplateId && TemplateId->hasInvalidName())
5370       return true;
5371     // FIXME: What about type templates that have only been annotated as
5372     // annot_template_id, not as annot_typename?
5373     if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
5374       return true;
5375     return isTypeConstraintAnnotation() &&
5376         GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5377   }
5378 
5379   case tok::kw___declspec:
5380   case tok::kw___cdecl:
5381   case tok::kw___stdcall:
5382   case tok::kw___fastcall:
5383   case tok::kw___thiscall:
5384   case tok::kw___regcall:
5385   case tok::kw___vectorcall:
5386   case tok::kw___w64:
5387   case tok::kw___sptr:
5388   case tok::kw___uptr:
5389   case tok::kw___ptr64:
5390   case tok::kw___ptr32:
5391   case tok::kw___forceinline:
5392   case tok::kw___pascal:
5393   case tok::kw___unaligned:
5394 
5395   case tok::kw__Nonnull:
5396   case tok::kw__Nullable:
5397   case tok::kw__Nullable_result:
5398   case tok::kw__Null_unspecified:
5399 
5400   case tok::kw___kindof:
5401 
5402   case tok::kw___private:
5403   case tok::kw___local:
5404   case tok::kw___global:
5405   case tok::kw___constant:
5406   case tok::kw___generic:
5407   case tok::kw___read_only:
5408   case tok::kw___read_write:
5409   case tok::kw___write_only:
5410 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5411 #include "clang/Basic/OpenCLImageTypes.def"
5412 
5413     return true;
5414 
5415   case tok::kw_private:
5416     return getLangOpts().OpenCL;
5417   }
5418 }
5419 
5420 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5421   TentativeParsingAction TPA(*this);
5422 
5423   // Parse the C++ scope specifier.
5424   CXXScopeSpec SS;
5425   if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5426                                      /*ObjectHasErrors=*/false,
5427                                      /*EnteringContext=*/true)) {
5428     TPA.Revert();
5429     return false;
5430   }
5431 
5432   // Parse the constructor name.
5433   if (Tok.is(tok::identifier)) {
5434     // We already know that we have a constructor name; just consume
5435     // the token.
5436     ConsumeToken();
5437   } else if (Tok.is(tok::annot_template_id)) {
5438     ConsumeAnnotationToken();
5439   } else {
5440     TPA.Revert();
5441     return false;
5442   }
5443 
5444   // There may be attributes here, appertaining to the constructor name or type
5445   // we just stepped past.
5446   SkipCXX11Attributes();
5447 
5448   // Current class name must be followed by a left parenthesis.
5449   if (Tok.isNot(tok::l_paren)) {
5450     TPA.Revert();
5451     return false;
5452   }
5453   ConsumeParen();
5454 
5455   // A right parenthesis, or ellipsis followed by a right parenthesis signals
5456   // that we have a constructor.
5457   if (Tok.is(tok::r_paren) ||
5458       (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5459     TPA.Revert();
5460     return true;
5461   }
5462 
5463   // A C++11 attribute here signals that we have a constructor, and is an
5464   // attribute on the first constructor parameter.
5465   if (getLangOpts().CPlusPlus11 &&
5466       isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5467                                 /*OuterMightBeMessageSend*/ true)) {
5468     TPA.Revert();
5469     return true;
5470   }
5471 
5472   // If we need to, enter the specified scope.
5473   DeclaratorScopeObj DeclScopeObj(*this, SS);
5474   if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5475     DeclScopeObj.EnterDeclaratorScope();
5476 
5477   // Optionally skip Microsoft attributes.
5478   ParsedAttributes Attrs(AttrFactory);
5479   MaybeParseMicrosoftAttributes(Attrs);
5480 
5481   // Check whether the next token(s) are part of a declaration
5482   // specifier, in which case we have the start of a parameter and,
5483   // therefore, we know that this is a constructor.
5484   bool IsConstructor = false;
5485   if (isDeclarationSpecifier())
5486     IsConstructor = true;
5487   else if (Tok.is(tok::identifier) ||
5488            (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5489     // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5490     // This might be a parenthesized member name, but is more likely to
5491     // be a constructor declaration with an invalid argument type. Keep
5492     // looking.
5493     if (Tok.is(tok::annot_cxxscope))
5494       ConsumeAnnotationToken();
5495     ConsumeToken();
5496 
5497     // If this is not a constructor, we must be parsing a declarator,
5498     // which must have one of the following syntactic forms (see the
5499     // grammar extract at the start of ParseDirectDeclarator):
5500     switch (Tok.getKind()) {
5501     case tok::l_paren:
5502       // C(X   (   int));
5503     case tok::l_square:
5504       // C(X   [   5]);
5505       // C(X   [   [attribute]]);
5506     case tok::coloncolon:
5507       // C(X   ::   Y);
5508       // C(X   ::   *p);
5509       // Assume this isn't a constructor, rather than assuming it's a
5510       // constructor with an unnamed parameter of an ill-formed type.
5511       break;
5512 
5513     case tok::r_paren:
5514       // C(X   )
5515 
5516       // Skip past the right-paren and any following attributes to get to
5517       // the function body or trailing-return-type.
5518       ConsumeParen();
5519       SkipCXX11Attributes();
5520 
5521       if (DeductionGuide) {
5522         // C(X) -> ... is a deduction guide.
5523         IsConstructor = Tok.is(tok::arrow);
5524         break;
5525       }
5526       if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5527         // Assume these were meant to be constructors:
5528         //   C(X)   :    (the name of a bit-field cannot be parenthesized).
5529         //   C(X)   try  (this is otherwise ill-formed).
5530         IsConstructor = true;
5531       }
5532       if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5533         // If we have a constructor name within the class definition,
5534         // assume these were meant to be constructors:
5535         //   C(X)   {
5536         //   C(X)   ;
5537         // ... because otherwise we would be declaring a non-static data
5538         // member that is ill-formed because it's of the same type as its
5539         // surrounding class.
5540         //
5541         // FIXME: We can actually do this whether or not the name is qualified,
5542         // because if it is qualified in this context it must be being used as
5543         // a constructor name.
5544         // currently, so we're somewhat conservative here.
5545         IsConstructor = IsUnqualified;
5546       }
5547       break;
5548 
5549     default:
5550       IsConstructor = true;
5551       break;
5552     }
5553   }
5554 
5555   TPA.Revert();
5556   return IsConstructor;
5557 }
5558 
5559 /// ParseTypeQualifierListOpt
5560 ///          type-qualifier-list: [C99 6.7.5]
5561 ///            type-qualifier
5562 /// [vendor]   attributes
5563 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
5564 ///            type-qualifier-list type-qualifier
5565 /// [vendor]   type-qualifier-list attributes
5566 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
5567 /// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
5568 ///              [ only if AttReqs & AR_CXX11AttributesParsed ]
5569 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5570 /// AttrRequirements bitmask values.
5571 void Parser::ParseTypeQualifierListOpt(
5572     DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5573     bool IdentifierRequired,
5574     Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5575   if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5576       isCXX11AttributeSpecifier()) {
5577     ParsedAttributesWithRange attrs(AttrFactory);
5578     ParseCXX11Attributes(attrs);
5579     DS.takeAttributesFrom(attrs);
5580   }
5581 
5582   SourceLocation EndLoc;
5583 
5584   while (true) {
5585     bool isInvalid = false;
5586     const char *PrevSpec = nullptr;
5587     unsigned DiagID = 0;
5588     SourceLocation Loc = Tok.getLocation();
5589 
5590     switch (Tok.getKind()) {
5591     case tok::code_completion:
5592       cutOffParsing();
5593       if (CodeCompletionHandler)
5594         (*CodeCompletionHandler)();
5595       else
5596         Actions.CodeCompleteTypeQualifiers(DS);
5597       return;
5598 
5599     case tok::kw_const:
5600       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
5601                                  getLangOpts());
5602       break;
5603     case tok::kw_volatile:
5604       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5605                                  getLangOpts());
5606       break;
5607     case tok::kw_restrict:
5608       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5609                                  getLangOpts());
5610       break;
5611     case tok::kw__Atomic:
5612       if (!AtomicAllowed)
5613         goto DoneWithTypeQuals;
5614       if (!getLangOpts().C11)
5615         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5616       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5617                                  getLangOpts());
5618       break;
5619 
5620     // OpenCL qualifiers:
5621     case tok::kw_private:
5622       if (!getLangOpts().OpenCL)
5623         goto DoneWithTypeQuals;
5624       LLVM_FALLTHROUGH;
5625     case tok::kw___private:
5626     case tok::kw___global:
5627     case tok::kw___local:
5628     case tok::kw___constant:
5629     case tok::kw___generic:
5630     case tok::kw___read_only:
5631     case tok::kw___write_only:
5632     case tok::kw___read_write:
5633       ParseOpenCLQualifiers(DS.getAttributes());
5634       break;
5635 
5636     case tok::kw___unaligned:
5637       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5638                                  getLangOpts());
5639       break;
5640     case tok::kw___uptr:
5641       // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5642       // with the MS modifier keyword.
5643       if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5644           IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5645         if (TryKeywordIdentFallback(false))
5646           continue;
5647       }
5648       LLVM_FALLTHROUGH;
5649     case tok::kw___sptr:
5650     case tok::kw___w64:
5651     case tok::kw___ptr64:
5652     case tok::kw___ptr32:
5653     case tok::kw___cdecl:
5654     case tok::kw___stdcall:
5655     case tok::kw___fastcall:
5656     case tok::kw___thiscall:
5657     case tok::kw___regcall:
5658     case tok::kw___vectorcall:
5659       if (AttrReqs & AR_DeclspecAttributesParsed) {
5660         ParseMicrosoftTypeAttributes(DS.getAttributes());
5661         continue;
5662       }
5663       goto DoneWithTypeQuals;
5664     case tok::kw___pascal:
5665       if (AttrReqs & AR_VendorAttributesParsed) {
5666         ParseBorlandTypeAttributes(DS.getAttributes());
5667         continue;
5668       }
5669       goto DoneWithTypeQuals;
5670 
5671     // Nullability type specifiers.
5672     case tok::kw__Nonnull:
5673     case tok::kw__Nullable:
5674     case tok::kw__Nullable_result:
5675     case tok::kw__Null_unspecified:
5676       ParseNullabilityTypeSpecifiers(DS.getAttributes());
5677       continue;
5678 
5679     // Objective-C 'kindof' types.
5680     case tok::kw___kindof:
5681       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5682                                 nullptr, 0, ParsedAttr::AS_Keyword);
5683       (void)ConsumeToken();
5684       continue;
5685 
5686     case tok::kw___attribute:
5687       if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5688         // When GNU attributes are expressly forbidden, diagnose their usage.
5689         Diag(Tok, diag::err_attributes_not_allowed);
5690 
5691       // Parse the attributes even if they are rejected to ensure that error
5692       // recovery is graceful.
5693       if (AttrReqs & AR_GNUAttributesParsed ||
5694           AttrReqs & AR_GNUAttributesParsedAndRejected) {
5695         ParseGNUAttributes(DS.getAttributes());
5696         continue; // do *not* consume the next token!
5697       }
5698       // otherwise, FALL THROUGH!
5699       LLVM_FALLTHROUGH;
5700     default:
5701       DoneWithTypeQuals:
5702       // If this is not a type-qualifier token, we're done reading type
5703       // qualifiers.  First verify that DeclSpec's are consistent.
5704       DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5705       if (EndLoc.isValid())
5706         DS.SetRangeEnd(EndLoc);
5707       return;
5708     }
5709 
5710     // If the specifier combination wasn't legal, issue a diagnostic.
5711     if (isInvalid) {
5712       assert(PrevSpec && "Method did not return previous specifier!");
5713       Diag(Tok, DiagID) << PrevSpec;
5714     }
5715     EndLoc = ConsumeToken();
5716   }
5717 }
5718 
5719 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5720 ///
5721 void Parser::ParseDeclarator(Declarator &D) {
5722   /// This implements the 'declarator' production in the C grammar, then checks
5723   /// for well-formedness and issues diagnostics.
5724   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5725 }
5726 
5727 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5728                                DeclaratorContext TheContext) {
5729   if (Kind == tok::star || Kind == tok::caret)
5730     return true;
5731 
5732   // OpenCL 2.0 and later define this keyword.
5733   if (Kind == tok::kw_pipe && Lang.OpenCL &&
5734       Lang.getOpenCLCompatibleVersion() >= 200)
5735     return true;
5736 
5737   if (!Lang.CPlusPlus)
5738     return false;
5739 
5740   if (Kind == tok::amp)
5741     return true;
5742 
5743   // We parse rvalue refs in C++03, because otherwise the errors are scary.
5744   // But we must not parse them in conversion-type-ids and new-type-ids, since
5745   // those can be legitimately followed by a && operator.
5746   // (The same thing can in theory happen after a trailing-return-type, but
5747   // since those are a C++11 feature, there is no rejects-valid issue there.)
5748   if (Kind == tok::ampamp)
5749     return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
5750                                 TheContext != DeclaratorContext::CXXNew);
5751 
5752   return false;
5753 }
5754 
5755 // Indicates whether the given declarator is a pipe declarator.
5756 static bool isPipeDeclerator(const Declarator &D) {
5757   const unsigned NumTypes = D.getNumTypeObjects();
5758 
5759   for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5760     if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5761       return true;
5762 
5763   return false;
5764 }
5765 
5766 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5767 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5768 /// isn't parsed at all, making this function effectively parse the C++
5769 /// ptr-operator production.
5770 ///
5771 /// If the grammar of this construct is extended, matching changes must also be
5772 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5773 /// isConstructorDeclarator.
5774 ///
5775 ///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5776 /// [C]     pointer[opt] direct-declarator
5777 /// [C++]   direct-declarator
5778 /// [C++]   ptr-operator declarator
5779 ///
5780 ///       pointer: [C99 6.7.5]
5781 ///         '*' type-qualifier-list[opt]
5782 ///         '*' type-qualifier-list[opt] pointer
5783 ///
5784 ///       ptr-operator:
5785 ///         '*' cv-qualifier-seq[opt]
5786 ///         '&'
5787 /// [C++0x] '&&'
5788 /// [GNU]   '&' restrict[opt] attributes[opt]
5789 /// [GNU?]  '&&' restrict[opt] attributes[opt]
5790 ///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5791 void Parser::ParseDeclaratorInternal(Declarator &D,
5792                                      DirectDeclParseFunction DirectDeclParser) {
5793   if (Diags.hasAllExtensionsSilenced())
5794     D.setExtension();
5795 
5796   // C++ member pointers start with a '::' or a nested-name.
5797   // Member pointers get special handling, since there's no place for the
5798   // scope spec in the generic path below.
5799   if (getLangOpts().CPlusPlus &&
5800       (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5801        (Tok.is(tok::identifier) &&
5802         (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5803        Tok.is(tok::annot_cxxscope))) {
5804     bool EnteringContext = D.getContext() == DeclaratorContext::File ||
5805                            D.getContext() == DeclaratorContext::Member;
5806     CXXScopeSpec SS;
5807     ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5808                                    /*ObjectHasErrors=*/false, EnteringContext);
5809 
5810     if (SS.isNotEmpty()) {
5811       if (Tok.isNot(tok::star)) {
5812         // The scope spec really belongs to the direct-declarator.
5813         if (D.mayHaveIdentifier())
5814           D.getCXXScopeSpec() = SS;
5815         else
5816           AnnotateScopeToken(SS, true);
5817 
5818         if (DirectDeclParser)
5819           (this->*DirectDeclParser)(D);
5820         return;
5821       }
5822 
5823       if (SS.isValid()) {
5824         checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
5825                            CompoundToken::MemberPtr);
5826       }
5827 
5828       SourceLocation StarLoc = ConsumeToken();
5829       D.SetRangeEnd(StarLoc);
5830       DeclSpec DS(AttrFactory);
5831       ParseTypeQualifierListOpt(DS);
5832       D.ExtendWithDeclSpec(DS);
5833 
5834       // Recurse to parse whatever is left.
5835       ParseDeclaratorInternal(D, DirectDeclParser);
5836 
5837       // Sema will have to catch (syntactically invalid) pointers into global
5838       // scope. It has to catch pointers into namespace scope anyway.
5839       D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
5840                         SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
5841                     std::move(DS.getAttributes()),
5842                     /* Don't replace range end. */ SourceLocation());
5843       return;
5844     }
5845   }
5846 
5847   tok::TokenKind Kind = Tok.getKind();
5848 
5849   if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5850     DeclSpec DS(AttrFactory);
5851     ParseTypeQualifierListOpt(DS);
5852 
5853     D.AddTypeInfo(
5854         DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5855         std::move(DS.getAttributes()), SourceLocation());
5856   }
5857 
5858   // Not a pointer, C++ reference, or block.
5859   if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5860     if (DirectDeclParser)
5861       (this->*DirectDeclParser)(D);
5862     return;
5863   }
5864 
5865   // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5866   // '&&' -> rvalue reference
5867   SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
5868   D.SetRangeEnd(Loc);
5869 
5870   if (Kind == tok::star || Kind == tok::caret) {
5871     // Is a pointer.
5872     DeclSpec DS(AttrFactory);
5873 
5874     // GNU attributes are not allowed here in a new-type-id, but Declspec and
5875     // C++11 attributes are allowed.
5876     unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5877                     ((D.getContext() != DeclaratorContext::CXXNew)
5878                          ? AR_GNUAttributesParsed
5879                          : AR_GNUAttributesParsedAndRejected);
5880     ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5881     D.ExtendWithDeclSpec(DS);
5882 
5883     // Recursively parse the declarator.
5884     ParseDeclaratorInternal(D, DirectDeclParser);
5885     if (Kind == tok::star)
5886       // Remember that we parsed a pointer type, and remember the type-quals.
5887       D.AddTypeInfo(DeclaratorChunk::getPointer(
5888                         DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5889                         DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5890                         DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5891                     std::move(DS.getAttributes()), SourceLocation());
5892     else
5893       // Remember that we parsed a Block type, and remember the type-quals.
5894       D.AddTypeInfo(
5895           DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5896           std::move(DS.getAttributes()), SourceLocation());
5897   } else {
5898     // Is a reference
5899     DeclSpec DS(AttrFactory);
5900 
5901     // Complain about rvalue references in C++03, but then go on and build
5902     // the declarator.
5903     if (Kind == tok::ampamp)
5904       Diag(Loc, getLangOpts().CPlusPlus11 ?
5905            diag::warn_cxx98_compat_rvalue_reference :
5906            diag::ext_rvalue_reference);
5907 
5908     // GNU-style and C++11 attributes are allowed here, as is restrict.
5909     ParseTypeQualifierListOpt(DS);
5910     D.ExtendWithDeclSpec(DS);
5911 
5912     // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5913     // cv-qualifiers are introduced through the use of a typedef or of a
5914     // template type argument, in which case the cv-qualifiers are ignored.
5915     if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5916       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5917         Diag(DS.getConstSpecLoc(),
5918              diag::err_invalid_reference_qualifier_application) << "const";
5919       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5920         Diag(DS.getVolatileSpecLoc(),
5921              diag::err_invalid_reference_qualifier_application) << "volatile";
5922       // 'restrict' is permitted as an extension.
5923       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5924         Diag(DS.getAtomicSpecLoc(),
5925              diag::err_invalid_reference_qualifier_application) << "_Atomic";
5926     }
5927 
5928     // Recursively parse the declarator.
5929     ParseDeclaratorInternal(D, DirectDeclParser);
5930 
5931     if (D.getNumTypeObjects() > 0) {
5932       // C++ [dcl.ref]p4: There shall be no references to references.
5933       DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5934       if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5935         if (const IdentifierInfo *II = D.getIdentifier())
5936           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5937            << II;
5938         else
5939           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5940             << "type name";
5941 
5942         // Once we've complained about the reference-to-reference, we
5943         // can go ahead and build the (technically ill-formed)
5944         // declarator: reference collapsing will take care of it.
5945       }
5946     }
5947 
5948     // Remember that we parsed a reference type.
5949     D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5950                                                 Kind == tok::amp),
5951                   std::move(DS.getAttributes()), SourceLocation());
5952   }
5953 }
5954 
5955 // When correcting from misplaced brackets before the identifier, the location
5956 // is saved inside the declarator so that other diagnostic messages can use
5957 // them.  This extracts and returns that location, or returns the provided
5958 // location if a stored location does not exist.
5959 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5960                                                 SourceLocation Loc) {
5961   if (D.getName().StartLocation.isInvalid() &&
5962       D.getName().EndLocation.isValid())
5963     return D.getName().EndLocation;
5964 
5965   return Loc;
5966 }
5967 
5968 /// ParseDirectDeclarator
5969 ///       direct-declarator: [C99 6.7.5]
5970 /// [C99]   identifier
5971 ///         '(' declarator ')'
5972 /// [GNU]   '(' attributes declarator ')'
5973 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
5974 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5975 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5976 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5977 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
5978 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5979 ///                    attribute-specifier-seq[opt]
5980 ///         direct-declarator '(' parameter-type-list ')'
5981 ///         direct-declarator '(' identifier-list[opt] ')'
5982 /// [GNU]   direct-declarator '(' parameter-forward-declarations
5983 ///                    parameter-type-list[opt] ')'
5984 /// [C++]   direct-declarator '(' parameter-declaration-clause ')'
5985 ///                    cv-qualifier-seq[opt] exception-specification[opt]
5986 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5987 ///                    attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5988 ///                    ref-qualifier[opt] exception-specification[opt]
5989 /// [C++]   declarator-id
5990 /// [C++11] declarator-id attribute-specifier-seq[opt]
5991 ///
5992 ///       declarator-id: [C++ 8]
5993 ///         '...'[opt] id-expression
5994 ///         '::'[opt] nested-name-specifier[opt] type-name
5995 ///
5996 ///       id-expression: [C++ 5.1]
5997 ///         unqualified-id
5998 ///         qualified-id
5999 ///
6000 ///       unqualified-id: [C++ 5.1]
6001 ///         identifier
6002 ///         operator-function-id
6003 ///         conversion-function-id
6004 ///          '~' class-name
6005 ///         template-id
6006 ///
6007 /// C++17 adds the following, which we also handle here:
6008 ///
6009 ///       simple-declaration:
6010 ///         <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
6011 ///
6012 /// Note, any additional constructs added here may need corresponding changes
6013 /// in isConstructorDeclarator.
6014 void Parser::ParseDirectDeclarator(Declarator &D) {
6015   DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6016 
6017   if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
6018     // This might be a C++17 structured binding.
6019     if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
6020         D.getCXXScopeSpec().isEmpty())
6021       return ParseDecompositionDeclarator(D);
6022 
6023     // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6024     // this context it is a bitfield. Also in range-based for statement colon
6025     // may delimit for-range-declaration.
6026     ColonProtectionRAIIObject X(
6027         *this, D.getContext() == DeclaratorContext::Member ||
6028                    (D.getContext() == DeclaratorContext::ForInit &&
6029                     getLangOpts().CPlusPlus11));
6030 
6031     // ParseDeclaratorInternal might already have parsed the scope.
6032     if (D.getCXXScopeSpec().isEmpty()) {
6033       bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6034                              D.getContext() == DeclaratorContext::Member;
6035       ParseOptionalCXXScopeSpecifier(
6036           D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6037           /*ObjectHasErrors=*/false, EnteringContext);
6038     }
6039 
6040     if (D.getCXXScopeSpec().isValid()) {
6041       if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
6042                                              D.getCXXScopeSpec()))
6043         // Change the declaration context for name lookup, until this function
6044         // is exited (and the declarator has been parsed).
6045         DeclScopeObj.EnterDeclaratorScope();
6046       else if (getObjCDeclContext()) {
6047         // Ensure that we don't interpret the next token as an identifier when
6048         // dealing with declarations in an Objective-C container.
6049         D.SetIdentifier(nullptr, Tok.getLocation());
6050         D.setInvalidType(true);
6051         ConsumeToken();
6052         goto PastIdentifier;
6053       }
6054     }
6055 
6056     // C++0x [dcl.fct]p14:
6057     //   There is a syntactic ambiguity when an ellipsis occurs at the end of a
6058     //   parameter-declaration-clause without a preceding comma. In this case,
6059     //   the ellipsis is parsed as part of the abstract-declarator if the type
6060     //   of the parameter either names a template parameter pack that has not
6061     //   been expanded or contains auto; otherwise, it is parsed as part of the
6062     //   parameter-declaration-clause.
6063     if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6064         !((D.getContext() == DeclaratorContext::Prototype ||
6065            D.getContext() == DeclaratorContext::LambdaExprParameter ||
6066            D.getContext() == DeclaratorContext::BlockLiteral) &&
6067           NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
6068           !Actions.containsUnexpandedParameterPacks(D) &&
6069           D.getDeclSpec().getTypeSpecType() != TST_auto)) {
6070       SourceLocation EllipsisLoc = ConsumeToken();
6071       if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
6072         // The ellipsis was put in the wrong place. Recover, and explain to
6073         // the user what they should have done.
6074         ParseDeclarator(D);
6075         if (EllipsisLoc.isValid())
6076           DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6077         return;
6078       } else
6079         D.setEllipsisLoc(EllipsisLoc);
6080 
6081       // The ellipsis can't be followed by a parenthesized declarator. We
6082       // check for that in ParseParenDeclarator, after we have disambiguated
6083       // the l_paren token.
6084     }
6085 
6086     if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
6087                     tok::tilde)) {
6088       // We found something that indicates the start of an unqualified-id.
6089       // Parse that unqualified-id.
6090       bool AllowConstructorName;
6091       bool AllowDeductionGuide;
6092       if (D.getDeclSpec().hasTypeSpecifier()) {
6093         AllowConstructorName = false;
6094         AllowDeductionGuide = false;
6095       } else if (D.getCXXScopeSpec().isSet()) {
6096         AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
6097                                 D.getContext() == DeclaratorContext::Member);
6098         AllowDeductionGuide = false;
6099       } else {
6100         AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
6101         AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
6102                                D.getContext() == DeclaratorContext::Member);
6103       }
6104 
6105       bool HadScope = D.getCXXScopeSpec().isValid();
6106       if (ParseUnqualifiedId(D.getCXXScopeSpec(),
6107                              /*ObjectType=*/nullptr,
6108                              /*ObjectHadErrors=*/false,
6109                              /*EnteringContext=*/true,
6110                              /*AllowDestructorName=*/true, AllowConstructorName,
6111                              AllowDeductionGuide, nullptr, D.getName()) ||
6112           // Once we're past the identifier, if the scope was bad, mark the
6113           // whole declarator bad.
6114           D.getCXXScopeSpec().isInvalid()) {
6115         D.SetIdentifier(nullptr, Tok.getLocation());
6116         D.setInvalidType(true);
6117       } else {
6118         // ParseUnqualifiedId might have parsed a scope specifier during error
6119         // recovery. If it did so, enter that scope.
6120         if (!HadScope && D.getCXXScopeSpec().isValid() &&
6121             Actions.ShouldEnterDeclaratorScope(getCurScope(),
6122                                                D.getCXXScopeSpec()))
6123           DeclScopeObj.EnterDeclaratorScope();
6124 
6125         // Parsed the unqualified-id; update range information and move along.
6126         if (D.getSourceRange().getBegin().isInvalid())
6127           D.SetRangeBegin(D.getName().getSourceRange().getBegin());
6128         D.SetRangeEnd(D.getName().getSourceRange().getEnd());
6129       }
6130       goto PastIdentifier;
6131     }
6132 
6133     if (D.getCXXScopeSpec().isNotEmpty()) {
6134       // We have a scope specifier but no following unqualified-id.
6135       Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
6136            diag::err_expected_unqualified_id)
6137           << /*C++*/1;
6138       D.SetIdentifier(nullptr, Tok.getLocation());
6139       goto PastIdentifier;
6140     }
6141   } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
6142     assert(!getLangOpts().CPlusPlus &&
6143            "There's a C++-specific check for tok::identifier above");
6144     assert(Tok.getIdentifierInfo() && "Not an identifier?");
6145     D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6146     D.SetRangeEnd(Tok.getLocation());
6147     ConsumeToken();
6148     goto PastIdentifier;
6149   } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
6150     // We're not allowed an identifier here, but we got one. Try to figure out
6151     // if the user was trying to attach a name to the type, or whether the name
6152     // is some unrelated trailing syntax.
6153     bool DiagnoseIdentifier = false;
6154     if (D.hasGroupingParens())
6155       // An identifier within parens is unlikely to be intended to be anything
6156       // other than a name being "declared".
6157       DiagnoseIdentifier = true;
6158     else if (D.getContext() == DeclaratorContext::TemplateArg)
6159       // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6160       DiagnoseIdentifier =
6161           NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
6162     else if (D.getContext() == DeclaratorContext::AliasDecl ||
6163              D.getContext() == DeclaratorContext::AliasTemplate)
6164       // The most likely error is that the ';' was forgotten.
6165       DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
6166     else if ((D.getContext() == DeclaratorContext::TrailingReturn ||
6167               D.getContext() == DeclaratorContext::TrailingReturnVar) &&
6168              !isCXX11VirtSpecifier(Tok))
6169       DiagnoseIdentifier = NextToken().isOneOf(
6170           tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
6171     if (DiagnoseIdentifier) {
6172       Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
6173         << FixItHint::CreateRemoval(Tok.getLocation());
6174       D.SetIdentifier(nullptr, Tok.getLocation());
6175       ConsumeToken();
6176       goto PastIdentifier;
6177     }
6178   }
6179 
6180   if (Tok.is(tok::l_paren)) {
6181     // If this might be an abstract-declarator followed by a direct-initializer,
6182     // check whether this is a valid declarator chunk. If it can't be, assume
6183     // that it's an initializer instead.
6184     if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
6185       RevertingTentativeParsingAction PA(*this);
6186       if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
6187               TPResult::False) {
6188         D.SetIdentifier(nullptr, Tok.getLocation());
6189         goto PastIdentifier;
6190       }
6191     }
6192 
6193     // direct-declarator: '(' declarator ')'
6194     // direct-declarator: '(' attributes declarator ')'
6195     // Example: 'char (*X)'   or 'int (*XX)(void)'
6196     ParseParenDeclarator(D);
6197 
6198     // If the declarator was parenthesized, we entered the declarator
6199     // scope when parsing the parenthesized declarator, then exited
6200     // the scope already. Re-enter the scope, if we need to.
6201     if (D.getCXXScopeSpec().isSet()) {
6202       // If there was an error parsing parenthesized declarator, declarator
6203       // scope may have been entered before. Don't do it again.
6204       if (!D.isInvalidType() &&
6205           Actions.ShouldEnterDeclaratorScope(getCurScope(),
6206                                              D.getCXXScopeSpec()))
6207         // Change the declaration context for name lookup, until this function
6208         // is exited (and the declarator has been parsed).
6209         DeclScopeObj.EnterDeclaratorScope();
6210     }
6211   } else if (D.mayOmitIdentifier()) {
6212     // This could be something simple like "int" (in which case the declarator
6213     // portion is empty), if an abstract-declarator is allowed.
6214     D.SetIdentifier(nullptr, Tok.getLocation());
6215 
6216     // The grammar for abstract-pack-declarator does not allow grouping parens.
6217     // FIXME: Revisit this once core issue 1488 is resolved.
6218     if (D.hasEllipsis() && D.hasGroupingParens())
6219       Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
6220            diag::ext_abstract_pack_declarator_parens);
6221   } else {
6222     if (Tok.getKind() == tok::annot_pragma_parser_crash)
6223       LLVM_BUILTIN_TRAP;
6224     if (Tok.is(tok::l_square))
6225       return ParseMisplacedBracketDeclarator(D);
6226     if (D.getContext() == DeclaratorContext::Member) {
6227       // Objective-C++: Detect C++ keywords and try to prevent further errors by
6228       // treating these keyword as valid member names.
6229       if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
6230           Tok.getIdentifierInfo() &&
6231           Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
6232         Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6233              diag::err_expected_member_name_or_semi_objcxx_keyword)
6234             << Tok.getIdentifierInfo()
6235             << (D.getDeclSpec().isEmpty() ? SourceRange()
6236                                           : D.getDeclSpec().getSourceRange());
6237         D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6238         D.SetRangeEnd(Tok.getLocation());
6239         ConsumeToken();
6240         goto PastIdentifier;
6241       }
6242       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6243            diag::err_expected_member_name_or_semi)
6244           << (D.getDeclSpec().isEmpty() ? SourceRange()
6245                                         : D.getDeclSpec().getSourceRange());
6246     } else if (getLangOpts().CPlusPlus) {
6247       if (Tok.isOneOf(tok::period, tok::arrow))
6248         Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
6249       else {
6250         SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
6251         if (Tok.isAtStartOfLine() && Loc.isValid())
6252           Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
6253               << getLangOpts().CPlusPlus;
6254         else
6255           Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6256                diag::err_expected_unqualified_id)
6257               << getLangOpts().CPlusPlus;
6258       }
6259     } else {
6260       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6261            diag::err_expected_either)
6262           << tok::identifier << tok::l_paren;
6263     }
6264     D.SetIdentifier(nullptr, Tok.getLocation());
6265     D.setInvalidType(true);
6266   }
6267 
6268  PastIdentifier:
6269   assert(D.isPastIdentifier() &&
6270          "Haven't past the location of the identifier yet?");
6271 
6272   // Don't parse attributes unless we have parsed an unparenthesized name.
6273   if (D.hasName() && !D.getNumTypeObjects())
6274     MaybeParseCXX11Attributes(D);
6275 
6276   while (true) {
6277     if (Tok.is(tok::l_paren)) {
6278       bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
6279       // Enter function-declaration scope, limiting any declarators to the
6280       // function prototype scope, including parameter declarators.
6281       ParseScope PrototypeScope(this,
6282                                 Scope::FunctionPrototypeScope|Scope::DeclScope|
6283                                 (IsFunctionDeclaration
6284                                    ? Scope::FunctionDeclarationScope : 0));
6285 
6286       // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6287       // In such a case, check if we actually have a function declarator; if it
6288       // is not, the declarator has been fully parsed.
6289       bool IsAmbiguous = false;
6290       if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
6291         // The name of the declarator, if any, is tentatively declared within
6292         // a possible direct initializer.
6293         TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6294         bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
6295         TentativelyDeclaredIdentifiers.pop_back();
6296         if (!IsFunctionDecl)
6297           break;
6298       }
6299       ParsedAttributes attrs(AttrFactory);
6300       BalancedDelimiterTracker T(*this, tok::l_paren);
6301       T.consumeOpen();
6302       if (IsFunctionDeclaration)
6303         Actions.ActOnStartFunctionDeclarationDeclarator(D,
6304                                                         TemplateParameterDepth);
6305       ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6306       if (IsFunctionDeclaration)
6307         Actions.ActOnFinishFunctionDeclarationDeclarator(D);
6308       PrototypeScope.Exit();
6309     } else if (Tok.is(tok::l_square)) {
6310       ParseBracketDeclarator(D);
6311     } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
6312       // This declarator is declaring a function, but the requires clause is
6313       // in the wrong place:
6314       //   void (f() requires true);
6315       // instead of
6316       //   void f() requires true;
6317       // or
6318       //   void (f()) requires true;
6319       Diag(Tok, diag::err_requires_clause_inside_parens);
6320       ConsumeToken();
6321       ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
6322          ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6323       if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
6324           !D.hasTrailingRequiresClause())
6325         // We're already ill-formed if we got here but we'll accept it anyway.
6326         D.setTrailingRequiresClause(TrailingRequiresClause.get());
6327     } else {
6328       break;
6329     }
6330   }
6331 }
6332 
6333 void Parser::ParseDecompositionDeclarator(Declarator &D) {
6334   assert(Tok.is(tok::l_square));
6335 
6336   // If this doesn't look like a structured binding, maybe it's a misplaced
6337   // array declarator.
6338   // FIXME: Consume the l_square first so we don't need extra lookahead for
6339   // this.
6340   if (!(NextToken().is(tok::identifier) &&
6341         GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
6342       !(NextToken().is(tok::r_square) &&
6343         GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
6344     return ParseMisplacedBracketDeclarator(D);
6345 
6346   BalancedDelimiterTracker T(*this, tok::l_square);
6347   T.consumeOpen();
6348 
6349   SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
6350   while (Tok.isNot(tok::r_square)) {
6351     if (!Bindings.empty()) {
6352       if (Tok.is(tok::comma))
6353         ConsumeToken();
6354       else {
6355         if (Tok.is(tok::identifier)) {
6356           SourceLocation EndLoc = getEndOfPreviousToken();
6357           Diag(EndLoc, diag::err_expected)
6358               << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6359         } else {
6360           Diag(Tok, diag::err_expected_comma_or_rsquare);
6361         }
6362 
6363         SkipUntil(tok::r_square, tok::comma, tok::identifier,
6364                   StopAtSemi | StopBeforeMatch);
6365         if (Tok.is(tok::comma))
6366           ConsumeToken();
6367         else if (Tok.isNot(tok::identifier))
6368           break;
6369       }
6370     }
6371 
6372     if (Tok.isNot(tok::identifier)) {
6373       Diag(Tok, diag::err_expected) << tok::identifier;
6374       break;
6375     }
6376 
6377     Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6378     ConsumeToken();
6379   }
6380 
6381   if (Tok.isNot(tok::r_square))
6382     // We've already diagnosed a problem here.
6383     T.skipToEnd();
6384   else {
6385     // C++17 does not allow the identifier-list in a structured binding
6386     // to be empty.
6387     if (Bindings.empty())
6388       Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6389 
6390     T.consumeClose();
6391   }
6392 
6393   return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6394                                     T.getCloseLocation());
6395 }
6396 
6397 /// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
6398 /// only called before the identifier, so these are most likely just grouping
6399 /// parens for precedence.  If we find that these are actually function
6400 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6401 ///
6402 ///       direct-declarator:
6403 ///         '(' declarator ')'
6404 /// [GNU]   '(' attributes declarator ')'
6405 ///         direct-declarator '(' parameter-type-list ')'
6406 ///         direct-declarator '(' identifier-list[opt] ')'
6407 /// [GNU]   direct-declarator '(' parameter-forward-declarations
6408 ///                    parameter-type-list[opt] ')'
6409 ///
6410 void Parser::ParseParenDeclarator(Declarator &D) {
6411   BalancedDelimiterTracker T(*this, tok::l_paren);
6412   T.consumeOpen();
6413 
6414   assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6415 
6416   // Eat any attributes before we look at whether this is a grouping or function
6417   // declarator paren.  If this is a grouping paren, the attribute applies to
6418   // the type being built up, for example:
6419   //     int (__attribute__(()) *x)(long y)
6420   // If this ends up not being a grouping paren, the attribute applies to the
6421   // first argument, for example:
6422   //     int (__attribute__(()) int x)
6423   // In either case, we need to eat any attributes to be able to determine what
6424   // sort of paren this is.
6425   //
6426   ParsedAttributes attrs(AttrFactory);
6427   bool RequiresArg = false;
6428   if (Tok.is(tok::kw___attribute)) {
6429     ParseGNUAttributes(attrs);
6430 
6431     // We require that the argument list (if this is a non-grouping paren) be
6432     // present even if the attribute list was empty.
6433     RequiresArg = true;
6434   }
6435 
6436   // Eat any Microsoft extensions.
6437   ParseMicrosoftTypeAttributes(attrs);
6438 
6439   // Eat any Borland extensions.
6440   if  (Tok.is(tok::kw___pascal))
6441     ParseBorlandTypeAttributes(attrs);
6442 
6443   // If we haven't past the identifier yet (or where the identifier would be
6444   // stored, if this is an abstract declarator), then this is probably just
6445   // grouping parens. However, if this could be an abstract-declarator, then
6446   // this could also be the start of function arguments (consider 'void()').
6447   bool isGrouping;
6448 
6449   if (!D.mayOmitIdentifier()) {
6450     // If this can't be an abstract-declarator, this *must* be a grouping
6451     // paren, because we haven't seen the identifier yet.
6452     isGrouping = true;
6453   } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
6454              (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6455               NextToken().is(tok::r_paren)) || // C++ int(...)
6456              isDeclarationSpecifier() ||       // 'int(int)' is a function.
6457              isCXX11AttributeSpecifier()) {    // 'int([[]]int)' is a function.
6458     // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6459     // considered to be a type, not a K&R identifier-list.
6460     isGrouping = false;
6461   } else {
6462     // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6463     isGrouping = true;
6464   }
6465 
6466   // If this is a grouping paren, handle:
6467   // direct-declarator: '(' declarator ')'
6468   // direct-declarator: '(' attributes declarator ')'
6469   if (isGrouping) {
6470     SourceLocation EllipsisLoc = D.getEllipsisLoc();
6471     D.setEllipsisLoc(SourceLocation());
6472 
6473     bool hadGroupingParens = D.hasGroupingParens();
6474     D.setGroupingParens(true);
6475     ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6476     // Match the ')'.
6477     T.consumeClose();
6478     D.AddTypeInfo(
6479         DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6480         std::move(attrs), T.getCloseLocation());
6481 
6482     D.setGroupingParens(hadGroupingParens);
6483 
6484     // An ellipsis cannot be placed outside parentheses.
6485     if (EllipsisLoc.isValid())
6486       DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6487 
6488     return;
6489   }
6490 
6491   // Okay, if this wasn't a grouping paren, it must be the start of a function
6492   // argument list.  Recognize that this declarator will never have an
6493   // identifier (and remember where it would have been), then call into
6494   // ParseFunctionDeclarator to handle of argument list.
6495   D.SetIdentifier(nullptr, Tok.getLocation());
6496 
6497   // Enter function-declaration scope, limiting any declarators to the
6498   // function prototype scope, including parameter declarators.
6499   ParseScope PrototypeScope(this,
6500                             Scope::FunctionPrototypeScope | Scope::DeclScope |
6501                             (D.isFunctionDeclaratorAFunctionDeclaration()
6502                                ? Scope::FunctionDeclarationScope : 0));
6503   ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6504   PrototypeScope.Exit();
6505 }
6506 
6507 void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
6508     const Declarator &D, const DeclSpec &DS,
6509     llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope) {
6510   // C++11 [expr.prim.general]p3:
6511   //   If a declaration declares a member function or member function
6512   //   template of a class X, the expression this is a prvalue of type
6513   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6514   //   and the end of the function-definition, member-declarator, or
6515   //   declarator.
6516   // FIXME: currently, "static" case isn't handled correctly.
6517   bool IsCXX11MemberFunction =
6518       getLangOpts().CPlusPlus11 &&
6519       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6520       (D.getContext() == DeclaratorContext::Member
6521            ? !D.getDeclSpec().isFriendSpecified()
6522            : D.getContext() == DeclaratorContext::File &&
6523                  D.getCXXScopeSpec().isValid() &&
6524                  Actions.CurContext->isRecord());
6525   if (!IsCXX11MemberFunction)
6526     return;
6527 
6528   Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6529   if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6530     Q.addConst();
6531   // FIXME: Collect C++ address spaces.
6532   // If there are multiple different address spaces, the source is invalid.
6533   // Carry on using the first addr space for the qualifiers of 'this'.
6534   // The diagnostic will be given later while creating the function
6535   // prototype for the method.
6536   if (getLangOpts().OpenCLCPlusPlus) {
6537     for (ParsedAttr &attr : DS.getAttributes()) {
6538       LangAS ASIdx = attr.asOpenCLLangAS();
6539       if (ASIdx != LangAS::Default) {
6540         Q.addAddressSpace(ASIdx);
6541         break;
6542       }
6543     }
6544   }
6545   ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6546                     IsCXX11MemberFunction);
6547 }
6548 
6549 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6550 /// declarator D up to a paren, which indicates that we are parsing function
6551 /// arguments.
6552 ///
6553 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6554 /// immediately after the open paren - they should be considered to be the
6555 /// first argument of a parameter.
6556 ///
6557 /// If RequiresArg is true, then the first argument of the function is required
6558 /// to be present and required to not be an identifier list.
6559 ///
6560 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6561 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6562 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
6563 /// (C++2a) the trailing requires-clause.
6564 ///
6565 /// [C++11] exception-specification:
6566 ///           dynamic-exception-specification
6567 ///           noexcept-specification
6568 ///
6569 void Parser::ParseFunctionDeclarator(Declarator &D,
6570                                      ParsedAttributes &FirstArgAttrs,
6571                                      BalancedDelimiterTracker &Tracker,
6572                                      bool IsAmbiguous,
6573                                      bool RequiresArg) {
6574   assert(getCurScope()->isFunctionPrototypeScope() &&
6575          "Should call from a Function scope");
6576   // lparen is already consumed!
6577   assert(D.isPastIdentifier() && "Should not call before identifier!");
6578 
6579   // This should be true when the function has typed arguments.
6580   // Otherwise, it is treated as a K&R-style function.
6581   bool HasProto = false;
6582   // Build up an array of information about the parsed arguments.
6583   SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6584   // Remember where we see an ellipsis, if any.
6585   SourceLocation EllipsisLoc;
6586 
6587   DeclSpec DS(AttrFactory);
6588   bool RefQualifierIsLValueRef = true;
6589   SourceLocation RefQualifierLoc;
6590   ExceptionSpecificationType ESpecType = EST_None;
6591   SourceRange ESpecRange;
6592   SmallVector<ParsedType, 2> DynamicExceptions;
6593   SmallVector<SourceRange, 2> DynamicExceptionRanges;
6594   ExprResult NoexceptExpr;
6595   CachedTokens *ExceptionSpecTokens = nullptr;
6596   ParsedAttributesWithRange FnAttrs(AttrFactory);
6597   TypeResult TrailingReturnType;
6598   SourceLocation TrailingReturnTypeLoc;
6599 
6600   /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6601      EndLoc is the end location for the function declarator.
6602      They differ for trailing return types. */
6603   SourceLocation StartLoc, LocalEndLoc, EndLoc;
6604   SourceLocation LParenLoc, RParenLoc;
6605   LParenLoc = Tracker.getOpenLocation();
6606   StartLoc = LParenLoc;
6607 
6608   if (isFunctionDeclaratorIdentifierList()) {
6609     if (RequiresArg)
6610       Diag(Tok, diag::err_argument_required_after_attribute);
6611 
6612     ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6613 
6614     Tracker.consumeClose();
6615     RParenLoc = Tracker.getCloseLocation();
6616     LocalEndLoc = RParenLoc;
6617     EndLoc = RParenLoc;
6618 
6619     // If there are attributes following the identifier list, parse them and
6620     // prohibit them.
6621     MaybeParseCXX11Attributes(FnAttrs);
6622     ProhibitAttributes(FnAttrs);
6623   } else {
6624     if (Tok.isNot(tok::r_paren))
6625       ParseParameterDeclarationClause(D.getContext(), FirstArgAttrs, ParamInfo,
6626                                       EllipsisLoc);
6627     else if (RequiresArg)
6628       Diag(Tok, diag::err_argument_required_after_attribute);
6629 
6630     HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6631                                 || getLangOpts().OpenCL;
6632 
6633     // If we have the closing ')', eat it.
6634     Tracker.consumeClose();
6635     RParenLoc = Tracker.getCloseLocation();
6636     LocalEndLoc = RParenLoc;
6637     EndLoc = RParenLoc;
6638 
6639     if (getLangOpts().CPlusPlus) {
6640       // FIXME: Accept these components in any order, and produce fixits to
6641       // correct the order if the user gets it wrong. Ideally we should deal
6642       // with the pure-specifier in the same way.
6643 
6644       // Parse cv-qualifier-seq[opt].
6645       ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6646                                 /*AtomicAllowed*/ false,
6647                                 /*IdentifierRequired=*/false,
6648                                 llvm::function_ref<void()>([&]() {
6649                                   Actions.CodeCompleteFunctionQualifiers(DS, D);
6650                                 }));
6651       if (!DS.getSourceRange().getEnd().isInvalid()) {
6652         EndLoc = DS.getSourceRange().getEnd();
6653       }
6654 
6655       // Parse ref-qualifier[opt].
6656       if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6657         EndLoc = RefQualifierLoc;
6658 
6659       llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
6660       InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
6661 
6662       // Parse exception-specification[opt].
6663       // FIXME: Per [class.mem]p6, all exception-specifications at class scope
6664       // should be delayed, including those for non-members (eg, friend
6665       // declarations). But only applying this to member declarations is
6666       // consistent with what other implementations do.
6667       bool Delayed = D.isFirstDeclarationOfMember() &&
6668                      D.isFunctionDeclaratorAFunctionDeclaration();
6669       if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6670           GetLookAheadToken(0).is(tok::kw_noexcept) &&
6671           GetLookAheadToken(1).is(tok::l_paren) &&
6672           GetLookAheadToken(2).is(tok::kw_noexcept) &&
6673           GetLookAheadToken(3).is(tok::l_paren) &&
6674           GetLookAheadToken(4).is(tok::identifier) &&
6675           GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6676         // HACK: We've got an exception-specification
6677         //   noexcept(noexcept(swap(...)))
6678         // or
6679         //   noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6680         // on a 'swap' member function. This is a libstdc++ bug; the lookup
6681         // for 'swap' will only find the function we're currently declaring,
6682         // whereas it expects to find a non-member swap through ADL. Turn off
6683         // delayed parsing to give it a chance to find what it expects.
6684         Delayed = false;
6685       }
6686       ESpecType = tryParseExceptionSpecification(Delayed,
6687                                                  ESpecRange,
6688                                                  DynamicExceptions,
6689                                                  DynamicExceptionRanges,
6690                                                  NoexceptExpr,
6691                                                  ExceptionSpecTokens);
6692       if (ESpecType != EST_None)
6693         EndLoc = ESpecRange.getEnd();
6694 
6695       // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6696       // after the exception-specification.
6697       MaybeParseCXX11Attributes(FnAttrs);
6698 
6699       // Parse trailing-return-type[opt].
6700       LocalEndLoc = EndLoc;
6701       if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6702         Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6703         if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6704           StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6705         LocalEndLoc = Tok.getLocation();
6706         SourceRange Range;
6707         TrailingReturnType =
6708             ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6709         TrailingReturnTypeLoc = Range.getBegin();
6710         EndLoc = Range.getEnd();
6711       }
6712     } else if (standardAttributesAllowed()) {
6713       MaybeParseCXX11Attributes(FnAttrs);
6714     }
6715   }
6716 
6717   // Collect non-parameter declarations from the prototype if this is a function
6718   // declaration. They will be moved into the scope of the function. Only do
6719   // this in C and not C++, where the decls will continue to live in the
6720   // surrounding context.
6721   SmallVector<NamedDecl *, 0> DeclsInPrototype;
6722   if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6723       !getLangOpts().CPlusPlus) {
6724     for (Decl *D : getCurScope()->decls()) {
6725       NamedDecl *ND = dyn_cast<NamedDecl>(D);
6726       if (!ND || isa<ParmVarDecl>(ND))
6727         continue;
6728       DeclsInPrototype.push_back(ND);
6729     }
6730   }
6731 
6732   // Remember that we parsed a function type, and remember the attributes.
6733   D.AddTypeInfo(DeclaratorChunk::getFunction(
6734                     HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6735                     ParamInfo.size(), EllipsisLoc, RParenLoc,
6736                     RefQualifierIsLValueRef, RefQualifierLoc,
6737                     /*MutableLoc=*/SourceLocation(),
6738                     ESpecType, ESpecRange, DynamicExceptions.data(),
6739                     DynamicExceptionRanges.data(), DynamicExceptions.size(),
6740                     NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6741                     ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6742                     LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
6743                     &DS),
6744                 std::move(FnAttrs), EndLoc);
6745 }
6746 
6747 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6748 /// true if a ref-qualifier is found.
6749 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6750                                SourceLocation &RefQualifierLoc) {
6751   if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6752     Diag(Tok, getLangOpts().CPlusPlus11 ?
6753          diag::warn_cxx98_compat_ref_qualifier :
6754          diag::ext_ref_qualifier);
6755 
6756     RefQualifierIsLValueRef = Tok.is(tok::amp);
6757     RefQualifierLoc = ConsumeToken();
6758     return true;
6759   }
6760   return false;
6761 }
6762 
6763 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6764 /// identifier list form for a K&R-style function:  void foo(a,b,c)
6765 ///
6766 /// Note that identifier-lists are only allowed for normal declarators, not for
6767 /// abstract-declarators.
6768 bool Parser::isFunctionDeclaratorIdentifierList() {
6769   return !getLangOpts().CPlusPlus
6770          && Tok.is(tok::identifier)
6771          && !TryAltiVecVectorToken()
6772          // K&R identifier lists can't have typedefs as identifiers, per C99
6773          // 6.7.5.3p11.
6774          && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6775          // Identifier lists follow a really simple grammar: the identifiers can
6776          // be followed *only* by a ", identifier" or ")".  However, K&R
6777          // identifier lists are really rare in the brave new modern world, and
6778          // it is very common for someone to typo a type in a non-K&R style
6779          // list.  If we are presented with something like: "void foo(intptr x,
6780          // float y)", we don't want to start parsing the function declarator as
6781          // though it is a K&R style declarator just because intptr is an
6782          // invalid type.
6783          //
6784          // To handle this, we check to see if the token after the first
6785          // identifier is a "," or ")".  Only then do we parse it as an
6786          // identifier list.
6787          && (!Tok.is(tok::eof) &&
6788              (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6789 }
6790 
6791 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6792 /// we found a K&R-style identifier list instead of a typed parameter list.
6793 ///
6794 /// After returning, ParamInfo will hold the parsed parameters.
6795 ///
6796 ///       identifier-list: [C99 6.7.5]
6797 ///         identifier
6798 ///         identifier-list ',' identifier
6799 ///
6800 void Parser::ParseFunctionDeclaratorIdentifierList(
6801        Declarator &D,
6802        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6803   // If there was no identifier specified for the declarator, either we are in
6804   // an abstract-declarator, or we are in a parameter declarator which was found
6805   // to be abstract.  In abstract-declarators, identifier lists are not valid:
6806   // diagnose this.
6807   if (!D.getIdentifier())
6808     Diag(Tok, diag::ext_ident_list_in_param);
6809 
6810   // Maintain an efficient lookup of params we have seen so far.
6811   llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6812 
6813   do {
6814     // If this isn't an identifier, report the error and skip until ')'.
6815     if (Tok.isNot(tok::identifier)) {
6816       Diag(Tok, diag::err_expected) << tok::identifier;
6817       SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6818       // Forget we parsed anything.
6819       ParamInfo.clear();
6820       return;
6821     }
6822 
6823     IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6824 
6825     // Reject 'typedef int y; int test(x, y)', but continue parsing.
6826     if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6827       Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6828 
6829     // Verify that the argument identifier has not already been mentioned.
6830     if (!ParamsSoFar.insert(ParmII).second) {
6831       Diag(Tok, diag::err_param_redefinition) << ParmII;
6832     } else {
6833       // Remember this identifier in ParamInfo.
6834       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6835                                                      Tok.getLocation(),
6836                                                      nullptr));
6837     }
6838 
6839     // Eat the identifier.
6840     ConsumeToken();
6841     // The list continues if we see a comma.
6842   } while (TryConsumeToken(tok::comma));
6843 }
6844 
6845 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6846 /// after the opening parenthesis. This function will not parse a K&R-style
6847 /// identifier list.
6848 ///
6849 /// DeclContext is the context of the declarator being parsed.  If FirstArgAttrs
6850 /// is non-null, then the caller parsed those attributes immediately after the
6851 /// open paren - they should be considered to be part of the first parameter.
6852 ///
6853 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6854 /// be the location of the ellipsis, if any was parsed.
6855 ///
6856 ///       parameter-type-list: [C99 6.7.5]
6857 ///         parameter-list
6858 ///         parameter-list ',' '...'
6859 /// [C++]   parameter-list '...'
6860 ///
6861 ///       parameter-list: [C99 6.7.5]
6862 ///         parameter-declaration
6863 ///         parameter-list ',' parameter-declaration
6864 ///
6865 ///       parameter-declaration: [C99 6.7.5]
6866 ///         declaration-specifiers declarator
6867 /// [C++]   declaration-specifiers declarator '=' assignment-expression
6868 /// [C++11]                                       initializer-clause
6869 /// [GNU]   declaration-specifiers declarator attributes
6870 ///         declaration-specifiers abstract-declarator[opt]
6871 /// [C++]   declaration-specifiers abstract-declarator[opt]
6872 ///           '=' assignment-expression
6873 /// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
6874 /// [C++11] attribute-specifier-seq parameter-declaration
6875 ///
6876 void Parser::ParseParameterDeclarationClause(
6877        DeclaratorContext DeclaratorCtx,
6878        ParsedAttributes &FirstArgAttrs,
6879        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6880        SourceLocation &EllipsisLoc) {
6881 
6882   // Avoid exceeding the maximum function scope depth.
6883   // See https://bugs.llvm.org/show_bug.cgi?id=19607
6884   // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
6885   // getFunctionPrototypeDepth() - 1.
6886   if (getCurScope()->getFunctionPrototypeDepth() - 1 >
6887       ParmVarDecl::getMaxFunctionScopeDepth()) {
6888     Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
6889         << ParmVarDecl::getMaxFunctionScopeDepth();
6890     cutOffParsing();
6891     return;
6892   }
6893 
6894   do {
6895     // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6896     // before deciding this was a parameter-declaration-clause.
6897     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6898       break;
6899 
6900     // Parse the declaration-specifiers.
6901     // Just use the ParsingDeclaration "scope" of the declarator.
6902     DeclSpec DS(AttrFactory);
6903 
6904     // Parse any C++11 attributes.
6905     MaybeParseCXX11Attributes(DS.getAttributes());
6906 
6907     // Skip any Microsoft attributes before a param.
6908     MaybeParseMicrosoftAttributes(DS.getAttributes());
6909 
6910     SourceLocation DSStart = Tok.getLocation();
6911 
6912     // If the caller parsed attributes for the first argument, add them now.
6913     // Take them so that we only apply the attributes to the first parameter.
6914     // FIXME: If we can leave the attributes in the token stream somehow, we can
6915     // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6916     // too much hassle.
6917     DS.takeAttributesFrom(FirstArgAttrs);
6918 
6919     ParseDeclarationSpecifiers(DS);
6920 
6921 
6922     // Parse the declarator.  This is "PrototypeContext" or
6923     // "LambdaExprParameterContext", because we must accept either
6924     // 'declarator' or 'abstract-declarator' here.
6925     Declarator ParmDeclarator(
6926         DS, DeclaratorCtx == DeclaratorContext::RequiresExpr
6927                 ? DeclaratorContext::RequiresExpr
6928                 : DeclaratorCtx == DeclaratorContext::LambdaExpr
6929                       ? DeclaratorContext::LambdaExprParameter
6930                       : DeclaratorContext::Prototype);
6931     ParseDeclarator(ParmDeclarator);
6932 
6933     // Parse GNU attributes, if present.
6934     MaybeParseGNUAttributes(ParmDeclarator);
6935 
6936     if (Tok.is(tok::kw_requires)) {
6937       // User tried to define a requires clause in a parameter declaration,
6938       // which is surely not a function declaration.
6939       // void f(int (*g)(int, int) requires true);
6940       Diag(Tok,
6941            diag::err_requires_clause_on_declarator_not_declaring_a_function);
6942       ConsumeToken();
6943       Actions.CorrectDelayedTyposInExpr(
6944          ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6945     }
6946 
6947     // Remember this parsed parameter in ParamInfo.
6948     IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6949 
6950     // DefArgToks is used when the parsing of default arguments needs
6951     // to be delayed.
6952     std::unique_ptr<CachedTokens> DefArgToks;
6953 
6954     // If no parameter was specified, verify that *something* was specified,
6955     // otherwise we have a missing type and identifier.
6956     if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6957         ParmDeclarator.getNumTypeObjects() == 0) {
6958       // Completely missing, emit error.
6959       Diag(DSStart, diag::err_missing_param);
6960     } else {
6961       // Otherwise, we have something.  Add it and let semantic analysis try
6962       // to grok it and add the result to the ParamInfo we are building.
6963 
6964       // Last chance to recover from a misplaced ellipsis in an attempted
6965       // parameter pack declaration.
6966       if (Tok.is(tok::ellipsis) &&
6967           (NextToken().isNot(tok::r_paren) ||
6968            (!ParmDeclarator.getEllipsisLoc().isValid() &&
6969             !Actions.isUnexpandedParameterPackPermitted())) &&
6970           Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6971         DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6972 
6973       // Now we are at the point where declarator parsing is finished.
6974       //
6975       // Try to catch keywords in place of the identifier in a declarator, and
6976       // in particular the common case where:
6977       //   1 identifier comes at the end of the declarator
6978       //   2 if the identifier is dropped, the declarator is valid but anonymous
6979       //     (no identifier)
6980       //   3 declarator parsing succeeds, and then we have a trailing keyword,
6981       //     which is never valid in a param list (e.g. missing a ',')
6982       // And we can't handle this in ParseDeclarator because in general keywords
6983       // may be allowed to follow the declarator. (And in some cases there'd be
6984       // better recovery like inserting punctuation). ParseDeclarator is just
6985       // treating this as an anonymous parameter, and fortunately at this point
6986       // we've already almost done that.
6987       //
6988       // We care about case 1) where the declarator type should be known, and
6989       // the identifier should be null.
6990       if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
6991           Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
6992           Tok.getIdentifierInfo() &&
6993           Tok.getIdentifierInfo()->isKeyword(getLangOpts())) {
6994         Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
6995         // Consume the keyword.
6996         ConsumeToken();
6997       }
6998       // Inform the actions module about the parameter declarator, so it gets
6999       // added to the current scope.
7000       Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
7001       // Parse the default argument, if any. We parse the default
7002       // arguments in all dialects; the semantic analysis in
7003       // ActOnParamDefaultArgument will reject the default argument in
7004       // C.
7005       if (Tok.is(tok::equal)) {
7006         SourceLocation EqualLoc = Tok.getLocation();
7007 
7008         // Parse the default argument
7009         if (DeclaratorCtx == DeclaratorContext::Member) {
7010           // If we're inside a class definition, cache the tokens
7011           // corresponding to the default argument. We'll actually parse
7012           // them when we see the end of the class definition.
7013           DefArgToks.reset(new CachedTokens);
7014 
7015           SourceLocation ArgStartLoc = NextToken().getLocation();
7016           if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
7017             DefArgToks.reset();
7018             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
7019           } else {
7020             Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
7021                                                       ArgStartLoc);
7022           }
7023         } else {
7024           // Consume the '='.
7025           ConsumeToken();
7026 
7027           // The argument isn't actually potentially evaluated unless it is
7028           // used.
7029           EnterExpressionEvaluationContext Eval(
7030               Actions,
7031               Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
7032               Param);
7033 
7034           ExprResult DefArgResult;
7035           if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
7036             Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
7037             DefArgResult = ParseBraceInitializer();
7038           } else
7039             DefArgResult = ParseAssignmentExpression();
7040           DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
7041           if (DefArgResult.isInvalid()) {
7042             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
7043             SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
7044           } else {
7045             // Inform the actions module about the default argument
7046             Actions.ActOnParamDefaultArgument(Param, EqualLoc,
7047                                               DefArgResult.get());
7048           }
7049         }
7050       }
7051 
7052       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7053                                           ParmDeclarator.getIdentifierLoc(),
7054                                           Param, std::move(DefArgToks)));
7055     }
7056 
7057     if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
7058       if (!getLangOpts().CPlusPlus) {
7059         // We have ellipsis without a preceding ',', which is ill-formed
7060         // in C. Complain and provide the fix.
7061         Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
7062             << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7063       } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
7064                  Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
7065         // It looks like this was supposed to be a parameter pack. Warn and
7066         // point out where the ellipsis should have gone.
7067         SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
7068         Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
7069           << ParmEllipsis.isValid() << ParmEllipsis;
7070         if (ParmEllipsis.isValid()) {
7071           Diag(ParmEllipsis,
7072                diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7073         } else {
7074           Diag(ParmDeclarator.getIdentifierLoc(),
7075                diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7076             << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
7077                                           "...")
7078             << !ParmDeclarator.hasName();
7079         }
7080         Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
7081           << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7082       }
7083 
7084       // We can't have any more parameters after an ellipsis.
7085       break;
7086     }
7087 
7088     // If the next token is a comma, consume it and keep reading arguments.
7089   } while (TryConsumeToken(tok::comma));
7090 }
7091 
7092 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
7093 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
7094 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
7095 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
7096 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
7097 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
7098 ///                           attribute-specifier-seq[opt]
7099 void Parser::ParseBracketDeclarator(Declarator &D) {
7100   if (CheckProhibitedCXX11Attribute())
7101     return;
7102 
7103   BalancedDelimiterTracker T(*this, tok::l_square);
7104   T.consumeOpen();
7105 
7106   // C array syntax has many features, but by-far the most common is [] and [4].
7107   // This code does a fast path to handle some of the most obvious cases.
7108   if (Tok.getKind() == tok::r_square) {
7109     T.consumeClose();
7110     ParsedAttributes attrs(AttrFactory);
7111     MaybeParseCXX11Attributes(attrs);
7112 
7113     // Remember that we parsed the empty array type.
7114     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
7115                                             T.getOpenLocation(),
7116                                             T.getCloseLocation()),
7117                   std::move(attrs), T.getCloseLocation());
7118     return;
7119   } else if (Tok.getKind() == tok::numeric_constant &&
7120              GetLookAheadToken(1).is(tok::r_square)) {
7121     // [4] is very common.  Parse the numeric constant expression.
7122     ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
7123     ConsumeToken();
7124 
7125     T.consumeClose();
7126     ParsedAttributes attrs(AttrFactory);
7127     MaybeParseCXX11Attributes(attrs);
7128 
7129     // Remember that we parsed a array type, and remember its features.
7130     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
7131                                             T.getOpenLocation(),
7132                                             T.getCloseLocation()),
7133                   std::move(attrs), T.getCloseLocation());
7134     return;
7135   } else if (Tok.getKind() == tok::code_completion) {
7136     cutOffParsing();
7137     Actions.CodeCompleteBracketDeclarator(getCurScope());
7138     return;
7139   }
7140 
7141   // If valid, this location is the position where we read the 'static' keyword.
7142   SourceLocation StaticLoc;
7143   TryConsumeToken(tok::kw_static, StaticLoc);
7144 
7145   // If there is a type-qualifier-list, read it now.
7146   // Type qualifiers in an array subscript are a C99 feature.
7147   DeclSpec DS(AttrFactory);
7148   ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
7149 
7150   // If we haven't already read 'static', check to see if there is one after the
7151   // type-qualifier-list.
7152   if (!StaticLoc.isValid())
7153     TryConsumeToken(tok::kw_static, StaticLoc);
7154 
7155   // Handle "direct-declarator [ type-qual-list[opt] * ]".
7156   bool isStar = false;
7157   ExprResult NumElements;
7158 
7159   // Handle the case where we have '[*]' as the array size.  However, a leading
7160   // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
7161   // the token after the star is a ']'.  Since stars in arrays are
7162   // infrequent, use of lookahead is not costly here.
7163   if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
7164     ConsumeToken();  // Eat the '*'.
7165 
7166     if (StaticLoc.isValid()) {
7167       Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
7168       StaticLoc = SourceLocation();  // Drop the static.
7169     }
7170     isStar = true;
7171   } else if (Tok.isNot(tok::r_square)) {
7172     // Note, in C89, this production uses the constant-expr production instead
7173     // of assignment-expr.  The only difference is that assignment-expr allows
7174     // things like '=' and '*='.  Sema rejects these in C89 mode because they
7175     // are not i-c-e's, so we don't need to distinguish between the two here.
7176 
7177     // Parse the constant-expression or assignment-expression now (depending
7178     // on dialect).
7179     if (getLangOpts().CPlusPlus) {
7180       NumElements = ParseConstantExpression();
7181     } else {
7182       EnterExpressionEvaluationContext Unevaluated(
7183           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7184       NumElements =
7185           Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
7186     }
7187   } else {
7188     if (StaticLoc.isValid()) {
7189       Diag(StaticLoc, diag::err_unspecified_size_with_static);
7190       StaticLoc = SourceLocation();  // Drop the static.
7191     }
7192   }
7193 
7194   // If there was an error parsing the assignment-expression, recover.
7195   if (NumElements.isInvalid()) {
7196     D.setInvalidType(true);
7197     // If the expression was invalid, skip it.
7198     SkipUntil(tok::r_square, StopAtSemi);
7199     return;
7200   }
7201 
7202   T.consumeClose();
7203 
7204   MaybeParseCXX11Attributes(DS.getAttributes());
7205 
7206   // Remember that we parsed a array type, and remember its features.
7207   D.AddTypeInfo(
7208       DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
7209                                 isStar, NumElements.get(), T.getOpenLocation(),
7210                                 T.getCloseLocation()),
7211       std::move(DS.getAttributes()), T.getCloseLocation());
7212 }
7213 
7214 /// Diagnose brackets before an identifier.
7215 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
7216   assert(Tok.is(tok::l_square) && "Missing opening bracket");
7217   assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
7218 
7219   SourceLocation StartBracketLoc = Tok.getLocation();
7220   Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
7221 
7222   while (Tok.is(tok::l_square)) {
7223     ParseBracketDeclarator(TempDeclarator);
7224   }
7225 
7226   // Stuff the location of the start of the brackets into the Declarator.
7227   // The diagnostics from ParseDirectDeclarator will make more sense if
7228   // they use this location instead.
7229   if (Tok.is(tok::semi))
7230     D.getName().EndLocation = StartBracketLoc;
7231 
7232   SourceLocation SuggestParenLoc = Tok.getLocation();
7233 
7234   // Now that the brackets are removed, try parsing the declarator again.
7235   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7236 
7237   // Something went wrong parsing the brackets, in which case,
7238   // ParseBracketDeclarator has emitted an error, and we don't need to emit
7239   // one here.
7240   if (TempDeclarator.getNumTypeObjects() == 0)
7241     return;
7242 
7243   // Determine if parens will need to be suggested in the diagnostic.
7244   bool NeedParens = false;
7245   if (D.getNumTypeObjects() != 0) {
7246     switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
7247     case DeclaratorChunk::Pointer:
7248     case DeclaratorChunk::Reference:
7249     case DeclaratorChunk::BlockPointer:
7250     case DeclaratorChunk::MemberPointer:
7251     case DeclaratorChunk::Pipe:
7252       NeedParens = true;
7253       break;
7254     case DeclaratorChunk::Array:
7255     case DeclaratorChunk::Function:
7256     case DeclaratorChunk::Paren:
7257       break;
7258     }
7259   }
7260 
7261   if (NeedParens) {
7262     // Create a DeclaratorChunk for the inserted parens.
7263     SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7264     D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
7265                   SourceLocation());
7266   }
7267 
7268   // Adding back the bracket info to the end of the Declarator.
7269   for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
7270     const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
7271     D.AddTypeInfo(Chunk, SourceLocation());
7272   }
7273 
7274   // The missing identifier would have been diagnosed in ParseDirectDeclarator.
7275   // If parentheses are required, always suggest them.
7276   if (!D.getIdentifier() && !NeedParens)
7277     return;
7278 
7279   SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
7280 
7281   // Generate the move bracket error message.
7282   SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
7283   SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7284 
7285   if (NeedParens) {
7286     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7287         << getLangOpts().CPlusPlus
7288         << FixItHint::CreateInsertion(SuggestParenLoc, "(")
7289         << FixItHint::CreateInsertion(EndLoc, ")")
7290         << FixItHint::CreateInsertionFromRange(
7291                EndLoc, CharSourceRange(BracketRange, true))
7292         << FixItHint::CreateRemoval(BracketRange);
7293   } else {
7294     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7295         << getLangOpts().CPlusPlus
7296         << FixItHint::CreateInsertionFromRange(
7297                EndLoc, CharSourceRange(BracketRange, true))
7298         << FixItHint::CreateRemoval(BracketRange);
7299   }
7300 }
7301 
7302 /// [GNU]   typeof-specifier:
7303 ///           typeof ( expressions )
7304 ///           typeof ( type-name )
7305 /// [GNU/C++] typeof unary-expression
7306 ///
7307 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
7308   assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
7309   Token OpTok = Tok;
7310   SourceLocation StartLoc = ConsumeToken();
7311 
7312   const bool hasParens = Tok.is(tok::l_paren);
7313 
7314   EnterExpressionEvaluationContext Unevaluated(
7315       Actions, Sema::ExpressionEvaluationContext::Unevaluated,
7316       Sema::ReuseLambdaContextDecl);
7317 
7318   bool isCastExpr;
7319   ParsedType CastTy;
7320   SourceRange CastRange;
7321   ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
7322       ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
7323   if (hasParens)
7324     DS.setTypeofParensRange(CastRange);
7325 
7326   if (CastRange.getEnd().isInvalid())
7327     // FIXME: Not accurate, the range gets one token more than it should.
7328     DS.SetRangeEnd(Tok.getLocation());
7329   else
7330     DS.SetRangeEnd(CastRange.getEnd());
7331 
7332   if (isCastExpr) {
7333     if (!CastTy) {
7334       DS.SetTypeSpecError();
7335       return;
7336     }
7337 
7338     const char *PrevSpec = nullptr;
7339     unsigned DiagID;
7340     // Check for duplicate type specifiers (e.g. "int typeof(int)").
7341     if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
7342                            DiagID, CastTy,
7343                            Actions.getASTContext().getPrintingPolicy()))
7344       Diag(StartLoc, DiagID) << PrevSpec;
7345     return;
7346   }
7347 
7348   // If we get here, the operand to the typeof was an expression.
7349   if (Operand.isInvalid()) {
7350     DS.SetTypeSpecError();
7351     return;
7352   }
7353 
7354   // We might need to transform the operand if it is potentially evaluated.
7355   Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
7356   if (Operand.isInvalid()) {
7357     DS.SetTypeSpecError();
7358     return;
7359   }
7360 
7361   const char *PrevSpec = nullptr;
7362   unsigned DiagID;
7363   // Check for duplicate type specifiers (e.g. "int typeof(int)").
7364   if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
7365                          DiagID, Operand.get(),
7366                          Actions.getASTContext().getPrintingPolicy()))
7367     Diag(StartLoc, DiagID) << PrevSpec;
7368 }
7369 
7370 /// [C11]   atomic-specifier:
7371 ///           _Atomic ( type-name )
7372 ///
7373 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
7374   assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
7375          "Not an atomic specifier");
7376 
7377   SourceLocation StartLoc = ConsumeToken();
7378   BalancedDelimiterTracker T(*this, tok::l_paren);
7379   if (T.consumeOpen())
7380     return;
7381 
7382   TypeResult Result = ParseTypeName();
7383   if (Result.isInvalid()) {
7384     SkipUntil(tok::r_paren, StopAtSemi);
7385     return;
7386   }
7387 
7388   // Match the ')'
7389   T.consumeClose();
7390 
7391   if (T.getCloseLocation().isInvalid())
7392     return;
7393 
7394   DS.setTypeofParensRange(T.getRange());
7395   DS.SetRangeEnd(T.getCloseLocation());
7396 
7397   const char *PrevSpec = nullptr;
7398   unsigned DiagID;
7399   if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
7400                          DiagID, Result.get(),
7401                          Actions.getASTContext().getPrintingPolicy()))
7402     Diag(StartLoc, DiagID) << PrevSpec;
7403 }
7404 
7405 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7406 /// from TryAltiVecVectorToken.
7407 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7408   Token Next = NextToken();
7409   switch (Next.getKind()) {
7410   default: return false;
7411   case tok::kw_short:
7412   case tok::kw_long:
7413   case tok::kw_signed:
7414   case tok::kw_unsigned:
7415   case tok::kw_void:
7416   case tok::kw_char:
7417   case tok::kw_int:
7418   case tok::kw_float:
7419   case tok::kw_double:
7420   case tok::kw_bool:
7421   case tok::kw__Bool:
7422   case tok::kw___bool:
7423   case tok::kw___pixel:
7424     Tok.setKind(tok::kw___vector);
7425     return true;
7426   case tok::identifier:
7427     if (Next.getIdentifierInfo() == Ident_pixel) {
7428       Tok.setKind(tok::kw___vector);
7429       return true;
7430     }
7431     if (Next.getIdentifierInfo() == Ident_bool ||
7432         Next.getIdentifierInfo() == Ident_Bool) {
7433       Tok.setKind(tok::kw___vector);
7434       return true;
7435     }
7436     return false;
7437   }
7438 }
7439 
7440 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7441                                       const char *&PrevSpec, unsigned &DiagID,
7442                                       bool &isInvalid) {
7443   const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7444   if (Tok.getIdentifierInfo() == Ident_vector) {
7445     Token Next = NextToken();
7446     switch (Next.getKind()) {
7447     case tok::kw_short:
7448     case tok::kw_long:
7449     case tok::kw_signed:
7450     case tok::kw_unsigned:
7451     case tok::kw_void:
7452     case tok::kw_char:
7453     case tok::kw_int:
7454     case tok::kw_float:
7455     case tok::kw_double:
7456     case tok::kw_bool:
7457     case tok::kw__Bool:
7458     case tok::kw___bool:
7459     case tok::kw___pixel:
7460       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7461       return true;
7462     case tok::identifier:
7463       if (Next.getIdentifierInfo() == Ident_pixel) {
7464         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7465         return true;
7466       }
7467       if (Next.getIdentifierInfo() == Ident_bool ||
7468           Next.getIdentifierInfo() == Ident_Bool) {
7469         isInvalid =
7470             DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7471         return true;
7472       }
7473       break;
7474     default:
7475       break;
7476     }
7477   } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7478              DS.isTypeAltiVecVector()) {
7479     isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7480     return true;
7481   } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7482              DS.isTypeAltiVecVector()) {
7483     isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
7484     return true;
7485   }
7486   return false;
7487 }
7488 
7489 void Parser::DiagnoseBitIntUse(const Token &Tok) {
7490   // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
7491   // the token is about _BitInt and gets (potentially) diagnosed as use of an
7492   // extension.
7493   assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
7494          "expected either an _ExtInt or _BitInt token!");
7495 
7496   SourceLocation Loc = Tok.getLocation();
7497   if (Tok.is(tok::kw__ExtInt)) {
7498     Diag(Loc, diag::warn_ext_int_deprecated)
7499         << FixItHint::CreateReplacement(Loc, "_BitInt");
7500   } else {
7501     // In C2x mode, diagnose that the use is not compatible with pre-C2x modes.
7502     // Otherwise, diagnose that the use is a Clang extension.
7503     if (getLangOpts().C2x)
7504       Diag(Loc, diag::warn_c17_compat_bit_int);
7505     else
7506       Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;
7507   }
7508 }
7509