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