Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseStmt.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
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 Statement and Block portions of the Parser
10
// interface.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/AST/PrettyDeclStackTrace.h"
15
#include "clang/Basic/Attributes.h"
16
#include "clang/Basic/PrettyStackTrace.h"
17
#include "clang/Parse/LoopHint.h"
18
#include "clang/Parse/Parser.h"
19
#include "clang/Parse/RAIIObjectsForParser.h"
20
#include "clang/Sema/DeclSpec.h"
21
#include "clang/Sema/Scope.h"
22
#include "clang/Sema/TypoCorrection.h"
23
#include "llvm/ADT/STLExtras.h"
24
25
using namespace clang;
26
27
//===----------------------------------------------------------------------===//
28
// C99 6.8: Statements and Blocks.
29
//===----------------------------------------------------------------------===//
30
31
/// Parse a standalone statement (for instance, as the body of an 'if',
32
/// 'while', or 'for').
33
StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
34
1.27M
                                  ParsedStmtContext StmtCtx) {
35
1.27M
  StmtResult Res;
36
37
  // We may get back a null statement if we found a #pragma. Keep going until
38
  // we get an actual statement.
39
1.27M
  do {
40
1.27M
    StmtVector Stmts;
41
1.27M
    Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
42
1.27M
  } while (!Res.isInvalid() && 
!Res.get()1.26M
);
43
44
1.27M
  return Res;
45
1.27M
}
46
47
/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
48
///       StatementOrDeclaration:
49
///         statement
50
///         declaration
51
///
52
///       statement:
53
///         labeled-statement
54
///         compound-statement
55
///         expression-statement
56
///         selection-statement
57
///         iteration-statement
58
///         jump-statement
59
/// [C++]   declaration-statement
60
/// [C++]   try-block
61
/// [MS]    seh-try-block
62
/// [OBC]   objc-throw-statement
63
/// [OBC]   objc-try-catch-statement
64
/// [OBC]   objc-synchronized-statement
65
/// [GNU]   asm-statement
66
/// [OMP]   openmp-construct             [TODO]
67
///
68
///       labeled-statement:
69
///         identifier ':' statement
70
///         'case' constant-expression ':' statement
71
///         'default' ':' statement
72
///
73
///       selection-statement:
74
///         if-statement
75
///         switch-statement
76
///
77
///       iteration-statement:
78
///         while-statement
79
///         do-statement
80
///         for-statement
81
///
82
///       expression-statement:
83
///         expression[opt] ';'
84
///
85
///       jump-statement:
86
///         'goto' identifier ';'
87
///         'continue' ';'
88
///         'break' ';'
89
///         'return' expression[opt] ';'
90
/// [GNU]   'goto' '*' expression ';'
91
///
92
/// [OBC] objc-throw-statement:
93
/// [OBC]   '@' 'throw' expression ';'
94
/// [OBC]   '@' 'throw' ';'
95
///
96
StmtResult
97
Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
98
                                    ParsedStmtContext StmtCtx,
99
9.05M
                                    SourceLocation *TrailingElseLoc) {
100
101
9.05M
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
102
103
  // Because we're parsing either a statement or a declaration, the order of
104
  // attribute parsing is important. [[]] attributes at the start of a
105
  // statement are different from [[]] attributes that follow an __attribute__
106
  // at the start of the statement. Thus, we're not using MaybeParseAttributes
107
  // here because we don't want to allow arbitrary orderings.
108
9.05M
  ParsedAttributes CXX11Attrs(AttrFactory);
109
9.05M
  MaybeParseCXX11Attributes(CXX11Attrs, /*MightBeObjCMessageSend*/ true);
110
9.05M
  ParsedAttributes GNUAttrs(AttrFactory);
111
9.05M
  if (getLangOpts().OpenCL)
112
35.3k
    MaybeParseGNUAttributes(GNUAttrs);
113
114
9.05M
  StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
115
9.05M
      Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs, GNUAttrs);
116
9.05M
  MaybeDestroyTemplateIds();
117
118
  // Attributes that are left should all go on the statement, so concatenate the
119
  // two lists.
120
9.05M
  ParsedAttributes Attrs(AttrFactory);
121
9.05M
  takeAndConcatenateAttrs(CXX11Attrs, GNUAttrs, Attrs);
122
123
9.05M
  assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
124
9.05M
         "attributes on empty statement");
125
126
9.05M
  if (Attrs.empty() || 
Res.isInvalid()1.71k
)
127
9.05M
    return Res;
128
129
1.70k
  return Actions.ActOnAttributedStmt(Attrs, Res.get());
130
9.05M
}
131
132
namespace {
133
class StatementFilterCCC final : public CorrectionCandidateCallback {
134
public:
135
2.71M
  StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
136
2.71M
    WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
137
2.71M
                                         tok::identifier, tok::star, tok::amp);
138
2.71M
    WantExpressionKeywords =
139
2.71M
        nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
140
2.71M
    WantRemainingKeywords =
141
2.71M
        nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
142
2.71M
    WantCXXNamedCasts = false;
143
2.71M
  }
144
145
204
  bool ValidateCandidate(const TypoCorrection &candidate) override {
146
204
    if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
147
17
      return !candidate.getCorrectionSpecifier() || 
isa<ObjCIvarDecl>(FD)2
;
148
187
    if (NextToken.is(tok::equal))
149
30
      return candidate.getCorrectionDeclAs<VarDecl>();
150
157
    if (NextToken.is(tok::period) &&
151
157
        
candidate.getCorrectionDeclAs<NamespaceDecl>()16
)
152
2
      return false;
153
155
    return CorrectionCandidateCallback::ValidateCandidate(candidate);
154
157
  }
155
156
341
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
157
341
    return std::make_unique<StatementFilterCCC>(*this);
158
341
  }
159
160
private:
161
  Token NextToken;
162
};
163
}
164
165
StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
166
    StmtVector &Stmts, ParsedStmtContext StmtCtx,
167
    SourceLocation *TrailingElseLoc, ParsedAttributes &CXX11Attrs,
168
9.05M
    ParsedAttributes &GNUAttrs) {
169
9.05M
  const char *SemiError = nullptr;
170
9.05M
  StmtResult Res;
171
9.05M
  SourceLocation GNUAttributeLoc;
172
173
  // Cases in this switch statement should fall through if the parser expects
174
  // the token to end in a semicolon (in which case SemiError should be set),
175
  // or they directly 'return;' if not.
176
11.7M
Retry:
177
11.7M
  tok::TokenKind Kind  = Tok.getKind();
178
11.7M
  SourceLocation AtLoc;
179
11.7M
  switch (Kind) {
180
996
  case tok::at: // May be a @try or @throw statement
181
996
    {
182
996
      AtLoc = ConsumeToken();  // consume @
183
996
      return ParseObjCAtStatement(AtLoc, StmtCtx);
184
0
    }
185
186
135
  case tok::code_completion:
187
135
    cutOffParsing();
188
135
    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
189
135
    return StmtError();
190
191
2.94M
  case tok::identifier: {
192
2.94M
    Token Next = NextToken();
193
2.94M
    if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
194
      // Both C++11 and GNU attributes preceding the label appertain to the
195
      // label, so put them in a single list to pass on to
196
      // ParseLabeledStatement().
197
3.60k
      ParsedAttributes Attrs(AttrFactory);
198
3.60k
      takeAndConcatenateAttrs(CXX11Attrs, GNUAttrs, Attrs);
199
200
      // identifier ':' statement
201
3.60k
      return ParseLabeledStatement(Attrs, StmtCtx);
202
3.60k
    }
203
204
    // Look up the identifier, and typo-correct it to a keyword if it's not
205
    // found.
206
2.94M
    if (Next.isNot(tok::coloncolon)) {
207
      // Try to limit which sets of keywords should be included in typo
208
      // correction based on what the next token is.
209
2.71M
      StatementFilterCCC CCC(Next);
210
2.71M
      if (TryAnnotateName(&CCC) == ANK_Error) {
211
        // Handle errors here by skipping up to the next semicolon or '}', and
212
        // eat the semicolon if that's what stopped us.
213
53
        SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
214
53
        if (Tok.is(tok::semi))
215
46
          ConsumeToken();
216
53
        return StmtError();
217
53
      }
218
219
      // If the identifier was typo-corrected, try again.
220
2.71M
      if (Tok.isNot(tok::identifier))
221
2.71M
        goto Retry;
222
2.71M
    }
223
224
    // Fall through
225
2.94M
    
LLVM_FALLTHROUGH229k
;
226
229k
  }
227
228
3.92M
  default: {
229
3.92M
    bool HaveAttrs = !CXX11Attrs.empty() || 
!GNUAttrs.empty()3.92M
;
230
3.92M
    auto IsStmtAttr = [](ParsedAttr &Attr) 
{ return Attr.isStmtAttr(); }2.67k
;
231
3.92M
    bool AllAttrsAreStmtAttrs = llvm::all_of(CXX11Attrs, IsStmtAttr) &&
232
3.92M
                                
llvm::all_of(GNUAttrs, IsStmtAttr)3.92M
;
233
3.92M
    if ((getLangOpts().CPlusPlus || 
getLangOpts().MicrosoftExt1.09M
||
234
3.92M
         (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
235
1.08M
             ParsedStmtContext()) &&
236
3.92M
        
(3.91M
(3.91M
GNUAttributeLoc.isValid()3.91M
&&
!(2.44k
HaveAttrs2.44k
&&
AllAttrsAreStmtAttrs2.44k
)) ||
237
3.91M
         
isDeclarationStatement()3.91M
)) {
238
1.46M
      SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
239
1.46M
      DeclGroupPtrTy Decl;
240
1.46M
      if (GNUAttributeLoc.isValid()) {
241
2.43k
        DeclStart = GNUAttributeLoc;
242
2.43k
        Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,
243
2.43k
                                GNUAttrs, &GNUAttributeLoc);
244
1.45M
      } else {
245
1.45M
        Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,
246
1.45M
                                GNUAttrs);
247
1.45M
      }
248
1.46M
      if (CXX11Attrs.Range.getBegin().isValid()) {
249
        // The caller must guarantee that the CXX11Attrs appear before the
250
        // GNUAttrs, and we rely on that here.
251
115
        assert(GNUAttrs.Range.getBegin().isInvalid() ||
252
115
               GNUAttrs.Range.getBegin() > CXX11Attrs.Range.getBegin());
253
0
        DeclStart = CXX11Attrs.Range.getBegin();
254
1.46M
      } else if (GNUAttrs.Range.getBegin().isValid())
255
2.50k
        DeclStart = GNUAttrs.Range.getBegin();
256
0
      return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
257
1.46M
    }
258
259
2.46M
    if (Tok.is(tok::r_brace)) {
260
43
      Diag(Tok, diag::err_expected_statement);
261
43
      return StmtError();
262
43
    }
263
264
2.46M
    return ParseExprStatement(StmtCtx);
265
2.46M
  }
266
267
2.51k
  case tok::kw___attribute: {
268
2.51k
    GNUAttributeLoc = Tok.getLocation();
269
2.51k
    ParseGNUAttributes(GNUAttrs);
270
2.51k
    goto Retry;
271
2.46M
  }
272
273
19.2k
  case tok::kw_case:                // C99 6.8.1: labeled-statement
274
19.2k
    return ParseCaseStatement(StmtCtx);
275
2.11k
  case tok::kw_default:             // C99 6.8.1: labeled-statement
276
2.11k
    return ParseDefaultStatement(StmtCtx);
277
278
505k
  case tok::l_brace:                // C99 6.8.2: compound-statement
279
505k
    return ParseCompoundStatement();
280
40.5k
  case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
281
40.5k
    bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
282
40.5k
    return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
283
2.46M
  }
284
285
596k
  case tok::kw_if:                  // C99 6.8.4.1: if-statement
286
596k
    return ParseIfStatement(TrailingElseLoc);
287
6.48k
  case tok::kw_switch:              // C99 6.8.4.2: switch-statement
288
6.48k
    return ParseSwitchStatement(TrailingElseLoc);
289
290
50.1k
  case tok::kw_while:               // C99 6.8.5.1: while-statement
291
50.1k
    return ParseWhileStatement(TrailingElseLoc);
292
9.85k
  case tok::kw_do:                  // C99 6.8.5.2: do-statement
293
9.85k
    Res = ParseDoStatement();
294
9.85k
    SemiError = "do/while";
295
9.85k
    break;
296
220k
  case tok::kw_for:                 // C99 6.8.5.3: for-statement
297
220k
    return ParseForStatement(TrailingElseLoc);
298
299
6.54k
  case tok::kw_goto:                // C99 6.8.6.1: goto-statement
300
6.54k
    Res = ParseGotoStatement();
301
6.54k
    SemiError = "goto";
302
6.54k
    break;
303
13.0k
  case tok::kw_continue:            // C99 6.8.6.2: continue-statement
304
13.0k
    Res = ParseContinueStatement();
305
13.0k
    SemiError = "continue";
306
13.0k
    break;
307
38.7k
  case tok::kw_break:               // C99 6.8.6.3: break-statement
308
38.7k
    Res = ParseBreakStatement();
309
38.7k
    SemiError = "break";
310
38.7k
    break;
311
3.33M
  case tok::kw_return:              // C99 6.8.6.4: return-statement
312
3.33M
    Res = ParseReturnStatement();
313
3.33M
    SemiError = "return";
314
3.33M
    break;
315
374
  case tok::kw_co_return:            // C++ Coroutines: co_return statement
316
374
    Res = ParseReturnStatement();
317
374
    SemiError = "co_return";
318
374
    break;
319
320
5.64k
  case tok::kw_asm: {
321
5.64k
    for (const ParsedAttr &AL : CXX11Attrs)
322
2
      Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
323
    // Prevent these from being interpreted as statement attributes later on.
324
5.64k
    CXX11Attrs.clear();
325
5.64k
    ProhibitAttributes(GNUAttrs);
326
5.64k
    bool msAsm = false;
327
5.64k
    Res = ParseAsmStatement(msAsm);
328
5.64k
    if (msAsm) 
return Res254
;
329
5.38k
    SemiError = "asm";
330
5.38k
    break;
331
5.64k
  }
332
333
15
  case tok::kw___if_exists:
334
29
  case tok::kw___if_not_exists:
335
29
    ProhibitAttributes(CXX11Attrs);
336
29
    ProhibitAttributes(GNUAttrs);
337
29
    ParseMicrosoftIfExistsStatement(Stmts);
338
    // An __if_exists block is like a compound statement, but it doesn't create
