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