Coverage Report

Created: 2022-01-18 06:27

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