339
    // a new scope.
340
29
    return StmtEmpty();
341
342
14.7k
  case tok::kw_try:                 // C++ 15: try-block
343
14.7k
    return ParseCXXTryBlock();
344
345
285
  case tok::kw___try:
346
285
    ProhibitAttributes(CXX11Attrs);
347
285
    ProhibitAttributes(GNUAttrs);
348
285
    return ParseSEHTryBlock();
349
350
35
  case tok::kw___leave:
351
35
    Res = ParseSEHLeaveStatement();
352
35
    SemiError = "__leave";
353
35
    break;
354
355
0
  case tok::annot_pragma_vis:
356
0
    ProhibitAttributes(CXX11Attrs);
357
0
    ProhibitAttributes(GNUAttrs);
358
0
    HandlePragmaVisibility();
359
0
    return StmtEmpty();
360
361
4
  case tok::annot_pragma_pack:
362
4
    ProhibitAttributes(CXX11Attrs);
363
4
    ProhibitAttributes(GNUAttrs);
364
4
    HandlePragmaPack();
365
4
    return StmtEmpty();
366
367
0
  case tok::annot_pragma_msstruct:
368
0
    ProhibitAttributes(CXX11Attrs);
369
0
    ProhibitAttributes(GNUAttrs);
370
0
    HandlePragmaMSStruct();
371
0
    return StmtEmpty();
372
373
1
  case tok::annot_pragma_align:
374
1
    ProhibitAttributes(CXX11Attrs);
375
1
    ProhibitAttributes(GNUAttrs);
376
1
    HandlePragmaAlign();
377
1
    return StmtEmpty();
378
379
9
  case tok::annot_pragma_weak:
380
9
    ProhibitAttributes(CXX11Attrs);
381
9
    ProhibitAttributes(GNUAttrs);
382
9
    HandlePragmaWeak();
383
9
    return StmtEmpty();
384
385
0
  case tok::annot_pragma_weakalias:
386
0
    ProhibitAttributes(CXX11Attrs);
387
0
    ProhibitAttributes(GNUAttrs);
388
0
    HandlePragmaWeakAlias();
389
0
    return StmtEmpty();
390
391
0
  case tok::annot_pragma_redefine_extname:
392
0
    ProhibitAttributes(CXX11Attrs);
393
0
    ProhibitAttributes(GNUAttrs);
394
0
    HandlePragmaRedefineExtname();
395
0
    return StmtEmpty();
396
397
3
  case tok::annot_pragma_fp_contract:
398
3
    ProhibitAttributes(CXX11Attrs);
399
3
    ProhibitAttributes(GNUAttrs);
400
3
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "fp_contract";
401
3
    ConsumeAnnotationToken();
402
3
    return StmtError();
403
404
3
  case tok::annot_pragma_fp:
405
3
    ProhibitAttributes(CXX11Attrs);
406
3
    ProhibitAttributes(GNUAttrs);
407
3
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "clang fp";
408
3
    ConsumeAnnotationToken();
409
3
    return StmtError();
410
411
3
  case tok::annot_pragma_fenv_access:
412
4
  case tok::annot_pragma_fenv_access_ms:
413
4
    ProhibitAttributes(CXX11Attrs);
414
4
    ProhibitAttributes(GNUAttrs);
415
4
    Diag(Tok, diag::err_pragma_file_or_compound_scope)
416
4
        << (Kind == tok::annot_pragma_fenv_access ? 
"STDC FENV_ACCESS"3
417
4
                                                    : 
"fenv_access"1
);
418
4
    ConsumeAnnotationToken();
419
4
    return StmtEmpty();
420
421
1
  case tok::annot_pragma_fenv_round:
422
1
    ProhibitAttributes(CXX11Attrs);
423
1
    ProhibitAttributes(GNUAttrs);
424
1
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "STDC FENV_ROUND";
425
1
    ConsumeAnnotationToken();
426
1
    return StmtError();
427
428
0
  case tok::annot_pragma_float_control:
429
0
    ProhibitAttributes(CXX11Attrs);
430
0
    ProhibitAttributes(GNUAttrs);
431
0
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "float_control";
432
0
    ConsumeAnnotationToken();
433
0
    return StmtError();
434
435
3
  case tok::annot_pragma_opencl_extension:
436
3
    ProhibitAttributes(CXX11Attrs);
437
3
    ProhibitAttributes(GNUAttrs);
438
3
    HandlePragmaOpenCLExtension();
439
3
    return StmtEmpty();
440
441
57
  case tok::annot_pragma_captured:
442
57
    ProhibitAttributes(CXX11Attrs);
443
57
    ProhibitAttributes(GNUAttrs);
444
57
    return HandlePragmaCaptured();
445
446
263k
  case tok::annot_pragma_openmp:
447
    // Prohibit attributes that are not OpenMP attributes, but only before
448
    // processing a #pragma omp clause.
449
263k
    ProhibitAttributes(CXX11Attrs);
450
263k
    ProhibitAttributes(GNUAttrs);
451
263k
    LLVM_FALLTHROUGH;
452
264k
  case tok::annot_attr_openmp:
453
    // Do not prohibit attributes if they were OpenMP attributes.
454
264k
    return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
455
456
0
  case tok::annot_pragma_ms_pointers_to_members:
457
0
    ProhibitAttributes(CXX11Attrs);
458
0
    ProhibitAttributes(GNUAttrs);
459
0
    HandlePragmaMSPointersToMembers();
460
0
    return StmtEmpty();
461
462
0
  case tok::annot_pragma_ms_pragma:
463
0
    ProhibitAttributes(CXX11Attrs);
464
0
    ProhibitAttributes(GNUAttrs);
465
0
    HandlePragmaMSPragma();
466
0
    return StmtEmpty();
467
468
1
  case tok::annot_pragma_ms_vtordisp:
469
1
    ProhibitAttributes(CXX11Attrs);
470
1
    ProhibitAttributes(GNUAttrs);
471
1
    HandlePragmaMSVtorDisp();
472
1
    return StmtEmpty();
473
474
211
  case tok::annot_pragma_loop_hint:
475
211
    ProhibitAttributes(CXX11Attrs);
476
211
    ProhibitAttributes(GNUAttrs);
477
211
    return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs);
478
479
2
  case tok::annot_pragma_dump:
480
2
    HandlePragmaDump();
481
2
    return StmtEmpty();
482
483
7
  case tok::annot_pragma_attribute:
484
7
    HandlePragmaAttribute();
485
7
    return StmtEmpty();
486
11.7M
  }
487
488
  // If we reached this code, the statement must end in a semicolon.
489
3.40M
  if (!TryConsumeToken(tok::semi) && 
!Res.isInvalid()84
) {
490
    // If the result was valid, then we do want to diagnose this.  Use
491
    // ExpectAndConsume to emit the diagnostic, even though we know it won't
492
    // succeed.
493
7
    ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
494
    // Skip until we see a } or ;, but don't eat it.
495
7
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
496
7
  }
497
498
3.40M
  return Res;
499
11.7M
}
500
501
/// Parse an expression statement.
502
2.46M
StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
503
  // If a case keyword is missing, this is where it should be inserted.
504
2.46M
  Token OldToken = Tok;
505
506
2.46M
  ExprStatementTokLoc = Tok.getLocation();
507
508
  // expression[opt] ';'
509
2.46M
  ExprResult Expr(ParseExpression());
510
2.46M
  if (Expr.isInvalid()) {
511
    // If the expression is invalid, skip ahead to the next semicolon or '}'.
512
    // Not doing this opens us up to the possibility of infinite loops if
513
    // ParseExpression does not consume any tokens.
514
5.28k
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
515
5.28k
    if (Tok.is(tok::semi))
516
4.64k
      ConsumeToken();
517
5.28k
    return Actions.ActOnExprStmtError();
518
5.28k
  }
519
520
2.45M
  if (Tok.is(tok::colon) && 
getCurScope()->isSwitchScope()19
&&
521
2.45M
      
Actions.CheckCaseExpression(Expr.get())18
) {
522
    // If a constant expression is followed by a colon inside a switch block,
523
    // suggest a missing case keyword.
524
18
    Diag(OldToken, diag::err_expected_case_before_expression)
525
18
      << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
526
527
    // Recover parsing as a case statement.
528
18
    return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
529
18
  }
530
531
  // Otherwise, eat the semicolon.
532
2.45M
  ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
533
2.45M
  return handleExprStmt(Expr, StmtCtx);
534
2.45M
}
535
536
/// ParseSEHTryBlockCommon
537
///
538
/// seh-try-block:
539
///   '__try' compound-statement seh-handler
540
///
541
/// seh-handler:
542
///   seh-except-block
543
///   seh-finally-block
544
///
545
285
StmtResult Parser::ParseSEHTryBlock() {
546
285
  assert(Tok.is(tok::kw___try) && "Expected '__try'");
547
0
  SourceLocation TryLoc = ConsumeToken();
548
549
285
  if (Tok.isNot(tok::l_brace))
550
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
551
552
284
  StmtResult TryBlock(ParseCompoundStatement(
553
284
      /*isStmtExpr=*/false,
554
284
      Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
555
284
  if (TryBlock.isInvalid())
556
0
    return TryBlock;
557
558
284
  StmtResult Handler;
559
284
  if (Tok.is(tok::identifier) &&
560
284
      
Tok.getIdentifierInfo() == getSEHExceptKeyword()135
) {
561
135
    SourceLocation Loc = ConsumeToken();
562
135
    Handler = ParseSEHExceptBlock(Loc);
563
149
  } else if (Tok.is(tok::kw___finally)) {
564
146
    SourceLocation Loc = ConsumeToken();
565
146
    Handler = ParseSEHFinallyBlock(Loc);
566
146
  } else {
567
3
    return StmtError(Diag(Tok, diag::err_seh_expected_handler));
568
3
  }
569
570
281
  if(Handler.isInvalid())
571
10
    return Handler;
572
573
271
  return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
574
271
                                  TryLoc,
575
271
                                  TryBlock.get(),
576
271
                                  Handler.get());
577
281
}
578
579
/// ParseSEHExceptBlock - Handle __except
580
///
581
/// seh-except-block:
582
///   '__except' '(' seh-filter-expression ')' compound-statement
583
///
584
136
StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
585
136
  PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
586
136
    raii2(Ident___exception_code, false),
587
136
    raii3(Ident_GetExceptionCode, false);
588
589
136
  if (ExpectAndConsume(tok::l_paren))
590
0
    return StmtError();
591
592
136
  ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
593
136
                                   Scope::SEHExceptScope);
594
595
136
  if (getLangOpts().Borland) {
596
15
    Ident__exception_info->setIsPoisoned(false);
597
15
    Ident___exception_info->setIsPoisoned(false);
598
15
    Ident_GetExceptionInfo->setIsPoisoned(false);
599
15
  }
600
601
136
  ExprResult FilterExpr;
602
136
  {
603
136
    ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
604
136
                                          Scope::SEHFilterScope);
605
136
    FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
606
136
  }
607
608
136
  if (getLangOpts().Borland) {
609
15
    Ident__exception_info->setIsPoisoned(true);
610
15
    Ident___exception_info->setIsPoisoned(true);
611
15
    Ident_GetExceptionInfo->setIsPoisoned(true);
612
15
  }
613
614
136
  if(FilterExpr.isInvalid())
615
6
    return StmtError();
616
617
130
  if (ExpectAndConsume(tok::r_paren))
618
0
    return StmtError();
619
620
130
  if (Tok.isNot(tok::l_brace))
621
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
622
623
129
  StmtResult Block(ParseCompoundStatement());
624
625
129
  if(Block.isInvalid())
626
0
    return Block;
627
628
129
  return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
629
129
}
630
631
/// ParseSEHFinallyBlock - Handle __finally
632
///
633
/// seh-finally-block:
634
///   '__finally' compound-statement
635
///
636
148
StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
637
148
  PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
638
148
    raii2(Ident___abnormal_termination, false),
639
148
    raii3(Ident_AbnormalTermination, false);
640
641
148
  if (Tok.isNot(tok::l_brace))
642
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
643
644
147
  ParseScope FinallyScope(this, 0);
645
147
  Actions.ActOnStartSEHFinallyBlock();
646
647
147
  StmtResult Block(ParseCompoundStatement());
648
147
  if(Block.isInvalid()) {
649
0
    Actions.ActOnAbortSEHFinallyBlock();
650
0
    return Block;
651
0
  }
652
653
147
  return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
654
147
}
655
656
/// Handle __leave
657
///
658
/// seh-leave-statement:
659
///   '__leave' ';'
660
///
661
35
StmtResult Parser::ParseSEHLeaveStatement() {
662
35
  SourceLocation LeaveLoc = ConsumeToken();  // eat the '__leave'.
663
35
  return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
664
35
}
665
666
/// ParseLabeledStatement - We have an identifier and a ':' after it.
667
///
668
///       labeled-statement:
669
///         identifier ':' statement
670
/// [GNU]   identifier ':' attributes[opt] statement
671
///
672
StmtResult Parser::ParseLabeledStatement(ParsedAttributes &Attrs,
673
3.60k
                                         ParsedStmtContext StmtCtx) {
674
3.60k
  assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
675
3.60k
         "Not an identifier!");
676
677
  // The substatement is always a 'statement', not a 'declaration', but is
678
  // otherwise in the same context as the labeled-statement.
679
0
  StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
680
681
3.60k
  Token IdentTok = Tok;  // Save the whole token.
682
3.60k
  ConsumeToken();  // eat the identifier.
683
684
3.60k
  assert(Tok.is(tok::colon) && "Not a label!");
685
686
  // identifier ':' statement
687
0
  SourceLocation ColonLoc = ConsumeToken();
688
689
  // Read label attributes, if present.
690
3.60k
  StmtResult SubStmt;
691
3.60k
  if (Tok.is(tok::kw___attribute)) {
692
14
    ParsedAttributes TempAttrs(AttrFactory);
693
14
    ParseGNUAttributes(TempAttrs);
694
695
    // In C++, GNU attributes only apply to the label if they are followed by a
696
    // semicolon, to disambiguate label attributes from attributes on a labeled
697
    // declaration.
698
    //
699
    // This doesn't quite match what GCC does; if the attribute list is empty
700
    // and followed by a semicolon, GCC will reject (it appears to parse the
701
    // attributes as part of a statement in that case). That looks like a bug.
702
14
    if (!getLangOpts().CPlusPlus || 
Tok.is(tok::semi)9
)
703
8
      Attrs.takeAllFrom(TempAttrs);
704
6
    else {
705
6
      StmtVector Stmts;
706
6
      ParsedAttributes EmptyCXX11Attrs(AttrFactory);
707
6
      SubStmt = ParseStatementOrDeclarationAfterAttributes(
708
6
          Stmts, StmtCtx, nullptr, EmptyCXX11Attrs, TempAttrs);
709
6
      if (!TempAttrs.empty() && 
!SubStmt.isInvalid()0
)
710
0
        SubStmt = Actions.ActOnAttributedStmt(TempAttrs, SubStmt.get());
711
6
    }
712
14
  }
