Coverage Report

Created: 2022-01-18 06:27

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