Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the Declaration portions of the Parser interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/Parse/RAIIObjectsForParser.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/DeclTemplate.h"
17
#include "clang/AST/PrettyDeclStackTrace.h"
18
#include "clang/Basic/AddressSpaces.h"
19
#include "clang/Basic/Attributes.h"
20
#include "clang/Basic/CharInfo.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/Parse/ParseDiagnostic.h"
23
#include "clang/Sema/Lookup.h"
24
#include "clang/Sema/ParsedTemplate.h"
25
#include "clang/Sema/Scope.h"
26
#include "clang/Sema/SemaDiagnostic.h"
27
#include "llvm/ADT/Optional.h"
28
#include "llvm/ADT/SmallSet.h"
29
#include "llvm/ADT/SmallString.h"
30
#include "llvm/ADT/StringSwitch.h"
31
32
using namespace clang;
33
34
//===----------------------------------------------------------------------===//
35
// C99 6.7: Declarations.
36
//===----------------------------------------------------------------------===//
37
38
/// ParseTypeName
39
///       type-name: [C99 6.7.6]
40
///         specifier-qualifier-list abstract-declarator[opt]
41
///
42
/// Called type-id in C++.
43
TypeResult Parser::ParseTypeName(SourceRange *Range,
44
                                 DeclaratorContext Context,
45
                                 AccessSpecifier AS,
46
                                 Decl **OwnedType,
47
3.82M
                                 ParsedAttributes *Attrs) {
48
3.82M
  DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
49
3.82M
  if (DSC == DeclSpecContext::DSC_normal)
50
283k
    DSC = DeclSpecContext::DSC_type_specifier;
51
52
  // Parse the common declaration-specifiers piece.
53
3.82M
  DeclSpec DS(AttrFactory);
54
3.82M
  if (Attrs)
55
57.5k
    DS.addAttributes(*Attrs);
56
3.82M
  ParseSpecifierQualifierList(DS, AS, DSC);
57
3.82M
  if (OwnedType)
58
57.5k
    *OwnedType = DS.isTypeSpecOwned() ? 
DS.getRepAsDecl()43
:
nullptr57.4k
;
59
60
  // Parse the abstract-declarator, if present.
61
3.82M
  Declarator DeclaratorInfo(DS, Context);
62
3.82M
  ParseDeclarator(DeclaratorInfo);
63
3.82M
  if (Range)
64
20.7k
    *Range = DeclaratorInfo.getSourceRange();
65
66
3.82M
  if (DeclaratorInfo.isInvalidType())
67
332
    return true;
68
69
3.82M
  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
70
3.82M
}
71
72
/// Normalizes an attribute name by dropping prefixed and suffixed __.
73
62.9M
static StringRef normalizeAttrName(StringRef Name) {
74
62.9M
  if (Name.size() >= 4 && 
Name.startswith("__")62.9M
&&
Name.endswith("__")56.3M
)
75
17.8M
    return Name.drop_front(2).drop_back(2);
76
45.0M
  return Name;
77
45.0M
}
78
79
/// isAttributeLateParsed - Return true if the attribute has arguments that
80
/// require late parsing.
81
2.91M
static bool isAttributeLateParsed(const IdentifierInfo &II) {
82
2.91M
#define CLANG_ATTR_LATE_PARSED_LIST
83
2.91M
    return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
84
2.91M
#include "clang/Parse/AttrParserStringSwitches.inc"
85
2.91M
        .Default(false);
86
2.91M
#undef CLANG_ATTR_LATE_PARSED_LIST
87
2.91M
}
88
89
/// Check if the a start and end source location expand to the same macro.
90
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
91
27.6M
                                     SourceLocation EndLoc) {
92
27.6M
  if (!StartLoc.isMacroID() || 
!EndLoc.isMacroID()19.7M
)
93
7.97M
    return false;
94
95
19.7M
  SourceManager &SM = PP.getSourceManager();
96
19.7M
  if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
97
17.3k
    return false;
98
99
19.7M
  bool AttrStartIsInMacro =
100
19.7M
      Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
101
19.7M
  bool AttrEndIsInMacro =
102
19.7M
      Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
103
19.7M
  return AttrStartIsInMacro && 
AttrEndIsInMacro7.13M
;
104
19.7M
}
105
106
/// ParseGNUAttributes - Parse a non-empty attributes list.
107
///
108
/// [GNU] attributes:
109
///         attribute
110
///         attributes attribute
111
///
112
/// [GNU]  attribute:
113
///          '__attribute__' '(' '(' attribute-list ')' ')'
114
///
115
/// [GNU]  attribute-list:
116
///          attrib
117
///          attribute_list ',' attrib
118
///
119
/// [GNU]  attrib:
120
///          empty
121
///          attrib-name
122
///          attrib-name '(' identifier ')'
123
///          attrib-name '(' identifier ',' nonempty-expr-list ')'
124
///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
125
///
126
/// [GNU]  attrib-name:
127
///          identifier
128
///          typespec
129
///          typequal
130
///          storageclass
131
///
132
/// Whether an attribute takes an 'identifier' is determined by the
133
/// attrib-name. GCC's behavior here is not worth imitating:
134
///
135
///  * In C mode, if the attribute argument list starts with an identifier
136
///    followed by a ',' or an ')', and the identifier doesn't resolve to
137
///    a type, it is parsed as an identifier. If the attribute actually
138
///    wanted an expression, it's out of luck (but it turns out that no
139
///    attributes work that way, because C constant expressions are very
140
///    limited).
141
///  * In C++ mode, if the attribute argument list starts with an identifier,
142
///    and the attribute *wants* an identifier, it is parsed as an identifier.
143
///    At block scope, any additional tokens between the identifier and the
144
///    ',' or ')' are ignored, otherwise they produce a parse error.
145
///
146
/// We follow the C++ model, but don't allow junk after the identifier.
147
void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
148
                                SourceLocation *endLoc,
149
                                LateParsedAttrList *LateAttrs,
150
15.3M
                                Declarator *D) {
151
15.3M
  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
152
153
43.1M
  while (Tok.is(tok::kw___attribute)) {
154
27.7M
    SourceLocation AttrTokLoc = ConsumeToken();
155
27.7M
    unsigned OldNumAttrs = attrs.size();
156
24.1M
    unsigned OldNumLateAttrs = LateAttrs ? 
LateAttrs->size()3.53M
: 0;
157
158
27.7M
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
159
0
                         "attribute")) {
160
0
      SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
161
0
      return;
162
0
    }
163
27.7M
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
164
0
      SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
165
0
      return;
166
0
    }
167
    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
168
45.2M
    
do 27.7M
{
169
      // Eat preceeding commas to allow __attribute__((,,,foo))
170
62.7M
      while (TryConsumeToken(tok::comma))
171
17.5M
        ;
172
173
      // Expect an identifier or declaration specifier (const, int, etc.)
174
45.2M
      if (Tok.isAnnotation())
175
0
        break;
176
45.2M
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
177
45.2M
      if (!AttrName)
178
34
        break;
179
180
45.2M
      SourceLocation AttrNameLoc = ConsumeToken();
181
182
45.2M
      if (Tok.isNot(tok::l_paren)) {
183
25.5M
        attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
184
25.5M
                     ParsedAttr::AS_GNU);
185
25.5M
        continue;
186
25.5M
      }
187
188
      // Handle "parameterized" attributes
189
19.6M
      if (!LateAttrs || 
!isAttributeLateParsed(*AttrName)2.91M
) {
190
19.6M
        ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
191
19.6M
                              SourceLocation(), ParsedAttr::AS_GNU, D);
192
19.6M
        continue;
193
19.6M
      }
194
195
      // Handle attributes with arguments that require late parsing.
196
10.0k
      LateParsedAttribute *LA =
197
10.0k
          new LateParsedAttribute(this, *AttrName, AttrNameLoc);
198
10.0k
      LateAttrs->push_back(LA);
199
200
      // Attributes in a class are parsed at the end of the class, along
201
      // with other late-parsed declarations.
202
10.0k
      if (!ClassStack.empty() && 
!LateAttrs->parseSoon()5.16k
)
203
5.16k
        getCurrentClass().LateParsedDeclarations.push_back(LA);
204
205
      // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
206
      // recursively consumes balanced parens.
207
10.0k
      LA->Toks.push_back(Tok);
208
10.0k
      ConsumeParen();
209
      // Consume everything up to and including the matching right parens.
210
10.0k
      ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
211
212
10.0k
      Token Eof;
213
10.0k
      Eof.startToken();
214
10.0k
      Eof.setLocation(Tok.getLocation());
215
10.0k
      LA->Toks.push_back(Eof);
216
45.2M
    } while (Tok.is(tok::comma));
217
218
27.7M
    if (ExpectAndConsume(tok::r_paren))
219
3
      SkipUntil(tok::r_paren, StopAtSemi);
220
27.7M
    SourceLocation Loc = Tok.getLocation();
221
27.7M
    if (ExpectAndConsume(tok::r_paren))
222
1
      SkipUntil(tok::r_paren, StopAtSemi);
223
27.7M
    if (endLoc)
224
5.86M
      *endLoc = Loc;
225
226
    // If this was declared in a macro, attach the macro IdentifierInfo to the
227
    // parsed attribute.
228
27.7M
    auto &SM = PP.getSourceManager();
229
27.7M
    if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
230
27.6M
        FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
231
4.37M
      CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
232
4.37M
      StringRef FoundName =
233
4.37M
          Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
234
4.37M
      IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
235
236
12.0M
      for (unsigned i = OldNumAttrs; i < attrs.size(); 
++i7.71M
)
237
7.71M
        attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
238
239
4.37M
      if (LateAttrs) {
240
994k
        for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); 
++i9.86k
)
241
9.86k
          (*LateAttrs)[i]->MacroII = MacroII;
242
984k
      }
243
4.37M
    }
244
27.7M
  }
245
15.3M
}
246
247
/// Determine whether the given attribute has an identifier argument.
248
7.92M
static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
249
7.92M
#define CLANG_ATTR_IDENTIFIER_ARG_LIST
250
7.92M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
251
7.92M
#include "clang/Parse/AttrParserStringSwitches.inc"
252
7.92M
           .Default(false);
253
7.92M
#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
254
7.92M
}
255
256
/// Determine whether the given attribute has a variadic identifier argument.
257
21.4k
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
258
21.4k
#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
259
21.4k
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
260
21.4k
#include "clang/Parse/AttrParserStringSwitches.inc"
261
21.4k
           .Default(false);
262
21.4k
#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
263
21.4k
}
264
265
/// Determine whether the given attribute treats kw_this as an identifier.
266
11.9M
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
267
11.9M
#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
268
11.9M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
269
11.9M
#include "clang/Parse/AttrParserStringSwitches.inc"
270
11.9M
           .Default(false);
271
11.9M
#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
272
11.9M
}
273
274
/// Determine whether the given attribute parses a type argument.
275
23.9M
static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
276
23.9M
#define CLANG_ATTR_TYPE_ARG_LIST
277
23.9M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
278
23.9M
#include "clang/Parse/AttrParserStringSwitches.inc"
279
23.9M
           .Default(false);
280
23.9M
#undef CLANG_ATTR_TYPE_ARG_LIST
281
23.9M
}
282
283
/// Determine whether the given attribute requires parsing its arguments
284
/// in an unevaluated context or not.
285
4.16M
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
286
4.16M
#define CLANG_ATTR_ARG_CONTEXT_LIST
287
4.16M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
288
4.16M
#include "clang/Parse/AttrParserStringSwitches.inc"
289
4.16M
           .Default(false);
290
4.16M
#undef CLANG_ATTR_ARG_CONTEXT_LIST
291
4.16M
}
292
293
15.6M
IdentifierLoc *Parser::ParseIdentifierLoc() {
294
15.6M
  assert(Tok.is(tok::identifier) && "expected an identifier");
295
15.6M
  IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
296
15.6M
                                            Tok.getLocation(),
297
15.6M
                                            Tok.getIdentifierInfo());
298
15.6M
  ConsumeToken();
299
15.6M
  return IL;
300
15.6M
}
301
302
void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
303
                                       SourceLocation AttrNameLoc,
304
                                       ParsedAttributes &Attrs,
305
                                       SourceLocation *EndLoc,
306
                                       IdentifierInfo *ScopeName,
307
                                       SourceLocation ScopeLoc,
308
50
                                       ParsedAttr::Syntax Syntax) {
309
50
  BalancedDelimiterTracker Parens(*this, tok::l_paren);
310
50
  Parens.consumeOpen();
311
312
50
  TypeResult T;
313
50
  if (Tok.isNot(tok::r_paren))
314
46
    T = ParseTypeName();
315
316
50
  if (Parens.consumeClose())
317
5
    return;
318
319
45
  if (T.isInvalid())
320
5
    return;
321
322
40
  if (T.isUsable())
323
36
    Attrs.addNewTypeAttr(&AttrName,
324
36
                         SourceRange(AttrNameLoc, Parens.getCloseLocation()),
325
36
                         ScopeName, ScopeLoc, T.get(), Syntax);
326
4
  else
327
4
    Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
328
4
                 ScopeName, ScopeLoc, nullptr, 0, Syntax);
329
40
}
330
331
unsigned Parser::ParseAttributeArgsCommon(
332
    IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
333
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
334
11.9M
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
335
  // Ignore the left paren location for now.
336
11.9M
  ConsumeParen();
337
338
11.9M
  bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
339
11.9M
  bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
340
341
  // Interpret "kw_this" as an identifier if the attributed requests it.
342
11.9M
  if (ChangeKWThisToIdent && 
Tok.is(tok::kw_this)142
)
343
1
    Tok.setKind(tok::identifier);
344
345
11.9M
  ArgsVector ArgExprs;
346
11.9M
  if (Tok.is(tok::identifier)) {
347
    // If this attribute wants an 'identifier' argument, make it so.
348
7.92M
    bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
349
10.5k
                           attributeHasVariadicIdentifierArg(*AttrName);
350
7.92M
    ParsedAttr::Kind AttrKind =
351
7.92M
        ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
352
353
    // If we don't know how to parse this attribute, but this is the only
354
    // token in this argument, assume it's meant to be an identifier.
355
7.92M
    if (AttrKind == ParsedAttr::UnknownAttribute ||
356
7.92M
        AttrKind == ParsedAttr::IgnoredAttribute) {
357
7
      const Token &Next = NextToken();
358
7
      IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
359
7
    }
360
361
7.92M
    if (IsIdentifierArg)
362
7.91M
      ArgExprs.push_back(ParseIdentifierLoc());
363
7.92M
  }
364
365
11.9M
  ParsedType TheParsedType;
366
11.9M
  if (!ArgExprs.empty() ? 
Tok.is(tok::comma)7.91M
:
Tok.isNot(tok::r_paren)4.05M
) {
367
    // Eat the comma.
368
4.09M
    if (!ArgExprs.empty())
369
37.4k
      ConsumeToken();
370
371
    // Parse the non-empty comma-separated list of expressions.
372
4.16M
    do {
373
      // Interpret "kw_this" as an identifier if the attributed requests it.
374
4.16M
      if (ChangeKWThisToIdent && 
Tok.is(tok::kw_this)269
)
375
4
        Tok.setKind(tok::identifier);
376
377
4.16M
      ExprResult ArgExpr;
378
4.16M
      if (AttributeIsTypeArgAttr) {
379
33
        TypeResult T = ParseTypeName();
380
33
        if (T.isInvalid()) {
381
2
          SkipUntil(tok::r_paren, StopAtSemi);
382
2
          return 0;
383
2
        }
384
31
        if (T.isUsable())
385
31
          TheParsedType = T.get();
386
31
        break; // FIXME: Multiple type arguments are not implemented.
387
4.16M
      } else if (Tok.is(tok::identifier) &&
388
10.9k
                 attributeHasVariadicIdentifierArg(*AttrName)) {
389
133
        ArgExprs.push_back(ParseIdentifierLoc());
390
4.16M
      } else {
391
4.16M
        bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
392
4.16M
        EnterExpressionEvaluationContext Unevaluated(
393
4.16M
            Actions,
394
3.14k
            Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
395
4.15M
                   : Sema::ExpressionEvaluationContext::ConstantEvaluated);
396
397
4.16M
        ExprResult ArgExpr(
398
4.16M
            Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
399
4.16M
        if (ArgExpr.isInvalid()) {
400
37
          SkipUntil(tok::r_paren, StopAtSemi);
401
37
          return 0;
402
37
        }
403
4.16M
        ArgExprs.push_back(ArgExpr.get());
404
4.16M
      }
405
      // Eat the comma, move to the next argument
406
4.16M
    } while (TryConsumeToken(tok::comma));
407
4.09M
  }
408
409
11.9M
  SourceLocation RParen = Tok.getLocation();
410
11.9M
  if (!ExpectAndConsume(tok::r_paren)) {
411
11.9M
    SourceLocation AttrLoc = ScopeLoc.isValid() ? 
ScopeLoc173
: AttrNameLoc;
412
413
11.9M
    if (AttributeIsTypeArgAttr && 
!TheParsedType.get().isNull()34
) {
414
31
      Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
415
31
                           ScopeName, ScopeLoc, TheParsedType, Syntax);
416
11.9M
    } else {
417
11.9M
      Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
418
11.9M
                   ArgExprs.data(), ArgExprs.size(), Syntax);
419
11.9M
    }
420
11.9M
  }
421
422
11.9M
  if (EndLoc)
423
99.7k
    *EndLoc = RParen;
424
425
11.9M
  return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
426
11.9M
}
427
428
/// Parse the arguments to a parameterized GNU attribute or
429
/// a C++11 attribute in "gnu" namespace.
430
void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
431
                                   SourceLocation AttrNameLoc,
432
                                   ParsedAttributes &Attrs,
433
                                   SourceLocation *EndLoc,
434
                                   IdentifierInfo *ScopeName,
435
                                   SourceLocation ScopeLoc,
436
                                   ParsedAttr::Syntax Syntax,
437
19.6M
                                   Declarator *D) {
438
439
19.6M
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
440
441
19.6M
  ParsedAttr::Kind AttrKind =
442
19.6M
      ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
443
444
19.6M
  if (AttrKind == ParsedAttr::AT_Availability) {
445
7.70M
    ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
446
7.70M
                               ScopeLoc, Syntax);
447
7.70M
    return;
448
11.9M
  } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
449
75
    ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
450
75
                                       ScopeName, ScopeLoc, Syntax);
451
75
    return;
452
11.9M
  } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
453
618
    ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
454
618
                                    ScopeName, ScopeLoc, Syntax);
455
618
    return;
456
11.9M
  } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
457
14.5k
    ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
458
14.5k
                               ScopeLoc, Syntax);
459
14.5k
    return;
460
11.9M
  } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
461
179
    ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
462
179
                                     ScopeName, ScopeLoc, Syntax);
463
179
    return;
464
11.9M
  } else if (attributeIsTypeArgAttr(*AttrName)) {
465
50
    ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
466
50
                              ScopeLoc, Syntax);
467
50
    return;
468
50
  }
469
470
  // These may refer to the function arguments, but need to be parsed early to
471
  // participate in determining whether it's a redeclaration.
472
11.9M
  llvm::Optional<ParseScope> PrototypeScope;
473
11.9M
  if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
474
10.5k
      D && 
D->isFunctionDeclarator()1.80k
) {
475
1.80k
    DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
476
1.80k
    PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
477
1.80k
                                     Scope::FunctionDeclarationScope |
478
1.80k
                                     Scope::DeclScope);
479
6.11k
    for (unsigned i = 0; i != FTI.NumParams; 
++i4.30k
) {
480
4.30k
      ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
481
4.30k
      Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
482
4.30k
    }
483
1.80k
  }
484
485
11.9M
  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
486
11.9M
                           ScopeLoc, Syntax);
487
11.9M
}
488
489
unsigned Parser::ParseClangAttributeArgs(
490
    IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
491
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
492
114
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
493
114
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
494
495
114
  ParsedAttr::Kind AttrKind =
496
114
      ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
497
498
114
  switch (AttrKind) {
499
89
  default:
500
89
    return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
501
89
                                    ScopeName, ScopeLoc, Syntax);
502
5
  case ParsedAttr::AT_ExternalSourceSymbol:
503
5
    ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
504
5
                                       ScopeName, ScopeLoc, Syntax);
505
5
    break;
506
7
  case ParsedAttr::AT_Availability:
507
7
    ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
508
7
                               ScopeLoc, Syntax);
509
7
    break;
510
4
  case ParsedAttr::AT_ObjCBridgeRelated:
511
4
    ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
512
4
                                    ScopeName, ScopeLoc, Syntax);
513
4
    break;
514
0
  case ParsedAttr::AT_SwiftNewType:
515
0
    ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
516
0
                               ScopeLoc, Syntax);
517
0
    break;
518
9
  case ParsedAttr::AT_TypeTagForDatatype:
519
9
    ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
520
9
                                     ScopeName, ScopeLoc, Syntax);
521
9
    break;
522
25
  }
523
25
  return !Attrs.empty() ? 
Attrs.begin()->getNumArgs()17
:
08
;
524
25
}
525
526
bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
527
                                        SourceLocation AttrNameLoc,
528
568
                                        ParsedAttributes &Attrs) {
529
  // If the attribute isn't known, we will not attempt to parse any
530
  // arguments.
531
568
  if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
532
1
                    getTargetInfo(), getLangOpts())) {
533
    // Eat the left paren, then skip to the ending right paren.
534
1
    ConsumeParen();
535
1
    SkipUntil(tok::r_paren);
536
1
    return false;
537
1
  }
538
539
567
  SourceLocation OpenParenLoc = Tok.getLocation();
540
541
567
  if (AttrName->getName() == "property") {
542
    // The property declspec is more complex in that it can take one or two
543
    // assignment expressions as a parameter, but the lhs of the assignment
544
    // must be named get or put.
545
546
103
    BalancedDelimiterTracker T(*this, tok::l_paren);
547
103
    T.expectAndConsume(diag::err_expected_lparen_after,
548
103
                       AttrName->getNameStart(), tok::r_paren);
549
550
103
    enum AccessorKind {
551
103
      AK_Invalid = -1,
552
103
      AK_Put = 0,
553
103
      AK_Get = 1 // indices into AccessorNames
554
103
    };
555
103
    IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
556
103
    bool HasInvalidAccessor = false;
557
558
    // Parse the accessor specifications.
559
140
    while (true) {
560
      // Stop if this doesn't look like an accessor spec.
561
140
      if (!Tok.is(tok::identifier)) {
562
        // If the user wrote a completely empty list, use a special diagnostic.
563
2
        if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
564
2
            AccessorNames[AK_Put] == nullptr &&
565
2
            AccessorNames[AK_Get] == nullptr) {
566
1
          Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
567
1
          break;
568
1
        }
569
570
1
        Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
571
1
        break;
572
1
      }
573
574
138
      AccessorKind Kind;
575
138
      SourceLocation KindLoc = Tok.getLocation();
576
138
      StringRef KindStr = Tok.getIdentifierInfo()->getName();
577
138
      if (KindStr == "get") {
578
97
        Kind = AK_Get;
579
41
      } else if (KindStr == "put") {
580
38
        Kind = AK_Put;
581
582
        // Recover from the common mistake of using 'set' instead of 'put'.
583
3
      } else if (KindStr == "set") {
584
1
        Diag(KindLoc, diag::err_ms_property_has_set_accessor)
585
1
            << FixItHint::CreateReplacement(KindLoc, "put");
586
1
        Kind = AK_Put;
587
588
        // Handle the mistake of forgetting the accessor kind by skipping
589
        // this accessor.
590
2
      } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
591
1
        Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
592
1
        ConsumeToken();
593
1
        HasInvalidAccessor = true;
594
1
        goto next_property_accessor;
595
596
        // Otherwise, complain about the unknown accessor kind.
597
1
      } else {
598
1
        Diag(KindLoc, diag::err_ms_property_unknown_accessor);
599
1
        HasInvalidAccessor = true;
600
1
        Kind = AK_Invalid;
601
602
        // Try to keep parsing unless it doesn't look like an accessor spec.
603
1
        if (!NextToken().is(tok::equal))
604
0
          break;
605
137
      }
606
607
      // Consume the identifier.
608
137
      ConsumeToken();
609
610
      // Consume the '='.
611
137
      if (!TryConsumeToken(tok::equal)) {
612
3
        Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
613
3
            << KindStr;
614
3
        break;
615
3
      }
616
617
      // Expect the method name.
618
134
      if (!Tok.is(tok::identifier)) {
619
1
        Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
620
1
        break;
621
1
      }
622
623
133
      if (Kind == AK_Invalid) {
624
        // Just drop invalid accessors.
625
132
      } else if (AccessorNames[Kind] != nullptr) {
626
        // Complain about the repeated accessor, ignore it, and keep parsing.
627
1
        Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
628
131
      } else {
629
131
        AccessorNames[Kind] = Tok.getIdentifierInfo();
630
131
      }
631
133
      ConsumeToken();
632
633
134
    next_property_accessor:
634
      // Keep processing accessors until we run out.
635
134
      if (TryConsumeToken(tok::comma))
636
37
        continue;
637
638
      // If we run into the ')', stop without consuming it.
639
97
      if (Tok.is(tok::r_paren))
640
96
        break;
641
642
1
      Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
643
1
      break;
644
1
    }
645
646
    // Only add the property attribute if it was well-formed.
647
103
    if (!HasInvalidAccessor)
648
101
      Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
649
101
                               AccessorNames[AK_Get], AccessorNames[AK_Put],
650
101
                               ParsedAttr::AS_Declspec);
651
103
    T.skipToEnd();
652
103
    return !HasInvalidAccessor;
653
464
  }
654
655
464
  unsigned NumArgs =
656
464
      ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
657
464
                               SourceLocation(), ParsedAttr::AS_Declspec);
658
659
  // If this attribute's args were parsed, and it was expected to have
660
  // arguments but none were provided, emit a diagnostic.
661
464
  if (!Attrs.empty() && 
Attrs.begin()->getMaxArgs()462
&&
!NumArgs461
) {
662
1
    Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
663
1
    return false;
664
1
  }
665
463
  return true;
666
463
}
667
668
/// [MS] decl-specifier:
669
///             __declspec ( extended-decl-modifier-seq )
670
///
671
/// [MS] extended-decl-modifier-seq:
672
///             extended-decl-modifier[opt]
673
///             extended-decl-modifier extended-decl-modifier-seq
674
void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
675
9.44k
                                     SourceLocation *End) {
676
9.44k
  assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
677
9.44k
  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
678
679
19.0k
  while (Tok.is(tok::kw___declspec)) {
680
9.56k
    ConsumeToken();
681
9.56k
    BalancedDelimiterTracker T(*this, tok::l_paren);
682
9.56k
    if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
683
9.56k
                           tok::r_paren))
684
0
      return;
685
686
    // An empty declspec is perfectly legal and should not warn.  Additionally,
687
    // you can specify multiple attributes per declspec.
688
19.1k
    