713
714
  // If we've not parsed a statement yet, parse one now.
715
3.60k
  if (!SubStmt.isInvalid() && !SubStmt.isUsable())
716
3.59k
    SubStmt = ParseStatement(nullptr, StmtCtx);
717
718
  // Broken substmt shouldn't prevent the label from being added to the AST.
719
3.60k
  if (SubStmt.isInvalid())
720
7
    SubStmt = Actions.ActOnNullStmt(ColonLoc);
721
722
3.60k
  LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
723
3.60k
                                              IdentTok.getLocation());
724
3.60k
  Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
725
3.60k
  Attrs.clear();
726
727
3.60k
  return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
728
3.60k
                                SubStmt.get());
729
3.60k
}
730
731
/// ParseCaseStatement
732
///       labeled-statement:
733
///         'case' constant-expression ':' statement
734
/// [GNU]   'case' constant-expression '...' constant-expression ':' statement
735
///
736
StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
737
19.2k
                                      bool MissingCase, ExprResult Expr) {
738
19.2k
  assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
739
740
  // The substatement is always a 'statement', not a 'declaration', but is
741
  // otherwise in the same context as the labeled-statement.
742
0
  StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
743
744
  // It is very very common for code to contain many case statements recursively
745
  // nested, as in (but usually without indentation):
746
  //  case 1:
747
  //    case 2:
748
  //      case 3:
749
  //         case 4:
750
  //           case 5: etc.
751
  //
752
  // Parsing this naively works, but is both inefficient and can cause us to run
753
  // out of stack space in our recursive descent parser.  As a special case,
754
  // flatten this recursion into an iterative loop.  This is complex and gross,
755
  // but all the grossness is constrained to ParseCaseStatement (and some
756
  // weirdness in the actions), so this is just local grossness :).
757
758
  // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
759
  // example above.
760
19.2k
  StmtResult TopLevelCase(true);
761
762
  // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
763
  // gets updated each time a new case is parsed, and whose body is unset so
764
  // far.  When parsing 'case 4', this is the 'case 3' node.
765
19.2k
  Stmt *DeepestParsedCaseStmt = nullptr;
766
767
  // While we have case statements, eat and stack them.
768
19.2k
  SourceLocation ColonLoc;
769
23.5k
  do {
770
23.5k
    SourceLocation CaseLoc = MissingCase ? 
Expr.get()->getExprLoc()18
:
771
23.5k
                                           
ConsumeToken()23.5k
; // eat the 'case'.
772
23.5k
    ColonLoc = SourceLocation();
773
774
23.5k
    if (Tok.is(tok::code_completion)) {
775
10
      cutOffParsing();
776
10
      Actions.CodeCompleteCase(getCurScope());
777
10
      return StmtError();
778
10
    }
779
780
    /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
781
    /// Disable this form of error recovery while we're parsing the case
782
    /// expression.
783
23.5k
    ColonProtectionRAIIObject ColonProtection(*this);
784
785
23.5k
    ExprResult LHS;
786
23.5k
    if (!MissingCase) {
787
23.5k
      LHS = ParseCaseExpression(CaseLoc);
788
23.5k
      if (LHS.isInvalid()) {
789
        // If constant-expression is parsed unsuccessfully, recover by skipping
790
        // current case statement (moving to the colon that ends it).
791
71
        if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
792
2
          return StmtError();
793
71
      }
794
23.5k
    } else {
795
18
      LHS = Expr;
796
18
      MissingCase = false;
797
18
    }
798
799
    // GNU case range extension.
800
23.5k
    SourceLocation DotDotDotLoc;
801
23.5k
    ExprResult RHS;
802
23.5k
    if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
803
104
      Diag(DotDotDotLoc, diag::ext_gnu_case_range);
804
104
      RHS = ParseCaseExpression(CaseLoc);
805
104
      if (RHS.isInvalid()) {
806
2
        if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
807
0
          return StmtError();
808
2
      }
809
104
    }
810
811
23.5k
    ColonProtection.restore();
812
813
23.5k
    if (TryConsumeToken(tok::colon, ColonLoc)) {
814
23.5k
    } else 
if (10
TryConsumeToken(tok::semi, ColonLoc)10
||
815
10
               
TryConsumeToken(tok::coloncolon, ColonLoc)5
) {
816
      // Treat "case blah;" or "case blah::" as a typo for "case blah:".
817
5
      Diag(ColonLoc, diag::err_expected_after)
818
5
          << "'case'" << tok::colon
819
5
          << FixItHint::CreateReplacement(ColonLoc, ":");
820
5
    } else {
821
5
      SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
822
5
      Diag(ExpectedLoc, diag::err_expected_after)
823
5
          << "'case'" << tok::colon
824
5
          << FixItHint::CreateInsertion(ExpectedLoc, ":");
825
5
      ColonLoc = ExpectedLoc;
826
5
    }
827
828
23.5k
    StmtResult Case =
829
23.5k
        Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
830
831
    // If we had a sema error parsing this case, then just ignore it and
832
    // continue parsing the sub-stmt.
833
23.5k
    if (Case.isInvalid()) {
834
74
      if (TopLevelCase.isInvalid())  // No parsed case stmts.
835
63
        return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
836
      // Otherwise, just don't add it as a nested case.
837
23.4k
    } else {
838
      // If this is the first case statement we parsed, it becomes TopLevelCase.
839
      // Otherwise we link it into the current chain.
840
23.4k
      Stmt *NextDeepest = Case.get();
841
23.4k
      if (TopLevelCase.isInvalid())
842
19.2k
        TopLevelCase = Case;
843
4.25k
      else
844
4.25k
        Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
845
23.4k
      DeepestParsedCaseStmt = NextDeepest;
846
23.4k
    }
847
848
    // Handle all case statements.
849
23.5k
  } while (
Tok.is(tok::kw_case)23.4k
);
850
851
  // If we found a non-case statement, start by parsing it.
852
19.1k
  StmtResult SubStmt;
853
854
19.1k
  if (Tok.isNot(tok::r_brace)) {
855
19.1k
    SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
856
19.1k
  } else {
857
    // Nicely diagnose the common error "switch (X) { case 4: }", which is
858
    // not valid.  If ColonLoc doesn't point to a valid text location, there was
859
    // another parsing error, so avoid producing extra diagnostics.
860
9
    if (ColonLoc.isValid()) {
861
9
      SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
862
9
      Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
863
9
        << FixItHint::CreateInsertion(AfterColonLoc, " ;");
864
9
    }
865
9
    SubStmt = StmtError();
866
9
  }
867
868
  // Install the body into the most deeply-nested case.
869
19.1k
  if (DeepestParsedCaseStmt) {
870
    // Broken sub-stmt shouldn't prevent forming the case statement properly.
871
19.1k
    if (SubStmt.isInvalid())
872
28
      SubStmt = Actions.ActOnNullStmt(SourceLocation());
873
19.1k
    Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
874
19.1k
  }
875
876
  // Return the top level parsed statement tree.
877
19.1k
  return TopLevelCase;
878
19.2k
}
879
880
/// ParseDefaultStatement
881
///       labeled-statement:
882
///         'default' ':' statement
883
/// Note that this does not parse the 'statement' at the end.
884
///
885
2.11k
StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
886
2.11k
  assert(Tok.is(tok::kw_default) && "Not a default stmt!");
887
888
  // The substatement is always a 'statement', not a 'declaration', but is
889
  // otherwise in the same context as the labeled-statement.
890
0
  StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
891
892
2.11k
  SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
893
894
2.11k
  SourceLocation ColonLoc;
895
2.11k
  if (TryConsumeToken(tok::colon, ColonLoc)) {
896
2.10k
  } else 
if (2
TryConsumeToken(tok::semi, ColonLoc)2
) {
897
    // Treat "default;" as a typo for "default:".
898
1
    Diag(ColonLoc, diag::err_expected_after)
899
1
        << "'default'" << tok::colon
900
1
        << FixItHint::CreateReplacement(ColonLoc, ":");
901
1
  } else {
902
1
    SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
903
1
    Diag(ExpectedLoc, diag::err_expected_after)
904
1
        << "'default'" << tok::colon
905
1
        << FixItHint::CreateInsertion(ExpectedLoc, ":");
906
1
    ColonLoc = ExpectedLoc;
907
1
  }
908
909
2.11k
  StmtResult SubStmt;
910
911
2.11k
  if (Tok.isNot(tok::r_brace)) {
912
2.10k
    SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
913
2.10k
  } else {
914
    // Diagnose the common error "switch (X) {... default: }", which is
915
    // not valid.
916
3
    SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
917
3
    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
918
3
      << FixItHint::CreateInsertion(AfterColonLoc, " ;");
919
3
    SubStmt = true;
920
3
  }
921
922
  // Broken sub-stmt shouldn't prevent forming the case statement properly.
923
2.11k
  if (SubStmt.isInvalid())
924
6
    SubStmt = Actions.ActOnNullStmt(ColonLoc);
925
926
2.11k
  return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
927
2.11k
                                  SubStmt.get(), getCurScope());
928
2.11k
}
929
930
530k
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
931
530k
  return ParseCompoundStatement(isStmtExpr,
932
530k
                                Scope::DeclScope | Scope::CompoundStmtScope);
933
530k
}
934
935
/// ParseCompoundStatement - Parse a "{}" block.
936
///
937
///       compound-statement: [C99 6.8.2]
938
///         { block-item-list[opt] }
939
/// [GNU]   { label-declarations block-item-list } [TODO]
940
///
941
///       block-item-list:
942
///         block-item
943
///         block-item-list block-item
944
///
945
///       block-item:
946
///         declaration
947
/// [GNU]   '__extension__' declaration
948
///         statement
949
///
950
/// [GNU] label-declarations:
951
/// [GNU]   label-declaration
952
/// [GNU]   label-declarations label-declaration
953
///
954
/// [GNU] label-declaration:
955
/// [GNU]   '__label__' identifier-list ';'
956
///
957
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
958
545k
                                          unsigned ScopeFlags) {
959
545k
  assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
960
961
  // Enter a scope to hold everything within the compound stmt.  Compound
962
  // statements can always hold declarations.
963
0
  ParseScope CompoundScope(this, ScopeFlags);
964
965
  // Parse the statements in the body.
966
545k
  return ParseCompoundStatementBody(isStmtExpr);
967
545k
}
968
969
/// Parse any pragmas at the start of the compound expression. We handle these
970
/// separately since some pragmas (FP_CONTRACT) must appear before any C
971
/// statement in the compound, but may be intermingled with other pragmas.
972
4.42M
void Parser::ParseCompoundStatementLeadingPragmas() {
973
4.42M
  bool checkForPragmas = true;
974
8.85M
  while (checkForPragmas) {
975
4.42M
    switch (Tok.getKind()) {
976
2
    case tok::annot_pragma_vis:
977
2
      HandlePragmaVisibility();
978
2
      break;
979
5
    case tok::annot_pragma_pack:
980
5
      HandlePragmaPack();
981
5
      break;
982
0
    case tok::annot_pragma_msstruct:
983
0
      HandlePragmaMSStruct();
984
0
      break;
985
1
    case tok::annot_pragma_align:
986
1
      HandlePragmaAlign();
987
1
      break;
988
1
    case tok::annot_pragma_weak:
989
1
      HandlePragmaWeak();
990
1
      break;
991
0
    case tok::annot_pragma_weakalias:
992
0
      HandlePragmaWeakAlias();
993
0
      break;
994
0
    case tok::annot_pragma_redefine_extname:
995
0
      HandlePragmaRedefineExtname();
996
0
      break;
997
0
    case tok::annot_pragma_opencl_extension:
998
0
      HandlePragmaOpenCLExtension();
999
0
      break;
1000
24
    case tok::annot_pragma_fp_contract:
1001
24
      HandlePragmaFPContract();
1002
24
      break;
1003
153
    case tok::annot_pragma_fp:
1004
153
      HandlePragmaFP();
1005
153
      break;
1006
53
    case tok::annot_pragma_fenv_access:
1007
53
    case tok::annot_pragma_fenv_access_ms:
1008
53
      HandlePragmaFEnvAccess();
1009
53
      break;
1010
56
    case tok::annot_pragma_fenv_round:
1011
56
      HandlePragmaFEnvRound();
1012
56
      break;
1013
179
    case tok::annot_pragma_float_control:
1014
179
      HandlePragmaFloatControl();
1015
179
      break;
1016
0
    case tok::annot_pragma_ms_pointers_to_members:
1017
0
      HandlePragmaMSPointersToMembers();
1018
0
      break;
1019
11
    case tok::annot_pragma_ms_pragma:
1020
11
      HandlePragmaMSPragma();
1021
11
      break;
1022
4
    case tok::annot_pragma_ms_vtordisp:
1023
4
      HandlePragmaMSVtorDisp();
1024
4
      break;
1025
0
    case tok::annot_pragma_dump:
1026
0
      HandlePragmaDump();
1027
0
      break;
1028
4.42M
    default:
1029
4.42M
      checkForPragmas = false;
1030
4.42M
      break;
1031
4.42M
    }
1032
4.42M
  }
1033
1034
4.42M
}
1035
1036
/// Consume any extra semi-colons resulting in null statements,
1037
/// returning true if any tok::semi were consumed.
1038
7.78M
bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
1039
7.78M
  if (!Tok.is(tok::semi))
1040
7.77M
    return false;
1041
1042
11.1k
  SourceLocation StartLoc = Tok.getLocation();
1043
11.1k
  SourceLocation EndLoc;
1044
1045
22.1k
  while (Tok.is(tok::semi) && 
!Tok.hasLeadingEmptyMacro()11.2k
&&
1046
22.1k
         
Tok.getLocation().isValid()10.9k
&&
!Tok.getLocation().isMacroID()10.9k
) {
1047
10.9k
    EndLoc = Tok.getLocation();
1048
1049
    // Don't just ConsumeToken() this tok::semi, do store it in AST.
1050
10.9k
    StmtResult R =
1051
10.9k
        ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
1052
10.9k
    if (R.isUsable())
1053
10.9k
      Stmts.push_back(R.get());
1054
10.9k
  }
