Coverage Report

Created: 2019-07-24 05:18

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