while (9.56k
Tok.isNot(tok::r_paren)) {
689
      // Attribute not present.
690
9.57k
      if (TryConsumeToken(tok::comma))
691
3
        continue;
692
693
      // We expect either a well-known identifier or a generic string.  Anything
694
      // else is a malformed declspec.
695
9.57k
      bool IsString = Tok.getKind() == tok::string_literal;
696
9.57k
      if (!IsString && 
Tok.getKind() != tok::identifier9.57k
&&
697
2
          Tok.getKind() != tok::kw_restrict) {
698
1
        Diag(Tok, diag::err_ms_declspec_type);
699
1
        T.skipToEnd();
700
1
        return;
701
1
      }
702
703
9.57k
      IdentifierInfo *AttrName;
704
9.57k
      SourceLocation AttrNameLoc;
705
9.57k
      if (IsString) {
706
2
        SmallString<8> StrBuffer;
707
2
        bool Invalid = false;
708
2
        StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
709
2
        if (Invalid) {
710
0
          T.skipToEnd();
711
0
          return;
712
0
        }
713
2
        AttrName = PP.getIdentifierInfo(Str);
714
2
        AttrNameLoc = ConsumeStringToken();
715
9.57k
      } else {
716
9.57k
        AttrName = Tok.getIdentifierInfo();
717
9.57k
        AttrNameLoc = ConsumeToken();
718
9.57k
      }
719
720
9.57k
      bool AttrHandled = false;
721
722
      // Parse attribute arguments.
723
9.57k
      if (Tok.is(tok::l_paren))
724
568
        AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
725
9.00k
      else if (AttrName->getName() == "property")
726
        // The property attribute must have an argument list.
727
1
        Diag(Tok.getLocation(), diag::err_expected_lparen_after)
728
1
            << AttrName->getName();
729
730
9.57k
      if (!AttrHandled)
731
9.00k
        Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
732
9.00k
                     ParsedAttr::AS_Declspec);
733
9.57k
    }
734
9.56k
    T.consumeClose();
735
9.56k
    if (End)
736
17
      *End = T.getCloseLocation();
737
9.56k
  }
738
9.44k
}
739
740
396k
void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
741
  // Treat these like attributes
742
397k
  while (true) {
743
397k
    switch (Tok.getKind()) {
744
947
    case tok::kw___fastcall:
745
947
    case tok::kw___stdcall:
746
947
    case tok::kw___thiscall:
747
947
    case tok::kw___regcall:
748
947
    case tok::kw___cdecl:
749
947
    case tok::kw___vectorcall:
750
947
    case tok::kw___ptr64:
751
947
    case tok::kw___w64:
752
947
    case tok::kw___ptr32:
753
947
    case tok::kw___sptr:
754
947
    case tok::kw___uptr: {
755
947
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
756
947
      SourceLocation AttrNameLoc = ConsumeToken();
757
947
      attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
758
947
                   ParsedAttr::AS_Keyword);
759
947
      break;
760
947
    }
761
396k
    default:
762
396k
      return;
763
397k
    }
764
397k
  }
765
396k
}
766
767
294
void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
768
294
  SourceLocation StartLoc = Tok.getLocation();
769
294
  SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
770
771
294
  if (EndLoc.isValid()) {
772
12
    SourceRange Range(StartLoc, EndLoc);
773
12
    Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
774
12
  }
775
294
}
776
777
294
SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
778
294
  SourceLocation EndLoc;
779
780
320
  while (true) {
781
320
    switch (Tok.getKind()) {
782
26
    case tok::kw_const:
783
26
    case tok::kw_volatile:
784
26
    case tok::kw___fastcall:
785
26
    case tok::kw___stdcall:
786
26
    case tok::kw___thiscall:
787
26
    case tok::kw___cdecl:
788
26
    case tok::kw___vectorcall:
789
26
    case tok::kw___ptr32:
790
26
    case tok::kw___ptr64:
791
26
    case tok::kw___w64:
792
26
    case tok::kw___unaligned:
793
26
    case tok::kw___sptr:
794
26
    case tok::kw___uptr:
795
26
      EndLoc = ConsumeToken();
796
26
      break;
797
294
    default:
798
294
      return EndLoc;
799
320
    }
800
320
  }
801
294
}
802
803
18
void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
804
  // Treat these like attributes
805
36
  while (Tok.is(tok::kw___pascal)) {
806
18
    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
807
18
    SourceLocation AttrNameLoc = ConsumeToken();
808
18
    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
809
18
                 ParsedAttr::AS_Keyword);
810
18
  }
811
18
}
812
813
847
void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
814
  // Treat these like attributes
815
1.69k
  while (Tok.is(tok::kw___kernel)) {
816
847
    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
817
847
    SourceLocation AttrNameLoc = ConsumeToken();
818
847
    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
819
847
                 ParsedAttr::AS_Keyword);
820
847
  }
821
847
}
822
823
42.0k
void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
824
42.0k
  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
825
42.0k
  SourceLocation AttrNameLoc = Tok.getLocation();
826
42.0k
  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
827
42.0k
               ParsedAttr::AS_Keyword);
828
42.0k
}
829
830
857k
void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
831
  // Treat these like attributes, even though they're type specifiers.
832
1.71M
  while (true) {
833
1.71M
    switch (Tok.getKind()) {
834
857k
    case tok::kw__Nonnull:
835
857k
    case tok::kw__Nullable:
836
857k
    case tok::kw__Null_unspecified: {
837
857k
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
838
857k
      SourceLocation AttrNameLoc = ConsumeToken();
839
857k
      if (!getLangOpts().ObjC)
840
50.5k
        Diag(AttrNameLoc, diag::ext_nullability)
841
50.5k
          << AttrName;
842
857k
      attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
843
857k
                   ParsedAttr::AS_Keyword);
844
857k
      break;
845
857k
    }
846
857k
    default:
847
857k
      return;
848
1.71M
    }
849
1.71M
  }
850
857k
}
851
852
7.44M
static bool VersionNumberSeparator(const char Separator) {
853
7.44M
  return (Separator == '.' || 
Separator == '_'119k
);
854
7.44M
}
855
856
/// Parse a version number.
857
///
858
/// version:
859
///   simple-integer
860
///   simple-integer '.' simple-integer
861
///   simple-integer '_' simple-integer
862
///   simple-integer '.' simple-integer '.' simple-integer
863
///   simple-integer '_' simple-integer '_' simple-integer
864
7.42M
VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
865
7.42M
  Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
866
867
7.42M
  if (!Tok.is(tok::numeric_constant)) {
868
1
    Diag(Tok, diag::err_expected_version);
869
1
    SkipUntil(tok::comma, tok::r_paren,
870
1
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
871
1
    return VersionTuple();
872
1
  }
873
874
  // Parse the major (and possibly minor and subminor) versions, which
875
  // are stored in the numeric constant. We utilize a quirk of the
876
  // lexer, which is that it handles something like 1.2.3 as a single
877
  // numeric constant, rather than two separate tokens.
878
7.42M
  SmallString<512> Buffer;
879
7.42M
  Buffer.resize(Tok.getLength()+1);
880
7.42M
  const char *ThisTokBegin = &Buffer[0];
881
882
  // Get the spelling of the token, which eliminates trigraphs, etc.
883
7.42M
  bool Invalid = false;
884
7.42M
  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
885
7.42M
  if (Invalid)
886
0
    return VersionTuple();
887
888
  // Parse the major version.
889
7.42M
  unsigned AfterMajor = 0;
890
7.42M
  unsigned Major = 0;
891
19.5M
  while (AfterMajor < ActualLength && 
isDigit(ThisTokBegin[AfterMajor])19.5M
) {
892
12.1M
    Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
893
12.1M
    ++AfterMajor;
894
12.1M
  }
895
896
7.42M
  if (AfterMajor == 0) {
897
0
    Diag(Tok, diag::err_expected_version);
898
0
    SkipUntil(tok::comma, tok::r_paren,
899
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
900
0
    return VersionTuple();
901
0
  }
902
903
7.42M
  if (AfterMajor == ActualLength) {
904
49.4k
    ConsumeToken();
905
906
    // We only had a single version component.
907
49.4k
    if (Major == 0) {
908
0
      Diag(Tok, diag::err_zero_version);
909
0
      return VersionTuple();
910
0
    }
911
912
49.4k
    return VersionTuple(Major);
913
49.4k
  }
914
915
7.37M
  const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
916
7.37M
  if (!VersionNumberSeparator(AfterMajorSeparator)
917
7.37M
      || (AfterMajor + 1 == ActualLength)) {
918
0
    Diag(Tok, diag::err_expected_version);
919
0
    SkipUntil(tok::comma, tok::r_paren,
920
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
921
0
    return VersionTuple();
922
0
  }
923
924
  // Parse the minor version.
925
7.37M
  unsigned AfterMinor = AfterMajor + 1;
926
7.37M
  unsigned Minor = 0;
927
15.4M
  while (AfterMinor < ActualLength && 
isDigit(ThisTokBegin[AfterMinor])8.09M
) {
928
8.03M
    Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
929
8.03M
    ++AfterMinor;
930
8.03M
  }
931
932
7.37M
  if (AfterMinor == ActualLength) {
933
7.31M
    ConsumeToken();
934
935
    // We had major.minor.
936
7.31M
    if (Major == 0 && 
Minor == 00
) {
937
0
      Diag(Tok, diag::err_zero_version);
938
0
      return VersionTuple();
939
0
    }
940
941
7.31M
    return VersionTuple(Major, Minor);
942
7.31M
  }
943
944
67.8k
  const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
945
  // If what follows is not a '.' or '_', we have a problem.
946
67.8k
  if (!VersionNumberSeparator(AfterMinorSeparator)) {
947
0
    Diag(Tok, diag::err_expected_version);
948
0
    SkipUntil(tok::comma, tok::r_paren,
949
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
950
0
    return VersionTuple();
951
0
  }
952
953
  // Warn if separators, be it '.' or '_', do not match.
954
67.8k
  if (AfterMajorSeparator != AfterMinorSeparator)
955
6
    Diag(Tok, diag::warn_expected_consistent_version_separator);
956
957
  // Parse the subminor version.
958
67.8k
  unsigned AfterSubminor = AfterMinor + 1;
959
67.8k
  unsigned Subminor = 0;
960
135k
  while (AfterSubminor < ActualLength && 
isDigit(ThisTokBegin[AfterSubminor])67.8k
) {
961
67.8k
    Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
962
67.8k
    ++AfterSubminor;
963
67.8k
  }
964
965
67.8k
  if (AfterSubminor != ActualLength) {
966
0
    Diag(Tok, diag::err_expected_version);
967
0
    SkipUntil(tok::comma, tok::r_paren,
968
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
969
0
    return VersionTuple();
970
0
  }
971
67.8k
  ConsumeToken();
972
67.8k
  return VersionTuple(Major, Minor, Subminor);
973
67.8k
}
974
975
/// Parse the contents of the "availability" attribute.
976
///
977
/// availability-attribute:
978
///   'availability' '(' platform ',' opt-strict version-arg-list,
979
///                      opt-replacement, opt-message')'
980
///
981
/// platform:
982
///   identifier
983
///
984
/// opt-strict:
985
///   'strict' ','
986
///
987
/// version-arg-list:
988
///   version-arg
989
///   version-arg ',' version-arg-list
990
///
991
/// version-arg:
992
///   'introduced' '=' version
993
///   'deprecated' '=' version
994
///   'obsoleted' = version
995
///   'unavailable'
996
/// opt-replacement:
997
///   'replacement' '=' <string>
998
/// opt-message:
999
///   'message' '=' <string>
1000
void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
1001
                                        SourceLocation AvailabilityLoc,
1002
                                        ParsedAttributes &attrs,
1003
                                        SourceLocation *endLoc,
1004
                                        IdentifierInfo *ScopeName,
1005
                                        SourceLocation ScopeLoc,
1006
7.70M
                                        ParsedAttr::Syntax Syntax) {
1007
7.70M
  enum { Introduced, Deprecated, Obsoleted, Unknown };
1008
7.70M
  AvailabilityChange Changes[Unknown];
1009
7.70M
  ExprResult MessageExpr, ReplacementExpr;
1010
1011
  // Opening '('.
1012
7.70M
  BalancedDelimiterTracker T(*this, tok::l_paren);
1013
7.70M
  if (T.consumeOpen()) {
1014
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1015
0
    return;
1016
0
  }
1017
1018
  // Parse the platform name.
1019
7.70M
  if (Tok.isNot(tok::identifier)) {
1020
0
    Diag(Tok, diag::err_availability_expected_platform);
1021
0
    SkipUntil(tok::r_paren, StopAtSemi);
1022
0
    return;
1023
0
  }
1024
7.70M
  IdentifierLoc *Platform = ParseIdentifierLoc();
1025
7.70M
  if (const IdentifierInfo *const Ident = Platform->Ident) {
1026
    // Canonicalize platform name from "macosx" to "macos".
1027
7.70M
    if (Ident->getName() == "macosx")
1028
1.19M
      Platform->Ident = PP.getIdentifierInfo("macos");
1029
    // Canonicalize platform name from "macosx_app_extension" to
1030
    // "macos_app_extension".
1031
6.51M
    else if (Ident->getName() == "macosx_app_extension")
1032
4
      Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1033
6.51M
    else
1034
6.51M
      Platform->Ident = PP.getIdentifierInfo(
1035
6.51M
          AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1036
7.70M
  }
1037
1038
  // Parse the ',' following the platform name.
1039
7.70M
  if (ExpectAndConsume(tok::comma)) {
1040
0
    SkipUntil(tok::r_paren, StopAtSemi);
1041
0
    return;
1042
0
  }
1043
1044
  // If we haven't grabbed the pointers for the identifiers
1045
  // "introduced", "deprecated", and "obsoleted", do so now.
1046
7.70M
  if (!Ident_introduced) {
1047
1.83k
    Ident_introduced = PP.getIdentifierInfo("introduced");
1048
1.83k
    Ident_deprecated = PP.getIdentifierInfo("deprecated");
1049
1.83k
    Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1050
1.83k
    Ident_unavailable = PP.getIdentifierInfo("unavailable");
1051
1.83k
    Ident_message = PP.getIdentifierInfo("message");
1052
1.83k
    Ident_strict = PP.getIdentifierInfo("strict");
1053
1.83k
    Ident_replacement = PP.getIdentifierInfo("replacement");
1054
1.83k
  }
1055
1056
  // Parse the optional "strict", the optional "replacement" and the set of
1057
  // introductions/deprecations/removals.
1058
7.70M
  SourceLocation UnavailableLoc, StrictLoc;
1059
9.77M
  do {
1060
9.77M
    if (Tok.isNot(tok::identifier)) {
1061
0
      Diag(Tok, diag::err_availability_expected_change);
1062
0
      SkipUntil(tok::r_paren, StopAtSemi);
1063
0
      return;
1064
0
    }
1065
9.77M
    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1066
9.77M
    SourceLocation KeywordLoc = ConsumeToken();
1067
1068
9.77M
    if (Keyword == Ident_strict) {
1069
5
      if (StrictLoc.isValid()) {
1070
0
        Diag(KeywordLoc, diag::err_availability_redundant)
1071
0
          << Keyword << SourceRange(StrictLoc);
1072
0
      }
1073
5
      StrictLoc = KeywordLoc;
1074
5
      continue;
1075
5
    }
1076
1077
9.77M
    if (Keyword == Ident_unavailable) {
1078
1.55M
      if (UnavailableLoc.isValid()) {
1079
1
        Diag(KeywordLoc, diag::err_availability_redundant)
1080
1
          << Keyword << SourceRange(UnavailableLoc);
1081
1
      }
1082
1.55M
      UnavailableLoc = KeywordLoc;
1083
1.55M
      continue;
1084
1.55M
    }
1085
1086
8.22M
    if (Keyword == Ident_deprecated && 
Platform->Ident1.35M
&&
1087
1.35M
        Platform->Ident->isStr("swift")) {
1088
      // For swift, we deprecate for all versions.
1089
3
      if (Changes[Deprecated].KeywordLoc.isValid()) {
1090
0
        Diag(KeywordLoc, diag::err_availability_redundant)
1091
0
          << Keyword
1092
0
          << SourceRange(Changes[Deprecated].KeywordLoc);
1093
0
      }
1094
1095
3
      Changes[Deprecated].KeywordLoc = KeywordLoc;
1096
      // Use a fake version here.
1097
3
      Changes[Deprecated].Version = VersionTuple(1);
1098
3
      continue;
1099
3
    }
1100
1101
8.22M
    if (Tok.isNot(tok::equal)) {
1102
1
      Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1103
1
      SkipUntil(tok::r_paren, StopAtSemi);
1104
1
      return;
1105
1
    }
1106
8.22M
    ConsumeToken();
1107
8.22M
    if (Keyword == Ident_message || 
Keyword == Ident_replacement7.54M
) {
1108
785k
      if (Tok.isNot(tok::string_literal)) {
1109
2
        Diag(Tok, diag::err_expected_string_literal)
1110
2
          << /*Source='availability attribute'*/2;
1111
2
        SkipUntil(tok::r_paren, StopAtSemi);
1112
2
        return;
1113
2
      }
1114
785k
      if (Keyword == Ident_message)
1115
678k
        MessageExpr = ParseStringLiteralExpression();
1116
106k
      else
1117
106k
        ReplacementExpr = ParseStringLiteralExpression();
1118
      // Also reject wide string literals.
1119
785k
      if (StringLiteral *MessageStringLiteral =
1120
678k
              cast_or_null<StringLiteral>(MessageExpr.get())) {
1121
678k
        if (MessageStringLiteral->getCharByteWidth() != 1) {
1122
1
          Diag(MessageStringLiteral->getSourceRange().getBegin(),
1123
1
               diag::err_expected_string_literal)
1124
1
            << /*Source='availability attribute'*/ 2;
1125
1
          SkipUntil(tok::r_paren, StopAtSemi);
1126
1
          return;
1127
1
        }
1128
785k
      }
1129
785k
      if (Keyword == Ident_message)
1130
678k
        break;
1131
106k
      else
1132
106k
        continue;
1133
7.43M
    }
1134
1135
    // Special handling of 'NA' only when applied to introduced or
1136
    // deprecated.
1137
7.43M
    if ((Keyword == Ident_introduced || 
Keyword == Ident_deprecated1.35M
) &&
1138
7.43M
        Tok.is(tok::identifier)) {
1139
8.21k
      IdentifierInfo *NA = Tok.getIdentifierInfo();
1140
8.21k
      if (NA->getName() == "NA") {
1141
8.21k
        ConsumeToken();
1142
8.21k
        if (Keyword == Ident_introduced)
1143
8.21k
          UnavailableLoc = KeywordLoc;
1144
8.21k
        continue;
1145
8.21k
      }
1146
7.42M
    }
1147
1148
7.42M
    SourceRange VersionRange;
1149
7.42M
    VersionTuple Version = ParseVersionTuple(VersionRange);
1150
1151
7.42M
    if (Version.empty()) {
1152
0
      SkipUntil(tok::r_paren, StopAtSemi);
1153
0
      return;
1154
0
    }
1155
1156
7.42M
    unsigned Index;
1157
7.42M
    if (Keyword == Ident_introduced)
1158
6.07M
      Index = Introduced;
1159
1.35M
    else if (Keyword == Ident_deprecated)
1160
1.35M
      Index = Deprecated;
1161
30
    else if (Keyword == Ident_obsoleted)
1162
29
      Index = Obsoleted;
1163
1
    else
1164
1
      Index = Unknown;
1165
1166
7.42M
    if (Index < Unknown) {
1167
7.42M
      if (!Changes[Index].KeywordLoc.isInvalid()) {
1168
1
        Diag(KeywordLoc, diag::err_availability_redundant)
1169
1
          << Keyword
1170
1
          << SourceRange(Changes[Index].KeywordLoc,
1171
1
                         Changes[Index].VersionRange.getEnd());
1172
1
      }
1173
1174
7.42M
      Changes[Index].KeywordLoc = KeywordLoc;
1175
7.42M
      Changes[Index].Version = Version;
1176
7.42M
      Changes[Index].VersionRange = VersionRange;
1177
1
    } else {
1178
1
      Diag(KeywordLoc, diag::err_availability_unknown_change)
1179
1
        << Keyword << VersionRange;
1180
1
    }
1181
1182
9.09M
  } while (TryConsumeToken(tok::comma));
1183
1184
  // Closing ')'.
1185
7.70M
  if (T.consumeClose())
1186
1
    return;
1187
1188
7.70M
  if (endLoc)
1189
5.57M
    *endLoc = T.getCloseLocation();
1190
1191
  // The 'unavailable' availability cannot be combined with any other
1192
  // availability changes. Make sure that hasn't happened.
1193
7.70M
  if (UnavailableLoc.isValid()) {
1194
1.56M
    bool Complained = false;
1195
6.25M
    for (unsigned Index = Introduced; Index != Unknown; 
++Index4.69M
) {
1196
4.69M
      if (Changes[Index].KeywordLoc.isValid()) {
1197
1
        if (!Complained) {
1198
1
          Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1199
1
            << SourceRange(Changes[Index].KeywordLoc,
1200
1
                           Changes[Index].VersionRange.getEnd());
1201
1
          Complained = true;
1202
1
        }
1203
1204
        // Clear out the availability.
1205
1
        Changes[Index] = AvailabilityChange();
1206
1
      }
1207
4.69M
    }
1208
1.56M
  }
1209
1210
  // Record this attribute
1211
7.70M
  attrs.addNew(&Availability,
1212
7.70M
               SourceRange(AvailabilityLoc, T.getCloseLocation()),
1213
7.70M
               ScopeName, ScopeLoc,
1214
7.70M
               Platform,
1215
7.70M
               Changes[Introduced],
1216
7.70M
               Changes[Deprecated],
1217
7.70M
               Changes[Obsoleted],
1218
7.70M
               UnavailableLoc, MessageExpr.get(),
1219
7.70M
               Syntax, StrictLoc, ReplacementExpr.get());
1220
7.70M
}
1221
1222
/// Parse the contents of the "external_source_symbol" attribute.
1223
///
1224
/// external-source-symbol-attribute:
1225
///   'external_source_symbol' '(' keyword-arg-list ')'
1226
///
1227
/// keyword-arg-list:
1228
///   keyword-arg
1229
///   keyword-arg ',' keyword-arg-list
1230
///
1231
/// keyword-arg:
1232
///   'language' '=' <string>
1233
///   'defined_in' '=' <string>
1234
///   'generated_declaration'
1235
void Parser::ParseExternalSourceSymbolAttribute(
1236
    IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1237
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1238
80
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1239
  // Opening '('.
1240
80
  BalancedDelimiterTracker T(*this, tok::l_paren);
1241
80
  if (T.expectAndConsume())
1242
0
    return;
1243
1244
  // Initialize the pointers for the keyword identifiers when required.
1245
80
  if (!Ident_language) {
1246
24
    Ident_language = PP.getIdentifierInfo("language");
1247
24
    Ident_defined_in = PP.getIdentifierInfo("defined_in");
1248
24
    Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1249
24
  }
1250
1251
80
  ExprResult Language;
1252
80
  bool HasLanguage = false;
1253
80
  ExprResult DefinedInExpr;
1254
80
  bool HasDefinedIn = false;
1255
80
  IdentifierLoc *GeneratedDeclaration = nullptr;
1256
1257
  // Parse the language/defined_in/generated_declaration keywords
1258
177
  do {
1259
177
    if (Tok.isNot(tok::identifier)) {
1260
5
      Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1261
5
      SkipUntil(tok::r_paren, StopAtSemi);
1262
5
      return;
1263
5
    }
1264
1265
172
    SourceLocation KeywordLoc = Tok.getLocation();
1266
172
    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1267
172
    if (Keyword == Ident_generated_declaration) {
1268
41
      if (GeneratedDeclaration) {
1269
4
        Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1270
4
        SkipUntil(tok::r_paren, StopAtSemi);
1271
4
        return;
1272
4
      }
1273
37
      GeneratedDeclaration = ParseIdentifierLoc();
1274
37
      continue;
1275
37
    }
1276
1277
131
    if (Keyword != Ident_language && 
Keyword != Ident_defined_in64
) {
1278
2
      Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1279
2
      SkipUntil(tok::r_paren, StopAtSemi);
1280
2
      return;
1281
2
    }
1282
1283
129
    ConsumeToken();
1284
129
    if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1285
1
                         Keyword->getName())) {
1286
1
      SkipUntil(tok::r_paren, StopAtSemi);
1287
1
      return;
1288
1
    }
1289
1290
128
    bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1291
128
    if (Keyword == Ident_language)
1292
66
      HasLanguage = true;
1293
62
    else
1294
62
      HasDefinedIn = true;
1295
1296
128
    if (Tok.isNot(tok::string_literal)) {
1297
9
      Diag(Tok, diag::err_expected_string_literal)
1298
9
          << /*Source='external_source_symbol attribute'*/ 3
1299
9
          << /*language | source container*/ (Keyword != Ident_language);
1300
9
      SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1301
9
      continue;
1302
9
    }
1303
119
    if (Keyword == Ident_language) {
1304
61
      if (HadLanguage) {
1305
2
        Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1306
2
            << Keyword;
1307
2
        ParseStringLiteralExpression();
1308
2
        continue;
1309
2
      }
1310
59
      Language = ParseStringLiteralExpression();
1311
58
    } else {
1312
58
      assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1313
58
      if (HadDefinedIn) {
1314
2
        Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1315
2
            << Keyword;
1316
2
        ParseStringLiteralExpression();
1317
2
        continue;
1318
2
      }
1319
56
      DefinedInExpr = ParseStringLiteralExpression();
1320
56
    }
1321
165
  } while (TryConsumeToken(tok::comma));
1322
1323
  // Closing ')'.
1324
68
  if (T.consumeClose())
1325
3
    return;
1326
65
  if (EndLoc)
1327
30
    *EndLoc = T.getCloseLocation();
1328
1329
65
  ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1330
65
                      GeneratedDeclaration};
1331
65
  Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1332
65
               ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1333
65
}
1334
1335
/// Parse the contents of the "objc_bridge_related" attribute.
1336
/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1337
/// related_class:
1338
///     Identifier
1339
///
1340
/// opt-class_method:
1341
///     Identifier: | <empty>
1342
///
1343
/// opt-instance_method:
1344
///     Identifier | <empty>
1345
///
1346
void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1347
                                SourceLocation ObjCBridgeRelatedLoc,
1348
                                ParsedAttributes &attrs,
1349
                                SourceLocation *endLoc,
1350
                                IdentifierInfo *ScopeName,
1351
                                SourceLocation ScopeLoc,
1352
622
                                ParsedAttr::Syntax Syntax) {
1353
  // Opening '('.
1354
622
  BalancedDelimiterTracker T(*this, tok::l_paren);
1355
622
  if (T.consumeOpen()) {
1356
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1357
0
    return;
1358
0
  }
1359
1360
  // Parse the related class name.
1361
622
  if (Tok.isNot(tok::identifier)) {
1362
4
    Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1363
4
    SkipUntil(tok::r_paren, StopAtSemi);
1364
4
    return;
1365
4
  }
1366
618
  IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1367
618
  if (ExpectAndConsume(tok::comma)) {
1368
0
    SkipUntil(tok::r_paren, StopAtSemi);
1369
0
    return;
1370
0
  }
1371
1372
  // Parse class method name.  It's non-optional in the sense that a trailing
1373
  // comma is required, but it can be the empty string, and then we record a
1374
  // nullptr.
1375
618
  IdentifierLoc *ClassMethod = nullptr;
1376
618
  if (Tok.is(tok::identifier)) {
1377
21
    ClassMethod = ParseIdentifierLoc();
1378
21
    if (!TryConsumeToken(tok::colon)) {
1379
2
      Diag(Tok, diag::err_objcbridge_related_selector_name);
1380
2
      SkipUntil(tok::r_paren, StopAtSemi);
1381
2
      return;
1382
2
    }
1383
616
  }
1384
616
  if (!TryConsumeToken(tok::comma)) {
1385
2
    if (Tok.is(tok::colon))
1386
1
      Diag(Tok, diag::err_objcbridge_related_selector_name);
1387
1
    else
1388
1
      Diag(Tok, diag::err_expected) << tok::comma;
1389
2
    SkipUntil(tok::r_paren, StopAtSemi);
1390
2
    return;
1391
2
  }
1392
1393
  // Parse instance method name.  Also non-optional but empty string is
1394
  // permitted.
1395
614
  IdentifierLoc *InstanceMethod = nullptr;
1396
614
  if (Tok.is(tok::identifier))
1397
19
    InstanceMethod = ParseIdentifierLoc();
1398
595
  else if (Tok.isNot(tok::r_paren)) {
1399
1
    Diag(Tok, diag::err_expected) << tok::r_paren;
1400
1
    SkipUntil(tok::r_paren, StopAtSemi);
1401
1
    return;
1402
1
  }
1403
1404
  // Closing ')'.
1405
613
  if (T.consumeClose())
1406
0
    return;
1407
1408
613
  if (endLoc)
1409
2
    *endLoc = T.getCloseLocation();
1410
1411
  // Record this attribute
1412
613
  attrs.addNew(&ObjCBridgeRelated,
1413
613
               SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1414
613
               ScopeName, ScopeLoc,
1415
613
               RelatedClass,
1416
613
               ClassMethod,
1417
613
               InstanceMethod,
1418
613
               Syntax);
1419
613
}
1420
1421
1422
void Parser::ParseSwiftNewTypeAttribute(
1423
    IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1424
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1425
14.5k
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1426
14.5k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1427
1428
  // Opening '('
1429
14.5k
  if (T.consumeOpen()) {
1430
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1431
0
    return;
1432
0
  }
1433
1434
14.5k
  if (Tok.is(tok::r_paren)) {
1435
1
    Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1436
1
    T.consumeClose();
1437
1
    return;
1438
1
  }
1439
14.5k
  if (Tok.isNot(tok::kw_struct) && 
Tok.isNot(tok::kw_enum)7.06k
) {
1440
2
    Diag(Tok, diag::warn_attribute_type_not_supported)
1441
2
        << &AttrName << Tok.getIdentifierInfo();
1442
2
    if (!isTokenSpecial())
1443
2
      ConsumeToken();
1444
2
    T.consumeClose();
1445
2
    return;
1446
2
  }
1447
1448
14.5k
  auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1449
14.5k
                                          Tok.getIdentifierInfo());