1055
1056
  // Did not consume any extra semi.
1057
11.1k
  if (EndLoc.isInvalid())
1058
333
    return false;
1059
1060
10.8k
  Diag(StartLoc, diag::warn_null_statement)
1061
10.8k
      << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
1062
10.8k
  return true;
1063
11.1k
}
1064
1065
2.46M
StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
1066
2.46M
  bool IsStmtExprResult = false;
1067
2.46M
  if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
1068
    // For GCC compatibility we skip past NullStmts.
1069
13.3k
    unsigned LookAhead = 0;
1070
13.3k
    while (GetLookAheadToken(LookAhead).is(tok::semi)) {
1071
10
      ++LookAhead;
1072
10
    }
1073
    // Then look to see if the next two tokens close the statement expression;
1074
    // if so, this expression statement is the last statement in a statment
1075
    // expression.
1076
13.3k
    IsStmtExprResult = GetLookAheadToken(LookAhead).is(tok::r_brace) &&
1077
13.3k
                       
GetLookAheadToken(LookAhead + 1).is(tok::r_paren)7.76k
;
1078
13.3k
  }
1079
1080
2.46M
  if (IsStmtExprResult)
1081
7.76k
    E = Actions.ActOnStmtExprResult(E);
1082
2.46M
  return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);
1083
2.46M
}
1084
1085
/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
1086
/// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
1087
/// consume the '}' at the end of the block.  It does not manipulate the scope
1088
/// stack.
1089
4.42M
StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
1090
4.42M
  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
1091
4.42M
                                Tok.getLocation(),
1092
4.42M
                                "in compound statement ('{}')");
1093
1094
  // Record the current FPFeatures, restore on leaving the
1095
  // compound statement.
1096
4.42M
  Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1097
1098
4.42M
  InMessageExpressionRAIIObject InMessage(*this, false);
1099
4.42M
  BalancedDelimiterTracker T(*this, tok::l_brace);
1100
4.42M
  if (T.consumeOpen())
1101
4
    return StmtError();
1102
1103
4.42M
  Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
1104
1105
  // Parse any pragmas at the beginning of the compound statement.
1106
4.42M
  ParseCompoundStatementLeadingPragmas();
1107
4.42M
  Actions.ActOnAfterCompoundStatementLeadingPragmas();
1108
1109
4.42M
  StmtVector Stmts;
1110
1111
  // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
1112
  // only allowed at the start of a compound stmt regardless of the language.
1113
4.42M
  while (Tok.is(tok::kw___label__)) {
1114
11
    SourceLocation LabelLoc = ConsumeToken();
1115
1116
11
    SmallVector<Decl *, 8> DeclsInGroup;
1117
11
    while (true) {
1118
11
      if (Tok.isNot(tok::identifier)) {
1119
0
        Diag(Tok, diag::err_expected) << tok::identifier;
1120
0
        break;
1121
0
      }
1122
1123
11
      IdentifierInfo *II = Tok.getIdentifierInfo();
1124
11
      SourceLocation IdLoc = ConsumeToken();
1125
11
      DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
1126
1127
11
      if (!TryConsumeToken(tok::comma))
1128
11
        break;
1129
11
    }
1130
1131
11
    DeclSpec DS(AttrFactory);
1132
11
    DeclGroupPtrTy Res =
1133
11
        Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1134
11
    StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
1135
1136
11
    ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
1137
11
    if (R.isUsable())
1138
11
      Stmts.push_back(R.get());
1139
11
  }
1140
1141
4.42M
  ParsedStmtContext SubStmtCtx =
1142
4.42M
      ParsedStmtContext::Compound |
1143
4.42M
      (isStmtExpr ? 
ParsedStmtContext::InStmtExpr8.96k
:
ParsedStmtContext()4.41M
);
1144
1145
12.2M
  while (!tryParseMisplacedModuleImport() && 
Tok.isNot(tok::r_brace)12.2M
&&
1146
12.2M
         
Tok.isNot(tok::eof)7.78M
) {
1147
7.78M
    if (Tok.is(tok::annot_pragma_unused)) {
1148
24
      HandlePragmaUnused();
1149
24
      continue;
1150
24
    }
1151
1152
7.78M
    if (ConsumeNullStmt(Stmts))
1153
10.8k
      continue;
1154
1155
7.77M
    StmtResult R;
1156
7.77M
    if (Tok.isNot(tok::kw___extension__)) {
1157
7.77M
      R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
1158
7.77M
    } else {
1159
      // __extension__ can start declarations and it can also be a unary
1160
      // operator for expressions.  Consume multiple __extension__ markers here
1161
      // until we can determine which is which.
1162
      // FIXME: This loses extension expressions in the AST!
1163
3.62k
      SourceLocation ExtLoc = ConsumeToken();
1164
3.62k
      while (Tok.is(tok::kw___extension__))
1165
0
        ConsumeToken();
1166
1167
3.62k
      ParsedAttributes attrs(AttrFactory);
1168
3.62k
      MaybeParseCXX11Attributes(attrs, /*MightBeObjCMessageSend*/ true);
1169
1170
      // If this is the start of a declaration, parse it as such.
1171
3.62k
      if (isDeclarationStatement()) {
1172
        // __extension__ silences extension warnings in the subdeclaration.
1173
        // FIXME: Save the __extension__ on the decl as a node somehow?
1174
17
        ExtensionRAIIObject O(Diags);
1175
1176
17
        SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1177
17
        ParsedAttributes DeclSpecAttrs(AttrFactory);
1178
17
        DeclGroupPtrTy Res = ParseDeclaration(DeclaratorContext::Block, DeclEnd,
1179
17
                                              attrs, DeclSpecAttrs);
1180
17
        R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1181
3.60k
      } else {
1182
        // Otherwise this was a unary __extension__ marker.
1183
3.60k
        ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1184
1185
3.60k
        if (Res.isInvalid()) {
1186
1
          SkipUntil(tok::semi);
1187
1
          continue;
1188
1
        }
1189
1190
        // Eat the semicolon at the end of stmt and convert the expr into a
1191
        // statement.
1192
3.60k
        ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1193
3.60k
        R = handleExprStmt(Res, SubStmtCtx);
1194
3.60k
        if (R.isUsable())
1195
3.60k
          R = Actions.ActOnAttributedStmt(attrs, R.get());
1196
3.60k
      }
1197
3.62k
    }
1198
1199
7.77M
    if (R.isUsable())
1200
7.74M
      Stmts.push_back(R.get());
1201
7.77M
  }
1202
  // Warn the user that using option `-ffp-eval-method=source` on a
1203
  // 32-bit target and feature `sse` disabled, or using
1204
  // `pragma clang fp eval_method=source` and feature `sse` disabled, is not
1205
  // supported.
1206
4.42M
  if (!PP.getTargetInfo().supportSourceEvalMethod() &&
1207
4.42M
      
(224k
PP.getLastFPEvalPragmaLocation().isValid()224k
||
1208
224k
       PP.getCurrentFPEvalMethod() ==
1209
224k
           LangOptions::FPEvalMethodKind::FEM_Source))
1210
107
    Diag(Tok.getLocation(),
1211
107
         diag::warn_no_support_for_eval_method_source_on_m32);
1212
1213
4.42M
  SourceLocation CloseLoc = Tok.getLocation();
1214
1215
  // We broke out of the while loop because we found a '}' or EOF.
1216
4.42M
  if (!T.consumeClose()) {
1217
    // If this is the '})' of a statement expression, check that it's written
1218
    // in a sensible way.
1219
4.42M
    if (isStmtExpr && 
Tok.is(tok::r_paren)8.96k
)
1220
8.95k
      checkCompoundToken(CloseLoc, tok::r_brace, CompoundToken::StmtExprEnd);
1221
4.42M
  } else {
1222
    // Recover by creating a compound statement with what we parsed so far,
1223
    // instead of dropping everything and returning StmtError().
1224
2.08k
  }
1225
1226
4.42M
  if (T.getCloseLocation().isValid())
1227
4.42M
    CloseLoc = T.getCloseLocation();
1228
1229
4.42M
  return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1230
4.42M
                                   Stmts, isStmtExpr);
1231
4.42M
}
1232
1233
/// ParseParenExprOrCondition:
1234
/// [C  ]     '(' expression ')'
1235
/// [C++]     '(' condition ')'
1236
/// [C++1z]   '(' init-statement[opt] condition ')'
1237
///
1238
/// This function parses and performs error recovery on the specified condition
1239
/// or expression (depending on whether we're in C++ or C mode).  This function
1240
/// goes out of its way to recover well.  It returns true if there was a parser
1241
/// error (the right paren couldn't be found), which indicates that the caller
1242
/// should try to recover harder.  It returns false if the condition is
1243
/// successfully parsed.  Note that a successful parse can still have semantic
1244
/// errors in the condition.
1245
/// Additionally, if LParenLoc and RParenLoc are non-null, it will assign
1246
/// the location of the outer-most '(' and ')', respectively, to them.
1247
bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1248
                                       Sema::ConditionResult &Cond,
1249
                                       SourceLocation Loc,
1250
                                       Sema::ConditionKind CK, bool MissingOK,
1251
                                       SourceLocation *LParenLoc,
1252
652k
                                       SourceLocation *RParenLoc) {
1253
652k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1254
652k
  T.consumeOpen();
1255
652k
  SourceLocation Start = Tok.getLocation();
1256
1257
652k
  if (getLangOpts().CPlusPlus) {
1258
627k
    Cond = ParseCXXCondition(InitStmt, Loc, CK, MissingOK);
1259
627k
  } else {
1260
25.1k
    ExprResult CondExpr = ParseExpression();
1261
1262
    // If required, convert to a boolean value.
1263
25.1k
    if (CondExpr.isInvalid())
1264
7
      Cond = Sema::ConditionError();
1265
25.1k
    else
1266
25.1k
      Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,
1267
25.1k
                                    MissingOK);
1268
25.1k
  }
1269
1270
  // If the parser was confused by the condition and we don't have a ')', try to
1271
  // recover by skipping ahead to a semi and bailing out.  If condexp is
1272
  // semantically invalid but we have well formed code, keep going.
1273
652k
  if (Cond.isInvalid() && 
Tok.isNot(tok::r_paren)124
) {
1274
29
    SkipUntil(tok::semi);
1275
    // Skipping may have stopped if it found the containing ')'.  If so, we can
1276
    // continue parsing the if statement.
1277
29
    if (Tok.isNot(tok::r_paren))
1278
17
      return true;
1279
29
  }
1280
1281
652k
  if (Cond.isInvalid()) {
1282
107
    ExprResult CondExpr = Actions.CreateRecoveryExpr(
1283
107
        Start, Tok.getLocation() == Start ? 
Start0
: PrevTokLocation, {},
1284
107
        Actions.PreferredConditionType(CK));
1285
107
    if (!CondExpr.isInvalid())
1286
103
      Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,
1287
103
                                    MissingOK);
1288
107
  }
1289
1290
  // Either the condition is valid or the rparen is present.
1291
652k
  T.consumeClose();
1292
1293
652k
  if (LParenLoc != nullptr) {
1294
652k
    *LParenLoc = T.getOpenLocation();
1295
652k
  }
1296
652k
  if (RParenLoc != nullptr) {
1297
652k
    *RParenLoc = T.getCloseLocation();
1298
652k
  }
1299
1300
  // Check for extraneous ')'s to catch things like "if (foo())) {".  We know
1301
  // that all callers are looking for a statement after the condition, so ")"
1302
  // isn't valid.
1303
652k
  while (Tok.is(tok::r_paren)) {
1304
1
    Diag(Tok, diag::err_extraneous_rparen_in_condition)
1305
1
      << FixItHint::CreateRemoval(Tok.getLocation());
1306
1
    ConsumeParen();
1307
1
  }
1308
1309
652k
  return false;
1310
652k
}
1311
1312
namespace {
1313
1314
enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
1315
1316
struct MisleadingIndentationChecker {
1317
  Parser &P;
1318
  SourceLocation StmtLoc;
1319
  SourceLocation PrevLoc;
1320
  unsigned NumDirectives;
1321
  MisleadingStatementKind Kind;
1322
  bool ShouldSkip;
1323
  MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
1324
                               SourceLocation SL)
1325
      : P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),
1326
        NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),
1327
978k
        ShouldSkip(P.getCurToken().is(tok::l_brace)) {
1328
978k
    if (!P.MisleadingIndentationElseLoc.isInvalid()) {
1329
22.5k
      StmtLoc = P.MisleadingIndentationElseLoc;
1330
22.5k
      P.MisleadingIndentationElseLoc = SourceLocation();
1331
22.5k
    }
1332
978k
    if (Kind == MSK_else && 
!ShouldSkip111k
)
1333
51.4k
      P.MisleadingIndentationElseLoc = SL;
1334
978k
  }
1335
1336
  /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1337
  /// gives the visual indentation of the SourceLocation.
1338
1.17k
  static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {
1339
1.17k
    unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;
1340
1341
1.17k
    unsigned ColNo = SM.getSpellingColumnNumber(Loc);
1342
1.17k
    if (ColNo == 0 || TabStop == 1)
1343
66
      return ColNo;
1344
1345
1.11k
    std::pair<FileID, unsigned> FIDAndOffset = SM.getDecomposedLoc(Loc);
1346
1347
1.11k
    bool Invalid;
1348
1.11k
    StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid);
1349
1.11k
    if (Invalid)
1350
0
      return 0;
1351
1352
1.11k
    const char *EndPos = BufData.data() + FIDAndOffset.second;
1353
    // FileOffset are 0-based and Column numbers are 1-based
1354
1.11k
    assert(FIDAndOffset.second + 1 >= ColNo &&
1355
1.11k
           "Column number smaller than file offset?");
1356
1357
0
    unsigned VisualColumn = 0; // Stored as 0-based column, here.
1358
    // Loop from beginning of line up to Loc's file position, counting columns,
1359
    // expanding tabs.
1360
5.23k
    for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
1361
4.12k
         ++CurPos) {
1362
4.12k
      if (*CurPos == '\t')
1363
        // Advance visual column to next tabstop.
1364
42
        VisualColumn += (TabStop - VisualColumn % TabStop);
1365
4.07k
      else
1366
4.07k
        VisualColumn++;
1367
4.12k
    }
