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