1450
14.5k
  ConsumeToken();
1451
1452
  // Closing ')'
1453
14.5k
  if (T.consumeClose())
1454
0
    return;
1455
14.5k
  if (EndLoc)
1456
14.5k
    *EndLoc = T.getCloseLocation();
1457
1458
14.5k
  ArgsUnion Args[] = {SwiftType};
1459
14.5k
  Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1460
14.5k
               ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1461
14.5k
}
1462
1463
1464
void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1465
                                              SourceLocation AttrNameLoc,
1466
                                              ParsedAttributes &Attrs,
1467
                                              SourceLocation *EndLoc,
1468
                                              IdentifierInfo *ScopeName,
1469
                                              SourceLocation ScopeLoc,
1470
188
                                              ParsedAttr::Syntax Syntax) {
1471
188
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1472
1473
188
  BalancedDelimiterTracker T(*this, tok::l_paren);
1474
188
  T.consumeOpen();
1475
1476
188
  if (Tok.isNot(tok::identifier)) {
1477
0
    Diag(Tok, diag::err_expected) << tok::identifier;
1478
0
    T.skipToEnd();
1479
0
    return;
1480
0
  }
1481
188
  IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1482
1483
188
  if (ExpectAndConsume(tok::comma)) {
1484
0
    T.skipToEnd();
1485
0
    return;
1486
0
  }
1487
1488
188
  SourceRange MatchingCTypeRange;
1489
188
  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1490
188
  if (MatchingCType.isInvalid()) {
1491
8
    T.skipToEnd();
1492
8
    return;
1493
8
  }
1494
1495
180
  bool LayoutCompatible = false;
1496
180
  bool MustBeNull = false;
1497
233
  while (TryConsumeToken(tok::comma)) {
1498
65
    if (Tok.isNot(tok::identifier)) {
1499
4
      Diag(Tok, diag::err_expected) << tok::identifier;
1500
4
      T.skipToEnd();
1501
4
      return;
1502
4
    }
1503
61
    IdentifierInfo *Flag = Tok.getIdentifierInfo();
1504
61
    if (Flag->isStr("layout_compatible"))
1505
46
      LayoutCompatible = true;
1506
15
    else if (Flag->isStr("must_be_null"))
1507
7
      MustBeNull = true;
1508
8
    else {
1509
8
      Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1510
8
      T.skipToEnd();
1511
8
      return;
1512
8
    }
1513
53
    ConsumeToken(); // consume flag
1514
53
  }
1515
1516
168
  if (!T.consumeClose()) {
1517
168
    Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1518
168
                                   ArgumentKind, MatchingCType.get(),
1519
168
                                   LayoutCompatible, MustBeNull, Syntax);
1520
168
  }
1521
1522
168
  if (EndLoc)
1523
168
    *EndLoc = T.getCloseLocation();
1524
168
}
1525
1526
/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1527
/// of a C++11 attribute-specifier in a location where an attribute is not
1528
/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1529
/// situation.
1530
///
1531
/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1532
/// this doesn't appear to actually be an attribute-specifier, and the caller
1533
/// should try to parse it.
1534
12
bool Parser::DiagnoseProhibitedCXX11Attribute() {
1535
12
  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1536
1537
12
  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1538
4
  case CAK_NotAttributeSpecifier:
1539
    // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1540
4
    return false;
1541
1542
4
  case CAK_InvalidAttributeSpecifier:
1543
4
    Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1544
4
    return false;
1545
1546
4
  case CAK_AttributeSpecifier:
1547
    // Parse and discard the attributes.
1548
4
    SourceLocation BeginLoc = ConsumeBracket();
1549
4
    ConsumeBracket();
1550
4
    SkipUntil(tok::r_square);
1551
4
    assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1552
4
    SourceLocation EndLoc = ConsumeBracket();
1553
4
    Diag(BeginLoc, diag::err_attributes_not_allowed)
1554
4
      << SourceRange(BeginLoc, EndLoc);
1555
4
    return true;
1556
0
  }
1557
0
  llvm_unreachable("All cases handled above.");
1558
0
}
1559
1560
/// We have found the opening square brackets of a C++11
1561
/// attribute-specifier in a location where an attribute is not permitted, but
1562
/// we know where the attributes ought to be written. Parse them anyway, and
1563
/// provide a fixit moving them to the right place.
1564
void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1565
24
                                             SourceLocation CorrectLocation) {
1566
24
  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1567
24
         Tok.is(tok::kw_alignas));
1568
1569
  // Consume the attributes.
1570
24
  SourceLocation Loc = Tok.getLocation();
1571
24
  ParseCXX11Attributes(Attrs);
1572
24
  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1573
  // FIXME: use err_attributes_misplaced
1574
24
  Diag(Loc, diag::err_attributes_not_allowed)
1575
24
    << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1576
24
    << FixItHint::CreateRemoval(AttrRange);
1577
24
}
1578
1579
void Parser::DiagnoseProhibitedAttributes(
1580
120
    const SourceRange &Range, const SourceLocation CorrectLocation) {
1581
120
  if (CorrectLocation.isValid()) {
1582
13
    CharSourceRange AttrRange(Range, true);
1583
13
    Diag(CorrectLocation, diag::err_attributes_misplaced)
1584
13
        << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1585
13
        << FixItHint::CreateRemoval(AttrRange);
1586
13
  } else
1587
107
    Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1588
120
}
1589
1590
void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1591
1.79k
                                     unsigned DiagID) {
1592
28
  for (const ParsedAttr &AL : Attrs) {
1593
28
    if (!AL.isCXX11Attribute() && 
!AL.isC2xAttribute()1
)
1594
0
      continue;
1595
28
    if (AL.getKind() == ParsedAttr::UnknownAttribute)
1596
7
      Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1597
7
          << AL << AL.getRange();
1598
21
    else {
1599
21
      Diag(AL.getLoc(), DiagID) << AL;
1600
21
      AL.setInvalid();
1601
21
    }
1602
28
  }
1603
1.79k
}
1604
1605
// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1606
// applies to var, not the type Foo.
1607
// As an exception to the rule, __declspec(align(...)) before the
1608
// class-key affects the type instead of the variable.
1609
// Also, Microsoft-style [attributes] seem to affect the type instead of the
1610
// variable.
1611
// This function moves attributes that should apply to the type off DS to Attrs.
1612
void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1613
                                            DeclSpec &DS,
1614
2.53M
                                            Sema::TagUseKind TUK) {
1615
2.53M
  if (TUK == Sema::TUK_Reference)
1616
913k
    return;
1617
1618
1.62M
  llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1619
1620
242
  for (ParsedAttr &AL : DS.getAttributes()) {
1621
242
    if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1622
47
         AL.isDeclspecAttribute()) ||
1623
234
        AL.isMicrosoftAttribute())
1624
59
      ToBeMoved.push_back(&AL);
1625
242
  }
1626
1627
59
  for (ParsedAttr *AL : ToBeMoved) {
1628
59
    DS.getAttributes().remove(AL);
1629
59
    Attrs.addAtEnd(AL);
1630
59
  }
1631
1.62M
}
1632
1633
/// ParseDeclaration - Parse a full 'declaration', which consists of
1634
/// declaration-specifiers, some number of declarators, and a semicolon.
1635
/// 'Context' should be a DeclaratorContext value.  This returns the
1636
/// location of the semicolon in DeclEnd.
1637
///
1638
///       declaration: [C99 6.7]
1639
///         block-declaration ->
1640
///           simple-declaration
1641
///           others                   [FIXME]
1642
/// [C++]   template-declaration
1643
/// [C++]   namespace-definition
1644
/// [C++]   using-directive
1645
/// [C++]   using-declaration
1646
/// [C++11/C11] static_assert-declaration
1647
///         others... [FIXME]
1648
///
1649
Parser::DeclGroupPtrTy
1650
Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1651
                         ParsedAttributesWithRange &attrs,
1652
4.18M
                         SourceLocation *DeclSpecStart) {
1653
4.18M
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1654
  // Must temporarily exit the objective-c container scope for
1655
  // parsing c none objective-c decls.
1656
4.18M
  ObjCDeclContextSwitch ObjCDC(*this);
1657
1658
4.18M
  Decl *SingleDecl = nullptr;
1659
4.18M
  switch (Tok.getKind()) {
1660
949k
  case tok::kw_template:
1661
949k
  case tok::kw_export:
1662
949k
    ProhibitAttributes(attrs);
1663
949k
    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1664
949k
    break;
1665
18.3k
  case tok::kw_inline:
1666
    // Could be the start of an inline namespace. Allowed as an ext in C++03.
1667
18.3k
    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1668
18.3k
      ProhibitAttributes(attrs);
1669
18.3k
      SourceLocation InlineLoc = ConsumeToken();
1670
18.3k
      return ParseNamespace(Context, DeclEnd, InlineLoc);
1671
18.3k
    }
1672
6
    return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1673
6
                                  DeclSpecStart);
1674
55.2k
  case tok::kw_namespace:
1675
55.2k
    ProhibitAttributes(attrs);
1676
55.2k
    return ParseNamespace(Context, DeclEnd);
1677
136k
  case tok::kw_using:
1678
136k
    return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1679
136k
                                            DeclEnd, attrs);
1680
28.8k
  case tok::kw_static_assert:
1681
28.8k
  case tok::kw__Static_assert:
1682
28.8k
    ProhibitAttributes(attrs);
1683
28.8k
    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1684
28.8k
    break;
1685
2.99M
  default:
1686
2.99M
    return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1687
2.99M
                                  DeclSpecStart);
1688
978k
  }
1689
1690
  // This routine returns a DeclGroup, if the thing we parsed only contains a
1691
  // single decl, convert it now.
1692
978k
  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1693
978k
}
1694
1695
///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1696
///         declaration-specifiers init-declarator-list[opt] ';'
1697
/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1698
///             init-declarator-list ';'
1699
///[C90/C++]init-declarator-list ';'                             [TODO]
1700
/// [OMP]   threadprivate-directive
1701
/// [OMP]   allocate-directive                                   [TODO]
1702
///
1703
///       for-range-declaration: [C++11 6.5p1: stmt.ranged]
1704
///         attribute-specifier-seq[opt] type-specifier-seq declarator
1705
///
1706
/// If RequireSemi is false, this does not check for a ';' at the end of the
1707
/// declaration.  If it is true, it checks for and eats it.
1708
///
1709
/// If FRI is non-null, we might be parsing a for-range-declaration instead
1710
/// of a simple-declaration. If we find that we are, we also parse the
1711
/// for-range-initializer, and place it here.
1712
///
1713
/// DeclSpecStart is used when decl-specifiers are parsed before parsing
1714
/// the Declaration. The SourceLocation for this Decl is set to
1715
/// DeclSpecStart if DeclSpecStart is non-null.
1716
Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1717
    DeclaratorContext Context, SourceLocation &DeclEnd,
1718
    ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1719
3.10M
    SourceLocation *DeclSpecStart) {
1720
  // Parse the common declaration-specifiers piece.
1721
3.10M
  ParsingDeclSpec DS(*this);
1722
1723
3.10M
  DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1724
3.10M
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1725
1726
  // If we had a free-standing type definition with a missing semicolon, we
1727
  // may get this far before the problem becomes obvious.
1728
3.10M
  if (DS.hasTagDefinition() &&
1729
353k
      DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1730
0
    return nullptr;
1731
1732
  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1733
  // declaration-specifiers init-declarator-list[opt] ';'
1734
3.10M
  if (Tok.is(tok::semi)) {
1735
32.4k
    ProhibitAttributes(Attrs);
1736
32.4k
    DeclEnd = Tok.getLocation();
1737
32.4k
    if (RequireSemi) ConsumeToken();
1738
32.4k
    RecordDecl *AnonRecord = nullptr;
1739
32.4k
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1740
32.4k
                                                       DS, AnonRecord);
1741
32.4k
    DS.complete(TheDecl);
1742
32.4k
    if (AnonRecord) {
1743
36
      Decl* decls[] = {AnonRecord, TheDecl};
1744
36
      return Actions.BuildDeclaratorGroup(decls);
1745
36
    }
1746
32.4k
    return Actions.ConvertDeclToDeclGroup(TheDecl);
1747
32.4k
  }
1748
1749
3.07M
  if (DeclSpecStart)
1750
2.27k
    DS.SetRangeStart(*DeclSpecStart);
1751
1752
3.07M
  DS.takeAttributesFrom(Attrs);
1753
3.07M
  return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1754
3.07M
}
1755
1756
/// Returns true if this might be the start of a declarator, or a common typo
1757
/// for a declarator.
1758
169k
bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1759
169k
  switch (Tok.getKind()) {
1760
18
  case tok::annot_cxxscope:
1761
18
  case tok::annot_template_id:
1762
18
  case tok::caret:
1763
18
  case tok::code_completion:
1764
18
  case tok::coloncolon:
1765
18
  case tok::ellipsis:
1766
18
  case tok::kw___attribute:
1767
18
  case tok::kw_operator:
1768
18
  case tok::l_paren:
1769
18
  case tok::star:
1770
18
    return true;
1771
1772
21
  case tok::amp:
1773
21
  case tok::ampamp:
1774
21
    return getLangOpts().CPlusPlus;
1775
1776
0
  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1777
0
    return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
1778
0
           NextToken().is(tok::l_square);
1779
1780
1.84k
  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1781
1.84k
    return Context == DeclaratorContext::Member || 
getLangOpts().CPlusPlus0
;
1782
1783
167k
  case tok::identifier:
1784
167k
    switch (NextToken().getKind()) {
1785
151k
    case tok::code_completion:
1786
151k
    case tok::coloncolon:
1787
151k
    case tok::comma:
1788
151k
    case tok::equal:
1789
151k
    case tok::equalequal: // Might be a typo for '='.
1790
151k
    case tok::kw_alignas:
1791
151k
    case tok::kw_asm:
1792
151k
    case tok::kw___attribute:
1793
151k
    case tok::l_brace:
1794
151k
    case tok::l_paren:
1795
151k
    case tok::l_square:
1796
151k
    case tok::less:
1797
151k
    case tok::r_brace:
1798
151k
    case tok::r_paren:
1799
151k
    case tok::r_square:
1800
151k
    case tok::semi:
1801
151k
      return true;
1802
1803
15.5k
    case tok::colon:
1804
      // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1805
      // and in block scope it's probably a label. Inside a class definition,
1806
      // this is a bit-field.
1807
15.5k
      return Context == DeclaratorContext::Member ||
1808
3
             (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
1809
1810
18
    case tok::identifier: // Possible virt-specifier.
1811
18
      return getLangOpts().CPlusPlus11 && 
isCXX11VirtSpecifier(NextToken())14
;
1812
1813
10
    default:
1814
10
      return false;
1815
0
    }
1816
1817
56
  default:
1818
56
    return false;
1819
169k
  }
1820
169k
}
1821
1822
/// Skip until we reach something which seems like a sensible place to pick
1823
/// up parsing after a malformed declaration. This will sometimes stop sooner
1824
/// than SkipUntil(tok::r_brace) would, but will never stop later.
1825
456
void Parser::SkipMalformedDecl() {
1826
1.04k
  while (true) {
1827
1.04k
    switch (Tok.getKind()) {
1828
72
    case tok::l_brace:
1829
      // Skip until matching }, then stop. We've probably skipped over
1830
      // a malformed class or function definition or similar.
1831
72
      ConsumeBrace();
1832
72
      SkipUntil(tok::r_brace);
1833
72
      if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1834
        // This declaration isn't over yet. Keep skipping.
1835
4
        continue;
1836
4
      }
1837
68
      TryConsumeToken(tok::semi);
1838
68
      return;
1839
1840
0
    case tok::l_square:
1841
0
      ConsumeBracket();
1842
0
      SkipUntil(tok::r_square);
1843
0
      continue;
1844
1845
40
    case tok::l_paren:
1846
40
      ConsumeParen();
1847
40
      SkipUntil(tok::r_paren);
1848
40
      continue;
1849
1850
9
    case tok::r_brace:
1851
9
      return;
1852
1853
247
    case tok::semi:
1854
247
      ConsumeToken();
1855
247
      return;
1856
1857
2
    case tok::kw_inline:
1858
      // 'inline namespace' at the start of a line is almost certainly
1859
      // a good place to pick back up parsing, except in an Objective-C
1860
      // @interface context.
1861
2
      if (Tok.isAtStartOfLine() && 
NextToken().is(tok::kw_namespace)1
&&
1862
1
          (!ParsingInObjCContainer || 
CurParsedObjCImpl0
))
1863
1
        return;
1864
1
      break;
1865
1866
6
    case tok::kw_namespace:
1867
      // 'namespace' at the start of a line is almost certainly a good
1868
      // place to pick back up parsing, except in an Objective-C
1869
      // @interface context.
1870
6
      if (Tok.isAtStartOfLine() &&
1871
4
          (!ParsingInObjCContainer || 
CurParsedObjCImpl3
))
1872
2
        return;
1873
4
      break;
1874
1875
2
    case tok::at:
1876
      // @end is very much like } in Objective-C contexts.
1877
2
      if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1878
2
          ParsingInObjCContainer)
1879
2
        return;
1880
0
      break;
1881
1882
16
    case tok::minus:
1883
16
    case tok::plus:
1884
      // - and + probably start new method declarations in Objective-C contexts.
1885
16
      if (Tok.isAtStartOfLine() && 
ParsingInObjCContainer5
)
1886
4
        return;
1887
12
      break;
1888
1889
123
    case tok::eof:
1890
123
    case tok::annot_module_begin:
1891
123
    case tok::annot_module_end:
1892
123
    case tok::annot_module_include:
1893
123
      return;
1894
1895
529
    default:
1896
529
      break;
1897
546
    }
1898
1899
546
    ConsumeAnyToken();
1900
546
  }
1901
456
}
1902
1903
/// ParseDeclGroup - Having concluded that this is either a function
1904
/// definition or a group of object declarations, actually parse the
1905
/// result.
1906
Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1907
                                              DeclaratorContext Context,
1908
                                              SourceLocation *DeclEnd,
1909
16.7M
                                              ForRangeInit *FRI) {
1910
  // Parse the first declarator.
1911
16.7M
  ParsingDeclarator D(*this, DS, Context);
1912
16.7M
  ParseDeclarator(D);
1913
1914
  // Bail out if the first declarator didn't seem well-formed.
1915
16.7M
  if (!D.hasName() && 
!D.mayOmitIdentifier()328
) {
1916
328
    SkipMalformedDecl();
1917
328
    return nullptr;
1918
328
  }
1919
1920
16.7M
  if (Tok.is(tok::kw_requires))
1921
36
    ParseTrailingRequiresClause(D);
1922
1923
  // Save late-parsed attributes for now; they need to be parsed in the
1924
  // appropriate function scope after the function Decl has been constructed.
1925
  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1926
16.7M
  LateParsedAttrList LateParsedAttrs(true);
1927
16.7M
  if (D.isFunctionDeclarator()) {
1928
12.5M
    MaybeParseGNUAttributes(D, &LateParsedAttrs);
1929
1930
    // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1931
    // attribute. If we find the keyword here, tell the user to put it
1932
    // at the start instead.
1933
12.5M
    if (Tok.is(tok::kw__Noreturn)) {
1934
6
      SourceLocation Loc = ConsumeToken();
1935
6
      const char *PrevSpec;
1936
6
      unsigned DiagID;
1937
1938
      // We can offer a fixit if it's valid to mark this function as _Noreturn
1939
      // and we don't have any other declarators in this declaration.
1940
6
      bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1941
6
      MaybeParseGNUAttributes(D, &LateParsedAttrs);
1942
6
      Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1943
1944
6
      Diag(Loc, diag::err_c11_noreturn_misplaced)
1945
6
          << (Fixit ? FixItHint::CreateRemoval(Loc) : 
FixItHint()0
)
1946
6
          << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
1947
0
                    : FixItHint());
1948
6
    }
1949
12.5M
  }
1950
1951
  // Check to see if we have a function *definition* which must have a body.
1952
16.7M
  if (D.isFunctionDeclarator()) {
1953
12.5M
    if (Tok.is(tok::equal) && 
NextToken().is(tok::code_completion)598
) {
1954
2
      Actions.CodeCompleteAfterFunctionEquals(D);
1955
2
      cutOffParsing();
1956
2
      return nullptr;
1957
2
    }
1958
    // Look at the next token to make sure that this isn't a function
1959
    // declaration.  We have to check this because __attribute__ might be the
1960
    // start of a function definition in GCC-extended K&R C.
1961
12.5M
    if (!isDeclarationAfterDeclarator()) {
1962
1963
      // Function definitions are only allowed at file scope and in C++ classes.
1964
      // The C++ inline method definition case is handled elsewhere, so we only
1965
      // need to handle the file scope definition case.
1966
2.15M
      if (Context == DeclaratorContext::File) {
1967
2.15M
        if (isStartOfFunctionDefinition(D)) {
1968
2.15M
          if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1969
9
            Diag(Tok, diag::err_function_declared_typedef);
1970
1971
            // Recover by treating the 'typedef' as spurious.
1972
9
            DS.ClearStorageClassSpecs();
1973
9
          }
1974
1975
2.15M
          Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
1976
2.15M
                                                  &LateParsedAttrs);
1977
2.15M
          return Actions.ConvertDeclToDeclGroup(TheDecl);
1978
2.15M
        }
1979
1980
35
        if (isDeclarationSpecifier()) {
1981
          // If there is an invalid declaration specifier right after the
1982
          // function prototype, then we must be in a missing semicolon case
1983
          // where this isn't actually a body.  Just fall through into the code
1984
          // that handles it as a prototype, and let the top-level code handle
1985
          // the erroneous declspec where it would otherwise expect a comma or
1986
          // semicolon.
1987
33
        } else {
1988
33
          Diag(Tok, diag::err_expected_fn_body);
1989
33
          SkipUntil(tok::semi);
1990
33
          return nullptr;
1991
33
        }
1992
12
      } else {
1993
12
        if (Tok.is(tok::l_brace)) {
1994
8
          Diag(Tok, diag::err_function_definition_not_allowed);
1995
8
          SkipMalformedDecl();
1996
8
          return nullptr;
1997
8
        }
1998
14.5M
      }
1999
2.15M
    }
2000
12.5M
  }
2001
2002
14.5M
  if (ParseAsmAttributesAfterDeclarator(D))
2003
8
    return nullptr;
2004
2005
  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2006
  // must parse and analyze the for-range-initializer before the declaration is
2007
  // analyzed.
2008
  //
2009
  // Handle the Objective-C for-in loop variable similarly, although we
2010
  // don't need to parse the container in advance.
2011
14.5M
  if (FRI && 
(109k
Tok.is(tok::colon)109k
||
isTokIdentifier_in()107k
)) {
2012
1.34k
    bool IsForRangeLoop = false;
2013
1.34k
    if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2014
1.30k
      IsForRangeLoop = true;
2015
1.30k
      if (getLangOpts().OpenMP)
2016
118
        Actions.startOpenMPCXXRangeFor();
2017
1.30k
      if (Tok.is(tok::l_brace))
2018
10
        FRI->RangeExpr = ParseBraceInitializer();
2019
1.29k
      else
2020
1.29k
        FRI->RangeExpr = ParseExpression();
2021
1.30k
    }
2022
2023
1.34k
    Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2024
1.34k
    if (IsForRangeLoop) {
2025
1.30k
      Actions.ActOnCXXForRangeDecl(ThisDecl);
2026
37
    } else {
2027
      // Obj-C for loop
2028
37
      if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2029
36
        VD->setObjCForDecl(true);
2030
37
    }
2031
1.34k
    Actions.FinalizeDeclaration(ThisDecl);
2032
1.34k
    D.complete(ThisDecl);
2033
1.34k
    return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2034
1.34k
  }
2035
2036
14.5M
  SmallVector<Decl *, 8> DeclsInGroup;
2037
14.5M
  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2038
14.5M
      D, ParsedTemplateInfo(), FRI);
2039
14.5M
  if (LateParsedAttrs.size() > 0)
2040
654
    ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2041
14.5M
  D.complete(FirstDecl);
2042
14.5M
  if (FirstDecl)
2043
14.5M
    DeclsInGroup.push_back(FirstDecl);