1368
1.11k
    return VisualColumn + 1;
1369
1.11k
  }
1370
1371
866k
  void Check() {
1372
866k
    Token Tok = P.getCurToken();
1373
866k
    if (P.getActions().getDiagnostics().isIgnored(
1374
866k
            diag::warn_misleading_indentation, Tok.getLocation()) ||
1375
866k
        
ShouldSkip942
||
NumDirectives != P.getPreprocessor().getNumDirectives()485
||
1376
866k
        
Tok.isOneOf(tok::semi, tok::r_brace)460
||
Tok.isAnnotation()412
||
1377
866k
        
Tok.getLocation().isMacroID()412
||
PrevLoc.isMacroID()408
||
1378
866k
        
StmtLoc.isMacroID()404
||
1379
866k
        
(404
Kind == MSK_else404
&&
P.MisleadingIndentationElseLoc.isInvalid()24
)) {
1380
866k
      P.MisleadingIndentationElseLoc = SourceLocation();
1381
866k
      return;
1382
866k
    }
1383
392
    if (Kind == MSK_else)
1384
12
      P.MisleadingIndentationElseLoc = SourceLocation();
1385
1386
392
    SourceManager &SM = P.getPreprocessor().getSourceManager();
1387
392
    unsigned PrevColNum = getVisualIndentation(SM, PrevLoc);
1388
392
    unsigned CurColNum = getVisualIndentation(SM, Tok.getLocation());
1389
392
    unsigned StmtColNum = getVisualIndentation(SM, StmtLoc);
1390
1391
392
    if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&
1392
392
        ((PrevColNum > StmtColNum && 
PrevColNum == CurColNum384
) ||
1393
392
         
!Tok.isAtStartOfLine()346
) &&
1394
392
        SM.getPresumedLineNumber(StmtLoc) !=
1395
59
            SM.getPresumedLineNumber(Tok.getLocation()) &&
1396
392
        
(50
Tok.isNot(tok::identifier)50
||
1397
50
         
P.getPreprocessor().LookAhead(0).isNot(tok::colon)26
)) {
1398
46
      P.Diag(Tok.getLocation(), diag::warn_misleading_indentation) << Kind;
1399
46
      P.Diag(StmtLoc, diag::note_previous_statement);
1400
46
    }
1401
392
  }
1402
};
1403
1404
}
1405
1406
/// ParseIfStatement
1407
///       if-statement: [C99 6.8.4.1]
1408
///         'if' '(' expression ')' statement
1409
///         'if' '(' expression ')' statement 'else' statement
1410
/// [C++]   'if' '(' condition ')' statement
1411
/// [C++]   'if' '(' condition ')' statement 'else' statement
1412
/// [C++23] 'if' '!' [opt] consteval compound-statement
1413
/// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
1414
///
1415
596k
StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1416
596k
  assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1417
0
  SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
1418
1419
596k
  bool IsConstexpr = false;
1420
596k
  bool IsConsteval = false;
1421
596k
  SourceLocation NotLocation;
1422
596k
  SourceLocation ConstevalLoc;
1423
1424
596k
  if (Tok.is(tok::kw_constexpr)) {
1425
555
    Diag(Tok, getLangOpts().CPlusPlus17 ? 
diag::warn_cxx14_compat_constexpr_if551
1426
555
                                        : 
diag::ext_constexpr_if4
);
1427
555
    IsConstexpr = true;
1428
555
    ConsumeToken();
1429
595k
  } else {
1430
595k
    if (Tok.is(tok::exclaim)) {
1431
24
      NotLocation = ConsumeToken();
1432
24
    }
1433
1434
595k
    if (Tok.is(tok::kw_consteval)) {
1435
59
      Diag(Tok, getLangOpts().CPlusPlus2b ? 
diag::warn_cxx20_compat_consteval_if51
1436
59
                                          : 
diag::ext_consteval_if8
);
1437
59
      IsConsteval = true;
1438
59
      ConstevalLoc = ConsumeToken();
1439
59
    }
1440
595k
  }
1441
596k
  if (!IsConsteval && 
(596k
NotLocation.isValid()596k
||
Tok.isNot(tok::l_paren)596k
)) {
1442
0
    Diag(Tok, diag::err_expected_lparen_after) << "if";
1443
0
    SkipUntil(tok::semi);
1444
0
    return StmtError();
1445
0
  }
1446
1447
596k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus572k
;
1448
1449
  // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
1450
  // the case for C90.
1451
  //
1452
  // C++ 6.4p3:
1453
  // A name introduced by a declaration in a condition is in scope from its
1454
  // point of declaration until the end of the substatements controlled by the
1455
  // condition.
1456
  // C++ 3.3.2p4:
1457
  // Names declared in the for-init-statement, and in the condition of if,
1458
  // while, for, and switch statements are local to the if, while, for, or
1459
  // switch statement (including the controlled statement).
1460
  //
1461
596k
  ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1462
1463
  // Parse the condition.
1464
596k
  StmtResult InitStmt;
1465
596k
  Sema::ConditionResult Cond;
1466
596k
  SourceLocation LParen;
1467
596k
  SourceLocation RParen;
1468
596k
  llvm::Optional<bool> ConstexprCondition;
1469
596k
  if (!IsConsteval) {
1470
1471
596k
    if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1472
596k
                                  IsConstexpr ? 
Sema::ConditionKind::ConstexprIf555
1473
596k
                                              : 
Sema::ConditionKind::Boolean595k
,
1474
596k
                                  /*MissingOK=*/false, &LParen, &RParen))
1475
10
      return StmtError();
1476
1477
596k
    if (IsConstexpr)
1478
555
      ConstexprCondition = Cond.getKnownValue();
1479
596k
  }
1480
1481
596k
  bool IsBracedThen = Tok.is(tok::l_brace);
1482
1483
  // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1484
  // there is no compound stmt.  C90 does not have this clause.  We only do this
1485
  // if the body isn't a compound statement to avoid push/pop in common cases.
1486
  //
1487
  // C++ 6.4p1:
1488
  // The substatement in a selection-statement (each substatement, in the else
1489
  // form of the if statement) implicitly defines a local scope.
1490
  //
1491
  // For C++ we create a scope for the condition and a new scope for
1492
  // substatements because:
1493
  // -When the 'then' scope exits, we want the condition declaration to still be
1494
  //    active for the 'else' scope too.
1495
  // -Sema will detect name clashes by considering declarations of a
1496
  //    'ControlScope' as part of its direct subscope.
1497
  // -If we wanted the condition and substatement to be in the same scope, we
1498
  //    would have to notify ParseStatement not to create a new scope. It's
1499
  //    simpler to let it create a new scope.
1500
  //
1501
596k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
1502
1503
596k
  MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
1504
1505
  // Read the 'then' stmt.
1506
596k
  SourceLocation ThenStmtLoc = Tok.getLocation();
1507
1508
596k
  SourceLocation InnerStatementTrailingElseLoc;
1509
596k
  StmtResult ThenStmt;
1510
596k
  {
1511
596k
    bool ShouldEnter = ConstexprCondition && 
!*ConstexprCondition90
;
1512
596k
    Sema::ExpressionEvaluationContext Context =
1513
596k
        Sema::ExpressionEvaluationContext::DiscardedStatement;
1514
596k
    if (NotLocation.isInvalid() && 
IsConsteval596k
) {
1515
35
      Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
1516
35
      ShouldEnter = true;
1517
35
    }
1518
1519
596k
    EnterExpressionEvaluationContext PotentiallyDiscarded(
1520
596k
        Actions, Context, nullptr,
1521
596k
        Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1522
596k
    ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1523
596k
  }
1524
1525
596k
  if (Tok.isNot(tok::kw_else))
1526
484k
    MIChecker.Check();
1527
1528
  // Pop the 'if' scope if needed.
1529
596k
  InnerScope.Exit();
1530
1531
  // If it has an else, parse it.
1532
596k
  SourceLocation ElseLoc;
1533
596k
  SourceLocation ElseStmtLoc;
1534
596k
  StmtResult ElseStmt;
1535
1536
596k
  if (Tok.is(tok::kw_else)) {
1537
111k
    if (TrailingElseLoc)
1538
11
      *TrailingElseLoc = Tok.getLocation();
1539
1540
111k
    ElseLoc = ConsumeToken();
1541
111k
    ElseStmtLoc = Tok.getLocation();
1542
1543
    // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1544
    // there is no compound stmt.  C90 does not have this clause.  We only do
1545
    // this if the body isn't a compound statement to avoid push/pop in common
1546
    // cases.
1547
    //
1548
    // C++ 6.4p1:
1549
    // The substatement in a selection-statement (each substatement, in the else
1550
    // form of the if statement) implicitly defines a local scope.
1551
    //
1552
111k
    ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1553
111k
                          Tok.is(tok::l_brace));
1554
1555
111k
    MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
1556
111k
    bool ShouldEnter = ConstexprCondition && 
*ConstexprCondition48
;
1557
111k
    Sema::ExpressionEvaluationContext Context =
1558
111k
        Sema::ExpressionEvaluationContext::DiscardedStatement;
1559
111k
    if (NotLocation.isValid() && 
IsConsteval11
) {
1560
11
      Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
1561
11
      ShouldEnter = true;
1562
11
    }
1563
1564
111k
    EnterExpressionEvaluationContext PotentiallyDiscarded(
1565
111k
        Actions, Context, nullptr,
1566
111k
        Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1567
111k
    ElseStmt = ParseStatement();
1568
1569
111k
    if (ElseStmt.isUsable())
1570
111k
      MIChecker.Check();
1571
1572
    // Pop the 'else' scope if needed.
1573
111k
    InnerScope.Exit();
1574
484k
  } else if (Tok.is(tok::code_completion)) {
1575
4
    cutOffParsing();
1576
4
    Actions.CodeCompleteAfterIf(getCurScope(), IsBracedThen);
1577
4
    return StmtError();
1578
484k
  } else if (InnerStatementTrailingElseLoc.isValid()) {
1579
6
    Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1580
6
  }
1581
1582
596k
  IfScope.Exit();
1583
1584
  // If the then or else stmt is invalid and the other is valid (and present),
1585
  // make turn the invalid one into a null stmt to avoid dropping the other
1586
  // part.  If both are invalid, return error.
1587
596k
  if ((ThenStmt.isInvalid() && 
ElseStmt.isInvalid()341
) ||
1588
596k
      (ThenStmt.isInvalid() && 
ElseStmt.get() == nullptr341
) ||
1589
596k
      
(596k
ThenStmt.get() == nullptr596k
&&
ElseStmt.isInvalid()81
)) {
1590
    // Both invalid, or one is invalid and other is non-present: return error.
1591
260
    return StmtError();
1592
260
  }
1593
1594
596k
  if (IsConsteval) {
1595
84
    auto IsCompoundStatement = [](const Stmt *S) {
1596
84
      if (const auto *Outer = dyn_cast_or_null<AttributedStmt>(S))
1597
2
        S = Outer->getSubStmt();
1598
84
      return isa_and_nonnull<clang::CompoundStmt>(S);
1599
84
    };
1600
1601
59
    if (!IsCompoundStatement(ThenStmt.get())) {
1602
2
      Diag(ConstevalLoc, diag::err_expected_after) << "consteval"
1603
2
                                                   << "{";
1604
2
      return StmtError();
1605
2
    }
1606
57
    if (!ElseStmt.isUnset() && 
!IsCompoundStatement(ElseStmt.get())25
) {
1607
1
      Diag(ElseLoc, diag::err_expected_after) << "else"
1608
1
                                              << "{";
1609
1
      return StmtError();
1610
1
    }
1611
57
  }
1612
1613
  // Now if either are invalid, replace with a ';'.
1614
596k
  if (ThenStmt.isInvalid())
1615
81
    ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1616
596k
  if (ElseStmt.isInvalid())
1617
1
    ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1618
1619
596k
  IfStatementKind Kind = IfStatementKind::Ordinary;
1620
596k
  if (IsConstexpr)
1621
555
    Kind = IfStatementKind::Constexpr;
1622
595k
  else if (IsConsteval)
1623
56
    Kind = NotLocation.isValid() ? 
IfStatementKind::ConstevalNegated24
1624
56
                                 : 
IfStatementKind::ConstevalNonNegated32
;
1625
1626
596k
  return Actions.ActOnIfStmt(IfLoc, Kind, LParen, InitStmt.get(), Cond, RParen,
1627
596k
                             ThenStmt.get(), ElseLoc, ElseStmt.get());
1628
596k
}
1629
1630
/// ParseSwitchStatement
1631
///       switch-statement:
1632
///         'switch' '(' expression ')' statement
1633
/// [C++]   'switch' '(' condition ')' statement
1634
6.48k
StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1635
6.48k
  assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1636
0
  SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
1637
1638
6.48k
  if (Tok.isNot(tok::l_paren)) {
1639
0
    Diag(Tok, diag::err_expected_lparen_after) << "switch";
1640
0
    SkipUntil(tok::semi);
1641
0
    return StmtError();
1642
0
  }
1643
1644
6.48k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus5.83k
;
1645
1646
  // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
1647
  // not the case for C90.  Start the switch scope.
1648
  //
1649
  // C++ 6.4p3:
1650
  // A name introduced by a declaration in a condition is in scope from its
1651
  // point of declaration until the end of the substatements controlled by the
1652
  // condition.
1653
  // C++ 3.3.2p4:
1654
  // Names declared in the for-init-statement, and in the condition of if,
1655
  // while, for, and switch statements are local to the if, while, for, or
1656
  // switch statement (including the controlled statement).
1657
  //
1658
6.48k
  unsigned ScopeFlags = Scope::SwitchScope;
1659
6.48k
  if (C99orCXX)
1660
6.45k
    ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1661
6.48k
  ParseScope SwitchScope(this, ScopeFlags);
1662
1663
  // Parse the condition.
1664
6.48k
  StmtResult InitStmt;
1665
6.48k
  Sema::ConditionResult Cond;
1666
6.48k
  SourceLocation LParen;
1667
6.48k
  SourceLocation RParen;
1668
6.48k
  if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1669
6.48k
                                Sema::ConditionKind::Switch,
1670
6.48k
                                /*MissingOK=*/false, &LParen, &RParen))
1671
2
    return StmtError();
1672
1673
6.48k
  StmtResult Switch = Actions.ActOnStartOfSwitchStmt(
1674
6.48k
      SwitchLoc, LParen, InitStmt.get(), Cond, RParen);
