Coverage Report

Created: 2020-02-15 09:57

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