2044
2045
14.5M
  bool ExpectSemi = Context != DeclaratorContext::ForInit;
2046
2047
  // If we don't have a comma, it is either the end of the list (a ';') or an
2048
  // error, bail out.
2049
14.5M
  SourceLocation CommaLoc;
2050
14.8M
  while (TryConsumeToken(tok::comma, CommaLoc)) {
2051
221k
    if (Tok.isAtStartOfLine() && 
ExpectSemi151k
&&
!MightBeDeclarator(Context)150k
) {
2052
      // This comma was followed by a line-break and something which can't be
2053
      // the start of a declarator. The comma was probably a typo for a
2054
      // semicolon.
2055
40
      Diag(CommaLoc, diag::err_expected_semi_declaration)
2056
40
        << FixItHint::CreateReplacement(CommaLoc, ";");
2057
40
      ExpectSemi = false;
2058
40
      break;
2059
40
    }
2060
2061
    // Parse the next declarator.
2062
221k
    D.clear();
2063
221k
    D.setCommaLoc(CommaLoc);
2064
2065
    // Accept attributes in an init-declarator.  In the first declarator in a
2066
    // declaration, these would be part of the declspec.  In subsequent
2067
    // declarators, they become part of the declarator itself, so that they
2068
    // don't apply to declarators after *this* one.  Examples:
2069
    //    short __attribute__((common)) var;    -> declspec
2070
    //    short var __attribute__((common));    -> declarator
2071
    //    short x, __attribute__((common)) var;    -> declarator
2072
221k
    MaybeParseGNUAttributes(D);
2073
2074
    // MSVC parses but ignores qualifiers after the comma as an extension.
2075
221k
    if (getLangOpts().MicrosoftExt)
2076
294
      DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2077
2078
221k
    ParseDeclarator(D);
2079
221k
    if (!D.isInvalidType()) {
2080
      // C++2a [dcl.decl]p1
2081
      //    init-declarator:
2082
      //        declarator initializer[opt]
2083
      //        declarator requires-clause
2084
221k
      if (Tok.is(tok::kw_requires))
2085
0
        ParseTrailingRequiresClause(D);
2086
221k
      Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2087
221k
      D.complete(ThisDecl);
2088
221k
      if (ThisDecl)
2089
221k
        DeclsInGroup.push_back(ThisDecl);
2090
221k
    }
2091
221k
  }
2092
2093
14.5M
  if (DeclEnd)
2094
3.06M
    *DeclEnd = Tok.getLocation();
2095
2096
14.5M
  if (ExpectSemi && ExpectAndConsumeSemi(
2097
14.4M
                        Context == DeclaratorContext::File
2098
13.3M
                            ? diag::err_invalid_token_after_toplevel_declarator
2099
1.12M
                            : diag::err_expected_semi_declaration)) {
2100
    // Okay, there was no semicolon and one was expected.  If we see a
2101
    // declaration specifier, just assume it was missing and continue parsing.
2102
    // Otherwise things are very confused and we skip to recover.
2103
268
    if (!isDeclarationSpecifier()) {
2104
243
      SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2105
243
      TryConsumeToken(tok::semi);
2106
243
    }
2107
268
  }
2108
2109
14.5M
  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2110
14.5M
}
2111
2112
/// Parse an optional simple-asm-expr and attributes, and attach them to a
2113
/// declarator. Returns true on an error.
2114
14.9M
bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2115
  // If a simple-asm-expr is present, parse it.
2116
14.9M
  if (Tok.is(tok::kw_asm)) {
2117
59.4k
    SourceLocation Loc;
2118
59.4k
    ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2119
59.4k
    if (AsmLabel.isInvalid()) {
2120
8
      SkipUntil(tok::semi, StopBeforeMatch);
2121
8
      return true;
2122
8
    }
2123
2124
59.3k
    D.setAsmLabel(AsmLabel.get());
2125
59.3k
    D.SetRangeEnd(Loc);
2126
59.3k
  }
2127
2128
14.9M
  MaybeParseGNUAttributes(D);
2129
14.9M
  return false;
2130
14.9M
}
2131
2132
/// Parse 'declaration' after parsing 'declaration-specifiers
2133
/// declarator'. This method parses the remainder of the declaration
2134
/// (including any attributes or initializer, among other things) and
2135
/// finalizes the declaration.
2136
///
2137
///       init-declarator: [C99 6.7]
2138
///         declarator
2139
///         declarator '=' initializer
2140
/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
2141
/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2142
/// [C++]   declarator initializer[opt]
2143
///
2144
/// [C++] initializer:
2145
/// [C++]   '=' initializer-clause
2146
/// [C++]   '(' expression-list ')'
2147
/// [C++0x] '=' 'default'                                                [TODO]
2148
/// [C++0x] '=' 'delete'
2149
/// [C++0x] braced-init-list
2150
///
2151
/// According to the standard grammar, =default and =delete are function
2152
/// definitions, but that definitely doesn't fit with the parser here.
2153
///
2154
Decl *Parser::ParseDeclarationAfterDeclarator(
2155
347k
    Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2156
347k
  if (ParseAsmAttributesAfterDeclarator(D))
2157
0
    return nullptr;
2158
2159
347k
  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2160
347k
}
2161
2162
Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2163
14.9M
    Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2164
  // RAII type used to track whether we're inside an initializer.
2165
14.9M
  struct InitializerScopeRAII {
2166
14.9M
    Parser &P;
2167
14.9M
    Declarator &D;
2168
14.9M
    Decl *ThisDecl;
2169
2170
14.9M
    InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2171
697k
        : P(P), D(D), ThisDecl(ThisDecl) {
2172
697k
      if (ThisDecl && 
P.getLangOpts().CPlusPlus697k
) {
2173
583k
        Scope *S = nullptr;
2174
583k
        if (D.getCXXScopeSpec().isSet()) {
2175
2.08k
          P.EnterScope(0);
2176
2.08k
          S = P.getCurScope();
2177
2.08k
        }
2178
583k
        P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2179
583k
      }
2180
697k
    }
2181
697k
    ~InitializerScopeRAII() { pop(); }
2182
1.39M
    void pop() {
2183
1.39M
      if (ThisDecl && 
P.getLangOpts().CPlusPlus697k
) {
2184
583k
        Scope *S = nullptr;
2185
583k
        if (D.getCXXScopeSpec().isSet())
2186
2.08k
          S = P.getCurScope();
2187
583k
        P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2188
583k
        if (S)
2189
2.08k
          P.ExitScope();
2190
583k
      }
2191
1.39M
      ThisDecl = nullptr;
2192
1.39M
    }
2193
14.9M
  };
2194
2195
  // Inform the current actions module that we just parsed this declarator.
2196
14.9M
  Decl *ThisDecl = nullptr;
2197
14.9M
  Decl *OuterDecl = nullptr;
2198
14.9M
  switch (TemplateInfo.Kind) {
2199
14.8M
  case ParsedTemplateInfo::NonTemplate:
2200
14.8M
    ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2201
14.8M
    break;
2202
2203
82.7k
  case ParsedTemplateInfo::Template:
2204
82.7k
  case ParsedTemplateInfo::ExplicitSpecialization: {
2205
82.7k
    ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2206
82.7k
                                               *TemplateInfo.TemplateParams,
2207
82.7k
                                               D);
2208
82.7k
    if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2209
      // Re-direct this decl to refer to the templated decl so that we can
2210
      // initialize it.
2211
1.97k
      ThisDecl = VT->getTemplatedDecl();
2212
1.97k
      OuterDecl = VT;
2213
1.97k
    }
2214
82.7k
    break;
2215
82.7k
  }
2216
43.6k
  case ParsedTemplateInfo::ExplicitInstantiation: {
2217
43.6k
    if (Tok.is(tok::semi)) {
2218
43.6k
      DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2219
43.6k
          getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2220
43.6k
      if (ThisRes.isInvalid()) {
2221
102
        SkipUntil(tok::semi, StopBeforeMatch);
2222
102
        return nullptr;
2223
102
      }
2224
43.5k
      ThisDecl = ThisRes.get();
2225
6
    } else {
2226
      // FIXME: This check should be for a variable template instantiation only.
2227
2228
      // Check that this is a valid instantiation
2229
6
      if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2230
        // If the declarator-id is not a template-id, issue a diagnostic and
2231
        // recover by ignoring the 'template' keyword.
2232
3
        Diag(Tok, diag::err_template_defn_explicit_instantiation)
2233
3
            << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2234
3
        ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2235
3
      } else {
2236
3
        SourceLocation LAngleLoc =
2237
3
            PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2238
3
        Diag(D.getIdentifierLoc(),
2239
3
             diag::err_explicit_instantiation_with_definition)
2240
3
            << SourceRange(TemplateInfo.TemplateLoc)
2241
3
            << FixItHint::CreateInsertion(LAngleLoc, "<>");
2242
2243
        // Recover as if it were an explicit specialization.
2244
3
        TemplateParameterLists FakedParamLists;
2245
3
        FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2246
3
            0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2247
3
            LAngleLoc, nullptr));
2248
2249
3
        ThisDecl =
2250
3
            Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2251
3
      }
2252
6
    }
2253
43.5k
    break;
2254
14.9M
    }
2255
14.9M
  }
2256
2257
  // Parse declarator '=' initializer.
2258
  // If a '==' or '+=' is found, suggest a fixit to '='.
2259
14.9M
  if (isTokenEqualOrEqualTypo()) {
2260
633k
    SourceLocation EqualLoc = ConsumeToken();
2261
2262
633k
    if (Tok.is(tok::kw_delete)) {
2263
3
      if (D.isFunctionDeclarator())
2264
1
        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2265
1
          << 1 /* delete */;
2266
2
      else
2267
2
        Diag(ConsumeToken(), diag::err_deleted_non_function);
2268
633k
    } else if (Tok.is(tok::kw_default)) {
2269
2
      if (D.isFunctionDeclarator())
2270
1
        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2271
1
          << 0 /* default */;
2272
1
      else
2273
1
        Diag(ConsumeToken(), diag::err_default_special_members)
2274
1
            << getLangOpts().CPlusPlus20;
2275
633k
    } else {
2276
633k
      InitializerScopeRAII InitScope(*this, D, ThisDecl);
2277
2278
633k
      if (Tok.is(tok::code_completion)) {
2279
42
        Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2280
42
        Actions.FinalizeDeclaration(ThisDecl);
2281
42
        cutOffParsing();
2282
42
        return nullptr;
2283
42
      }
2284
2285
633k
      PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2286
633k
      ExprResult Init = ParseInitializer();
2287
2288
      // If this is the only decl in (possibly) range based for statement,
2289
      // our best guess is that the user meant ':' instead of '='.
2290
633k
      if (Tok.is(tok::r_paren) && 
FRI4
&&
D.isFirstDeclarator()3
) {
2291
3
        Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2292
3
            << FixItHint::CreateReplacement(EqualLoc, ":");
2293
        // We are trying to stop parser from looking for ';' in this for
2294
        // statement, therefore preventing spurious errors to be issued.
2295
3
        FRI->ColonLoc = EqualLoc;
2296
3
        Init = ExprError();
2297
3
        FRI->RangeExpr = Init;
2298
3
      }
2299
2300
633k
      InitScope.pop();
2301
2302
633k
      if (Init.isInvalid()) {
2303
1.08k
        SmallVector<tok::TokenKind, 2> StopTokens;
2304
1.08k
        StopTokens.push_back(tok::comma);
2305
1.08k
        if (D.getContext() == DeclaratorContext::ForInit ||
2306
1.08k
            D.getContext() == DeclaratorContext::SelectionInit)
2307
3
          StopTokens.push_back(tok::r_paren);
2308
1.08k
        SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2309
1.08k
        Actions.ActOnInitializerError(ThisDecl);
2310
1.08k
      } else
2311
632k
        Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2312
632k
                                     /*DirectInit=*/false);
2313
633k
    }
2314
14.3M
  } else if (Tok.is(tok::l_paren)) {
2315
    // Parse C++ direct initializer: '(' expression-list ')'
2316
58.3k
    BalancedDelimiterTracker T(*this, tok::l_paren);
2317
58.3k
    T.consumeOpen();
2318
2319
58.3k
    ExprVector Exprs;
2320
58.3k
    CommaLocsTy CommaLocs;
2321
2322
58.3k
    InitializerScopeRAII InitScope(*this, D, ThisDecl);
2323
2324
58.3k
    auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2325
13
    auto RunSignatureHelp = [&]() {
2326
13
      QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2327
13
          getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2328
13
          ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2329
13
      CalledSignatureHelp = true;
2330
13
      return PreferredType;
2331
13
    };
2332
85.4k
    auto SetPreferredType = [&] {
2333
85.4k
      PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2334
85.4k
    };
2335
2336
58.3k
    llvm::function_ref<void()> ExpressionStarts;
2337
58.3k
    if (ThisVarDecl) {
2338
      // ParseExpressionList can sometimes succeed even when ThisDecl is not
2339
      // VarDecl. This is an error and it is reported in a call to
2340
      // Actions.ActOnInitializerError(). However, we call
2341
      // ProduceConstructorSignatureHelp only on VarDecls.
2342
58.3k
      ExpressionStarts = SetPreferredType;
2343
58.3k
    }
2344
58.3k
    if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2345
76
      if (ThisVarDecl && 
PP.isCodeCompletionReached()75
&&
!CalledSignatureHelp19
) {
2346
2
        Actions.ProduceConstructorSignatureHelp(
2347
2
            getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2348
2
            ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2349
2
        CalledSignatureHelp = true;
2350
2
      }
2351
76
      Actions.ActOnInitializerError(ThisDecl);
2352
76
      SkipUntil(tok::r_paren, StopAtSemi);
2353
58.2k
    } else {
2354
      // Match the ')'.
2355
58.2k
      T.consumeClose();
2356
2357
58.2k
      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2358
58.2k
             "Unexpected number of commas!");
2359
2360
58.2k
      InitScope.pop();
2361
2362
58.2k
      ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2363
58.2k
                                                          T.getCloseLocation(),
2364
58.2k
                                                          Exprs);
2365
58.2k
      Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2366
58.2k
                                   /*DirectInit=*/true);
2367
58.2k
    }
2368
14.2M
  } else if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)1.78M
&&
2369
5.35k
             (!CurParsedObjCImpl || 
!D.isFunctionDeclarator()1
)) {
2370
    // Parse C++0x braced-init-list.
2371
5.35k
    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2372
2373
5.35k
    InitializerScopeRAII InitScope(*this, D, ThisDecl);
2374
2375
5.35k
    PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2376
5.35k
    ExprResult Init(ParseBraceInitializer());
2377
2378
5.35k
    InitScope.pop();
2379
2380
5.35k
    if (Init.isInvalid()) {
2381
9
      Actions.ActOnInitializerError(ThisDecl);
2382
9
    } else
2383
5.35k
      Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2384
2385
14.2M
  } else {
2386
14.2M
    Actions.ActOnUninitializedDecl(ThisDecl);
2387
14.2M
  }
2388
2389
14.9M
  Actions.FinalizeDeclaration(ThisDecl);
2390
14.9M
  return OuterDecl ? 
OuterDecl1.97k
: ThisDecl;
2391
14.9M
}
2392
2393
/// ParseSpecifierQualifierList
2394
///        specifier-qualifier-list:
2395
///          type-specifier specifier-qualifier-list[opt]
2396
///          type-qualifier specifier-qualifier-list[opt]
2397
/// [GNU]    attributes     specifier-qualifier-list[opt]
2398
///
2399
void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2400
13.6M
                                         DeclSpecContext DSC) {
2401
  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
2402
  /// parse declaration-specifiers and complain about extra stuff.
2403
  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2404
13.6M
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2405
2406
  // Validate declspec for type-name.
2407
13.6M
  unsigned Specs = DS.getParsedSpecifiers();
2408
13.6M
  if (isTypeSpecifier(DSC) && 
!DS.hasTypeSpecifier()4.08M
) {
2409
148
    Diag(Tok, diag::err_expected_type);
2410
148
    DS.SetTypeSpecError();
2411
13.6M
  } else if (Specs == DeclSpec::PQ_None && 
!DS.hasAttributes()46
) {
2412
29
    Diag(Tok, diag::err_typename_requires_specqual);
2413
29
    if (!DS.hasTypeSpecifier())
2414
29
      DS.SetTypeSpecError();
2415
29
  }
2416
2417
  // Issue diagnostic and remove storage class if present.
2418
13.6M
  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2419
16
    if (DS.getStorageClassSpecLoc().isValid())
2420
11
      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2421
5
    else
2422
5
      Diag(DS.getThreadStorageClassSpecLoc(),
2423
5
           diag::err_typename_invalid_storageclass);
2424
16
    DS.ClearStorageClassSpecs();
2425
16
  }
2426
2427
  // Issue diagnostic and remove function specifier if present.
2428
13.6M
  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2429
6
    if (DS.isInlineSpecified())
2430
2
      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2431
6
    if (DS.isVirtualSpecified())
2432
2
      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2433
6
    if (DS.hasExplicitSpecifier())
2434
2
      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2435
6
    DS.ClearFunctionSpecs();
2436
6
  }
2437
2438
  // Issue diagnostic and remove constexpr specifier if present.
2439
13.6M
  if (DS.hasConstexprSpecifier() && 
DSC != DeclSpecContext::DSC_condition34
) {
2440
7
    Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2441
7
        << static_cast<int>(DS.getConstexprSpecifier());
2442
7
    DS.ClearConstexprSpec();
2443
7
  }
2444
13.6M
}
2445
2446
/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2447
/// specified token is valid after the identifier in a declarator which
2448
/// immediately follows the declspec.  For example, these things are valid:
2449
///
2450
///      int x   [             4];         // direct-declarator
2451
///      int x   (             int y);     // direct-declarator
2452
///  int(int x   )                         // direct-declarator
2453
///      int x   ;                         // simple-declaration
2454
///      int x   =             17;         // init-declarator-list
2455
///      int x   ,             y;          // init-declarator-list
2456
///      int x   __asm__       ("foo");    // init-declarator-list
2457
///      int x   :             4;          // struct-declarator
2458
///      int x   {             5};         // C++'0x unified initializers
2459
///
2460
/// This is not, because 'x' does not immediately follow the declspec (though
2461
/// ')' happens to be valid anyway).
2462
///    int (x)
2463
///
2464
434
static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2465
434
  return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2466
434
                   tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2467
434
                   tok::colon);
2468
434
}
2469
2470
/// ParseImplicitInt - This method is called when we have an non-typename
2471
/// identifier in a declspec (which normally terminates the decl spec) when
2472
/// the declspec has no type specifier.  In this case, the declspec is either
2473
/// malformed or is "implicit int" (in K&R and C89).
2474
///
2475
/// This method handles diagnosing this prettily and returns false if the
2476
/// declspec is done being processed.  If it recovers and thinks there may be
2477
/// other pieces of declspec after it, it returns true.
2478
///
2479
bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2480
                              const ParsedTemplateInfo &TemplateInfo,
2481
                              AccessSpecifier AS, DeclSpecContext DSC,
2482
1.61k
                              ParsedAttributesWithRange &Attrs) {
2483
1.61k
  assert(Tok.is(tok::identifier) && "should have identifier");
2484
2485
1.61k
  SourceLocation Loc = Tok.getLocation();
2486
  // If we see an identifier that is not a type name, we normally would
2487
  // parse it as the identifier being declared.  However, when a typename
2488
  // is typo'd or the definition is not included, this will incorrectly
2489
  // parse the typename as the identifier name and fall over misparsing
2490
  // later parts of the diagnostic.
2491
  //
2492
  // As such, we try to do some look-ahead in cases where this would
2493
  // otherwise be an "implicit-int" case to see if this is invalid.  For
2494
  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
2495
  // an identifier with implicit int, we'd get a parse error because the
2496
  // next token is obviously invalid for a type.  Parse these as a case
2497
  // with an invalid type specifier.
2498
1.61k
  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2499
2500
  // Since we know that this either implicit int (which is rare) or an
2501
  // error, do lookahead to try to do better recovery. This never applies
2502
  // within a type specifier. Outside of C++, we allow this even if the
2503
  // language doesn't "officially" support implicit int -- we support
2504
  // implicit int as an extension in C99 and C11.
2505
1.61k
  if (!isTypeSpecifier(DSC) && 
!getLangOpts().CPlusPlus1.47k
&&
2506
434
      isValidAfterIdentifierInDeclarator(NextToken())) {
2507
    // If this token is valid for implicit int, e.g. "static x = 4", then
2508
    // we just avoid eating the identifier, so it will be parsed as the
2509
    // identifier in the declarator.
2510
87
    return false;
2511
87
  }
2512
2513
  // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2514
  // for incomplete declarations such as `pipe p`.
2515
1.52k
  if (getLangOpts().OpenCLCPlusPlus && 
DS.isTypeSpecPipe()1
)
2516
1
    return false;
2517
2518
1.52k
  if (getLangOpts().CPlusPlus &&
2519
1.16k
      DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2520
    // Don't require a type specifier if we have the 'auto' storage class
2521
    // specifier in C++98 -- we'll promote it to a type specifier.
2522
72
    if (SS)
2523
3
      AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2524
72
    return false;
2525
72
  }
2526
2527
1.45k
  if (getLangOpts().CPlusPlus && 
(1.09k
!SS1.09k
||
SS->isEmpty()451
) &&
2528
643
      getLangOpts().MSVCCompat) {
2529
    // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2530
    // Give Sema a chance to recover if we are in a template with dependent base
2531
    // classes.
2532
36
    if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2533
15
            *Tok.getIdentifierInfo(), Tok.getLocation(),
2534
15
            DSC == DeclSpecContext::DSC_template_type_arg)) {
2535
15
      const char *PrevSpec;
2536
15
      unsigned DiagID;
2537
15
      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2538
15
                         Actions.getASTContext().getPrintingPolicy());
2539
15
      DS.SetRangeEnd(Tok.getLocation());
2540
15
      ConsumeToken();
2541
15
      return false;
2542
15
    }
2543
1.44k
  }
2544
2545
  // Otherwise, if we don't consume this token, we are going to emit an
2546
  // error anyway.  Try to recover from various common problems.  Check
2547
  // to see if this was a reference to a tag name without a tag specified.
2548
  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2549
  //
2550
  // C++ doesn't need this, and isTagName doesn't take SS.
2551
1.44k
  if (SS == nullptr) {
2552
990
    const char *TagName = nullptr, *FixitTagName = nullptr;
2553
990
    tok::TokenKind TagKind = tok::unknown;
2554
2555
990
    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2556
956
      default: break;
2557
11
      case DeclSpec::TST_enum:
2558
11
        TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
2559
0
      case DeclSpec::TST_union:
2560
0
        TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2561
14
      case DeclSpec::TST_struct:
2562
14
        TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2563
0
      case DeclSpec::TST_interface:
2564
0
        TagName="__interface"; FixitTagName = "__interface ";
2565
0
        TagKind=tok::kw___interface;break;
2566
9
      case DeclSpec::TST_class:
2567
9
        TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2568
990
    }
2569
2570
990
    if (TagName) {
2571
34
      IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2572
34
      LookupResult R(Actions, TokenName, SourceLocation(),
2573
34
                     Sema::LookupOrdinaryName);
2574
2575
34
      Diag(Loc, diag::err_use_of_tag_name_without_tag)
2576
34
        << TokenName << TagName << getLangOpts().CPlusPlus
2577
34
        << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2578
2579
34
      if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2580
19
        for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2581
38
             I != IEnd; 
++I19
)
2582
19
          Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2583
19
            << TokenName << TagName;
2584
19
      }
2585
2586
      // Parse this as a tag as if the missing tag were present.
2587
34
      if (TagKind == tok::kw_enum)
2588
11
        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2589
11
                           DeclSpecContext::DSC_normal);
2590
23
      else
2591
23
        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2592
23
                            /*EnteringContext*/ false,
2593
23
                            DeclSpecContext::DSC_normal, Attrs);
2594
34
      return true;
2595
34
    }
2596
1.40k
  }
2597
2598
  // Determine whether this identifier could plausibly be the name of something
2599
  // being declared (with a missing type).
2600
1.40k
  if (!isTypeSpecifier(DSC) && 
(1.28k
!SS1.28k
||
DSC == DeclSpecContext::DSC_top_level422
||
2601
1.13k
                                
DSC == DeclSpecContext::DSC_class257
)) {
2602
    // Look ahead to the next token to try to figure out what this declaration
2603
    // was supposed to be.
2604
1.13k
    switch (NextToken().getKind()) {
2605
64
    case tok::l_paren: {
2606
      // static x(4); // 'x' is not a type
2607
      // x(int n);    // 'x' is not a type
2608
      // x (*p)[];    // 'x' is a type
2609
      //
2610
      // Since we're in an error case, we can afford to perform a tentative
2611
      // parse to determine which case we're in.
2612
64
      TentativeParsingAction PA(*this);
2613
64
      ConsumeToken();
2614
64
      TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2615
64
      PA.Revert();
2616
2617
64
      if (TPR != TPResult::False) {
2618
        // The identifier is followed by a parenthesized declarator.
2619
        // It's supposed to be a type.
2620
2
        break;
2621
2
      }
2622
2623
      // If we're in a context where we could be declaring a constructor,
2624
      // check whether this is a constructor declaration with a bogus name.
2625
62
      if (DSC == DeclSpecContext::DSC_class ||
2626
40
          (DSC == DeclSpecContext::DSC_top_level && 
SS38
)) {
2627
40
        IdentifierInfo *II = Tok.getIdentifierInfo();
2628
40
        if (Actions.isCurrentClassNameTypo(II, SS)) {
2629
10
          Diag(Loc, diag::err_constructor_bad_name)
2630
10
            << Tok.getIdentifierInfo() << II
2631
10
            << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2632
10
          Tok.setIdentifierInfo(II);
2633
10
        }
2634
40
      }
2635
      // Fall through.
2636
62
      LLVM_FALLTHROUGH;
2637
62
    }
2638
176
    case tok::comma:
2639
176
    case tok::equal:
2640
176
    case tok::kw_asm:
2641
176
    case tok::l_brace:
2642
176
    case tok::l_square:
2643
176
    case tok::semi:
2644
      // This looks like a variable or function declaration. The type is
2645
      // probably missing. We're done parsing decl-specifiers.
2646
      // But only if we are not in a function prototype scope.
2647
176
      if (getCurScope()->isFunctionPrototypeScope())
2648
8
        break;
2649
168
      if (SS)
2650
36
        AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2651
168
      return false;
2652
2653
958
    default:
2654
      // This is probably supposed to be a type. This includes cases like:
2655
      //   int f(itn);
2656
      //   struct S { unsigned : 4; };
2657
958
      break;
2658
1.23k
    }
2659
1.23k
  }
2660
2661
  // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2662
  // and attempt to recover.
2663
1.23k
  ParsedType T;
2664
1.23k
  IdentifierInfo *II = Tok.getIdentifierInfo();
2665
1.23k
  bool IsTemplateName = getLangOpts().CPlusPlus && 
NextToken().is(tok::less)892
;
2666
1.23k
  Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2667
1.23k
                                  IsTemplateName);