1675
1676
6.48k
  if (Switch.isInvalid()) {
1677
    // Skip the switch body.
1678
    // FIXME: This is not optimal recovery, but parsing the body is more
1679
    // dangerous due to the presence of case and default statements, which
1680
    // will have no place to connect back with the switch.
1681
1
    if (Tok.is(tok::l_brace)) {
1682
1
      ConsumeBrace();
1683
1
      SkipUntil(tok::r_brace);
1684
1
    } else
1685
0
      SkipUntil(tok::semi);
1686
1
    return Switch;
1687
1
  }
1688
1689
  // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1690
  // there is no compound stmt.  C90 does not have this clause.  We only do this
1691
  // if the body isn't a compound statement to avoid push/pop in common cases.
1692
  //
1693
  // C++ 6.4p1:
1694
  // The substatement in a selection-statement (each substatement, in the else
1695
  // form of the if statement) implicitly defines a local scope.
1696
  //
1697
  // See comments in ParseIfStatement for why we create a scope for the
1698
  // condition and a new scope for substatement in C++.
1699
  //
1700
6.47k
  getCurScope()->AddFlags(Scope::BreakScope);
1701
6.47k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1702
1703
  // We have incremented the mangling number for the SwitchScope and the
1704
  // InnerScope, which is one too many.
1705
6.47k
  if (C99orCXX)
1706
6.45k
    getCurScope()->decrementMSManglingNumber();
1707
1708
  // Read the body statement.
1709
6.47k
  StmtResult Body(ParseStatement(TrailingElseLoc));
1710
1711
  // Pop the scopes.
1712
6.47k
  InnerScope.Exit();
1713
6.47k
  SwitchScope.Exit();
1714
1715
6.47k
  return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1716
6.48k
}
1717
1718
/// ParseWhileStatement
1719
///       while-statement: [C99 6.8.5.1]
1720
///         'while' '(' expression ')' statement
1721
/// [C++]   'while' '(' condition ')' statement
1722
50.1k
StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1723
50.1k
  assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1724
0
  SourceLocation WhileLoc = Tok.getLocation();
1725
50.1k
  ConsumeToken();  // eat the 'while'.
1726
1727
50.1k
  if (Tok.isNot(tok::l_paren)) {
1728
0
    Diag(Tok, diag::err_expected_lparen_after) << "while";
1729
0
    SkipUntil(tok::semi);
1730
0
    return StmtError();
1731
0
  }
1732
1733
50.1k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus49.5k
;
1734
1735
  // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
1736
  // the case for C90.  Start the loop scope.
1737
  //
1738
  // C++ 6.4p3:
1739
  // A name introduced by a declaration in a condition is in scope from its
1740
  // point of declaration until the end of the substatements controlled by the
1741
  // condition.
1742
  // C++ 3.3.2p4:
1743
  // Names declared in the for-init-statement, and in the condition of if,
1744
  // while, for, and switch statements are local to the if, while, for, or
1745
  // switch statement (including the controlled statement).
1746
  //
1747
50.1k
  unsigned ScopeFlags;
1748
50.1k
  if (C99orCXX)
1749
50.1k
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1750
50.1k
                 Scope::DeclScope  | Scope::ControlScope;
1751
25
  else
1752
25
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1753
50.1k
  ParseScope WhileScope(this, ScopeFlags);
1754
1755
  // Parse the condition.
1756
50.1k
  Sema::ConditionResult Cond;
1757
50.1k
  SourceLocation LParen;
1758
50.1k
  SourceLocation RParen;
1759
50.1k
  if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1760
50.1k
                                Sema::ConditionKind::Boolean,
1761
50.1k
                                /*MissingOK=*/false, &LParen, &RParen))
1762
5
    return StmtError();
1763
1764
  // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1765
  // there is no compound stmt.  C90 does not have this clause.  We only do this
1766
  // if the body isn't a compound statement to avoid push/pop in common cases.
1767
  //
1768
  // C++ 6.5p2:
1769
  // The substatement in an iteration-statement implicitly defines a local scope
1770
  // which is entered and exited each time through the loop.
1771
  //
1772
  // See comments in ParseIfStatement for why we create a scope for the
1773
  // condition and a new scope for substatement in C++.
1774
  //
1775
50.1k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1776
1777
50.1k
  MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
1778
1779
  // Read the body statement.
1780
50.1k
  StmtResult Body(ParseStatement(TrailingElseLoc));
1781
1782
50.1k
  if (Body.isUsable())
1783
50.1k
    MIChecker.Check();
1784
  // Pop the body scope if needed.
1785
50.1k
  InnerScope.Exit();
1786
50.1k
  WhileScope.Exit();
1787
1788
50.1k
  if (Cond.isInvalid() || 
Body.isInvalid()50.1k
)
1789
10
    return StmtError();
1790
1791
50.1k
  return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get());
1792
50.1k
}
1793
1794
/// ParseDoStatement
1795
///       do-statement: [C99 6.8.5.2]
1796
///         'do' statement 'while' '(' expression ')' ';'
1797
/// Note: this lets the caller parse the end ';'.
1798
9.85k
StmtResult Parser::ParseDoStatement() {
1799
9.85k
  assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1800
0
  SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
1801
1802
  // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
1803
  // the case for C90.  Start the loop scope.
1804
9.85k
  unsigned ScopeFlags;
1805
9.85k
  if (getLangOpts().C99)
1806
282
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1807
9.57k
  else
1808
9.57k
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1809
1810
9.85k
  ParseScope DoScope(this, ScopeFlags);
1811
1812
  // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1813
  // there is no compound stmt.  C90 does not have this clause. We only do this
1814
  // if the body isn't a compound statement to avoid push/pop in common cases.
1815
  //
1816
  // C++ 6.5p2:
1817
  // The substatement in an iteration-statement implicitly defines a local scope
1818
  // which is entered and exited each time through the loop.
1819
  //
1820
9.85k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus9.57k
;
1821
9.85k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1822
1823
  // Read the body statement.
1824
9.85k
  StmtResult Body(ParseStatement());
1825
1826
  // Pop the body scope if needed.
1827
9.85k
  InnerScope.Exit();
1828
1829
9.85k
  if (Tok.isNot(tok::kw_while)) {
1830
6
    if (!Body.isInvalid()) {
1831
5
      Diag(Tok, diag::err_expected_while);
1832
5
      Diag(DoLoc, diag::note_matching) << "'do'";
1833
5
      SkipUntil(tok::semi, StopBeforeMatch);
1834
5
    }
1835
6
    return StmtError();
1836
6
  }
1837
9.84k
  SourceLocation WhileLoc = ConsumeToken();
1838
1839
9.84k
  if (Tok.isNot(tok::l_paren)) {
1840
0
    Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1841
0
    SkipUntil(tok::semi, StopBeforeMatch);
1842
0
    return StmtError();
1843
0
  }
1844
1845
  // Parse the parenthesized expression.
1846
9.84k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1847
9.84k
  T.consumeOpen();
1848
1849
  // A do-while expression is not a condition, so can't have attributes.
1850
9.84k
  DiagnoseAndSkipCXX11Attributes();
1851
1852
9.84k
  SourceLocation Start = Tok.getLocation();
1853
9.84k
  ExprResult Cond = ParseExpression();
1854
  // Correct the typos in condition before closing the scope.
1855
9.84k
  if (Cond.isUsable())
1856
9.84k
    Cond = Actions.CorrectDelayedTyposInExpr(Cond);
1857
6
  else {
1858
6
    if (!Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
1859
0
      SkipUntil(tok::semi);
1860
6
    Cond = Actions.CreateRecoveryExpr(
1861
6
        Start, Start == Tok.getLocation() ? 
Start3
:
PrevTokLocation3
, {},
1862
6
        Actions.getASTContext().BoolTy);
1863
6
  }
1864
9.84k
  T.consumeClose();
1865
9.84k
  DoScope.Exit();
1866
1867
9.84k
  if (Cond.isInvalid() || Body.isInvalid())
1868
8
    return StmtError();
1869
1870
9.83k
  return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1871
9.83k
                             Cond.get(), T.getCloseLocation());
1872
9.84k
}
1873
1874
51.5k
bool Parser::isForRangeIdentifier() {
1875
51.5k
  assert(Tok.is(tok::identifier));
1876
1877
0
  const Token &Next = NextToken();
1878
51.5k
  if (Next.is(tok::colon))
1879
3
    return true;
1880
1881
51.5k
  if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1882
118
    TentativeParsingAction PA(*this);
1883
118
    ConsumeToken();
1884
118
    SkipCXX11Attributes();
1885
118
    bool Result = Tok.is(tok::colon);
1886
118
    PA.Revert();
1887
118
    return Result;
1888
118
  }
1889
1890
51.4k
  return false;
1891
51.5k
}
1892
1893
/// ParseForStatement
1894
///       for-statement: [C99 6.8.5.3]
1895
///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1896
///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1897
/// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1898
/// [C++]       statement
1899
/// [C++0x] 'for'
1900
///             'co_await'[opt]    [Coroutines]
1901
///             '(' for-range-declaration ':' for-range-initializer ')'
1902
///             statement
1903
/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1904
/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1905
///
1906
/// [C++] for-init-statement:
1907
/// [C++]   expression-statement
1908
/// [C++]   simple-declaration
1909
/// [C++2b] alias-declaration
1910
///
1911
/// [C++0x] for-range-declaration:
1912
/// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
1913
/// [C++0x] for-range-initializer:
1914
/// [C++0x]   expression
1915
/// [C++0x]   braced-init-list            [TODO]
1916
220k
StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1917
220k
  assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1918
0
  SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
1919
1920
220k
  SourceLocation CoawaitLoc;
1921
220k
  if (Tok.is(tok::kw_co_await))
1922
16
    CoawaitLoc = ConsumeToken();
1923
1924
220k
  if (Tok.isNot(tok::l_paren)) {
1925
0
    Diag(Tok, diag::err_expected_lparen_after) << "for";
1926
0
    SkipUntil(tok::semi);
1927
0
    return StmtError();
1928
0
  }
1929
1930
220k
  bool C99orCXXorObjC = getLangOpts().C99 || 
getLangOpts().CPlusPlus211k
||
1931
220k
    
getLangOpts().ObjC58
;
1932
1933
  // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1934
  // the case for C90.  Start the loop scope.
1935
  //
1936
  // C++ 6.4p3:
1937
  // A name introduced by a declaration in a condition is in scope from its
1938
  // point of declaration until the end of the substatements controlled by the
1939
  // condition.
1940
  // C++ 3.3.2p4:
1941
  // Names declared in the for-init-statement, and in the condition of if,
1942
  // while, for, and switch statements are local to the if, while, for, or
1943
  // switch statement (including the controlled statement).
1944
  // C++ 6.5.3p1:
1945
  // Names declared in the for-init-statement are in the same declarative-region
1946
  // as those declared in the condition.
1947
  //
1948
220k
  unsigned ScopeFlags = 0;
1949
220k
  if (C99orCXXorObjC)
1950
220k
    ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1951
1952
220k
  ParseScope ForScope(this, ScopeFlags);
1953
1954
220k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1955
220k
  T.consumeOpen();
1956
1957
220k
  ExprResult Value;
1958
1959
220k
  bool ForEach = false;
1960
220k
  StmtResult FirstPart;
1961
220k
  Sema::ConditionResult SecondPart;
1962
220k
  ExprResult Collection;
1963
220k
  ForRangeInfo ForRangeInfo;
1964
220k
  FullExprArg ThirdPart(Actions);
1965
1966
220k
  if (Tok.is(tok::code_completion)) {
1967
6
    cutOffParsing();
1968
6
    Actions.CodeCompleteOrdinaryName(getCurScope(),
1969
6
                                     C99orCXXorObjC? Sema::PCC_ForInit
1970
6
                                                   : 
Sema::PCC_Expression0
);
1971
6
    return StmtError();
1972
6
  }
1973
1974
220k
  ParsedAttributes attrs(AttrFactory);
1975
220k
  MaybeParseCXX11Attributes(attrs);
1976
1977
220k
  SourceLocation EmptyInitStmtSemiLoc;
1978
1979
  // Parse the first part of the for specifier.
1980
220k
  if (Tok.is(tok::semi)) {  // for (;
1981
50.4k
    ProhibitAttributes(attrs);
1982
    // no first part, eat the ';'.
1983
50.4k
    SourceLocation SemiLoc = Tok.getLocation();
1984
50.4k
    if (!Tok.hasLeadingEmptyMacro() && 
!SemiLoc.isMacroID()50.4k
)
1985
50.4k
      EmptyInitStmtSemiLoc = SemiLoc;
1986
50.4k
    ConsumeToken();
1987
170k
  } else if (getLangOpts().CPlusPlus && 
Tok.is(tok::identifier)161k
&&
1988
170k
             
isForRangeIdentifier()51.5k
) {
1989
6
    ProhibitAttributes(attrs);
1990
6
    IdentifierInfo *Name = Tok.getIdentifierInfo();
1991
6
    SourceLocation Loc = ConsumeToken();
1992
6
    MaybeParseCXX11Attributes(attrs);
1993
1994
6
    ForRangeInfo.ColonLoc = ConsumeToken();
1995
6
    if (Tok.is(tok::l_brace))
1996
0
      ForRangeInfo.RangeExpr = ParseBraceInitializer();
1997
6
    else
1998
6
      ForRangeInfo.RangeExpr = ParseExpression();
1999
2000
6
    Diag(Loc, diag::err_for_range_identifier)
2001
6
      << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
2002
6
              ? FixItHint::CreateInsertion(Loc, "auto &&")
2003
6
              : 
FixItHint()0
);
2004
2005
6
    ForRangeInfo.LoopVar =
2006
6
        Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name, attrs);
2007
170k
  } else if (isForInitDeclaration()) {  // for (int X = 4;
2008
135k
    ParenBraceBracketBalancer BalancerRAIIObj(*this);
2009
2010
    // Parse declaration, which eats the ';'.
2011
135k
    if (!C99orCXXorObjC) {   // Use of C99-style for loops in C90 mode?
2012
5
      Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
2013
5
      Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
2014
5
    }
2015
135k
    DeclGroupPtrTy DG;
2016
135k
    if (Tok.is(tok::kw_using)) {
2017
6
      DG = ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit,
2018
6
                                                attrs);
2019
135k
    } else {
2020
      // In C++0x, "for (T NS:a" might not be a typo for ::
2021
135k
      bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
2022
135k
      ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
2023
2024
135k
      SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2025
135k
      ParsedAttributes DeclSpecAttrs(AttrFactory);
2026
135k
      DG = ParseSimpleDeclaration(
2027
135k
          DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false,
2028
135k
          MightBeForRangeStmt ? 
&ForRangeInfo133k
:
nullptr2.10k
);
2029
135k
      FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2030
135k
      if (ForRangeInfo.ParsedForRangeDecl()) {
2031
1.40k
        Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11
2032
1.40k
                                        ? 
diag::warn_cxx98_compat_for_range1.38k
2033
1.40k
                                        : 
diag::ext_for_range12
);
2034
1.40k
        ForRangeInfo.LoopVar = FirstPart;
2035
1.40k
        FirstPart = StmtResult();
2036
133k
      } else if (Tok.is(tok::semi)) { // for (int x = 4;
2037
133k
        ConsumeToken();
2038
133k
      } else 
