Coverage Report

Created: 2021-06-15 06:44

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