2668
1.23k
  if (T) {
2669
    // The action has suggested that the type T could be used. Set that as
2670
    // the type in the declaration specifiers, consume the would-be type
2671
    // name token, and we're done.
2672
406
    const char *PrevSpec;
2673
406
    unsigned DiagID;
2674
406
    DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2675
406
                       Actions.getASTContext().getPrintingPolicy());
2676
406
    DS.SetRangeEnd(Tok.getLocation());
2677
406
    ConsumeToken();
2678
    // There may be other declaration specifiers after this.
2679
406
    return true;
2680
833
  } else if (II != Tok.getIdentifierInfo()) {
2681
    // If no type was suggested, the correction is to a keyword
2682
12
    Tok.setKind(II->getTokenID());
2683
    // There may be other declaration specifiers after this.
2684
12
    return true;
2685
12
  }
2686
2687
  // Otherwise, the action had no suggestion for us.  Mark this as an error.
2688
821
  DS.SetTypeSpecError();
2689
821
  DS.SetRangeEnd(Tok.getLocation());
2690
821
  ConsumeToken();
2691
2692
  // Eat any following template arguments.
2693
821
  if (IsTemplateName) {
2694
2
    SourceLocation LAngle, RAngle;
2695
2
    TemplateArgList Args;
2696
2
    ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2697
2
  }
2698
2699
  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2700
  // avoid rippling error messages on subsequent uses of the same type,
2701
  // could be useful if #include was forgotten.
2702
821
  return true;
2703
821
}
2704
2705
/// Determine the declaration specifier context from the declarator
2706
/// context.
2707
///
2708
/// \param Context the declarator context, which is one of the
2709
/// DeclaratorContext enumerator values.
2710
Parser::DeclSpecContext
2711
7.90M
Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2712
7.90M
  if (Context == DeclaratorContext::Member)
2713
0
    return DeclSpecContext::DSC_class;
2714
7.90M
  if (Context == DeclaratorContext::File)
2715
2.80M
    return DeclSpecContext::DSC_top_level;
2716
5.09M
  if (Context == DeclaratorContext::TemplateParam)
2717
0
    return DeclSpecContext::DSC_template_param;
2718
5.09M
  if (Context == DeclaratorContext::TemplateArg ||
2719
1.70M
      Context == DeclaratorContext::TemplateTypeArg)
2720
3.46M
    return DeclSpecContext::DSC_template_type_arg;
2721
1.63M
  if (Context == DeclaratorContext::TrailingReturn ||
2722
1.62M
      Context == DeclaratorContext::TrailingReturnVar)
2723
19.1k
    return DeclSpecContext::DSC_trailing;
2724
1.61M
  if (Context == DeclaratorContext::AliasDecl ||
2725
1.59M
      Context == DeclaratorContext::AliasTemplate)
2726
57.5k
    return DeclSpecContext::DSC_alias_declaration;
2727
1.55M
  return DeclSpecContext::DSC_normal;
2728
1.55M
}
2729
2730
/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2731
///
2732
/// FIXME: Simply returns an alignof() expression if the argument is a
2733
/// type. Ideally, the type should be propagated directly into Sema.
2734
///
2735
/// [C11]   type-id
2736
/// [C11]   constant-expression
2737
/// [C++0x] type-id ...[opt]
2738
/// [C++0x] assignment-expression ...[opt]
2739
ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2740
8.73k
                                      SourceLocation &EllipsisLoc) {
2741
8.73k
  ExprResult ER;
2742
8.73k
  if (isTypeIdInParens()) {
2743
76
    SourceLocation TypeLoc = Tok.getLocation();
2744
76
    ParsedType Ty = ParseTypeName().get();
2745
76
    SourceRange TypeRange(Start, Tok.getLocation());
2746
76
    ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2747
76
                                               Ty.getAsOpaquePtr(), TypeRange);
2748
76
  } else
2749
8.66k
    ER = ParseConstantExpression();
2750
2751
8.73k
  if (getLangOpts().CPlusPlus11)
2752
8.68k
    TryConsumeToken(tok::ellipsis, EllipsisLoc);
2753
2754
8.73k
  return ER;
2755
8.73k
}
2756
2757
/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2758
/// attribute to Attrs.
2759
///
2760
/// alignment-specifier:
2761
/// [C11]   '_Alignas' '(' type-id ')'
2762
/// [C11]   '_Alignas' '(' constant-expression ')'
2763
/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2764
/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2765
void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2766
8.73k
                                     SourceLocation *EndLoc) {
2767
8.73k
  assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2768
8.73k
         "Not an alignment-specifier!");
2769
2770
8.73k
  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2771
8.73k
  SourceLocation KWLoc = ConsumeToken();
2772
2773
8.73k
  BalancedDelimiterTracker T(*this, tok::l_paren);
2774
8.73k
  if (T.expectAndConsume())
2775
1
    return;
2776
2777
8.73k
  SourceLocation EllipsisLoc;
2778
8.73k
  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2779
8.73k
  if (ArgExpr.isInvalid()) {
2780
10
    T.skipToEnd();
2781
10
    return;
2782
10
  }
2783
2784
8.72k
  T.consumeClose();
2785
8.72k
  if (EndLoc)
2786
7.54k
    *EndLoc = T.getCloseLocation();
2787
2788
8.72k
  ArgsVector ArgExprs;
2789
8.72k
  ArgExprs.push_back(ArgExpr.get());
2790
8.72k
  Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2791
8.72k
               ParsedAttr::AS_Keyword, EllipsisLoc);
2792
8.72k
}
2793
2794
911
ExprResult Parser::ParseExtIntegerArgument() {
2795
911
  assert(Tok.is(tok::kw__ExtInt) && "Not an extended int type");
2796
911
  ConsumeToken();
2797
2798
911
  BalancedDelimiterTracker T(*this, tok::l_paren);
2799
911
  if (T.expectAndConsume())
2800
1
    return ExprError();
2801
2802
910
  ExprResult ER = ParseConstantExpression();
2803
910
  if (ER.isInvalid()) {
2804
1
    T.skipToEnd();
2805
1
    return ExprError();
2806
1
  }
2807
2808
909
  if(T.consumeClose())
2809
1
    return ExprError();
2810
908
  return ER;
2811
908
}
2812
2813
/// Determine whether we're looking at something that might be a declarator
2814
/// in a simple-declaration. If it can't possibly be a declarator, maybe
2815
/// diagnose a missing semicolon after a prior tag definition in the decl
2816
/// specifier.
2817
///
2818
/// \return \c true if an error occurred and this can't be any kind of
2819
/// declaration.
2820
bool
2821
Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2822
                                              DeclSpecContext DSContext,
2823
1.35M
                                              LateParsedAttrList *LateAttrs) {
2824
1.35M
  assert(DS.hasTagDefinition() && "shouldn't call this");
2825
2826
1.35M
  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2827
1.31M
                          DSContext == DeclSpecContext::DSC_top_level);
2828
2829
1.35M
  if (getLangOpts().CPlusPlus &&
2830
342k
      Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2831
342k
                  tok::annot_template_id) &&
2832
63.1k
      TryAnnotateCXXScopeToken(EnteringContext)) {
2833
0
    SkipMalformedDecl();
2834
0
    return true;
2835
0
  }
2836
2837
1.35M
  bool HasScope = Tok.is(tok::annot_cxxscope);
2838
  // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2839
1.35M
  Token AfterScope = HasScope ? 
NextToken()20
: Tok;
2840
2841
  // Determine whether the following tokens could possibly be a
2842
  // declarator.
2843
1.35M
  bool MightBeDeclarator = true;
2844
1.35M
  if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2845
    // A declarator-id can't start with 'typename'.
2846
0
    MightBeDeclarator = false;
2847
1.35M
  } else if (AfterScope.is(tok::annot_template_id)) {
2848
    // If we have a type expressed as a template-id, this cannot be a
2849
    // declarator-id (such a type cannot be redeclared in a simple-declaration).
2850
8
    TemplateIdAnnotation *Annot =
2851
8
        static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2852
8
    if (Annot->Kind == TNK_Type_template)
2853
8
      MightBeDeclarator = false;
2854
1.35M
  } else if (AfterScope.is(tok::identifier)) {
2855
327k
    const Token &Next = HasScope ? 
GetLookAheadToken(2)10
: NextToken();
2856
2857
    // These tokens cannot come after the declarator-id in a
2858
    // simple-declaration, and are likely to come after a type-specifier.
2859
327k
    if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2860
5
                     tok::annot_cxxscope, tok::coloncolon)) {
2861
      // Missing a semicolon.
2862
5
      MightBeDeclarator = false;
2863
327k
    } else if (HasScope) {
2864
      // If the declarator-id has a scope specifier, it must redeclare a
2865
      // previously-declared entity. If that's a type (and this is not a
2866
      // typedef), that's an error.
2867
9
      CXXScopeSpec SS;
2868
9
      Actions.RestoreNestedNameSpecifierAnnotation(
2869
9
          Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2870
9
      IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2871
9
      Sema::NameClassification Classification = Actions.ClassifyName(
2872
9
          getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2873
9
          /*CCC=*/nullptr);
2874
9
      switch (Classification.getKind()) {
2875
0
      case Sema::NC_Error:
2876
0
        SkipMalformedDecl();
2877
0
        return true;
2878
2879
0
      case Sema::NC_Keyword:
2880
0
        llvm_unreachable("typo correction is not possible here");
2881
2882
1
      case Sema::NC_Type:
2883
1
      case Sema::NC_TypeTemplate:
2884
1
      case Sema::NC_UndeclaredNonType:
2885
1
      case Sema::NC_UndeclaredTemplate:
2886
        // Not a previously-declared non-type entity.
2887
1
        MightBeDeclarator = false;
2888
1
        break;
2889
2890
8
      case Sema::NC_Unknown:
2891
8
      case Sema::NC_NonType:
2892
8
      case Sema::NC_DependentNonType:
2893
8
      case Sema::NC_OverloadSet:
2894
8
      case Sema::NC_VarTemplate:
2895
8
      case Sema::NC_FunctionTemplate:
2896
8
      case Sema::NC_Concept:
2897
        // Might be a redeclaration of a prior entity.
2898
8
        break;
2899
1.35M
      }
2900
1.35M
    }
2901
327k
  }
2902
2903
1.35M
  if (MightBeDeclarator)
2904
1.35M
    return false;
2905
2906
14
  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2907
14
  Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2908
14
       diag::err_expected_after)
2909
14
      << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2910
2911
  // Try to recover from the typo, by dropping the tag definition and parsing
2912
  // the problematic tokens as a type.
2913
  //
2914
  // FIXME: Split the DeclSpec into pieces for the standalone
2915
  // declaration and pieces for the following declaration, instead
2916
  // of assuming that all the other pieces attach to new declaration,
2917
  // and call ParsedFreeStandingDeclSpec as appropriate.
2918
14
  DS.ClearTypeSpecType();
2919
14
  ParsedTemplateInfo NotATemplate;
2920
14
  ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2921
14
  return false;
2922
14
}
2923
2924
// Choose the apprpriate diagnostic error for why fixed point types are
2925
// disabled, set the previous specifier, and mark as invalid.
2926
static void SetupFixedPointError(const LangOptions &LangOpts,
2927
                                 const char *&PrevSpec, unsigned &DiagID,
2928
9
                                 bool &isInvalid) {
2929
9
  assert(!LangOpts.FixedPoint);
2930
9
  DiagID = diag::err_fixed_point_not_enabled;
2931
9
  PrevSpec = "";  // Not used by diagnostic
2932
9
  isInvalid = true;
2933
9
}
2934
2935
/// ParseDeclarationSpecifiers
2936
///       declaration-specifiers: [C99 6.7]
2937
///         storage-class-specifier declaration-specifiers[opt]
2938
///         type-specifier declaration-specifiers[opt]
2939
/// [C99]   function-specifier declaration-specifiers[opt]
2940
/// [C11]   alignment-specifier declaration-specifiers[opt]
2941
/// [GNU]   attributes declaration-specifiers[opt]
2942
/// [Clang] '__module_private__' declaration-specifiers[opt]
2943
/// [ObjC1] '__kindof' declaration-specifiers[opt]
2944
///
2945
///       storage-class-specifier: [C99 6.7.1]
2946
///         'typedef'
2947
///         'extern'
2948
///         'static'
2949
///         'auto'
2950
///         'register'
2951
/// [C++]   'mutable'
2952
/// [C++11] 'thread_local'
2953
/// [C11]   '_Thread_local'
2954
/// [GNU]   '__thread'
2955
///       function-specifier: [C99 6.7.4]
2956
/// [C99]   'inline'
2957
/// [C++]   'virtual'
2958
/// [C++]   'explicit'
2959
/// [OpenCL] '__kernel'
2960
///       'friend': [C++ dcl.friend]
2961
///       'constexpr': [C++0x dcl.constexpr]
2962
void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2963
                                        const ParsedTemplateInfo &TemplateInfo,
2964
                                        AccessSpecifier AS,
2965
                                        DeclSpecContext DSContext,
2966
70.4M
                                        LateParsedAttrList *LateAttrs) {
2967
70.4M
  if (DS.getSourceRange().isInvalid()) {
2968
    // Start the range at the current token but make the end of the range
2969
    // invalid.  This will make the entire range invalid unless we successfully
2970
    // consume a token.
2971
70.4M
    DS.SetRangeStart(Tok.getLocation());
2972
70.4M
    DS.SetRangeEnd(SourceLocation());
2973
70.4M
  }
2974
2975
70.4M
  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2976
68.0M
                          DSContext == DeclSpecContext::DSC_top_level);
2977
70.4M
  bool AttrsLastTime = false;
2978
70.4M
  ParsedAttributesWithRange attrs(AttrFactory);
2979
  // We use Sema's policy to get bool macros right.
2980
70.4M
  PrintingPolicy Policy = Actions.getPrintingPolicy();
2981
185M
  while (1) {
2982
185M
    bool isInvalid = false;
2983
185M
    bool isStorageClass = false;
2984
185M
    const char *PrevSpec = nullptr;
2985
185M
    unsigned DiagID = 0;
2986
2987
    // This value needs to be set to the location of the last token if the last
2988
    // token of the specifier is already consumed.
2989
185M
    SourceLocation ConsumedEnd;
2990
2991
    // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2992
    // implementation for VS2013 uses _Atomic as an identifier for one of the
2993
    // classes in <atomic>.
2994
    //
2995
    // A typedef declaration containing _Atomic<...> is among the places where
2996
    // the class is used.  If we are currently parsing such a declaration, treat
2997
    // the token as an identifier.
2998
185M
    if (getLangOpts().MSVCCompat && 
Tok.is(tok::kw__Atomic)1.00M
&&
2999
31
        DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3000
4
        !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3001
2
      Tok.setKind(tok::identifier);
3002
3003
185M
    SourceLocation Loc = Tok.getLocation();
3004
3005
185M
    switch (Tok.getKind()) {
3006
40.8M
    default:
3007
70.4M
    DoneWithDeclSpec:
3008
70.4M
      if (!AttrsLastTime)
3009
70.4M
        ProhibitAttributes(attrs);
3010
38
      else {
3011
        // Reject C++11 attributes that appertain to decl specifiers as
3012
        // we don't support any C++11 attributes that appertain to decl
3013
        // specifiers. This also conforms to what g++ 4.8 is doing.
3014
38
        ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3015
3016
38
        DS.takeAttributesFrom(attrs);
3017
38
      }
3018
3019
      // If this is not a declaration specifier token, we're done reading decl
3020
      // specifiers.  First verify that DeclSpec's are consistent.
3021
70.4M
      DS.Finish(Actions, Policy);
3022
70.4M
      return;
3023
3024
23.1k
    case tok::l_square:
3025
23.1k
    case tok::kw_alignas:
3026
23.1k
      if (!standardAttributesAllowed() || 
!isCXX11AttributeSpecifier()13.8k
)
3027
23.1k
        goto DoneWithDeclSpec;
3028
3029
47
      ProhibitAttributes(attrs);
3030
      // FIXME: It would be good to recover by accepting the attributes,
3031
      //        but attempting to do that now would cause serious
3032
      //        madness in terms of diagnostics.
3033
47
      attrs.clear();
3034
47
      attrs.Range = SourceRange();
3035
3036
47
      ParseCXX11Attributes(attrs);
3037
47
      AttrsLastTime = true;
3038
47
      continue;
3039
3040
45
    case tok::code_completion: {
3041
45
      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3042
45
      if (DS.hasTypeSpecifier()) {
3043
35
        bool AllowNonIdentifiers
3044
35
          = (getCurScope()->getFlags() & (Scope::ControlScope |
3045
35
                                          Scope::BlockScope |
3046
35
                                          Scope::TemplateParamScope |
3047
35
                                          Scope::FunctionPrototypeScope |
3048
35
                                          Scope::AtCatchScope)) == 0;
3049
35
        bool AllowNestedNameSpecifiers
3050
35
          = DSContext == DeclSpecContext::DSC_top_level ||
3051
24
            (DSContext == DeclSpecContext::DSC_class && 
DS.isFriendSpecified()13
);
3052
3053
35
        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3054
35
                                     AllowNonIdentifiers,
3055
35
                                     AllowNestedNameSpecifiers);
3056
35
        return cutOffParsing();
3057
35
      }
3058
3059
10
      if (getCurScope()->getFnParent() || 
getCurScope()->getBlockParent()9
)
3060
1
        CCC = Sema::PCC_LocalDeclarationSpecifiers;
3061
9
      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3062
0
        CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3063
0
                                                      : Sema::PCC_Template;
3064
9
      else if (DSContext == DeclSpecContext::DSC_class)
3065
8
        CCC = Sema::PCC_Class;
3066
1
      else if (CurParsedObjCImpl)
3067
0
        CCC = Sema::PCC_ObjCImplementation;
3068
3069
10
      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3070
10
      return cutOffParsing();
3071
10
    }
3072
3073
578
    case tok::coloncolon: // ::foo::bar
3074
      // C++ scope specifier.  Annotate and loop, or bail out on error.
3075
578
      if (TryAnnotateCXXScopeToken(EnteringContext)) {
3076
0
        if (!DS.hasTypeSpecifier())
3077
0
          DS.SetTypeSpecError();
3078
0
        goto DoneWithDeclSpec;
3079
0
      }
3080
578
      if (Tok.is(tok::coloncolon)) // ::new or ::delete
3081
3
        goto DoneWithDeclSpec;
3082
575
      continue;
3083
3084
140k
    case tok::annot_cxxscope: {
3085
140k
      if (DS.hasTypeSpecifier() || 
DS.isTypeAltiVecVector()140k
)
3086
53
        goto DoneWithDeclSpec;
3087
3088
140k
      CXXScopeSpec SS;
3089
140k
      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3090
140k
                                                   Tok.getAnnotationRange(),
3091
140k
                                                   SS);
3092
3093
      // We are looking for a qualified typename.
3094
140k
      Token Next = NextToken();
3095
3096
140k
      TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3097
23.0k
                                             ? takeTemplateIdAnnotation(Next)
3098
117k
                                             : nullptr;
3099
140k
      if (TemplateId && 
TemplateId->hasInvalidName()23.0k
) {
3100
        // We found something like 'T::U<Args> x', but U is not a template.
3101
        // Assume it was supposed to be a type.
3102
1
        DS.SetTypeSpecError();
3103
1
        ConsumeAnnotationToken();
3104
1
        break;
3105
1
      }
3106
3107
140k
      if (TemplateId && 
TemplateId->Kind == TNK_Type_template23.0k
) {
3108
        // We have a qualified template-id, e.g., N::A<int>
3109
3110
        // If this would be a valid constructor declaration with template
3111
        // arguments, we will reject the attempt to form an invalid type-id
3112
        // referring to the injected-class-name when we annotate the token,
3113
        // per C++ [class.qual]p2.
3114
        //
3115
        // To improve diagnostics for this case, parse the declaration as a
3116
        // constructor (and reject the extra template arguments later).
3117
23.0k
        if ((DSContext == DeclSpecContext::DSC_top_level ||
3118
18.5k
             DSContext == DeclSpecContext::DSC_class) &&
3119
11.2k
            TemplateId->Name &&
3120
11.2k
            Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3121
25
            isConstructorDeclarator(/*Unqualified=*/false)) {
3122
          // The user meant this to be an out-of-line constructor
3123
          // definition, but template arguments are not allowed
3124
          // there.  Just allow this as a constructor; we'll
3125
          // complain about it later.
3126
16
          goto DoneWithDeclSpec;
3127
16
        }
3128
3129
22.9k
        DS.getTypeSpecScope() = SS;
3130
22.9k
        ConsumeAnnotationToken(); // The C++ scope.
3131
22.9k
        assert(Tok.is(tok::annot_template_id) &&
3132
22.9k
               "ParseOptionalCXXScopeSpecifier not working");
3133
22.9k
        AnnotateTemplateIdTokenAsType(SS);
3134
22.9k
        continue;
3135
22.9k
      }
3136
3137
117k
      if (TemplateId && 
TemplateId->Kind == TNK_Concept_template33
&&
3138
25
          GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3139
25
        DS.getTypeSpecScope() = SS;
3140
        // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3141
        // Consume the scope annotation and continue to consume the template-id
3142
        // as a placeholder-specifier.
3143
25
        ConsumeAnnotationToken();
3144
25
        continue;
3145
25
      }
3146
3147
117k
      if (Next.is(tok::annot_typename)) {
3148
0
        DS.getTypeSpecScope() = SS;
3149
0
        ConsumeAnnotationToken(); // The C++ scope.
3150
0
        TypeResult T = getTypeAnnotation(Tok);
3151
0
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3152
0
                                       Tok.getAnnotationEndLoc(),
3153
0
                                       PrevSpec, DiagID, T, Policy);
3154
0
        if (isInvalid)
3155
0
          break;
3156
0
        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3157
0
        ConsumeAnnotationToken(); // The typename
3158
0
      }
3159
3160
117k
      if (Next.isNot(tok::identifier))
3161
4.63k
        goto DoneWithDeclSpec;
3162
3163
      // Check whether this is a constructor declaration. If we're in a
3164
      // context where the identifier could be a class name, and it has the
3165
      // shape of a constructor declaration, process it as one.
3166
112k
      if ((DSContext == DeclSpecContext::DSC_top_level ||
3167
65.9k
           DSContext == DeclSpecContext::DSC_class) &&
3168
67.4k
          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3169
67.4k
                                     &SS) &&
3170
34.3k
          isConstructorDeclarator(/*Unqualified*/ false))
3171
34.2k
        goto DoneWithDeclSpec;
3172
3173
78.4k
      ParsedType TypeRep =
3174
78.4k
          Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3175
78.4k
                              getCurScope(), &SS, false, false, nullptr,
3176
78.4k
                              /*IsCtorOrDtorName=*/false,
3177
78.4k
                              /*WantNontrivialTypeSourceInfo=*/true,
3178
78.4k
                              isClassTemplateDeductionContext(DSContext));
3179
3180
      // If the referenced identifier is not a type, then this declspec is
3181
      // erroneous: We already checked about that it has no type specifier, and
3182
      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
3183
      // typename.
3184
78.4k
      if (!TypeRep) {
3185
463
        if (TryAnnotateTypeConstraint())
3186
0
          goto DoneWithDeclSpec;
3187
463
        if (Tok.isNot(tok::annot_cxxscope) ||
3188
463
            NextToken().isNot(tok::identifier))
3189
9
          continue;
3190
        // Eat the scope spec so the identifier is current.
3191
454
        ConsumeAnnotationToken();
3192
454
        ParsedAttributesWithRange Attrs(AttrFactory);
3193
454
        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3194
415
          if (!Attrs.empty()) {
3195
0
            AttrsLastTime = true;
3196
0
            attrs.takeAllFrom(Attrs);
3197
0
          }
3198
415
          continue;
3199
415
        }
3200
39
        goto DoneWithDeclSpec;
3201
39
      }
3202
3203
78.0k
      DS.getTypeSpecScope() = SS;
3204
78.0k
      ConsumeAnnotationToken(); // The C++ scope.
3205
3206
78.0k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3207
78.0k
                                     DiagID, TypeRep, Policy);
3208
78.0k
      if (isInvalid)
3209
0
        break;
3210
3211
78.0k
      DS.SetRangeEnd(Tok.getLocation());
3212
78.0k
      ConsumeToken(); // The typename.
3213
3214
78.0k
      continue;
3215
78.0k
    }
3216
3217
21.5M
    case tok::annot_typename: {
3218
      // If we've previously seen a tag definition, we were almost surely
3219
      // missing a semicolon after it.
3220
21.5M
      if (DS.hasTypeSpecifier() && 
DS.hasTagDefinition()3
)
3221
0
        goto DoneWithDeclSpec;
3222
3223
21.5M
      TypeResult T = getTypeAnnotation(Tok);
3224
21.5M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3225
21.5M
                                     DiagID, T, Policy);
3226
21.5M
      if (isInvalid)
3227
3
        break;
3228
3229
21.5M
      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3230
21.5M
      ConsumeAnnotationToken(); // The typename
3231
3232
21.5M
      continue;
3233
21.5M
    }
3234
3235
1
    case tok::kw___is_signed:
3236
      // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3237
      // typically treats it as a trait. If we see __is_signed as it appears
3238
      // in libstdc++, e.g.,
3239
      //
3240
      //   static const bool __is_signed;
3241
      //
3242
      // then treat __is_signed as an identifier rather than as a keyword.
3243
1
      if (DS.getTypeSpecType() == TST_bool &&
3244
1
          DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3245
1
          DS.getStorageClassSpec() == DeclSpec::SCS_static)
3246
1
        TryKeywordIdentFallback(true);
3247
3248
      // We're done with the declaration-specifiers.
3249
1
      goto DoneWithDeclSpec;
3250
3251
      // typedef-name
3252
67.6M
    case tok::kw___super:
3253
67.6M
    case tok::kw_decltype:
3254
67.6M
    case tok::identifier: {
3255
      // This identifier can only be a typedef name if we haven't already seen
3256
      // a type-specifier.  Without this check we misparse:
3257
      //  typedef int X; struct Y { short X; };  as 'short int'.
3258
67.6M
      if (DS.hasTypeSpecifier())
3259
29.3M
        goto DoneWithDeclSpec;
3260
3261
      // If the token is an identifier named "__declspec" and Microsoft
3262
      // extensions are not enabled, it is likely that there will be cascading
3263
      // parse errors if this really is a __declspec attribute. Attempt to
3264
      // recognize that scenario and recover gracefully.
3265
38.2M
      if (!getLangOpts().DeclSpecKeyword && 
Tok.is(tok::identifier)38.1M
&&
3266
38.0M
          Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3267
2
        Diag(Loc, diag::err_ms_attributes_not_enabled);
3268
3269
        // The next token should be an open paren. If it is, eat the entire
3270
        // attribute declaration and continue.
3271
2
        if (NextToken().is(tok::l_paren)) {
3272
          // Consume the __declspec identifier.
3273
2
          ConsumeToken();
3274
3275
          // Eat the parens and everything between them.
3276
2
          BalancedDelimiterTracker T(*this, tok::l_paren);
3277
2
          if (T.consumeOpen()) {
3278
0
            assert(false && "Not a left paren?");
3279
0
            return;
3280
0
          }
3281
2
          T.skipToEnd();
3282
2
          continue;
3283
2
        }
3284
2
      }
3285
3286
      // In C++, check to see if this is a scope specifier like foo::bar::, if
3287
      // so handle it as such.  This is important for ctor parsing.
3288
38.2M
      if (getLangOpts().CPlusPlus) {
3289
5.97M
        if (TryAnnotateCXXScopeToken(EnteringContext)) {
3290
24
          DS.SetTypeSpecError();
3291
24
          goto DoneWithDeclSpec;
3292
24
        }
3293
5.97M
        if (!Tok.is(tok::identifier))
3294
708k
          continue;
3295
37.5M
      }
3296
3297
      // Check for need to substitute AltiVec keyword tokens.
3298
37.5M
      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3299
326k
        break;
3300
3301
      // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3302
      //                allow the use of a typedef name as a type specifier.
3303
37.2M
      if (DS.isTypeAltiVecVector())
3304
7.16k
        goto DoneWithDeclSpec;
3305
3306
37.2M
      if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3307
146k
          isObjCInstancetype()) {
3308
145k
        ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3309
145k
        assert(TypeRep);
3310
145k
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3311
145k
                                       DiagID, TypeRep, Policy);