if (238
(ForEach = isTokIdentifier_in())238
) {
2039
230
        Actions.ActOnForEachDeclStmt(DG);
2040
        // ObjC: for (id x in expr)
2041
230
        ConsumeToken(); // consume 'in'
2042
2043
230
        if (Tok.is(tok::code_completion)) {
2044
2
          cutOffParsing();
2045
2
          Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
2046
2
          return StmtError();
2047
2
        }
2048
228
        Collection = ParseExpression();
2049
228
      } else {
2050
8
        Diag(Tok, diag::err_expected_semi_for);
2051
8
      }
2052
135k
    }
2053
135k
  } else {
2054
34.9k
    ProhibitAttributes(attrs);
2055
34.9k
    Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2056
2057
34.9k
    ForEach = isTokIdentifier_in();
2058
2059
    // Turn the expression into a stmt.
2060
34.9k
    if (!Value.isInvalid()) {
2061
34.9k
      if (ForEach)
2062
49
        FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
2063
34.8k
      else {
2064
        // We already know this is not an init-statement within a for loop, so
2065
        // if we are parsing a C++11 range-based for loop, we should treat this
2066
        // expression statement as being a discarded value expression because
2067
        // we will err below. This way we do not warn on an unused expression
2068
        // that was an error in the first place, like with: for (expr : expr);
2069
34.8k
        bool IsRangeBasedFor =
2070
34.8k
            getLangOpts().CPlusPlus11 && 
!ForEach28.2k
&&
Tok.is(tok::colon)28.2k
;
2071
34.8k
        FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
2072
34.8k
      }
2073
34.9k
    }
2074
2075
34.9k
    if (Tok.is(tok::semi)) {
2076
34.8k
      ConsumeToken();
2077
34.8k
    } else 
if (65
ForEach65
) {
2078
49
      ConsumeToken(); // consume 'in'
2079
2080
49
      if (Tok.is(tok::code_completion)) {
2081
0
        cutOffParsing();
2082
0
        Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
2083
0
        return StmtError();
2084
0
      }
2085
49
      Collection = ParseExpression();
2086
49
    } else 
if (16
getLangOpts().CPlusPlus1116
&&
Tok.is(tok::colon)14
&&
FirstPart.get()8
) {
2087
      // User tried to write the reasonable, but ill-formed, for-range-statement
2088
      //   for (expr : expr) { ... }
2089
6
      Diag(Tok, diag::err_for_range_expected_decl)
2090
6
        << FirstPart.get()->getSourceRange();
2091
6
      SkipUntil(tok::r_paren, StopBeforeMatch);
2092
6
      SecondPart = Sema::ConditionError();
2093
10
    } else {
2094
10
      if (!Value.isInvalid()) {
2095
3
        Diag(Tok, diag::err_expected_semi_for);
2096
7
      } else {
2097
        // Skip until semicolon or rparen, don't consume it.
2098
7
        SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
2099
7
        if (Tok.is(tok::semi))
2100
2
          ConsumeToken();
2101
7
      }
2102
10
    }
2103
34.9k
  }
2104
2105
  // Parse the second part of the for specifier.
2106
220k
  if (!ForEach && 
!ForRangeInfo.ParsedForRangeDecl()220k
&&
2107
220k
      
!SecondPart.isInvalid()218k
) {
2108
    // Parse the second part of the for specifier.
2109
218k
    if (Tok.is(tok::semi)) {  // for (...;;
2110
      // no second part.
2111
217k
    } else if (Tok.is(tok::r_paren)) {
2112
      // missing both semicolons.
2113
217k
    } else {
2114
217k
      if (getLangOpts().CPlusPlus) {
2115
        // C++2a: We've parsed an init-statement; we might have a
2116
        // for-range-declaration next.
2117
209k
        bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
2118
209k
        ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
2119
209k
        SecondPart = ParseCXXCondition(
2120
209k
            nullptr, ForLoc, Sema::ConditionKind::Boolean,
2121
            // FIXME: recovery if we don't see another semi!
2122
209k
            /*MissingOK=*/true, MightBeForRangeStmt ? &ForRangeInfo : 
nullptr0
,
2123
209k
            /*EnterForConditionScope*/ true);
2124
2125
209k
        if (ForRangeInfo.ParsedForRangeDecl()) {
2126
64
          Diag(FirstPart.get() ? 
FirstPart.get()->getBeginLoc()45
2127
64
                               : 
ForRangeInfo.ColonLoc19
,
2128
64
               getLangOpts().CPlusPlus20
2129
64
                   ? 
diag::warn_cxx17_compat_for_range_init_stmt59
2130
64
                   : 
diag::ext_for_range_init_stmt5
)
2131
64
              << (FirstPart.get() ? 
FirstPart.get()->getSourceRange()45
2132
64
                                  : 
SourceRange()19
);
2133
64
          if (EmptyInitStmtSemiLoc.isValid()) {
2134
4
            Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
2135
4
                << /*for-loop*/ 2
2136
4
                << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
2137
4
          }
2138
64
        }
2139
209k
      } else {
2140
        // We permit 'continue' and 'break' in the condition of a for loop.
2141
8.69k
        getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
2142
2143
8.69k
        ExprResult SecondExpr = ParseExpression();
2144
8.69k
        if (SecondExpr.isInvalid())
2145
1
          SecondPart = Sema::ConditionError();
2146
8.69k
        else
2147
8.69k
          SecondPart = Actions.ActOnCondition(
2148
8.69k
              getCurScope(), ForLoc, SecondExpr.get(),
2149
8.69k
              Sema::ConditionKind::Boolean, /*MissingOK=*/true);
2150
8.69k
      }
2151
217k
    }
2152
218k
  }
2153
2154
  // Enter a break / continue scope, if we didn't already enter one while
2155
  // parsing the second part.
2156
220k
  if (!getCurScope()->isContinueScope())
2157
2.75k
    getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
2158
2159
  // Parse the third part of the for statement.
2160
220k
  if (!ForEach && 
!ForRangeInfo.ParsedForRangeDecl()220k
) {
2161
218k
    if (Tok.isNot(tok::semi)) {
2162
24
      if (!SecondPart.isInvalid())
2163
11
        Diag(Tok, diag::err_expected_semi_for);
2164
13
      else
2165
        // Skip until semicolon or rparen, don't consume it.
2166
13
        SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
2167
24
    }
2168
2169
218k
    if (Tok.is(tok::semi)) {
2170
218k
      ConsumeToken();
2171
218k
    }
2172
2173
218k
    if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
2174
213k
      ExprResult Third = ParseExpression();
2175
      // FIXME: The C++11 standard doesn't actually say that this is a
2176
      // discarded-value expression, but it clearly should be.
2177
213k
      ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
2178
213k
    }
2179
218k
  }
2180
  // Match the ')'.
2181
220k
  T.consumeClose();
2182
2183
  // C++ Coroutines [stmt.iter]:
2184
  //   'co_await' can only be used for a range-based for statement.
2185
220k
  if (CoawaitLoc.isValid() && 
!ForRangeInfo.ParsedForRangeDecl()16
) {
2186
1
    Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
2187
1
    CoawaitLoc = SourceLocation();
2188
1
  }
2189
2190
220k
  if (CoawaitLoc.isValid() && 
getLangOpts().CPlusPlus2015
)
2191
7
    Diag(CoawaitLoc, diag::warn_deprecated_for_co_await);
2192
2193
  // We need to perform most of the semantic analysis for a C++0x for-range
2194
  // statememt before parsing the body, in order to be able to deduce the type
2195
  // of an auto-typed loop variable.
2196
220k
  StmtResult ForRangeStmt;
2197
220k
  StmtResult ForEachStmt;
2198
2199
220k
  if (ForRangeInfo.ParsedForRangeDecl()) {
2200
1.47k
    ExprResult CorrectedRange =
2201
1.47k
        Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
2202
1.47k
    ForRangeStmt = Actions.ActOnCXXForRangeStmt(
2203
1.47k
        getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
2204
1.47k
        ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
2205
1.47k
        T.getCloseLocation(), Sema::BFRK_Build);
2206
2207
  // Similarly, we need to do the semantic analysis for a for-range
2208
  // statement immediately in order to close over temporaries correctly.
2209
219k
  } else if (ForEach) {
2210
277
    ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
2211
277
                                                     FirstPart.get(),
2212
277
                                                     Collection.get(),
2213
277
                                                     T.getCloseLocation());
2214
218k
  } else {
2215
    // In OpenMP loop region loop control variable must be captured and be
2216
    // private. Perform analysis of first part (if any).
2217
218k
    if (getLangOpts().OpenMP && 
FirstPart.isUsable()124k
) {
2218
124k
      Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
2219
124k
    }
2220
218k
  }
2221
2222
  // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2223
  // there is no compound stmt.  C90 does not have this clause.  We only do this
2224
  // if the body isn't a compound statement to avoid push/pop in common cases.
2225
  //
2226
  // C++ 6.5p2:
2227
  // The substatement in an iteration-statement implicitly defines a local scope
2228
  // which is entered and exited each time through the loop.
2229
  //
2230
  // See comments in ParseIfStatement for why we create a scope for
2231
  // for-init-statement/condition and a new scope for substatement in C++.
2232
  //
2233
220k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
2234
220k
                        Tok.is(tok::l_brace));
2235
2236
  // The body of the for loop has the same local mangling number as the
2237
  // for-init-statement.
2238
  // It will only be incremented if the body contains other things that would
2239
  // normally increment the mangling number (like a compound statement).
2240
220k
  if (C99orCXXorObjC)
2241
220k
    getCurScope()->decrementMSManglingNumber();
2242
2243
220k
  MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
2244
2245
  // Read the body statement.
2246
220k
  StmtResult Body(ParseStatement(TrailingElseLoc));
2247
2248
220k
  if (Body.isUsable())
2249
220k
    MIChecker.Check();
2250
2251
  // Pop the body scope if needed.
2252
220k
  InnerScope.Exit();
2253
2254
  // Leave the for-scope.
2255
220k
  ForScope.Exit();
2256
2257
220k
  if (Body.isInvalid())
2258
145
    return StmtError();
2259
2260
220k
  if (ForEach)
2261
277
   return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
2262
277
                                              Body.get());
2263
2264
220k
  if (ForRangeInfo.ParsedForRangeDecl())
2265
1.46k
    return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
2266
2267
218k
  return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
2268
218k
                              SecondPart, ThirdPart, T.getCloseLocation(),
2269
218k
                              Body.get());
2270
220k
}
2271
2272
/// ParseGotoStatement
2273
///       jump-statement:
2274
///         'goto' identifier ';'
2275
/// [GNU]   'goto' '*' expression ';'
2276
///
2277
/// Note: this lets the caller parse the end ';'.
2278
///
2279
6.54k
StmtResult Parser::ParseGotoStatement() {
2280
6.54k
  assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
2281
0
  SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
2282
2283
6.54k
  StmtResult Res;
2284
6.54k
  if (Tok.is(tok::identifier)) {
2285
6.40k
    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
2286
6.40k
                                                Tok.getLocation());
2287
6.40k
    Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
2288
6.40k
    ConsumeToken();
2289
6.40k
  } else 
if (132
Tok.is(tok::star)132
) {
2290
    // GNU indirect goto extension.
2291
131
    Diag(Tok, diag::ext_gnu_indirect_goto);
2292
131
    SourceLocation StarLoc = ConsumeToken();
2293
131
    ExprResult R(ParseExpression());
2294
131
    if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
2295
0
      SkipUntil(tok::semi, StopBeforeMatch);
2296
0
      return StmtError();
2297
0
    }
2298
131
    Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
2299
131
  } else {
2300
1
    Diag(Tok, diag::err_expected) << tok::identifier;
2301
1
    return StmtError();
2302
1
  }
2303
2304
6.54k
  return Res;
2305
6.54k
}
2306
2307
/// ParseContinueStatement
2308
///       jump-statement:
2309
///         'continue' ';'
2310
///
2311
/// Note: this lets the caller parse the end ';'.
2312
///
2313
13.0k
StmtResult Parser::ParseContinueStatement() {
2314
13.0k
  SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
2315
13.0k
  return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
2316
13.0k
}
2317
2318
/// ParseBreakStatement
2319
///       jump-statement:
2320
///         'break' ';'
2321
///
2322
/// Note: this lets the caller parse the end ';'.
2323
///
2324
38.7k
StmtResult Parser::ParseBreakStatement() {
2325
38.7k
  SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
2326
38.7k
  return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
2327
38.7k
}
2328
2329
/// ParseReturnStatement
2330
///       jump-statement:
2331
///         'return' expression[opt] ';'
2332
///         'return' braced-init-list ';'
2333
///         'co_return' expression[opt] ';'
2334
///         'co_return' braced-init-list ';'
2335
3.33M
StmtResult Parser::ParseReturnStatement() {
2336
3.33M
  assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
2337
3.33M
         "Not a return stmt!");
2338
0
  bool IsCoreturn = Tok.is(tok::kw_co_return);
2339
3.33M
  SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
2340
2341
3.33M
  ExprResult R;
