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