3312
145k
        if (isInvalid)
3313
0
          break;
3314
3315
145k
        DS.SetRangeEnd(Loc);
3316
145k
        ConsumeToken();
3317
145k
        continue;
3318
145k
      }
3319
3320
      // If we're in a context where the identifier could be a class name,
3321
      // check whether this is a constructor declaration.
3322
37.1M
      if (getLangOpts().CPlusPlus && 
DSContext == DeclSpecContext::DSC_class5.20M
&&
3323
1.35M
          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3324
327k
          isConstructorDeclarator(/*Unqualified*/true))
3325
223k
        goto DoneWithDeclSpec;
3326
3327
36.8M
      ParsedType TypeRep = Actions.getTypeName(
3328
36.8M
          *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3329
36.8M
          false, false, nullptr, false, false,
3330
36.8M
          isClassTemplateDeductionContext(DSContext));
3331
3332
      // If this is not a typedef name, don't parse it as part of the declspec,
3333
      // it must be an implicit int or an error.
3334
36.8M
      if (!TypeRep) {
3335
1.17k
        if (TryAnnotateTypeConstraint())
3336
0
          goto DoneWithDeclSpec;
3337
1.17k
        if (Tok.isNot(tok::identifier))
3338
14
          continue;
3339
1.16k
        ParsedAttributesWithRange Attrs(AttrFactory);
3340
1.16k
        if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3341
858
          if (!Attrs.empty()) {
3342
0
            AttrsLastTime = true;
3343
0
            attrs.takeAllFrom(Attrs);
3344
0
          }
3345
858
          continue;
3346
858
        }
3347
304
        goto DoneWithDeclSpec;
3348
304
      }
3349
3350
      // Likewise, if this is a context where the identifier could be a template
3351
      // name, check whether this is a deduction guide declaration.
3352
36.8M
      if (getLangOpts().CPlusPlus17 &&
3353
184k
          (DSContext == DeclSpecContext::DSC_class ||
3354
154k
           DSContext == DeclSpecContext::DSC_top_level) &&
3355
75.6k
          Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3356
75.6k
                                       Tok.getLocation()) &&
3357
577
          isConstructorDeclarator(/*Unqualified*/ true,
3358
577
                                  /*DeductionGuide*/ true))
3359
403
        goto DoneWithDeclSpec;
3360
3361
36.8M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3362
36.8M
                                     DiagID, TypeRep, Policy);
3363
36.8M
      if (isInvalid)
3364
0
        break;
3365
3366
36.8M
      DS.SetRangeEnd(Tok.getLocation());
3367
36.8M
      ConsumeToken(); // The identifier
3368
3369
      // Objective-C supports type arguments and protocol references
3370
      // following an Objective-C object or object pointer
3371
      // type. Handle either one of them.
3372
36.8M
      if (Tok.is(tok::less) && 
getLangOpts().ObjC68.7k
) {
3373
68.7k
        SourceLocation NewEndLoc;
3374
68.7k
        TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3375
68.7k
                                  Loc, TypeRep, /*consumeLastToken=*/true,
3376
68.7k
                                  NewEndLoc);
3377
68.7k
        if (NewTypeRep.isUsable()) {
3378
68.7k
          DS.UpdateTypeRep(NewTypeRep.get());
3379
68.7k
          DS.SetRangeEnd(NewEndLoc);
3380
68.7k
        }
3381
68.7k
      }
3382
3383
      // Need to support trailing type qualifiers (e.g. "id<p> const").
3384
      // If a type specifier follows, it will be diagnosed elsewhere.
3385
36.8M
      continue;
3386
36.8M
    }
3387
3388
      // type-name or placeholder-specifier
3389
564k
    case tok::annot_template_id: {
3390
564k
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3391
3392
564k
      if (TemplateId->hasInvalidName()) {
3393
0
        DS.SetTypeSpecError();
3394
0
        break;
3395
0
      }
3396
3397
564k
      if (TemplateId->Kind == TNK_Concept_template) {
3398
        // If we've already diagnosed that this type-constraint has invalid
3399
        // arguemnts, drop it and just form 'auto' or 'decltype(auto)'.
3400
111
        if (TemplateId->hasInvalidArgs())
3401
0
          TemplateId = nullptr;
3402
3403
111
        if (NextToken().is(tok::identifier)) {
3404
1
          Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3405
1
              << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3406
          // Attempt to continue as if 'auto' was placed here.
3407
1
          isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3408
1
                                         TemplateId, Policy);
3409
1
          break;
3410
1
        }
3411
110
        if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3412
0
            goto DoneWithDeclSpec;
3413
110
        ConsumeAnnotationToken();
3414
110
        SourceLocation AutoLoc = Tok.getLocation();
3415
110
        if (TryConsumeToken(tok::kw_decltype)) {
3416
9
          BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3417
9
          if (Tracker.consumeOpen()) {
3418
            // Something like `void foo(Iterator decltype i)`
3419
1
            Diag(Tok, diag::err_expected) << tok::l_paren;
3420
8
          } else {
3421
8
            if (!TryConsumeToken(tok::kw_auto)) {
3422
              // Something like `void foo(Iterator decltype(int) i)`
3423
1
              Tracker.skipToEnd();
3424
1
              Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3425
1
                << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3426
1
                                                            Tok.getLocation()),
3427
1
                                                "auto");
3428
7
            } else {
3429
7
              Tracker.consumeClose();
3430
7
            }
3431
8
          }
3432
9
          ConsumedEnd = Tok.getLocation();
3433
          // Even if something went wrong above, continue as if we've seen
3434
          // `decltype(auto)`.
3435
9
          isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3436
9
                                         DiagID, TemplateId, Policy);
3437
101
        } else {
3438
101
          isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3439
101
                                         TemplateId, Policy);
3440
101
        }
3441
110
        break;
3442
110
      }
3443
3444
564k
      if (TemplateId->Kind != TNK_Type_template &&
3445
56
          TemplateId->Kind != TNK_Undeclared_template) {
3446
        // This template-id does not refer to a type name, so we're
3447
        // done with the type-specifiers.
3448
10
        goto DoneWithDeclSpec;
3449
10
      }
3450
3451
      // If we're in a context where the template-id could be a
3452
      // constructor name or specialization, check whether this is a
3453
      // constructor declaration.
3454
564k
      if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3455
62.7k
          Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3456
11.2k
          isConstructorDeclarator(/*Unqualified=*/true))
3457
10
        goto DoneWithDeclSpec;
3458
3459
      // Turn the template-id annotation token into a type annotation
3460
      // token, then try again to parse it as a type-specifier.
3461
564k
      CXXScopeSpec SS;
3462
564k
      AnnotateTemplateIdTokenAsType(SS);
3463
564k
      continue;
3464
564k
    }
3465
3466
    // GNU attributes support.
3467
11.7M
    case tok::kw___attribute:
3468
11.7M
      ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3469
11.7M
      continue;
3470
3471
    // Microsoft declspec support.
3472
7.52k
    case tok::kw___declspec:
3473
7.52k
      ParseMicrosoftDeclSpecs(DS.getAttributes());
3474
7.52k
      continue;
3475
3476
    // Microsoft single token adornments.
3477
14
    case tok::kw___forceinline: {
3478
14
      isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3479
14
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3480
14
      SourceLocation AttrNameLoc = Tok.getLocation();
3481
14
      DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3482
14
                                nullptr, 0, ParsedAttr::AS_Keyword);
3483
14
      break;
3484
564k
    }
3485
3486
129
    case tok::kw___unaligned:
3487
129
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3488
129
                                 getLangOpts());
3489
129
      break;
3490
3491
734
    case tok::kw___sptr:
3492
734
    case tok::kw___uptr:
3493
734
    case tok::kw___ptr64:
3494
734
    case tok::kw___ptr32:
3495
734
    case tok::kw___w64:
3496
734
    case tok::kw___cdecl:
3497
734
    case tok::kw___stdcall:
3498
734
    case tok::kw___fastcall:
3499
734
    case tok::kw___thiscall:
3500
734
    case tok::kw___regcall:
3501
734
    case tok::kw___vectorcall:
3502
734
      ParseMicrosoftTypeAttributes(DS.getAttributes());
3503
734
      continue;
3504
3505
    // Borland single token adornments.
3506
14
    case tok::kw___pascal:
3507
14
      ParseBorlandTypeAttributes(DS.getAttributes());
3508
14
      continue;
3509
3510
    // OpenCL single token adornments.
3511
847
    case tok::kw___kernel:
3512
847
      ParseOpenCLKernelAttributes(DS.getAttributes());
3513
847
      continue;
3514
3515
    // Nullability type specifiers.
3516
486k
    case tok::kw__Nonnull:
3517
486k
    case tok::kw__Nullable:
3518
486k
    case tok::kw__Null_unspecified:
3519
486k
      ParseNullabilityTypeSpecifiers(DS.getAttributes());
3520
486k
      continue;
3521
3522
    // Objective-C 'kindof' types.
3523
1.51k
    case tok::kw___kindof:
3524
1.51k
      DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3525
1.51k
                                nullptr, 0, ParsedAttr::AS_Keyword);
3526
1.51k
      (void)ConsumeToken();
3527
1.51k
      continue;
3528
3529
    // storage-class-specifier
3530
2.23M
    case tok::kw_typedef:
3531
2.23M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3532
2.23M
                                         PrevSpec, DiagID, Policy);
3533
2.23M
      isStorageClass = true;
3534
2.23M
      break;
3535
2.55M
    case tok::kw_extern:
3536
2.55M
      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3537
2
        Diag(Tok, diag::ext_thread_before) << "extern";
3538
2.55M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3539
2.55M
                                         PrevSpec, DiagID, Policy);
3540
2.55M
      isStorageClass = true;
3541
2.55M
      break;
3542
66
    case tok::kw___private_extern__:
3543
66
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3544
66
                                         Loc, PrevSpec, DiagID, Policy);
3545
66
      isStorageClass = true;
3546
66
      break;
3547
9.87M
    case tok::kw_static:
3548
9.87M
      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3549
11
        Diag(Tok, diag::ext_thread_before) << "static";
3550
9.87M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3551
9.87M
                                         PrevSpec, DiagID, Policy);
3552
9.87M
      isStorageClass = true;
3553
9.87M
      break;
3554
31.9k
    case tok::kw_auto:
3555
31.9k
      if (getLangOpts().CPlusPlus11) {
3556
31.7k
        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3557
27
          isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3558
27
                                             PrevSpec, DiagID, Policy);
3559
27
          if (!isInvalid)
3560
27
            Diag(Tok, diag::ext_auto_storage_class)
3561
27
              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3562
27
        } else
3563
31.7k
          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3564
31.7k
                                         DiagID, Policy);
3565
31.7k
      } else
3566
136
        isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3567
136
                                           PrevSpec, DiagID, Policy);
3568
31.9k
      isStorageClass = true;
3569
31.9k
      break;
3570
35
    case tok::kw___auto_type:
3571
35
      Diag(Tok, diag::ext_auto_type);
3572
35
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3573
35
                                     DiagID, Policy);
3574
35
      break;
3575
681
    case tok::kw_register:
3576
681
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3577
681
                                         PrevSpec, DiagID, Policy);
3578
681
      isStorageClass = true;
3579
681
      break;
3580
2.88k
    case tok::kw_mutable:
3581
2.88k
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3582
2.88k
                                         PrevSpec, DiagID, Policy);
3583
2.88k
      isStorageClass = true;
3584
2.88k
      break;
3585
294
    case tok::kw___thread:
3586
294
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3587
294
                                               PrevSpec, DiagID);
3588
294
      isStorageClass = true;
3589
294
      break;
3590
524
    case tok::kw_thread_local:
3591
524
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3592
524
                                               PrevSpec, DiagID);
3593
524
      isStorageClass = true;
3594
524
      break;
3595
98
    case tok::kw__Thread_local:
3596
98
      if (!getLangOpts().C11)
3597
77
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3598
98
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3599
98
                                               Loc, PrevSpec, DiagID);
3600
98
      isStorageClass = true;
3601
98
      break;
3602
3603
    // function-specifier
3604
9.93M
    case tok::kw_inline:
3605
9.93M
      isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3606
9.93M
      break;
3607
49.6k
    case tok::kw_virtual:
3608
      // C++ for OpenCL does not allow virtual function qualifier, to avoid
3609
      // function pointers restricted in OpenCL v2.0 s6.9.a.
3610
49.6k
      if (getLangOpts().OpenCLCPlusPlus) {
3611
3
        DiagID = diag::err_openclcxx_virtual_function;
3612
3
        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3613
3
        isInvalid = true;
3614
3
      }
3615
49.6k
      else {
3616
49.6k
        isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3617
49.6k
      }
3618
49.6k
      break;
3619
59.7k
    case tok::kw_explicit: {
3620
59.7k
      SourceLocation ExplicitLoc = Loc;
3621
59.7k
      SourceLocation CloseParenLoc;
3622
59.7k
      ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3623
59.7k
      ConsumedEnd = ExplicitLoc;
3624
59.7k
      ConsumeToken(); // kw_explicit
3625
59.7k
      if (Tok.is(tok::l_paren)) {
3626
125
        if (getLangOpts().CPlusPlus20 || 
isExplicitBool() == TPResult::True37
) {
3627
119
          Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
3628
88
                                      ? diag::warn_cxx17_compat_explicit_bool
3629
31
                                      : diag::ext_explicit_bool);
3630
3631
119
          ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3632
119
          BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3633
119
          Tracker.consumeOpen();
3634
119
          ExplicitExpr = ParseConstantExpression();
3635
119
          ConsumedEnd = Tok.getLocation();
3636
119
          if (ExplicitExpr.isUsable()) {
3637
110
            CloseParenLoc = Tok.getLocation();
3638
110
            Tracker.consumeClose();
3639
110
            ExplicitSpec =
3640
110
                Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3641
110
          } else
3642
9
            Tracker.skipToEnd();
3643
6
        } else {
3644
6
          Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
3645
6
        }
3646
125
      }
3647
59.7k
      isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3648
59.7k
                                             ExplicitSpec, CloseParenLoc);
3649
59.7k
      break;
3650
486k
    }
3651
66
    case tok::kw__Noreturn:
3652
66
      if (!getLangOpts().C11)
3653
40
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3654
66
      isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3655
66
      break;
3656
3657
    // alignment-specifier
3658
1.18k
    case tok::kw__Alignas:
3659
1.18k
      if (!getLangOpts().C11)
3660
1.14k
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3661
1.18k
      ParseAlignmentSpecifier(DS.getAttributes());
3662
1.18k
      continue;
3663
3664
    // friend
3665
50.5k
    case tok::kw_friend:
3666
50.5k
      if (DSContext == DeclSpecContext::DSC_class)
3667
50.5k
        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3668
15
      else {
3669
15
        PrevSpec = ""; // not actually used by the diagnostic
3670
15
        DiagID = diag::err_friend_invalid_in_context;
3671
15
        isInvalid = true;
3672
15
      }
3673
50.5k
      break;
3674
3675
    // Modules
3676
52
    case tok::kw___module_private__:
3677
52
      isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3678
52
      break;
3679
3680
    // constexpr, consteval, constinit specifiers
3681
294k
    case tok::kw_constexpr:
3682
294k
      isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
3683
294k
                                      PrevSpec, DiagID);
3684
294k
      break;
3685
141
    case tok::kw_consteval:
3686
141
      isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
3687
141
                                      PrevSpec, DiagID);
3688
141
      break;
3689
73
    case tok::kw_constinit:
3690
73
      isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constinit, Loc,
3691
73
                                      PrevSpec, DiagID);
3692
73
      break;
3693
3694
    // type-specifier
3695
359k
    case tok::kw_short:
3696
359k
      isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec,
3697
359k
                                      DiagID, Policy);
3698
359k
      break;
3699
856k
    case tok::kw_long:
3700
856k
      if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
3701
615k
        isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec,
3702
615k
                                        DiagID, Policy);
3703
241k
      else
3704
241k
        isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
3705
241k
                                        PrevSpec, DiagID, Policy);
3706
856k
      break;
3707
2.68k
    case tok::kw___int64:
3708
2.68k
      isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
3709
2.68k
                                      PrevSpec, DiagID, Policy);
3710
2.68k
      break;
3711
151k
    case tok::kw_signed:
3712
151k
      isInvalid =
3713
151k
          DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
3714
151k
      break;
3715
878k
    case tok::kw_unsigned:
3716
878k
      isInvalid = DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec,
3717
878k
                                     DiagID);
3718
878k
      break;
3719
7.82k
    case tok::kw__Complex:
3720
7.82k
      if (!getLangOpts().C99)
3721
2.18k
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3722
7.82k
      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3723
7.82k
                                        DiagID);
3724
7.82k
      break;
3725
4
    case tok::kw__Imaginary:
3726
4
      if (!getLangOpts().C99)
3727
2
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3728
4
      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3729
4
                                        DiagID);
3730
4
      break;
3731
2.76M
    case tok::kw_void:
3732
2.76M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3733
2.76M
                                     DiagID, Policy);
3734
2.76M
      break;
3735
1.13M
    case tok::kw_char:
3736
1.13M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3737
1.13M
                                     DiagID, Policy);
3738
1.13M
      break;
3739
2.38M
    case tok::kw_int:
3740
2.38M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3741
2.38M
                                     DiagID, Policy);
3742
2.38M
      break;
3743
911
    case tok::kw__ExtInt: {
3744
911
      ExprResult ER = ParseExtIntegerArgument();
3745
911
      if (ER.isInvalid())
3746
3
        continue;
3747
908
      isInvalid = DS.SetExtIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
3748
908
      ConsumedEnd = PrevTokLocation;
3749
908
      break;
3750
908
    }
3751
7.29k
    case tok::kw___int128:
3752
7.29k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3753
7.29k
                                     DiagID, Policy);
3754
7.29k
      break;
3755
21.8k
    case tok::kw_half:
3756
21.8k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3757
21.8k
                                     DiagID, Policy);
3758
21.8k
      break;
3759
456
    case tok::kw___bf16:
3760
456
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
3761
456
                                     DiagID, Policy);
3762
456
      break;
3763
258k
    case tok::kw_float:
3764
258k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3765
258k
                                     DiagID, Policy);
3766
258k
      break;
3767
342k
    case tok::kw_double:
3768
342k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3769
342k
                                     DiagID, Policy);
3770
342k
      break;
3771
264
    case tok::kw__Float16:
3772
264
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3773
264
                                     DiagID, Policy);
3774
264
      break;
3775
1.00k
    case tok::kw__Accum:
3776
1.00k
      if (!getLangOpts().FixedPoint) {
3777
9
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3778
991
      } else {
3779
991
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3780
991
                                       DiagID, Policy);
3781
991
      }
3782
1.00k
      break;
3783
544
    case tok::kw__Fract:
3784
544
      if (!getLangOpts().FixedPoint) {
3785
0
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3786
544
      } else {
3787
544
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3788
544
                                       DiagID, Policy);
3789
544
      }
3790
544
      break;
3791
547
    case tok::kw__Sat:
3792
547
      if (!getLangOpts().FixedPoint) {
3793
0
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3794
547
      } else {
3795
547
        isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3796
547
      }
3797
547
      break;
3798
417
    case tok::kw___float128:
3799
417
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3800
417
                                     DiagID, Policy);
3801
417
      break;
3802
125k
    case tok::kw_wchar_t:
3803
125k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3804
125k
                                     DiagID, Policy);
3805
125k
      break;
3806
55
    case tok::kw_char8_t:
3807
55
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3808
55
                                     DiagID, Policy);
3809
55
      break;
3810
9.13k
    case tok::kw_char16_t:
3811
9.13k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3812
9.13k
                                     DiagID, Policy);
3813
9.13k
      break;
3814
9.13k
    case tok::kw_char32_t:
3815
9.13k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3816
9.13k
                                     DiagID, Policy);
3817
9.13k
      break;
3818
592k
    case tok::kw_bool:
3819
592k
    case tok::kw__Bool:
3820
592k
      if (Tok.is(tok::kw__Bool) && 
!getLangOpts().C99111k
)
3821
2
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3822
3823
592k
      if (Tok.is(tok::kw_bool) &&
3824
480k
          DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3825
3
          DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3826
3
        PrevSpec = ""; // Not used by the diagnostic.
3827
3
        DiagID = diag::err_bool_redeclaration;
3828
        // For better error recovery.
3829
3
        Tok.setKind(tok::identifier);
3830
3
        isInvalid = true;
3831
592k
      } else {
3832
592k
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3833
592k
                                       DiagID, Policy);
3834
592k
      }
3835
592k
      break;
3836
5
    case tok::kw__Decimal32:
3837
5
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3838
5
                                     DiagID, Policy);
3839
5
      break;
3840
0
    case tok::kw__Decimal64:
3841
0
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3842
0
                                     DiagID, Policy);
3843
0
      break;
3844
1
    case tok::kw__Decimal128:
3845
1
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3846
1
                                     DiagID, Policy);
3847
1
      break;
3848
344k
    case tok::kw___vector:
3849
344k
      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3850
344k
      break;
3851
20
    case tok::kw___pixel:
3852
20
      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3853
20
      break;
3854
16.2k
    case tok::kw___bool:
3855
16.2k
      isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3856
16.2k
      break;
3857
120
    case tok::kw_pipe:
3858
120
      if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3859
34
                                    !getLangOpts().OpenCLCPlusPlus)) {
3860
        // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3861
        // support the "pipe" word as identifier.
3862
1
        Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3863
1
        goto DoneWithDeclSpec;
3864
1
      }
3865
119
      isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3866
119
      break;
3867
119
#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3868
8.43k
  case tok::kw_##ImgType##_t: \
3869
8.43k
    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3870
8.43k
                                   DiagID, Policy); \
3871
8.43k
    break;
3872
119
#include "clang/Basic/OpenCLImageTypes.def"
3873
62
    case tok::kw___unknown_anytype:
3874
62
      isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3875
62
                                     PrevSpec, DiagID, Policy);
3876
62
      break;
3877
3878
    // class-specifier:
3879
1.92M
    case tok::kw_class:
3880
1.92M
    case tok::kw_struct:
3881
1.92M
    case tok::kw___interface:
3882
1.92M
    case tok::kw_union: {
3883
1.92M
      tok::TokenKind Kind = Tok.getKind();
3884
1.92M
      ConsumeToken();
3885
3886
      // These are attributes following class specifiers.
3887
      // To produce better diagnostic, we parse them when
3888
      // parsing class specifier.
3889
1.92M
      ParsedAttributesWithRange Attributes(AttrFactory);
3890
1.92M
      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3891
1.92M
                          EnteringContext, DSContext, Attributes);
3892
3893
      // If there are attributes following class specifier,
3894
      // take them over and handle them here.
3895
1.92M
      if (!Attributes.empty()) {
3896
0
        AttrsLastTime = true;
3897
0
        attrs.takeAllFrom(Attributes);
3898
0
      }
3899
1.92M
      continue;
3900
1.92M
    }
3901
3902
    // enum-specifier:
3903
819k
    case tok::kw_enum:
3904
819k
      ConsumeToken();
3905
819k
      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3906
819k
      continue;
3907
3908
    // cv-qualifier:
3909
3.68M
    case tok::kw_const:
3910
3.68M
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3911
3.68M
                                 getLangOpts());
3912
3.68M
      break;
3913
100k
    case tok::kw_volatile:
3914
100k
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3915
100k
                                 getLangOpts());
3916
100k
      break;
3917
288
    case tok::kw_restrict:
3918
288
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3919
288
                                 getLangOpts());
3920
288
      break;
3921
3922
    // C++ typename-specifier:
3923
357k
    case tok::kw_typename:
3924
357k
      if (TryAnnotateTypeOrScopeToken()) {
3925
3
        DS.SetTypeSpecError();
3926
3
        goto DoneWithDeclSpec;
3927
3
      }
3928
357k
      if (!Tok.is(tok::kw_typename))
3929
357k
        continue;
3930
0
      break;
3931
3932
    // GNU typeof support.
3933
2.98k
    case tok::kw_typeof:
3934
2.98k
      ParseTypeofSpecifier(DS);
3935
2.98k
      continue;
3936
3937
32.5k
    case tok::annot_decltype:
3938
32.5k
      ParseDecltypeSpecifier(DS);
3939
32.5k
      continue;
3940
3941
1
    case tok::annot_pragma_pack:
3942
1
      HandlePragmaPack();
3943
1
      continue;
3944
3945
0
    case tok::annot_pragma_ms_pragma:
3946
0
      HandlePragmaMSPragma();
3947
0
      continue;
3948
3949
0
    case tok::annot_pragma_ms_vtordisp:
3950
0
      HandlePragmaMSVtorDisp();
3951
0
      continue;
3952
3953
0
    case tok::annot_pragma_ms_pointers_to_members:
3954
0
      HandlePragmaMSPointersToMembers();
3955
0
      continue;
3956
3957
491
    case tok::kw___underlying_type:
3958
491
      ParseUnderlyingTypeSpecifier(DS);
3959
491
      continue;
3960
3961
2.29k
    case tok::kw__Atomic:
3962
      // C11 6.7.2.4/4:
3963
      //   If the _Atomic keyword is immediately followed by a left parenthesis,
3964
      //   it is interpreted as a type specifier (with a type name), not as a
3965
      //   type qualifier.
3966
2.29k
      if (!getLangOpts().C11)
3967
1.17k
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3968
3969
2.29k
      if (NextToken().is(tok::l_paren)) {
3970
2.18k
        ParseAtomicSpecifier(DS);
3971
2.18k
        continue;
3972
2.18k
      }
3973
113
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3974
113
                                 getLangOpts());
3975
113
      break;
3976
3977
    // OpenCL address space qualifiers:
3978
451
    case tok::kw___generic:
3979
      // generic address space is introduced only in OpenCL v2.0
3980
      // see OpenCL C Spec v2.0 s6.5.5