2342
3.33M
  if (Tok.isNot(tok::semi)) {
2343
3.30M
    if (!IsCoreturn)
2344
3.30M
      PreferredType.enterReturn(Actions, Tok.getLocation());
2345
    // FIXME: Code completion for co_return.
2346
3.30M
    if (Tok.is(tok::code_completion) && 
!IsCoreturn15
) {
2347
15
      cutOffParsing();
2348
15
      Actions.CodeCompleteExpression(getCurScope(),
2349
15
                                     PreferredType.get(Tok.getLocation()));
2350
15
      return StmtError();
2351
15
    }
2352
2353
3.30M
    if (Tok.is(tok::l_brace) && 
getLangOpts().CPlusPlus1.73k
) {
2354
1.73k
      R = ParseInitializer();
2355
1.73k
      if (R.isUsable())
2356
1.73k
        Diag(R.get()->getBeginLoc(),
2357
1.73k
             getLangOpts().CPlusPlus11
2358
1.73k
                 ? 
diag::warn_cxx98_compat_generalized_initializer_lists1.73k
2359
1.73k
                 : 
diag::ext_generalized_initializer_lists2
)
2360
1.73k
            << R.get()->getSourceRange();
2361
1.73k
    } else
2362
3.30M
      R = ParseExpression();
2363
3.30M
    if (R.isInvalid()) {
2364
482
      SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2365
482
      return StmtError();
2366
482
    }
2367
3.30M
  }
2368
3.33M
  if (IsCoreturn)
2369
374
    return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
2370
3.33M
  return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
2371
3.33M
}
2372
2373
StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2374
                                       ParsedStmtContext StmtCtx,
2375
                                       SourceLocation *TrailingElseLoc,
2376
211
                                       ParsedAttributes &Attrs) {
2377
  // Create temporary attribute list.
2378
211
  ParsedAttributes TempAttrs(AttrFactory);
2379
2380
211
  SourceLocation StartLoc = Tok.getLocation();
2381
2382
  // Get loop hints and consume annotated token.
2383
616
  while (Tok.is(tok::annot_pragma_loop_hint)) {
2384
405
    LoopHint Hint;
2385
405
    if (!HandlePragmaLoopHint(Hint))
2386
48
      continue;
2387
2388
357
    ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2389
357
                            ArgsUnion(Hint.ValueExpr)};
2390
357
    TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
2391
357
                     Hint.PragmaNameLoc->Loc, ArgHints, 4,
2392
357
                     ParsedAttr::AS_Pragma);
2393
357
  }
2394
2395
  // Get the next statement.
2396
211
  MaybeParseCXX11Attributes(Attrs);
2397
2398
211
  ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2399
211
  StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2400
211
      Stmts, StmtCtx, TrailingElseLoc, Attrs, EmptyDeclSpecAttrs);
2401
2402
211
  Attrs.takeAllFrom(TempAttrs);
2403
2404
  // Start of attribute range may already be set for some invalid input.
2405
  // See PR46336.
2406
211
  if (Attrs.Range.getBegin().isInvalid())
2407
210
    Attrs.Range.setBegin(StartLoc);
2408
2409
211
  return S;
2410
211
}
2411
2412
3.86M
Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2413
3.86M
  assert(Tok.is(tok::l_brace));
2414
0
  SourceLocation LBraceLoc = Tok.getLocation();
2415
2416
3.86M
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2417
3.86M
                                      "parsing function body");
2418
2419
  // Save and reset current vtordisp stack if we have entered a C++ method body.
2420
3.86M
  bool IsCXXMethod =
2421
3.86M
      getLangOpts().CPlusPlus && 
Decl2.07M
&&
isa<CXXMethodDecl>(Decl)2.07M
;
2422
3.86M
  Sema::PragmaStackSentinelRAII
2423
3.86M
    PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2424
2425
  // Do not enter a scope for the brace, as the arguments are in the same scope
2426
  // (the function body) as the body itself.  Instead, just read the statement
2427
  // list and put it into a CompoundStmt for safe keeping.
2428
3.86M
  StmtResult FnBody(ParseCompoundStatementBody());
2429
2430
  // If the function body could not be parsed, make a bogus compoundstmt.
2431
3.86M
  if (FnBody.isInvalid()) {
2432
0
    Sema::CompoundScopeRAII CompoundScope(Actions);
2433
0
    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2434
0
  }
2435
2436
3.86M
  BodyScope.Exit();
2437
3.86M
  return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2438
3.86M
}
2439
2440
/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2441
///
2442
///       function-try-block:
2443
///         'try' ctor-initializer[opt] compound-statement handler-seq
2444
///
2445
217
Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2446
217
  assert(Tok.is(tok::kw_try) && "Expected 'try'");
2447
0
  SourceLocation TryLoc = ConsumeToken();
2448
2449
217
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2450
217
                                      "parsing function try block");
2451
2452
  // Constructor initializer list?
2453
217
  if (Tok.is(tok::colon))
2454
10
    ParseConstructorInitializer(Decl);
2455
207
  else
2456
207
    Actions.ActOnDefaultCtorInitializers(Decl);
2457
2458
  // Save and reset current vtordisp stack if we have entered a C++ method body.
2459
217
  bool IsCXXMethod =
2460
217
      getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2461
217
  Sema::PragmaStackSentinelRAII
2462
217
    PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2463
2464
217
  SourceLocation LBraceLoc = Tok.getLocation();
2465
217
  StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2466
  // If we failed to parse the try-catch, we just give the function an empty
2467
  // compound statement as the body.
2468
217
  if (FnBody.isInvalid()) {
2469
4
    Sema::CompoundScopeRAII CompoundScope(Actions);
2470
4
    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2471
4
  }
2472
2473
217
  BodyScope.Exit();
2474
217
  return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2475
217
}
2476
2477
2.53k
bool Parser::trySkippingFunctionBody() {
2478
2.53k
  assert(SkipFunctionBodies &&
2479
2.53k
         "Should only be called when SkipFunctionBodies is enabled");
2480
2.53k
  if (!PP.isCodeCompletionEnabled()) {
2481
30
    SkipFunctionBody();
2482
30
    return true;
2483
30
  }
2484
2485
  // We're in code-completion mode. Skip parsing for all function bodies unless
2486
  // the body contains the code-completion point.
2487
2.50k
  TentativeParsingAction PA(*this);
2488
2.50k
  bool IsTryCatch = Tok.is(tok::kw_try);
2489
2.50k
  CachedTokens Toks;
2490
2.50k
  bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2491
3.24k
  if (
llvm::any_of(Toks, [](const Token &Tok) 2.50k
{
2492
3.24k
        return Tok.is(tok::code_completion);
2493
3.24k
      })) {
2494
36
    PA.Revert();
2495
36
    return false;
2496
36
  }
2497
2.46k
  if (ErrorInPrologue) {
2498
1
    PA.Commit();
2499
1
    SkipMalformedDecl();
2500
1
    return true;
2501
1
  }
2502
2.46k
  if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2503
889
    PA.Revert();
2504
889
    return false;
2505
889
  }
2506
1.61k
  
while (1.57k
IsTryCatch &&
Tok.is(tok::kw_catch)76
) {
2507
38
    if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2508
38
        !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2509
0
      PA.Revert();
2510
0
      return false;
2511
0
    }
2512
38
  }
2513
1.57k
  PA.Commit();
2514
1.57k
  return true;
2515
1.57k
}
2516
2517
/// ParseCXXTryBlock - Parse a C++ try-block.
2518
///
2519
///       try-block:
2520
///         'try' compound-statement handler-seq
2521
///
2522
14.7k
StmtResult Parser::ParseCXXTryBlock() {
2523
14.7k
  assert(Tok.is(tok::kw_try) && "Expected 'try'");
2524
2525
0
  SourceLocation TryLoc = ConsumeToken();
2526
14.7k
  return ParseCXXTryBlockCommon(TryLoc);
2527
14.7k
}
2528
2529
/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2530
/// function-try-block.
2531
///
2532
///       try-block:
2533
///         'try' compound-statement handler-seq
2534
///
2535
///       function-try-block:
2536
///         'try' ctor-initializer[opt] compound-statement handler-seq
2537
///
2538
///       handler-seq:
2539
///         handler handler-seq[opt]
2540
///
2541
///       [Borland] try-block:
2542
///         'try' compound-statement seh-except-block
2543
///         'try' compound-statement seh-finally-block
2544
///
2545
15.0k
StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2546
15.0k
  if (Tok.isNot(tok::l_brace))
2547
6
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2548
2549
15.0k
  StmtResult TryBlock(ParseCompoundStatement(
2550
15.0k
      /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2551
15.0k
                                Scope::CompoundStmtScope |
2552
15.0k
                                (FnTry ? 
Scope::FnTryCatchScope213
:
014.7k
)));
2553
15.0k
  if (TryBlock.isInvalid())
2554
0
    return TryBlock;
2555
2556
  // Borland allows SEH-handlers with 'try'
2557
2558
15.0k
  if ((Tok.is(tok::identifier) &&
2559
15.0k
       
Tok.getIdentifierInfo() == getSEHExceptKeyword()1
) ||
2560
15.0k
      
Tok.is(tok::kw___finally)14.9k
) {
2561
    // TODO: Factor into common return ParseSEHHandlerCommon(...)
2562
3
    StmtResult Handler;
2563
3
    if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2564
1
      SourceLocation Loc = ConsumeToken();
2565
1
      Handler = ParseSEHExceptBlock(Loc);
2566
1
    }
2567
2
    else {
2568
2
      SourceLocation Loc = ConsumeToken();
2569
2
      Handler = ParseSEHFinallyBlock(Loc);
2570
2
    }
2571
3
    if(Handler.isInvalid())
2572
0
      return Handler;
2573
2574
3
    return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2575
3
                                    TryLoc,
2576
3
                                    TryBlock.get(),
2577
3
                                    Handler.get());
2578
3
  }
2579
14.9k
  else {
2580
14.9k
    StmtVector Handlers;
2581
2582
    // C++11 attributes can't appear here, despite this context seeming
2583
    // statement-like.
2584
14.9k
    DiagnoseAndSkipCXX11Attributes();
2585
2586
14.9k
    if (Tok.isNot(tok::kw_catch))
2587
0
      return StmtError(Diag(Tok, diag::err_expected_catch));
2588
30.1k
    
while (14.9k
Tok.is(tok::kw_catch)) {
2589
15.1k
      StmtResult Handler(ParseCXXCatchBlock(FnTry));
2590
15.1k
      if (!Handler.isInvalid())
2591
15.1k
        Handlers.push_back(Handler.get());
2592
15.1k
    }
2593
    // Don't bother creating the full statement if we don't have any usable
2594
    // handlers.
2595
14.9k
    if (Handlers.empty())
2596
3
      return StmtError();
2597
2598
14.9k
    return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2599
14.9k
  }
2600
15.0k
}
2601
2602
/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2603
///
2604
///   handler:
2605
///     'catch' '(' exception-declaration ')' compound-statement
2606
///
2607
///   exception-declaration:
2608
///     attribute-specifier-seq[opt] type-specifier-seq declarator
2609
///     attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2610
///     '...'
2611
///
2612
15.1k
StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2613
15.1k
  assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2614
2615
0
  SourceLocation CatchLoc = ConsumeToken();
2616
2617
15.1k
  BalancedDelimiterTracker T(*this, tok::l_paren);
2618
15.1k
  if (T.expectAndConsume())
2619
2
    return StmtError();
2620
2621
  // C++ 3.3.2p3:
2622
  // The name in a catch exception-declaration is local to the handler and
2623
  // shall not be redeclared in the outermost block of the handler.
2624
15.1k
  ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2625
15.1k
                                  Scope::CatchScope |
2626
15.1k
                                  (FnCatch ? 
Scope::FnTryCatchScope225
:
014.8k
));
2627
2628
  // exception-declaration is equivalent to '...' or a parameter-declaration
2629
  // without default arguments.
2630
15.1k
  Decl *ExceptionDecl = nullptr;
2631
15.1k
  if (Tok.isNot(tok::ellipsis)) {
2632
714
    ParsedAttributes Attributes(AttrFactory);
2633
714
    MaybeParseCXX11Attributes(Attributes);
2634
2635
714
    DeclSpec DS(AttrFactory);
2636
2637
714
    if (ParseCXXTypeSpecifierSeq(DS))
2638
0
      return StmtError();
2639
2640
714
    Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);
2641
714
    ParseDeclarator(ExDecl);
2642
714
    ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2643
714
  } else
2644
14.4k
    ConsumeToken();
2645
2646
15.1k
  T.consumeClose();
2647
15.1k
  if (T.getCloseLocation().isInvalid())
2648
0
    return StmtError();
2649
2650
15.1k
  if (Tok.isNot(tok::l_brace))
2651
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2652
2653
  // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2654
15.1k
  StmtResult Block(ParseCompoundStatement());
2655
15.1k
  if (Block.isInvalid())
2656
0
    return Block;
2657
2658
15.1k
  return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2659
15.1k
}
2660
2661
29
void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2662
29
  IfExistsCondition Result;
2663
29
  if (ParseMicrosoftIfExistsCondition(Result))
2664
2
    return;
2665
2666
  // Handle dependent statements by parsing the braces as a compound statement.
2667
  // This is not the same behavior as Visual C++, which don't treat this as a
2668
  // compound statement, but for Clang's type checking we can't have anything
2669
  // inside these braces escaping to the surrounding code.
2670
27
  if (Result.Behavior == IEB_Dependent) {
2671
8
    if (!Tok.is(tok::l_brace)) {
2672
0
      Diag(Tok, diag::err_expected) << tok::l_brace;
2673
0
      return;
2674
0
    }
2675
2676
8
    StmtResult Compound = ParseCompoundStatement();
2677
8
    if (Compound.isInvalid())
2678
0
      return;
2679
2680
8
    StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2681
8
                                                              Result.IsIfExists,
2682
8
                                                              Result.SS,
2683
8
                                                              Result.Name,
2684
8
                                                              Compound.get());
2685
8
    if (DepResult.isUsable())
2686
8
      Stmts.push_back(DepResult.get());
2687
8
    return;
2688
8
  }
2689
2690
19
  BalancedDelimiterTracker Braces(*this, tok::l_brace);
2691
19
  if (Braces.consumeOpen()) {
2692
0
    Diag(Tok, diag::err_expected) << tok::l_brace;
2693
0
    return;
2694
0
  }
2695
2696
19
  switch (Result.Behavior) {
2697
14
  case IEB_Parse:
2698
    // Parse the statements below.
2699
14
    break;
2700
2701
0
  case IEB_Dependent:
2702
0
    llvm_unreachable("Dependent case handled above");
2703
2704
5
  case IEB_Skip:
2705
5
    Braces.skipToEnd();
2706
5
    return;
2707
19
  }
2708
2709
  // Condition is true, parse the statements.
2710
34
  
while (14
Tok.isNot(tok::r_brace)) {
2711
20
    StmtResult R =
2712
20
        ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
2713
20
    if (R.isUsable())
2714
18
      Stmts.push_back(R.get());
2715
20
  }
2716
14
  Braces.consumeClose();
2717
14
}