3981
451
      if (Actions.getLangOpts().OpenCLVersion < 200 &&
3982
78
          !Actions.getLangOpts().OpenCLCPlusPlus) {
3983
10
        DiagID = diag::err_opencl_unknown_type_specifier;
3984
10
        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3985
10
        isInvalid = true;
3986
10
        break;
3987
10
      }
3988
441
      LLVM_FALLTHROUGH;
3989
462
    case tok::kw_private:
3990
      // It's fine (but redundant) to check this for __generic on the
3991
      // fallthrough path; we only form the __generic token in OpenCL mode.
3992
462
      if (!getLangOpts().OpenCL)
3993
3
        goto DoneWithDeclSpec;
3994
459
      LLVM_FALLTHROUGH;
3995
41.8k
    case tok::kw___private:
3996
41.8k
    case tok::kw___global:
3997
41.8k
    case tok::kw___local:
3998
41.8k
    case tok::kw___constant:
3999
    // OpenCL access qualifiers:
4000
41.8k
    case tok::kw___read_only:
4001
41.8k
    case tok::kw___write_only:
4002
41.8k
    case tok::kw___read_write:
4003
41.8k
      ParseOpenCLQualifiers(DS.getAttributes());
4004
41.8k
      break;
4005
4006
19
    case tok::less:
4007
      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4008
      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
4009
      // but we support it.
4010
19
      if (DS.hasTypeSpecifier() || 
!getLangOpts().ObjC9
)
4011
12
        goto DoneWithDeclSpec;
4012
4013
7
      SourceLocation StartLoc = Tok.getLocation();
4014
7
      SourceLocation EndLoc;
4015
7
      TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4016
7
      if (Type.isUsable()) {
4017
7
        if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4018
7
                               PrevSpec, DiagID, Type.get(),
4019
7
                               Actions.getASTContext().getPrintingPolicy()))
4020
0
          Diag(StartLoc, DiagID) << PrevSpec;
4021
4022
7
        DS.SetRangeEnd(EndLoc);
4023
0
      } else {
4024
0
        DS.SetTypeSpecError();
4025
0
      }
4026
4027
      // Need to support trailing type qualifiers (e.g. "id<p> const").
4028
      // If a type specifier follows, it will be diagnosed elsewhere.
4029
7
      continue;
4030
39.5M
    }
4031
4032
39.5M
    DS.SetRangeEnd(ConsumedEnd.isValid() ? 
ConsumedEnd60.6k
:
Tok.getLocation()39.4M
);
4033
4034
    // If the specifier wasn't legal, issue a diagnostic.
4035
39.5M
    if (isInvalid) {
4036
157
      assert(PrevSpec && "Method did not return previous specifier!");
4037
157
      assert(DiagID);
4038
4039
157
      if (DiagID == diag::ext_duplicate_declspec ||
4040
157
          DiagID == diag::ext_warn_duplicate_declspec ||
4041
114
          DiagID == diag::err_duplicate_declspec)
4042
45
        Diag(Loc, DiagID) << PrevSpec
4043
45
                          << FixItHint::CreateRemoval(
4044
45
                                 SourceRange(Loc, DS.getEndLoc()));
4045
112
      else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4046
16
        Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
4047
16
                          << getLangOpts().getOpenCLVersionTuple().getAsString()
4048
16
                          << PrevSpec << isStorageClass;
4049
16
      } else
4050
96
        Diag(Loc, DiagID) << PrevSpec;
4051
157
    }
4052
4053
39.5M
    if (DiagID != diag::err_bool_redeclaration && 
ConsumedEnd.isInvalid()39.5M
)
4054
      // After an error the next token can be an annotation token.
4055
39.4M
      ConsumeAnyToken();
4056
4057
39.5M
    AttrsLastTime = false;
4058
39.5M
  }
4059
70.4M
}
4060
4061
/// ParseStructDeclaration - Parse a struct declaration without the terminating
4062
/// semicolon.
4063
///
4064
/// Note that a struct declaration refers to a declaration in a struct,
4065
/// not to the declaration of a struct.
4066
///
4067
///       struct-declaration:
4068
/// [C2x]   attributes-specifier-seq[opt]
4069
///           specifier-qualifier-list struct-declarator-list
4070
/// [GNU]   __extension__ struct-declaration
4071
/// [GNU]   specifier-qualifier-list
4072
///       struct-declarator-list:
4073
///         struct-declarator
4074
///         struct-declarator-list ',' struct-declarator
4075
/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
4076
///       struct-declarator:
4077
///         declarator
4078
/// [GNU]   declarator attributes[opt]
4079
///         declarator[opt] ':' constant-expression
4080
/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
4081
///
4082
void Parser::ParseStructDeclaration(
4083
    ParsingDeclSpec &DS,
4084
3.00M
    llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4085
4086
3.00M
  if (Tok.is(tok::kw___extension__)) {
4087
    // __extension__ silences extension warnings in the subexpression.
4088
2
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
4089
2
    ConsumeToken();
4090
2
    return ParseStructDeclaration(DS, FieldsCallback);
4091
2
  }
4092
4093
  // Parse leading attributes.
4094
3.00M
  ParsedAttributesWithRange Attrs(AttrFactory);
4095
3.00M
  MaybeParseCXX11Attributes(Attrs);
4096
3.00M
  DS.takeAttributesFrom(Attrs);
4097
4098
  // Parse the common specifier-qualifiers-list piece.
4099
3.00M
  ParseSpecifierQualifierList(DS);
4100
4101
  // If there are no declarators, this is a free-standing declaration
4102
  // specifier. Let the actions module cope with it.
4103
3.00M
  if (Tok.is(tok::semi)) {
4104
313
    RecordDecl *AnonRecord = nullptr;
4105
313
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4106
313
                                                       DS, AnonRecord);
4107
313
    assert(!AnonRecord && "Did not expect anonymous struct or union here");
4108
313
    DS.complete(TheDecl);
4109
313
    return;
4110
313
  }
4111
4112
  // Read struct-declarators until we find the semicolon.
4113
3.00M
  bool FirstDeclarator = true;
4114
3.00M
  SourceLocation CommaLoc;
4115
3.01M
  while (1) {
4116
3.01M
    ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4117
3.01M
    DeclaratorInfo.D.setCommaLoc(CommaLoc);
4118
4119
    // Attributes are only allowed here on successive declarators.
4120
3.01M
    if (!FirstDeclarator) {
4121
      // However, this does not apply for [[]] attributes (which could show up
4122
      // before or after the __attribute__ attributes).
4123
15.6k
      DiagnoseAndSkipCXX11Attributes();
4124
15.6k
      MaybeParseGNUAttributes(DeclaratorInfo.D);
4125
15.6k
      DiagnoseAndSkipCXX11Attributes();
4126
15.6k
    }
4127
4128
    /// struct-declarator: declarator
4129
    /// struct-declarator: declarator[opt] ':' constant-expression
4130
3.01M
    if (Tok.isNot(tok::colon)) {
4131
      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4132
3.01M
      ColonProtectionRAIIObject X(*this);
4133
3.01M
      ParseDeclarator(DeclaratorInfo.D);
4134
3.01M
    } else
4135
1.81k
      DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4136
4137
3.01M
    if (TryConsumeToken(tok::colon)) {
4138
37.8k
      ExprResult Res(ParseConstantExpression());
4139
37.8k
      if (Res.isInvalid())
4140
1
        SkipUntil(tok::semi, StopBeforeMatch);
4141
37.8k
      else
4142
37.8k
        DeclaratorInfo.BitfieldSize = Res.get();
4143
37.8k
    }
4144
4145
    // If attributes exist after the declarator, parse them.
4146
3.01M
    MaybeParseGNUAttributes(DeclaratorInfo.D);
4147
4148
    // We're done with this declarator;  invoke the callback.
4149
3.01M
    FieldsCallback(DeclaratorInfo);
4150
4151
    // If we don't have a comma, it is either the end of the list (a ';')
4152
    // or an error, bail out.
4153
3.01M
    if (!TryConsumeToken(tok::comma, CommaLoc))
4154
3.00M
      return;
4155
4156
15.6k
    FirstDeclarator = false;
4157
15.6k
  }
4158
3.00M
}
4159
4160
/// ParseStructUnionBody
4161
///       struct-contents:
4162
///         struct-declaration-list
4163
/// [EXT]   empty
4164
/// [GNU]   "struct-declaration-list" without terminating ';'
4165
///       struct-declaration-list:
4166
///         struct-declaration
4167
///         struct-declaration-list struct-declaration
4168
/// [OBC]   '@' 'defs' '(' class-name ')'
4169
///
4170
void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4171
507k
                                  DeclSpec::TST TagType, RecordDecl *TagDecl) {
4172
507k
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4173
507k
                                      "parsing struct/union body");
4174
507k
  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4175
4176
507k
  BalancedDelimiterTracker T(*this, tok::l_brace);
4177
507k
  if (T.consumeOpen())
4178
0
    return;
4179
4180
507k
  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4181
507k
  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4182
4183
  // While we still have something to read, read the declarations in the struct.
4184
2.87M
  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4185
2.36M
         Tok.isNot(tok::eof)) {
4186
    // Each iteration of this loop reads one struct-declaration.
4187
4188
    // Check for extraneous top-level semicolon.
4189
2.36M
    if (Tok.is(tok::semi)) {
4190
5
      ConsumeExtraSemi(InsideStruct, TagType);
4191
5
      continue;
4192
5
    }
4193
4194
    // Parse _Static_assert declaration.
4195
2.36M
    if (Tok.is(tok::kw__Static_assert)) {
4196
28
      SourceLocation DeclEnd;
4197
28
      ParseStaticAssertDeclaration(DeclEnd);
4198
28
      continue;
4199
28
    }
4200
4201
2.36M
    if (Tok.is(tok::annot_pragma_pack)) {
4202
6
      HandlePragmaPack();
4203
6
      continue;
4204
6
    }
4205
4206
2.36M
    if (Tok.is(tok::annot_pragma_align)) {
4207
2
      HandlePragmaAlign();
4208
2
      continue;
4209
2
    }
4210
4211
2.36M
    if (Tok.is(tok::annot_pragma_openmp)) {
4212
      // Result can be ignored, because it must be always empty.
4213
21
      AccessSpecifier AS = AS_none;
4214
21
      ParsedAttributesWithRange Attrs(AttrFactory);
4215
21
      (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4216
21
      continue;
4217
21
    }
4218
4219
2.36M
    if (tok::isPragmaAnnotation(Tok.getKind())) {
4220
2
      Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4221
2
          << DeclSpec::getSpecifierName(
4222
2
                 TagType, Actions.getASTContext().getPrintingPolicy());
4223
2
      ConsumeAnnotationToken();
4224
2
      continue;
4225
2
    }
4226
4227
2.36M
    if (!Tok.is(tok::at)) {
4228
2.37M
      auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4229
        // Install the declarator into the current TagDecl.
4230
2.37M
        Decl *Field =
4231
2.37M
            Actions.ActOnField(getCurScope(), TagDecl,
4232
2.37M
                               FD.D.getDeclSpec().getSourceRange().getBegin(),
4233
2.37M
                               FD.D, FD.BitfieldSize);
4234
2.37M
        FD.complete(Field);
4235
2.37M
      };
4236
4237
      // Parse all the comma separated declarators.
4238
2.36M
      ParsingDeclSpec DS(*this);
4239
2.36M
      ParseStructDeclaration(DS, CFieldCallback);
4240
8
    } else { // Handle @defs
4241
8
      ConsumeToken();
4242
8
      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4243
4
        Diag(Tok, diag::err_unexpected_at);
4244
4
        SkipUntil(tok::semi);
4245
4
        continue;
4246
4
      }
4247
4
      ConsumeToken();
4248
4
      ExpectAndConsume(tok::l_paren);
4249
4
      if (!Tok.is(tok::identifier)) {
4250
0
        Diag(Tok, diag::err_expected) << tok::identifier;
4251
0
        SkipUntil(tok::semi);
4252
0
        continue;
4253
0
      }
4254
4
      SmallVector<Decl *, 16> Fields;
4255
4
      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4256
4
                        Tok.getIdentifierInfo(), Fields);
4257
4
      ConsumeToken();
4258
4
      ExpectAndConsume(tok::r_paren);
4259
4
    }
4260
4261
2.36M
    if (TryConsumeToken(tok::semi))
4262
2.36M
      continue;
4263
4264
20
    if (Tok.is(tok::r_brace)) {
4265
8
      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4266
8
      break;
4267
8
    }
4268
4269
12
    ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4270
    // Skip to end of block or statement to avoid ext-warning on extra ';'.
4271
12
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4272
    // If we stopped at a ';', eat it.
4273
12
    TryConsumeToken(tok::semi);
4274
12
  }
4275
4276
507k
  T.consumeClose();
4277
4278
507k
  ParsedAttributes attrs(AttrFactory);
4279
  // If attributes exist after struct contents, parse them.
4280
507k
  MaybeParseGNUAttributes(attrs);
4281
4282
507k
  SmallVector<Decl *, 32> FieldDecls(TagDecl->field_begin(),
4283
507k
                                     TagDecl->field_end());
4284
4285
507k
  Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4286
507k
                      T.getOpenLocation(), T.getCloseLocation(), attrs);
4287
507k
  StructScope.Exit();
4288
507k
  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4289
507k
}
4290
4291
/// ParseEnumSpecifier
4292
///       enum-specifier: [C99 6.7.2.2]
4293
///         'enum' identifier[opt] '{' enumerator-list '}'
4294
///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4295
/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4296
///                                                 '}' attributes[opt]
4297
/// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4298
///                                                 '}'
4299
///         'enum' identifier
4300
/// [GNU]   'enum' attributes[opt] identifier
4301
///
4302
/// [C++11] enum-head '{' enumerator-list[opt] '}'
4303
/// [C++11] enum-head '{' enumerator-list ','  '}'
4304
///
4305
///       enum-head: [C++11]
4306
///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4307
///         enum-key attribute-specifier-seq[opt] nested-name-specifier
4308
///             identifier enum-base[opt]
4309
///
4310
///       enum-key: [C++11]
4311
///         'enum'
4312
///         'enum' 'class'
4313
///         'enum' 'struct'
4314
///
4315
///       enum-base: [C++11]
4316
///         ':' type-specifier-seq
4317
///
4318
/// [C++] elaborated-type-specifier:
4319
/// [C++]   'enum' nested-name-specifier[opt] identifier
4320
///
4321
void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4322
                                const ParsedTemplateInfo &TemplateInfo,
4323
819k
                                AccessSpecifier AS, DeclSpecContext DSC) {
4324
  // Parse the tag portion of this.
4325
819k
  if (Tok.is(tok::code_completion)) {
4326
    // Code completion for an enum name.
4327
2
    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4328
2
    return cutOffParsing();
4329
2
  }
4330
4331
  // If attributes exist after tag, parse them.
4332
819k
  ParsedAttributesWithRange attrs(AttrFactory);
4333
819k
  MaybeParseGNUAttributes(attrs);
4334
819k
  MaybeParseCXX11Attributes(attrs);
4335
819k
  MaybeParseMicrosoftDeclSpecs(attrs);
4336
4337
819k
  SourceLocation ScopedEnumKWLoc;
4338
819k
  bool IsScopedUsingClassTag = false;
4339
4340
  // In C++11, recognize 'enum class' and 'enum struct'.
4341
819k
  if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4342
2.14k
    Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4343
69
                                        : diag::ext_scoped_enum);
4344
2.21k
    IsScopedUsingClassTag = Tok.is(tok::kw_class);
4345
2.21k
    ScopedEnumKWLoc = ConsumeToken();
4346
4347
    // Attributes are not allowed between these keywords.  Diagnose,
4348
    // but then just treat them like they appeared in the right place.
4349
2.21k
    ProhibitAttributes(attrs);
4350
4351
    // They are allowed afterwards, though.
4352
2.21k
    MaybeParseGNUAttributes(attrs);
4353
2.21k
    MaybeParseCXX11Attributes(attrs);
4354
2.21k
    MaybeParseMicrosoftDeclSpecs(attrs);
4355
2.21k
  }
4356
4357
  // C++11 [temp.explicit]p12:
4358
  //   The usual access controls do not apply to names used to specify
4359
  //   explicit instantiations.
4360
  // We extend this to also cover explicit specializations.  Note that
4361
  // we don't suppress if this turns out to be an elaborated type
4362
  // specifier.
4363
819k
  bool shouldDelayDiagsInTag =
4364
819k
    (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4365
819k
     TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4366
819k
  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4367
4368
  // Determine whether this declaration is permitted to have an enum-base.
4369
819k
  AllowDefiningTypeSpec AllowEnumSpecifier =
4370
819k
      isDefiningTypeSpecifierContext(DSC);
4371
819k
  bool CanBeOpaqueEnumDeclaration =
4372
819k
      DS.isEmpty() && 
isOpaqueEnumDeclarationContext(DSC)711k
;
4373
819k
  bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || 
getLangOpts().ObjC725k
||
4374
124k
                          getLangOpts().MicrosoftExt) &&
4375
695k
                         (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4376
46
                          CanBeOpaqueEnumDeclaration);
4377
4378
819k
  CXXScopeSpec &SS = DS.getTypeSpecScope();
4379
819k
  if (getLangOpts().CPlusPlus) {
4380
    // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4381
94.5k
    ColonProtectionRAIIObject X(*this);
4382
4383
94.5k
    CXXScopeSpec Spec;
4384
94.5k
    if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4385
94.5k
                                       /*ObjectHadErrors=*/false,
4386
94.5k
                                       /*EnteringContext=*/true))
4387
0
      return;
4388
4389
94.5k
    if (Spec.isSet() && 
Tok.isNot(tok::identifier)176
) {
4390
6
      Diag(Tok, diag::err_expected) << tok::identifier;
4391
6
      if (Tok.isNot(tok::l_brace)) {
4392
        // Has no name and is not a definition.
4393
        // Skip the rest of this declarator, up until the comma or semicolon.
4394
6
        SkipUntil(tok::comma, StopAtSemi);
4395
6
        return;
4396
6
      }
4397
94.5k
    }
4398
4399
94.5k
    SS = Spec;
4400
94.5k
  }
4401
4402
  // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4403
819k
  if (Tok.isNot(tok::identifier) && 
Tok.isNot(tok::l_brace)489k
&&
4404
39.2k
      Tok.isNot(tok::colon)) {
4405
3
    Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4406
4407
    // Skip the rest of this declarator, up until the comma or semicolon.
4408
3
    SkipUntil(tok::comma, StopAtSemi);
4409
3
    return;
4410
3
  }
4411
4412
  // If an identifier is present, consume and remember it.
4413
819k
  IdentifierInfo *Name = nullptr;
4414
819k
  SourceLocation NameLoc;
4415
819k
  if (Tok.is(tok::identifier)) {
4416
329k
    Name = Tok.getIdentifierInfo();
4417
329k
    NameLoc = ConsumeToken();
4418
329k
  }
4419
4420
819k
  if (!Name && 
ScopedEnumKWLoc.isValid()489k
) {
4421
    // C++0x 7.2p2: The optional identifier shall not be omitted in the
4422
    // declaration of a scoped enumeration.
4423
8
    Diag(Tok, diag::err_scoped_enum_missing_identifier);
4424
8
    ScopedEnumKWLoc = SourceLocation();
4425
8
    IsScopedUsingClassTag = false;
4426
8
  }
4427
4428
  // Okay, end the suppression area.  We'll decide whether to emit the
4429
  // diagnostics in a second.
4430
819k
  if (shouldDelayDiagsInTag)
4431
66
    diagsFromTag.done();
4432
4433
819k
  TypeResult BaseType;
4434
819k
  SourceRange BaseRange;
4435
4436
819k
  bool CanBeBitfield = (getCurScope()->getFlags() & Scope::ClassScope) &&
4437
12.1k
                       ScopedEnumKWLoc.isInvalid() && 
Name11.9k
;
4438
4439
  // Parse the fixed underlying type.
4440
819k
  if (Tok.is(tok::colon)) {
4441
    // This might be an enum-base or part of some unrelated enclosing context.
4442
    //
4443
    // 'enum E : base' is permitted in two circumstances:
4444
    //
4445
    // 1) As a defining-type-specifier, when followed by '{'.
4446
    // 2) As the sole constituent of a complete declaration -- when DS is empty
4447
    //    and the next token is ';'.
4448
    //
4449
    // The restriction to defining-type-specifiers is important to allow parsing
4450
    //   a ? new enum E : int{}
4451
    //   _Generic(a, enum E : int{})
4452
    // properly.
4453
    //
4454
    // One additional consideration applies:
4455
    //
4456
    // C++ [dcl.enum]p1:
4457
    //   A ':' following "enum nested-name-specifier[opt] identifier" within
4458
    //   the decl-specifier-seq of a member-declaration is parsed as part of
4459
    //   an enum-base.
4460
    //
4461
    // Other language modes supporting enumerations with fixed underlying types
4462
    // do not have clear rules on this, so we disambiguate to determine whether
4463
    // the tokens form a bit-field width or an enum-base.
4464
4465
225k
    if (CanBeBitfield && 
!isEnumBase(CanBeOpaqueEnumDeclaration)144
) {
4466
      // Outside C++11, do not interpret the tokens as an enum-base if they do
4467
      // not make sense as one. In C++11, it's an error if this happens.
4468
19
      if (getLangOpts().CPlusPlus11)
4469
13
        Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4470
225k
    } else if (CanHaveEnumBase || 
!ColonIsSacred70
) {
4471
225k
      SourceLocation ColonLoc = ConsumeToken();
4472
4473
      // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4474
      // because under -fms-extensions,
4475
      //   enum E : int *p;
4476
      // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4477
225k
      DeclSpec DS(AttrFactory);
4478
225k
      ParseSpecifierQualifierList(DS, AS, DeclSpecContext::DSC_type_specifier);
4479
225k
      Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
4480
225k
      BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4481
4482
225k
      BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4483
4484
225k
      if (!getLangOpts().ObjC) {
4485
3.61k
        if (getLangOpts().CPlusPlus11)
4486
3.56k
          Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4487
3.56k
              << BaseRange;
4488
55
        else if (getLangOpts().CPlusPlus)
4489
13
          Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4490
13
              << BaseRange;
4491
42
        else if (getLangOpts().MicrosoftExt)
4492
7
          Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4493
7
              << BaseRange;
4494
35
        else
4495
35
          Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4496
35
              << BaseRange;
4497
3.61k
      }
4498
225k
    }
4499
225k
  }
4500
4501
  // There are four options here.  If we have 'friend enum foo;' then this is a
4502
  // friend declaration, and cannot have an accompanying definition. If we have
4503
  // 'enum foo;', then this is a forward declaration.  If we have
4504
  // 'enum foo {...' then this is a definition. Otherwise we have something
4505
  // like 'enum foo xyz', a reference.
4506
  //
4507
  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4508
  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
4509
  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
4510
  //
4511
819k
  Sema::TagUseKind TUK;
4512
819k
  if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4513
10
    TUK = Sema::TUK_Reference;
4514
819k
  else if (Tok.is(tok::l_brace)) {
4515
602k
    if (DS.isFriendSpecified()) {
4516
4
      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4517
4
        << SourceRange(DS.getFriendSpecLoc());
4518
4
      ConsumeBrace();
4519
4
      SkipUntil(tok::r_brace, StopAtSemi);
4520
      // Discard any other definition-only pieces.
4521
4
      attrs.clear();
4522
4
      ScopedEnumKWLoc = SourceLocation();
4523
4
      IsScopedUsingClassTag = false;
4524
4
      BaseType = TypeResult();
4525
4
      TUK = Sema::TUK_Friend;
4526
602k
    } else {
4527
602k
      TUK = Sema::TUK_Definition;
4528
602k
    }
4529
217k
  } else if (!isTypeSpecifier(DSC) &&
4530
217k
             (Tok.is(tok::semi) ||
4531
217k
              (Tok.isAtStartOfLine() &&
4532
412
               
!isValidAfterTypeSpecifier(CanBeBitfield)33
))) {
4533
    // An opaque-enum-declaration is required to be standalone (no preceding or
4534
    // following tokens in the declaration). Sema enforces this separately by
4535
    // diagnosing anything else in the DeclSpec.
4536
392
    TUK = DS.isFriendSpecified() ? 
Sema::TUK_Friend20
: Sema::TUK_Declaration;
4537
412
    if (Tok.isNot(tok::semi)) {
4538
      // A semicolon was missing after this declaration. Diagnose and recover.
4539
2
      ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4540
2
      PP.EnterToken(Tok, /*IsReinject=*/true);
4541
2
      Tok.setKind(tok::semi);
4542
2
    }
4543
217k
  } else {
4544
217k
    TUK = Sema::TUK_Reference;
4545
217k
  }
4546
4547
819k
  bool IsElaboratedTypeSpecifier =
4548
819k
      TUK == Sema::TUK_Reference || 
TUK == Sema::TUK_Friend602k
;
4549
4550
  // If this is an elaborated type specifier nested in a larger declaration,
4551
  // and we delayed diagnostics before, just merge them into the current pool.
4552
819k
  if (TUK == Sema::TUK_Reference && 
shouldDelayDiagsInTag217k
) {
4553
0
    diagsFromTag.redelay();
4554
0
  }
4555
4556
819k
  MultiTemplateParamsArg TParams;
4557
819k
  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4558
99
      TUK != Sema::TUK_Reference) {
4559
98
    if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4560
      // Skip the rest of this declarator, up until the comma or semicolon.
4561
1
      Diag(Tok, diag::err_enum_template);
4562
1
      SkipUntil(tok::comma, StopAtSemi);
4563
1
      return;
4564
1
    }
4565
4566
97
    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4567
      // Enumerations can't be explicitly instantiated.
4568
5
      DS.SetTypeSpecError();
4569
5
      Diag(StartLoc, diag::err_explicit_instantiation_enum);
4570
5
      return;
4571
5
    }
4572
4573
92
    assert(TemplateInfo.TemplateParams && "no template parameters");
4574
92
    TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4575
92
                                     TemplateInfo.TemplateParams->size());
4576
92
  }
4577
4578
819k
  if (!Name && 
TUK != Sema::TUK_Definition489k
) {
4579
2
    Diag(Tok, diag::err_enumerator_unnamed_no_def);
4580
4581
    // Skip the rest of this declarator, up until the comma or semicolon.
4582
2
    SkipUntil(tok::comma, StopAtSemi);
4583
2
    return;
4584
2
  }
4585
4586
  // An elaborated-type-specifier has a much more constrained grammar:
4587
  //
4588
  //   'enum' nested-name-specifier[opt] identifier
4589
  //
4590
  // If we parsed any other bits, reject them now.
4591
  //
4592
  // MSVC and (for now at least) Objective-C permit a full enum-specifier
4593
  // or opaque-enum-declaration anywhere.
4594
819k
  if (IsElaboratedTypeSpecifier && 
!getLangOpts().MicrosoftExt217k
&&
4595
217k
      !getLangOpts().ObjC) {
4596
120k
    ProhibitAttributes(attrs);
4597
120k
    if (BaseType.isUsable())
4598
440
      Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
4599
440
          << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
4600
120k
    else if (ScopedEnumKWLoc.isValid())
4601
21
      Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
4602
21
        << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
4603
120k
  }
4604
4605
819k
  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4606
4607
819k
  Sema::SkipBodyInfo SkipBody;
4608
819k
  if (!Name && 
TUK == Sema::TUK_Definition489k
&&
Tok.is(tok::l_brace)489k
&&
4609
489k
      NextToken().is(tok::identifier))
4610
489k
    SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4611
489k
                                              NextToken().getIdentifierInfo(),
4612
489k
                                              NextToken().getLocation());
4613
4614
819k
  bool Owned = false;
4615
819k
  bool IsDependent = false;
4616
819k
  const char *PrevSpec = nullptr;
4617
819k
  unsigned DiagID;
4618
819k
  Decl *TagDecl = Actions.ActOnTag(
4619
819k
      getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4620
819k
      attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4621
819k
      ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4622
819k
      DSC == DeclSpecContext::DSC_type_specifier,
4623
819k
      DSC == DeclSpecContext::DSC_template_param ||
4624
819k
          DSC == DeclSpecContext::DSC_template_type_arg,
4625
819k
      &SkipBody);
4626
4627
819k
  if (SkipBody.ShouldSkip) {
4628
18
    assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4629
4630
18
    BalancedDelimiterTracker T(*this, tok::l_brace);
4631
18
    T.consumeOpen();
4632
18
    T.skipToEnd();
4633
4634
18
    if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4635
13
                           NameLoc.isValid() ? NameLoc : 
StartLoc5
,
4636
18
                           PrevSpec, DiagID, TagDecl, Owned,
4637
18
                           Actions.getASTContext().getPrintingPolicy()))
4638
0
      Diag(StartLoc, DiagID) << PrevSpec;
4639
18
    return;
4640
18
  }
4641
4642
819k
  if (IsDependent) {
4643
    // This enum has a dependent nested-name-specifier. Handle it as a
4644
    // dependent tag.
4645
11
    if (!Name) {
4646
0
      DS.SetTypeSpecError();
4647
0
      Diag(Tok, diag::err_expected_type_name_after_typename);
4648
0
      return;
4649
0
    }
4650
4651
11
    TypeResult Type = Actions.ActOnDependentTag(
4652
11
        getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4653
11
    if (Type.isInvalid()) {
4654
0
      DS.SetTypeSpecError();
4655
0
      return;
4656
0
    }
4657
4658
11
    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4659
11
                           NameLoc.isValid() ? NameLoc : 
StartLoc0
,
4660
11
                           PrevSpec, DiagID, Type.get(),
4661
11
                           Actions.getASTContext().getPrintingPolicy()))
4662
0
      Diag(StartLoc, DiagID) << PrevSpec;
4663
4664
11
    return;
4665
11
  }
4666
4667
819k
  if (!TagDecl) {
4668
    // The action failed to produce an enumeration tag. If this is a
4669
    // definition, consume the entire definition.
4670
68
    if (Tok.is(tok::l_brace) && 
TUK != Sema::TUK_Reference46
) {
4671
46
      ConsumeBrace();
4672
46
      SkipUntil(tok::r_brace, StopAtSemi);
4673
46
    }
4674
4675
68
    DS.SetTypeSpecError();
4676
68
    return;
4677
68
  }
4678
4679
819k
  if (Tok.is(tok::l_brace) && 
TUK == Sema::TUK_Definition602k
) {
4680
602k
    Decl *D = SkipBody.CheckSameAsPrevious ? 
SkipBody.New4
: TagDecl;
4681
602k
    ParseEnumBody(StartLoc, D);
4682
602k
    if (SkipBody.CheckSameAsPrevious &&
4683
4
        !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4684
2
      DS.SetTypeSpecError();
4685
2
      return;
4686
2
    }
4687
819k
  }
4688
4689
819k
  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4690
489k
                         NameLoc.isValid() ? 
NameLoc329k
: StartLoc,
4691
819k
                         PrevSpec, DiagID, TagDecl, Owned,
4692
819k
                         Actions.getASTContext().getPrintingPolicy()))
4693
0
    Diag(StartLoc, DiagID) << PrevSpec;
4694
819k
}
4695
4696
/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4697
///       enumerator-list:
4698
///         enumerator
4699
///         enumerator-list ',' enumerator
4700
///       enumerator:
4701
///         enumeration-constant attributes[opt]
4702
///         enumeration-constant attributes[opt] '=' constant-expression
4703
///       enumeration-constant:
4704
///         identifier
4705
///
4706
602k
void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4707
  // Enter the scope of the enum body and start the definition.
4708
602k
  ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4709
602k
  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4710
4711
602k
  BalancedDelimiterTracker T(*this, tok::l_brace);
4712
602k
  T.consumeOpen();
4713
4714
  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4715
602k
  if (Tok.is(tok::r_brace) && 
!getLangOpts().CPlusPlus1.45k
)
4716
1
    Diag(Tok, diag::err_empty_enum);
4717
4718
602k
  SmallVector<Decl *, 32> EnumConstantDecls;
4719
602k
  SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4720
4721
602k
  Decl *LastEnumConstDecl = nullptr;
4722
4723
  // Parse the enumerator-list.
4724
5.47M
  while (Tok.isNot(tok::r_brace)) {
4725
    // Parse enumerator. If failed, try skipping till the start of the next
4726
    // enumerator definition.
4727
4.92M
    if (Tok.isNot(tok::identifier)) {
4728
9
      Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4729
9
      if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4730
9
          TryConsumeToken(tok::comma))
4731
2
        continue;
4732
7
      break;
4733
7
    }
4734
4.92M
    IdentifierInfo *Ident = Tok.getIdentifierInfo();
4735
4.92M
    SourceLocation IdentLoc = ConsumeToken();
4736
4737
    // If attributes exist after the enumerator, parse them.
4738
4.92M
    ParsedAttributesWithRange attrs(AttrFactory);
4739
4.92M
    MaybeParseGNUAttributes(attrs);
4740
4.92M
    ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4741
4.92M
    if (standardAttributesAllowed() && 
isCXX11AttributeSpecifier()616k
) {
4742
16
      if (getLangOpts().CPlusPlus)
4743
9
        Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4744
7
                                    ? diag::warn_cxx14_compat_ns_enum_attribute
4745
2
                                    : diag::ext_ns_enum_attribute)
4746
9
            << 1 /*enumerator*/;
4747
16
      ParseCXX11Attributes(attrs);
4748
16
    }
4749
4750
4.92M
    SourceLocation EqualLoc;
4751
4.92M
    ExprResult AssignedVal;
4752
4.92M
    EnumAvailabilityDiags.emplace_back(*this);
4753
4754
4.92M
    EnterExpressionEvaluationContext ConstantEvaluated(
4755
4.92M
        Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4756
4.92M
    if (TryConsumeToken(tok::equal, EqualLoc)) {
4757
4.71M
      AssignedVal = ParseConstantExpressionInExprEvalContext();
4758
4.71M
      if (AssignedVal.isInvalid())
4759
7
        SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4760
4.71M
    }
4761
4762
    // Install the enumerator constant into EnumDecl.
4763
4.92M
    Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4764
4.92M
        getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4765
4.92M
        EqualLoc, AssignedVal.get());
4766
4.92M
    EnumAvailabilityDiags.back().done();
4767
4768
4.92M
    EnumConstantDecls.push_back(EnumConstDecl);
4769
4.92M
    LastEnumConstDecl = EnumConstDecl;
4770
4771
4.92M
    if (Tok.is(tok::identifier)) {
4772
      // We're missing a comma between enumerators.
4773
4
      SourceLocation Loc = getEndOfPreviousToken();
4774
4
      Diag(Loc, diag::err_enumerator_list_missing_comma)
4775
4
        << FixItHint::CreateInsertion(Loc, ", ");
4776
4
      continue;
4777
4
    }
4778
4779
    // Emumerator definition must be finished, only comma or r_brace are
4780
    // allowed here.
4781
4.92M
    SourceLocation CommaLoc;
4782
4.92M
    if (Tok.isNot(tok::r_brace) && 
!TryConsumeToken(tok::comma, CommaLoc)4.38M
) {
4783
7
      if (EqualLoc.isValid())
4784
5
        Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4785
5
                                                           << tok::comma;
4786
2
      else
4787
2
        Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4788
7
      if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4789
7
        if (TryConsumeToken(tok::comma, CommaLoc))
4790
2
          continue;
4791
0
      } else {
4792
0
        break;
4793
0
      }
4794
4.92M
    }
4795
4796
    // If comma is followed by r_brace, emit appropriate warning.
4797
4.92M
    if (Tok.is(tok::r_brace) && 
CommaLoc.isValid()600k
) {
4798
55.3k
      if (!getLangOpts().C99 && 
!getLangOpts().CPlusPlus118.03k
)
4799
8
        Diag(CommaLoc, getLangOpts().CPlusPlus ?
4800
7
               diag::ext_enumerator_list_comma_cxx :
4801
1
               diag::ext_enumerator_list_comma_c)
4802
8
          << FixItHint::CreateRemoval(CommaLoc);
4803
55.3k
      else if (getLangOpts().CPlusPlus11)
4804
8.02k
        Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4805
8.02k
          << FixItHint::CreateRemoval(CommaLoc);
4806
55.3k
      break;
4807
55.3k
    }
4808
4.92M
  }
4809
4810
  // Eat the }.
4811
602k
  T.consumeClose();
4812
4813
  // If attributes exist after the identifier list, parse them.
4814
602k
  ParsedAttributes attrs(AttrFactory);
4815
602k
  MaybeParseGNUAttributes(attrs);
4816
4817
602k
  Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4818
602k
                        getCurScope(), attrs);
4819
4820
  // Now handle enum constant availability diagnostics.
4821
602k
  assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4822
5.53M
  for (size_t i = 0, e = EnumConstantDecls.size(); i != e; 
++i4.92M
) {
4823
4.92M
    ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4824
4.92M
    EnumAvailabilityDiags[i].redelay();
4825
4.92M
    PD.complete(EnumConstantDecls[i]);
4826
4.92M
  }
4827
4828
602k
  EnumScope.Exit();
4829
602k
  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4830
4831
  // The next token must be valid after an enum definition. If not, a ';'
4832
  // was probably forgotten.
4833
602k
  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4834
602k
  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4835
6
    ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4836
    // Push this token back into the preprocessor and change our current token
4837
    // to ';' so that the rest of the code recovers as though there were an
4838
    // ';' after the definition.
4839
6
    PP.EnterToken(Tok, /*IsReinject=*/true);
4840
6
    Tok.setKind(tok::semi);
4841
6
  }
4842
602k
}
4843
4844
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4845
/// is definitely a type-specifier.  Return false if it isn't part of a type
4846
/// specifier or if we're not sure.
4847
85.4k
bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4848
85.4k
  switch (Tok.getKind()) {
4849
85.4k
  default: return false;
4850
    // type-specifiers
4851
30
  case tok::kw_short:
4852
30
  case tok::kw_long:
4853
30
  case tok::kw___int64:
4854
30
  case tok::kw___int128:
4855
30
  case tok::kw_signed:
4856
30
  case tok::kw_unsigned:
4857
30
  case tok::kw__Complex:
4858
30
  case tok::kw__Imaginary:
4859
30
  case tok::kw_void:
4860
30
  case tok::kw_char:
4861
30
  case tok::kw_wchar_t:
4862
30
  case tok::kw_char8_t:
4863
30
  case tok::kw_char16_t:
4864
30
  case tok::kw_char32_t:
4865
30
  case tok::kw_int:
4866
30
  case tok::kw__ExtInt:
4867
30
  case tok::kw___bf16:
4868
30
  case tok::kw_half:
4869
30
  case tok::kw_float:
4870
30
  case tok::kw_double:
4871
30
  case tok::kw__Accum:
4872
30
  case tok::kw__Fract:
4873
30
  case tok::kw__Float16:
4874
30
  case tok::kw___float128:
4875
30
  case tok::kw_bool:
4876
30
  case tok::kw__Bool:
4877
30
  case tok::kw__Decimal32:
4878
30
  case tok::kw__Decimal64:
4879
30
  case tok::kw__Decimal128:
4880
30
  case tok::kw___vector:
4881
360
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4882
360
#include 
"clang/Basic/OpenCLImageTypes.def"30
4883
4884
    // struct-or-union-specifier (C99) or class-specifier (C++)
4885
30
  case tok::kw_class:
4886
30
  case tok::kw_struct:
4887
30
  case tok::kw___interface:
4888
30
  case tok::kw_union:
4889
    // enum-specifier
4890
30
  case tok::kw_enum:
4891
4892
    // typedef-name
4893
30
  case tok::annot_typename:
4894
30
    return true;
4895
85.4k
  }
4896
85.4k
}
4897
4898
/// isTypeSpecifierQualifier - Return true if the current token could be the
4899
/// start of a specifier-qualifier-list.
4900
11.5M
bool Parser::isTypeSpecifierQualifier() {
4901
11.5M
  switch (Tok.getKind()) {
4902
386k
  default: return false;
4903
4904
5.54M
  case tok::identifier:   // foo::bar
4905
5.54M
    if (TryAltiVecVectorToken())
4906
118k
      return true;
4907
5.42M
    LLVM_FALLTHROUGH;
4908
5.42M
  case tok::kw_typename:  // typename T::type
4909
    // Annotate typenames and C++ scope specifiers.  If we get one, just
4910
    // recurse to handle whatever we get.
4911
5.42M
    if (TryAnnotateTypeOrScopeToken())
4912
0
      return true;
4913
5.42M
    if (Tok.is(tok::identifier))
4914
397k
      return false;
4915
5.02M
    return isTypeSpecifierQualifier();
4916
4917
0
  case tok::coloncolon:   // ::foo::bar
4918
0
    if (NextToken().is(tok::kw_new) ||    // ::new
4919
0
        NextToken().is(tok::kw_delete))   // ::delete
4920
0
      return false;
4921
4922
0
    if (TryAnnotateTypeOrScopeToken())
4923
0
      return true;
4924
0
    return isTypeSpecifierQualifier();
4925
4926
    // GNU attributes support.
4927
5.60M
  case tok::kw___attribute:
4928
    // GNU typeof support.
4929
5.60M
  case tok::kw_typeof:
4930
4931
    // type-specifiers
4932
5.60M
  case tok::kw_short:
4933
5.60M
  case tok::kw_long:
4934
5.60M
  case tok::kw___int64:
4935
5.60M
  case tok::kw___int128:
4936
5.60M
  case tok::kw_signed:
4937
5.60M
  case tok::kw_unsigned:
4938
5.60M
  case tok::kw__Complex:
4939
5.60M
  case tok::kw__Imaginary:
4940
5.60M
  case tok::kw_void:
4941
5.60M
  case tok::kw_char:
4942
5.60M
  case tok::kw_wchar_t:
4943
5.60M
  case tok::kw_char8_t:
4944
5.60M
  case tok::kw_char16_t:
4945
5.60M
  case tok::kw_char32_t:
4946
5.60M
  case tok::kw_int:
4947
5.60M
  case tok::kw__ExtInt:
4948
5.60M
  case tok::kw_half:
4949
5.60M
  case tok::kw___bf16:
4950
5.60M
  case tok::kw_float:
4951
5.60M
  case tok::kw_double:
4952
5.60M
  case tok::kw__Accum:
4953
5.60M
  case tok::kw__Fract:
4954
5.60M
  case tok::kw__Float16:
4955
5.60M
  case tok::kw___float128:
4956
5.60M
  case tok::kw_bool:
4957
5.60M
  case tok::kw__Bool:
4958
5.60M
  case tok::kw__Decimal32:
4959
5.60M
  case tok::kw__Decimal64:
4960
5.60M
  case tok::kw__Decimal128:
4961
5.60M
  case tok::kw___vector:
4962
67.2M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4963
67.2M
#include 
"clang/Basic/OpenCLImageTypes.def"5.60M
4964
4965
    // struct-or-union-specifier (C99) or class-specifier (C++)
4966
5.60M
  case tok::kw_class:
4967
5.60M
  case tok::kw_struct:
4968
5.60M
  case tok::kw___interface:
4969
5.60M
  case tok::kw_union:
4970
    // enum-specifier
4971
5.60M
  case tok::kw_enum:
4972
4973
    // type-qualifier
4974
5.60M
  case tok::kw_const:
4975
5.60M
  case tok::kw_volatile:
4976
5.60M
  case tok::kw_restrict:
4977
5.60M
  case tok::kw__Sat:
4978
4979
    // Debugger support.
4980
5.60M
  case tok::kw___unknown_anytype:
4981
4982
    // typedef-name
4983
5.60M
  case tok::annot_typename:
4984
5.60M
    return true;
4985
4986
    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4987
3
  case tok::less:
4988
3
    return getLangOpts().ObjC;
4989
4990
886
  case tok::kw___cdecl:
4991
886
  case tok::kw___stdcall:
4992
886
  case tok::kw___fastcall:
4993
886
  case tok::kw___thiscall:
4994
886
  case tok::kw___regcall:
4995
886
  case tok::kw___vectorcall:
4996
886
  case tok::kw___w64:
4997
886
  case tok::kw___ptr64:
4998
886
  case tok::kw___ptr32:
4999
886
  case tok::kw___pascal:
5000
886
  case tok::kw___unaligned:
5001
5002
886
  case tok::kw__Nonnull:
5003
886
  case tok::kw__Nullable:
5004
886
  case tok::kw__Null_unspecified:
5005
5006
886
  case tok::kw___kindof:
5007
5008
886
  case tok::kw___private:
5009
886
  case tok::kw___local:
5010
886
  case tok::kw___global:
5011
886
  case tok::kw___constant:
5012
886
  case tok::kw___generic:
5013
886
  case tok::kw___read_only:
5014
886
  case tok::kw___read_write:
5015
886
  case tok::kw___write_only:
5016
886
    return true;
5017
5018
0
  case tok::kw_private:
5019
0
    return getLangOpts().OpenCL;
5020
5021
  // C11 _Atomic
5022
69
  case tok::kw__Atomic:
5023
69
    return true;
5024
11.5M
  }
5025
11.5M
}
5026
5027
/// isDeclarationSpecifier() - Return true if the current token is part of a
5028
/// declaration specifier.
5029
///
5030
/// \param DisambiguatingWithExpression True to indicate that the purpose of
5031
/// this check is to disambiguate between an expression and a declaration.
5032
1.63M
bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
5033
1.63M
  switch (Tok.getKind()) {
5034
687k
  default: return false;
5035
5036
3
  case tok::kw_pipe:
5037
3
    return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
5038
0
           getLangOpts().OpenCLCPlusPlus;
5039
5040
184k
  case tok::identifier:   // foo::bar
5041
    // Unfortunate hack to support "Class.factoryMethod" notation.
5042
184k
    if (getLangOpts().ObjC && 
NextToken().is(tok::period)5.05k
)
5043
82
      return false;
5044
183k
    if (TryAltiVecVectorToken())
5045
5.95k
      return true;
5046
178k
    LLVM_FALLTHROUGH;
5047
178k
  case tok::kw_decltype: // decltype(T())::type
5048
178k
  case tok::kw_typename: // typename T::type
5049
    // Annotate typenames and C++ scope specifiers.  If we get one, just
5050
    // recurse to handle whatever we get.
5051
178k
    if (TryAnnotateTypeOrScopeToken())
5052
1
      return true;
5053
178k
    if (TryAnnotateTypeConstraint())
5054
0
      return true;
5055
178k
    if (Tok.is(tok::identifier))
5056
7.78k
      return false;
5057
5058
    // If we're in Objective-C and we have an Objective-C class type followed
5059
    // by an identifier and then either ':' or ']', in a place where an
5060
    // expression is permitted, then this is probably a class message send
5061
    // missing the initial '['. In this case, we won't consider this to be
5062
    // the start of a declaration.
5063
170k
    if (DisambiguatingWithExpression &&
5064
213
        isStartOfObjCClassMessageMissingOpenBracket())
5065
0
      return false;
5066
5067
170k
    return isDeclarationSpecifier();
5068
5069
1
  case tok::coloncolon:   // ::foo::bar
5070
1
    if (NextToken().is(tok::kw_new) ||    // ::new
5071
1
        NextToken().is(tok::kw_delete))   // ::delete
5072
0
      return false;
5073
5074
    // Annotate typenames and C++ scope specifiers.  If we get one, just
5075
    // recurse to handle whatever we get.
5076
1
    if (TryAnnotateTypeOrScopeToken())
5077
0
      return true;
5078
1
    return isDeclarationSpecifier();
5079
5080
    // storage-class-specifier
5081
160k
  case tok::kw_typedef:
5082
160k
  case tok::kw_extern:
5083
160k
  case tok::kw___private_extern__:
5084
160k
  case tok::kw_static:
5085
160k
  case tok::kw_auto:
5086
160k
  case tok::kw___auto_type:
5087
160k
  case tok::kw_register:
5088
160k
  case tok::kw___thread:
5089
160k
  case tok::kw_thread_local:
5090
160k
  case tok::kw__Thread_local:
5091
5092
    // Modules
5093
160k
  case tok::kw___module_private__:
5094
5095
    // Debugger support
5096
160k
  case tok::kw___unknown_anytype:
5097
5098
    // type-specifiers
5099
160k
  case tok::kw_short:
5100
160k
  case tok::kw_long:
5101
160k
  case tok::kw___int64:
5102
160k
  case tok::kw___int128:
5103
160k
  case tok::kw_signed:
5104
160k
  case tok::kw_unsigned:
5105
160k
  case tok::kw__Complex:
5106
160k
  case tok::kw__Imaginary:
5107
160k
  case tok::kw_void:
5108
160k
  case tok::kw_char:
5109
160k
  case tok::kw_wchar_t:
5110
160k
  case tok::kw_char8_t:
5111
160k
  case tok::kw_char16_t:
5112
160k
  case tok::kw_char32_t:
5113
5114
160k
  case tok::kw_int:
5115
160k
  case tok::kw__ExtInt:
5116
160k
  case tok::kw_half:
5117
160k
  case tok::kw___bf16:
5118
160k
  case tok::kw_float:
5119
160k
  case tok::kw_double:
5120
160k
  case tok::kw__Accum:
5121
160k
  case tok::kw__Fract:
5122
160k
  case tok::kw__Float16:
5123
160k
  case tok::kw___float128:
5124
160k
  case tok::kw_bool:
5125
160k
  case tok::kw__Bool:
5126
160k
  case tok::kw__Decimal32:
5127
160k
  case tok::kw__Decimal64:
5128
160k
  case tok::kw__Decimal128:
5129
160k
  case tok::kw___vector:
5130
5131
    // struct-or-union-specifier (C99) or class-specifier (C++)
5132
160k
  case tok::kw_class:
5133
160k
  case tok::kw_struct:
5134
160k
  case tok::kw_union:
5135
160k
  case tok::kw___interface:
5136
    // enum-specifier
5137
160k
  case tok::kw_enum:
5138
5139
    // type-qualifier
5140
160k
  case tok::kw_const:
5141
160k
  case tok::kw_volatile:
5142
160k
  case tok::kw_restrict:
5143
160k
  case tok::kw__Sat:
5144
5145
    // function-specifier
5146
160k
  case tok::kw_inline:
5147
160k
  case tok::kw_virtual:
5148
160k
  case tok::kw_explicit:
5149
160k
  case tok::kw__Noreturn:
5150
5151
    // alignment-specifier
5152
160k
  case tok::kw__Alignas:
5153
5154
    // friend keyword.
5155
160k
  case tok::kw_friend:
5156
5157
    // static_assert-declaration
5158
160k
  case tok::kw__Static_assert:
5159
5160
    // GNU typeof support.
5161
160k
  case tok::kw_typeof:
5162
5163
    // GNU attributes.
5164
160k
  case tok::kw___attribute:
5165
5166
    // C++11 decltype and constexpr.
5167
160k
  case tok::annot_decltype:
5168
160k
  case tok::kw_constexpr:
5169
5170
    // C++20 consteval and constinit.
5171
160k
  case tok::kw_consteval:
5172
160k
  case tok::kw_constinit:
5173
5174
    // C11 _Atomic
5175
160k
  case tok::kw__Atomic:
5176
160k
    return true;
5177
5178
    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5179
5
  case tok::less:
5180
5
    return getLangOpts().ObjC;
5181
5182
    // typedef-name
5183
564k
  case tok::annot_typename:
5184
564k
    return !DisambiguatingWithExpression ||
5185
390k
           !isStartOfObjCClassMessageMissingOpenBracket();
5186
5187
    // placeholder-type-specifier
5188
9
  case tok::annot_template_id: {
5189
9
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5190
9
    if (TemplateId->hasInvalidName())
5191
0
      return true;
5192
    // FIXME: What about type templates that have only been annotated as
5193
    // annot_template_id, not as annot_typename?
5194
9
    return isTypeConstraintAnnotation() &&
5195
5
           (NextToken().is(tok::kw_auto) || 
NextToken().is(tok::kw_decltype)0
);
5196
9
  }
5197
5198
41.3k
  case tok::annot_cxxscope: {
5199
41.3k
    TemplateIdAnnotation *TemplateId =
5200
41.3k
        NextToken().is(tok::annot_template_id)
5201
2
            ? takeTemplateIdAnnotation(NextToken())
5202
41.3k
            : nullptr;
5203
41.3k
    if (TemplateId && 
TemplateId->hasInvalidName()2
)
5204
0
      return true;
5205
    // FIXME: What about type templates that have only been annotated as
5206
    // annot_template_id, not as annot_typename?
5207
41.3k
    if (NextToken().is(tok::identifier) && 
TryAnnotateTypeConstraint()27
)
5208
0
      return true;
5209
41.3k
    return isTypeConstraintAnnotation() &&
5210
2
        GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5211
41.3k
  }
5212
5213
663
  case tok::kw___declspec:
5214
663
  case tok::kw___cdecl:
5215
663
  case tok::kw___stdcall:
5216
663
  case tok::kw___fastcall:
5217
663
  case tok::kw___thiscall:
5218
663
  case tok::kw___regcall:
5219
663
  case tok::kw___vectorcall:
5220
663
  case tok::kw___w64:
5221
663
  case tok::kw___sptr:
5222
663
  case tok::kw___uptr:
5223
663
  case tok::kw___ptr64:
5224
663
  case tok::kw___ptr32:
5225
663
  case tok::kw___forceinline:
5226
663
  case tok::kw___pascal:
5227
663
  case tok::kw___unaligned:
5228
5229
663
  case tok::kw__Nonnull:
5230
663
  case tok::kw__Nullable:
5231
663
  case tok::kw__Null_unspecified:
5232
5233
663
  case tok::kw___kindof:
5234
5235
663
  case tok::kw___private:
5236
663
  case tok::kw___local:
5237
663
  case tok::kw___global:
5238
663
  case tok::kw___constant:
5239
663
  case tok::kw___generic:
5240
663
  case tok::kw___read_only:
5241
663
  case tok::kw___read_write:
5242
663
  case tok::kw___write_only:
5243
7.95k
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5244
663
#include "clang/Basic/OpenCLImageTypes.def"
5245
5246
663
    return true;
5247
5248
0
  case tok::kw_private:
5249
0
    return getLangOpts().OpenCL;
5250
1.63M
  }
5251
1.63M
}
5252
5253
374k
bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {