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/Diagnostic.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Scope.h"
25#include "clang/Sema/TypoCorrection.h"
26#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCObjectFileInfo.h"
29#include "llvm/MC/MCParser/MCAsmParser.h"
30#include "llvm/MC/MCRegisterInfo.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSubtargetInfo.h"
33#include "llvm/MC/MCTargetAsmParser.h"
34#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
37#include "llvm/ADT/SmallString.h"
38using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// C99 6.8: Statements and Blocks.
42//===----------------------------------------------------------------------===//
43
44/// \brief Parse a standalone statement (for instance, as the body of an 'if',
45/// 'while', or 'for').
46StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) {
47  StmtResult Res;
48
49  // We may get back a null statement if we found a #pragma. Keep going until
50  // we get an actual statement.
51  do {
52    StmtVector Stmts;
53    Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
54  } while (!Res.isInvalid() && !Res.get());
55
56  return Res;
57}
58
59/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
60///       StatementOrDeclaration:
61///         statement
62///         declaration
63///
64///       statement:
65///         labeled-statement
66///         compound-statement
67///         expression-statement
68///         selection-statement
69///         iteration-statement
70///         jump-statement
71/// [C++]   declaration-statement
72/// [C++]   try-block
73/// [MS]    seh-try-block
74/// [OBC]   objc-throw-statement
75/// [OBC]   objc-try-catch-statement
76/// [OBC]   objc-synchronized-statement
77/// [GNU]   asm-statement
78/// [OMP]   openmp-construct             [TODO]
79///
80///       labeled-statement:
81///         identifier ':' statement
82///         'case' constant-expression ':' statement
83///         'default' ':' statement
84///
85///       selection-statement:
86///         if-statement
87///         switch-statement
88///
89///       iteration-statement:
90///         while-statement
91///         do-statement
92///         for-statement
93///
94///       expression-statement:
95///         expression[opt] ';'
96///
97///       jump-statement:
98///         'goto' identifier ';'
99///         'continue' ';'
100///         'break' ';'
101///         'return' expression[opt] ';'
102/// [GNU]   'goto' '*' expression ';'
103///
104/// [OBC] objc-throw-statement:
105/// [OBC]   '@' 'throw' expression ';'
106/// [OBC]   '@' 'throw' ';'
107///
108StmtResult
109Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
110                                    SourceLocation *TrailingElseLoc) {
111
112  ParenBraceBracketBalancer BalancerRAIIObj(*this);
113
114  ParsedAttributesWithRange Attrs(AttrFactory);
115  MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
116
117  StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
118                                 OnlyStatement, TrailingElseLoc, Attrs);
119
120  assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
121         "attributes on empty statement");
122
123  if (Attrs.empty() || Res.isInvalid())
124    return Res;
125
126  return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
127}
128
129namespace {
130class StatementFilterCCC : public CorrectionCandidateCallback {
131public:
132  StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
133    WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
134                         nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
135                         nextTok.is(tok::amp) || nextTok.is(tok::l_square);
136    WantExpressionKeywords = nextTok.is(tok::l_paren) ||
137                             nextTok.is(tok::identifier) ||
138                             nextTok.is(tok::arrow) || nextTok.is(tok::period);
139    WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
140                            nextTok.is(tok::identifier) ||
141                            nextTok.is(tok::l_brace);
142    WantCXXNamedCasts = false;
143  }
144
145  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
146    if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
147      return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
148    if (NextToken.is(tok::equal))
149      return candidate.getCorrectionDeclAs<VarDecl>();
150    if (NextToken.is(tok::period) &&
151        candidate.getCorrectionDeclAs<NamespaceDecl>())
152      return false;
153    return CorrectionCandidateCallback::ValidateCandidate(candidate);
154  }
155
156private:
157  Token NextToken;
158};
159}
160
161StmtResult
162Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
163          bool OnlyStatement, SourceLocation *TrailingElseLoc,
164          ParsedAttributesWithRange &Attrs) {
165  const char *SemiError = 0;
166  StmtResult Res;
167
168  // Cases in this switch statement should fall through if the parser expects
169  // the token to end in a semicolon (in which case SemiError should be set),
170  // or they directly 'return;' if not.
171Retry:
172  tok::TokenKind Kind  = Tok.getKind();
173  SourceLocation AtLoc;
174  switch (Kind) {
175  case tok::at: // May be a @try or @throw statement
176    {
177      ProhibitAttributes(Attrs); // TODO: is it correct?
178      AtLoc = ConsumeToken();  // consume @
179      return ParseObjCAtStatement(AtLoc);
180    }
181
182  case tok::code_completion:
183    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
184    cutOffParsing();
185    return StmtError();
186
187  case tok::identifier: {
188    Token Next = NextToken();
189    if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
190      // identifier ':' statement
191      return ParseLabeledStatement(Attrs);
192    }
193
194    // Look up the identifier, and typo-correct it to a keyword if it's not
195    // found.
196    if (Next.isNot(tok::coloncolon)) {
197      // Try to limit which sets of keywords should be included in typo
198      // correction based on what the next token is.
199      StatementFilterCCC Validator(Next);
200      if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
201            == ANK_Error) {
202        // Handle errors here by skipping up to the next semicolon or '}', and
203        // eat the semicolon if that's what stopped us.
204        SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
205        if (Tok.is(tok::semi))
206          ConsumeToken();
207        return StmtError();
208      }
209
210      // If the identifier was typo-corrected, try again.
211      if (Tok.isNot(tok::identifier))
212        goto Retry;
213    }
214
215    // Fall through
216  }
217
218  default: {
219    if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
220      SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
221      DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
222                                             DeclEnd, Attrs);
223      return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
224    }
225
226    if (Tok.is(tok::r_brace)) {
227      Diag(Tok, diag::err_expected_statement);
228      return StmtError();
229    }
230
231    return ParseExprStatement();
232  }
233
234  case tok::kw_case:                // C99 6.8.1: labeled-statement
235    return ParseCaseStatement();
236  case tok::kw_default:             // C99 6.8.1: labeled-statement
237    return ParseDefaultStatement();
238
239  case tok::l_brace:                // C99 6.8.2: compound-statement
240    return ParseCompoundStatement();
241  case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
242    bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
243    return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
244  }
245
246  case tok::kw_if:                  // C99 6.8.4.1: if-statement
247    return ParseIfStatement(TrailingElseLoc);
248  case tok::kw_switch:              // C99 6.8.4.2: switch-statement
249    return ParseSwitchStatement(TrailingElseLoc);
250
251  case tok::kw_while:               // C99 6.8.5.1: while-statement
252    return ParseWhileStatement(TrailingElseLoc);
253  case tok::kw_do:                  // C99 6.8.5.2: do-statement
254    Res = ParseDoStatement();
255    SemiError = "do/while";
256    break;
257  case tok::kw_for:                 // C99 6.8.5.3: for-statement
258    return ParseForStatement(TrailingElseLoc);
259
260  case tok::kw_goto:                // C99 6.8.6.1: goto-statement
261    Res = ParseGotoStatement();
262    SemiError = "goto";
263    break;
264  case tok::kw_continue:            // C99 6.8.6.2: continue-statement
265    Res = ParseContinueStatement();
266    SemiError = "continue";
267    break;
268  case tok::kw_break:               // C99 6.8.6.3: break-statement
269    Res = ParseBreakStatement();
270    SemiError = "break";
271    break;
272  case tok::kw_return:              // C99 6.8.6.4: return-statement
273    Res = ParseReturnStatement();
274    SemiError = "return";
275    break;
276
277  case tok::kw_asm: {
278    ProhibitAttributes(Attrs);
279    bool msAsm = false;
280    Res = ParseAsmStatement(msAsm);
281    Res = Actions.ActOnFinishFullStmt(Res.get());
282    if (msAsm) return Res;
283    SemiError = "asm";
284    break;
285  }
286
287  case tok::kw_try:                 // C++ 15: try-block
288    return ParseCXXTryBlock();
289
290  case tok::kw___try:
291    ProhibitAttributes(Attrs); // TODO: is it correct?
292    return ParseSEHTryBlock();
293
294  case tok::annot_pragma_vis:
295    ProhibitAttributes(Attrs);
296    HandlePragmaVisibility();
297    return StmtEmpty();
298
299  case tok::annot_pragma_pack:
300    ProhibitAttributes(Attrs);
301    HandlePragmaPack();
302    return StmtEmpty();
303
304  case tok::annot_pragma_msstruct:
305    ProhibitAttributes(Attrs);
306    HandlePragmaMSStruct();
307    return StmtEmpty();
308
309  case tok::annot_pragma_align:
310    ProhibitAttributes(Attrs);
311    HandlePragmaAlign();
312    return StmtEmpty();
313
314  case tok::annot_pragma_weak:
315    ProhibitAttributes(Attrs);
316    HandlePragmaWeak();
317    return StmtEmpty();
318
319  case tok::annot_pragma_weakalias:
320    ProhibitAttributes(Attrs);
321    HandlePragmaWeakAlias();
322    return StmtEmpty();
323
324  case tok::annot_pragma_redefine_extname:
325    ProhibitAttributes(Attrs);
326    HandlePragmaRedefineExtname();
327    return StmtEmpty();
328
329  case tok::annot_pragma_fp_contract:
330    ProhibitAttributes(Attrs);
331    Diag(Tok, diag::err_pragma_fp_contract_scope);
332    ConsumeToken();
333    return StmtError();
334
335  case tok::annot_pragma_opencl_extension:
336    ProhibitAttributes(Attrs);
337    HandlePragmaOpenCLExtension();
338    return StmtEmpty();
339
340  case tok::annot_pragma_captured:
341    ProhibitAttributes(Attrs);
342    return HandlePragmaCaptured();
343
344  case tok::annot_pragma_openmp:
345    ProhibitAttributes(Attrs);
346    return ParseOpenMPDeclarativeOrExecutableDirective();
347
348  }
349
350  // If we reached this code, the statement must end in a semicolon.
351  if (Tok.is(tok::semi)) {
352    ConsumeToken();
353  } else if (!Res.isInvalid()) {
354    // If the result was valid, then we do want to diagnose this.  Use
355    // ExpectAndConsume to emit the diagnostic, even though we know it won't
356    // succeed.
357    ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
358    // Skip until we see a } or ;, but don't eat it.
359    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
360  }
361
362  return Res;
363}
364
365/// \brief Parse an expression statement.
366StmtResult Parser::ParseExprStatement() {
367  // If a case keyword is missing, this is where it should be inserted.
368  Token OldToken = Tok;
369
370  // expression[opt] ';'
371  ExprResult Expr(ParseExpression());
372  if (Expr.isInvalid()) {
373    // If the expression is invalid, skip ahead to the next semicolon or '}'.
374    // Not doing this opens us up to the possibility of infinite loops if
375    // ParseExpression does not consume any tokens.
376    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
377    if (Tok.is(tok::semi))
378      ConsumeToken();
379    return Actions.ActOnExprStmtError();
380  }
381
382  if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
383      Actions.CheckCaseExpression(Expr.get())) {
384    // If a constant expression is followed by a colon inside a switch block,
385    // suggest a missing case keyword.
386    Diag(OldToken, diag::err_expected_case_before_expression)
387      << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
388
389    // Recover parsing as a case statement.
390    return ParseCaseStatement(/*MissingCase=*/true, Expr);
391  }
392
393  // Otherwise, eat the semicolon.
394  ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
395  return Actions.ActOnExprStmt(Expr);
396}
397
398StmtResult Parser::ParseSEHTryBlock() {
399  assert(Tok.is(tok::kw___try) && "Expected '__try'");
400  SourceLocation Loc = ConsumeToken();
401  return ParseSEHTryBlockCommon(Loc);
402}
403
404/// ParseSEHTryBlockCommon
405///
406/// seh-try-block:
407///   '__try' compound-statement seh-handler
408///
409/// seh-handler:
410///   seh-except-block
411///   seh-finally-block
412///
413StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
414  if(Tok.isNot(tok::l_brace))
415    return StmtError(Diag(Tok,diag::err_expected_lbrace));
416
417  StmtResult TryBlock(ParseCompoundStatement());
418  if(TryBlock.isInvalid())
419    return TryBlock;
420
421  StmtResult Handler;
422  if (Tok.is(tok::identifier) &&
423      Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
424    SourceLocation Loc = ConsumeToken();
425    Handler = ParseSEHExceptBlock(Loc);
426  } else if (Tok.is(tok::kw___finally)) {
427    SourceLocation Loc = ConsumeToken();
428    Handler = ParseSEHFinallyBlock(Loc);
429  } else {
430    return StmtError(Diag(Tok,diag::err_seh_expected_handler));
431  }
432
433  if(Handler.isInvalid())
434    return Handler;
435
436  return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
437                                  TryLoc,
438                                  TryBlock.take(),
439                                  Handler.take());
440}
441
442/// ParseSEHExceptBlock - Handle __except
443///
444/// seh-except-block:
445///   '__except' '(' seh-filter-expression ')' compound-statement
446///
447StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
448  PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
449    raii2(Ident___exception_code, false),
450    raii3(Ident_GetExceptionCode, false);
451
452  if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
453    return StmtError();
454
455  ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
456
457  if (getLangOpts().Borland) {
458    Ident__exception_info->setIsPoisoned(false);
459    Ident___exception_info->setIsPoisoned(false);
460    Ident_GetExceptionInfo->setIsPoisoned(false);
461  }
462  ExprResult FilterExpr(ParseExpression());
463
464  if (getLangOpts().Borland) {
465    Ident__exception_info->setIsPoisoned(true);
466    Ident___exception_info->setIsPoisoned(true);
467    Ident_GetExceptionInfo->setIsPoisoned(true);
468  }
469
470  if(FilterExpr.isInvalid())
471    return StmtError();
472
473  if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
474    return StmtError();
475
476  StmtResult Block(ParseCompoundStatement());
477
478  if(Block.isInvalid())
479    return Block;
480
481  return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
482}
483
484/// ParseSEHFinallyBlock - Handle __finally
485///
486/// seh-finally-block:
487///   '__finally' compound-statement
488///
489StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
490  PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
491    raii2(Ident___abnormal_termination, false),
492    raii3(Ident_AbnormalTermination, false);
493
494  StmtResult Block(ParseCompoundStatement());
495  if(Block.isInvalid())
496    return Block;
497
498  return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
499}
500
501/// ParseLabeledStatement - We have an identifier and a ':' after it.
502///
503///       labeled-statement:
504///         identifier ':' statement
505/// [GNU]   identifier ':' attributes[opt] statement
506///
507StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
508  assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
509         "Not an identifier!");
510
511  Token IdentTok = Tok;  // Save the whole token.
512  ConsumeToken();  // eat the identifier.
513
514  assert(Tok.is(tok::colon) && "Not a label!");
515
516  // identifier ':' statement
517  SourceLocation ColonLoc = ConsumeToken();
518
519  // Read label attributes, if present.
520  StmtResult SubStmt;
521  if (Tok.is(tok::kw___attribute)) {
522    ParsedAttributesWithRange TempAttrs(AttrFactory);
523    ParseGNUAttributes(TempAttrs);
524
525    // In C++, GNU attributes only apply to the label if they are followed by a
526    // semicolon, to disambiguate label attributes from attributes on a labeled
527    // declaration.
528    //
529    // This doesn't quite match what GCC does; if the attribute list is empty
530    // and followed by a semicolon, GCC will reject (it appears to parse the
531    // attributes as part of a statement in that case). That looks like a bug.
532    if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
533      attrs.takeAllFrom(TempAttrs);
534    else if (isDeclarationStatement()) {
535      StmtVector Stmts;
536      // FIXME: We should do this whether or not we have a declaration
537      // statement, but that doesn't work correctly (because ProhibitAttributes
538      // can't handle GNU attributes), so only call it in the one case where
539      // GNU attributes are allowed.
540      SubStmt = ParseStatementOrDeclarationAfterAttributes(
541          Stmts, /*OnlyStmts*/ true, 0, TempAttrs);
542      if (!TempAttrs.empty() && !SubStmt.isInvalid())
543        SubStmt = Actions.ProcessStmtAttributes(
544            SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
545    } else {
546      Diag(Tok, diag::err_expected_semi_after) << "__attribute__";
547    }
548  }
549
550  // If we've not parsed a statement yet, parse one now.
551  if (!SubStmt.isInvalid() && !SubStmt.isUsable())
552    SubStmt = ParseStatement();
553
554  // Broken substmt shouldn't prevent the label from being added to the AST.
555  if (SubStmt.isInvalid())
556    SubStmt = Actions.ActOnNullStmt(ColonLoc);
557
558  LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
559                                              IdentTok.getLocation());
560  if (AttributeList *Attrs = attrs.getList()) {
561    Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
562    attrs.clear();
563  }
564
565  return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
566                                SubStmt.get());
567}
568
569/// ParseCaseStatement
570///       labeled-statement:
571///         'case' constant-expression ':' statement
572/// [GNU]   'case' constant-expression '...' constant-expression ':' statement
573///
574StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
575  assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
576
577  // It is very very common for code to contain many case statements recursively
578  // nested, as in (but usually without indentation):
579  //  case 1:
580  //    case 2:
581  //      case 3:
582  //         case 4:
583  //           case 5: etc.
584  //
585  // Parsing this naively works, but is both inefficient and can cause us to run
586  // out of stack space in our recursive descent parser.  As a special case,
587  // flatten this recursion into an iterative loop.  This is complex and gross,
588  // but all the grossness is constrained to ParseCaseStatement (and some
589  // weirdness in the actions), so this is just local grossness :).
590
591  // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
592  // example above.
593  StmtResult TopLevelCase(true);
594
595  // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
596  // gets updated each time a new case is parsed, and whose body is unset so
597  // far.  When parsing 'case 4', this is the 'case 3' node.
598  Stmt *DeepestParsedCaseStmt = 0;
599
600  // While we have case statements, eat and stack them.
601  SourceLocation ColonLoc;
602  do {
603    SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
604                                           ConsumeToken();  // eat the 'case'.
605
606    if (Tok.is(tok::code_completion)) {
607      Actions.CodeCompleteCase(getCurScope());
608      cutOffParsing();
609      return StmtError();
610    }
611
612    /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
613    /// Disable this form of error recovery while we're parsing the case
614    /// expression.
615    ColonProtectionRAIIObject ColonProtection(*this);
616
617    ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
618    MissingCase = false;
619    if (LHS.isInvalid()) {
620      SkipUntil(tok::colon, StopAtSemi);
621      return StmtError();
622    }
623
624    // GNU case range extension.
625    SourceLocation DotDotDotLoc;
626    ExprResult RHS;
627    if (Tok.is(tok::ellipsis)) {
628      Diag(Tok, diag::ext_gnu_case_range);
629      DotDotDotLoc = ConsumeToken();
630
631      RHS = ParseConstantExpression();
632      if (RHS.isInvalid()) {
633        SkipUntil(tok::colon, StopAtSemi);
634        return StmtError();
635      }
636    }
637
638    ColonProtection.restore();
639
640    if (Tok.is(tok::colon)) {
641      ColonLoc = ConsumeToken();
642
643    // Treat "case blah;" as a typo for "case blah:".
644    } else if (Tok.is(tok::semi)) {
645      ColonLoc = ConsumeToken();
646      Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
647        << FixItHint::CreateReplacement(ColonLoc, ":");
648    } else {
649      SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
650      Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
651        << FixItHint::CreateInsertion(ExpectedLoc, ":");
652      ColonLoc = ExpectedLoc;
653    }
654
655    StmtResult Case =
656      Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
657                            RHS.get(), ColonLoc);
658
659    // If we had a sema error parsing this case, then just ignore it and
660    // continue parsing the sub-stmt.
661    if (Case.isInvalid()) {
662      if (TopLevelCase.isInvalid())  // No parsed case stmts.
663        return ParseStatement();
664      // Otherwise, just don't add it as a nested case.
665    } else {
666      // If this is the first case statement we parsed, it becomes TopLevelCase.
667      // Otherwise we link it into the current chain.
668      Stmt *NextDeepest = Case.get();
669      if (TopLevelCase.isInvalid())
670        TopLevelCase = Case;
671      else
672        Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
673      DeepestParsedCaseStmt = NextDeepest;
674    }
675
676    // Handle all case statements.
677  } while (Tok.is(tok::kw_case));
678
679  assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
680
681  // If we found a non-case statement, start by parsing it.
682  StmtResult SubStmt;
683
684  if (Tok.isNot(tok::r_brace)) {
685    SubStmt = ParseStatement();
686  } else {
687    // Nicely diagnose the common error "switch (X) { case 4: }", which is
688    // not valid.
689    SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
690    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
691      << FixItHint::CreateInsertion(AfterColonLoc, " ;");
692    SubStmt = true;
693  }
694
695  // Broken sub-stmt shouldn't prevent forming the case statement properly.
696  if (SubStmt.isInvalid())
697    SubStmt = Actions.ActOnNullStmt(SourceLocation());
698
699  // Install the body into the most deeply-nested case.
700  Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
701
702  // Return the top level parsed statement tree.
703  return TopLevelCase;
704}
705
706/// ParseDefaultStatement
707///       labeled-statement:
708///         'default' ':' statement
709/// Note that this does not parse the 'statement' at the end.
710///
711StmtResult Parser::ParseDefaultStatement() {
712  assert(Tok.is(tok::kw_default) && "Not a default stmt!");
713  SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
714
715  SourceLocation ColonLoc;
716  if (Tok.is(tok::colon)) {
717    ColonLoc = ConsumeToken();
718
719  // Treat "default;" as a typo for "default:".
720  } else if (Tok.is(tok::semi)) {
721    ColonLoc = ConsumeToken();
722    Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
723      << FixItHint::CreateReplacement(ColonLoc, ":");
724  } else {
725    SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
726    Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
727      << FixItHint::CreateInsertion(ExpectedLoc, ":");
728    ColonLoc = ExpectedLoc;
729  }
730
731  StmtResult SubStmt;
732
733  if (Tok.isNot(tok::r_brace)) {
734    SubStmt = ParseStatement();
735  } else {
736    // Diagnose the common error "switch (X) {... default: }", which is
737    // not valid.
738    SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
739    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
740      << FixItHint::CreateInsertion(AfterColonLoc, " ;");
741    SubStmt = true;
742  }
743
744  // Broken sub-stmt shouldn't prevent forming the case statement properly.
745  if (SubStmt.isInvalid())
746    SubStmt = Actions.ActOnNullStmt(ColonLoc);
747
748  return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
749                                  SubStmt.get(), getCurScope());
750}
751
752StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
753  return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
754}
755
756/// ParseCompoundStatement - Parse a "{}" block.
757///
758///       compound-statement: [C99 6.8.2]
759///         { block-item-list[opt] }
760/// [GNU]   { label-declarations block-item-list } [TODO]
761///
762///       block-item-list:
763///         block-item
764///         block-item-list block-item
765///
766///       block-item:
767///         declaration
768/// [GNU]   '__extension__' declaration
769///         statement
770/// [OMP]   openmp-directive            [TODO]
771///
772/// [GNU] label-declarations:
773/// [GNU]   label-declaration
774/// [GNU]   label-declarations label-declaration
775///
776/// [GNU] label-declaration:
777/// [GNU]   '__label__' identifier-list ';'
778///
779/// [OMP] openmp-directive:             [TODO]
780/// [OMP]   barrier-directive
781/// [OMP]   flush-directive
782///
783StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
784                                          unsigned ScopeFlags) {
785  assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
786
787  // Enter a scope to hold everything within the compound stmt.  Compound
788  // statements can always hold declarations.
789  ParseScope CompoundScope(this, ScopeFlags);
790
791  // Parse the statements in the body.
792  return ParseCompoundStatementBody(isStmtExpr);
793}
794
795/// Parse any pragmas at the start of the compound expression. We handle these
796/// separately since some pragmas (FP_CONTRACT) must appear before any C
797/// statement in the compound, but may be intermingled with other pragmas.
798void Parser::ParseCompoundStatementLeadingPragmas() {
799  bool checkForPragmas = true;
800  while (checkForPragmas) {
801    switch (Tok.getKind()) {
802    case tok::annot_pragma_vis:
803      HandlePragmaVisibility();
804      break;
805    case tok::annot_pragma_pack:
806      HandlePragmaPack();
807      break;
808    case tok::annot_pragma_msstruct:
809      HandlePragmaMSStruct();
810      break;
811    case tok::annot_pragma_align:
812      HandlePragmaAlign();
813      break;
814    case tok::annot_pragma_weak:
815      HandlePragmaWeak();
816      break;
817    case tok::annot_pragma_weakalias:
818      HandlePragmaWeakAlias();
819      break;
820    case tok::annot_pragma_redefine_extname:
821      HandlePragmaRedefineExtname();
822      break;
823    case tok::annot_pragma_opencl_extension:
824      HandlePragmaOpenCLExtension();
825      break;
826    case tok::annot_pragma_fp_contract:
827      HandlePragmaFPContract();
828      break;
829    default:
830      checkForPragmas = false;
831      break;
832    }
833  }
834
835}
836
837/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
838/// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
839/// consume the '}' at the end of the block.  It does not manipulate the scope
840/// stack.
841StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
842  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
843                                Tok.getLocation(),
844                                "in compound statement ('{}')");
845
846  // Record the state of the FP_CONTRACT pragma, restore on leaving the
847  // compound statement.
848  Sema::FPContractStateRAII SaveFPContractState(Actions);
849
850  InMessageExpressionRAIIObject InMessage(*this, false);
851  BalancedDelimiterTracker T(*this, tok::l_brace);
852  if (T.consumeOpen())
853    return StmtError();
854
855  Sema::CompoundScopeRAII CompoundScope(Actions);
856
857  // Parse any pragmas at the beginning of the compound statement.
858  ParseCompoundStatementLeadingPragmas();
859
860  StmtVector Stmts;
861
862  // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
863  // only allowed at the start of a compound stmt regardless of the language.
864  while (Tok.is(tok::kw___label__)) {
865    SourceLocation LabelLoc = ConsumeToken();
866
867    SmallVector<Decl *, 8> DeclsInGroup;
868    while (1) {
869      if (Tok.isNot(tok::identifier)) {
870        Diag(Tok, diag::err_expected_ident);
871        break;
872      }
873
874      IdentifierInfo *II = Tok.getIdentifierInfo();
875      SourceLocation IdLoc = ConsumeToken();
876      DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
877
878      if (!Tok.is(tok::comma))
879        break;
880      ConsumeToken();
881    }
882
883    DeclSpec DS(AttrFactory);
884    DeclGroupPtrTy Res =
885        Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
886    StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
887
888    ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
889    if (R.isUsable())
890      Stmts.push_back(R.release());
891  }
892
893  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
894    if (Tok.is(tok::annot_pragma_unused)) {
895      HandlePragmaUnused();
896      continue;
897    }
898
899    if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
900        Tok.is(tok::kw___if_not_exists))) {
901      ParseMicrosoftIfExistsStatement(Stmts);
902      continue;
903    }
904
905    StmtResult R;
906    if (Tok.isNot(tok::kw___extension__)) {
907      R = ParseStatementOrDeclaration(Stmts, false);
908    } else {
909      // __extension__ can start declarations and it can also be a unary
910      // operator for expressions.  Consume multiple __extension__ markers here
911      // until we can determine which is which.
912      // FIXME: This loses extension expressions in the AST!
913      SourceLocation ExtLoc = ConsumeToken();
914      while (Tok.is(tok::kw___extension__))
915        ConsumeToken();
916
917      ParsedAttributesWithRange attrs(AttrFactory);
918      MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
919
920      // If this is the start of a declaration, parse it as such.
921      if (isDeclarationStatement()) {
922        // __extension__ silences extension warnings in the subdeclaration.
923        // FIXME: Save the __extension__ on the decl as a node somehow?
924        ExtensionRAIIObject O(Diags);
925
926        SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
927        DeclGroupPtrTy Res = ParseDeclaration(Stmts,
928                                              Declarator::BlockContext, DeclEnd,
929                                              attrs);
930        R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
931      } else {
932        // Otherwise this was a unary __extension__ marker.
933        ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
934
935        if (Res.isInvalid()) {
936          SkipUntil(tok::semi);
937          continue;
938        }
939
940        // FIXME: Use attributes?
941        // Eat the semicolon at the end of stmt and convert the expr into a
942        // statement.
943        ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
944        R = Actions.ActOnExprStmt(Res);
945      }
946    }
947
948    if (R.isUsable())
949      Stmts.push_back(R.release());
950  }
951
952  SourceLocation CloseLoc = Tok.getLocation();
953
954  // We broke out of the while loop because we found a '}' or EOF.
955  if (!T.consumeClose())
956    // Recover by creating a compound statement with what we parsed so far,
957    // instead of dropping everything and returning StmtError();
958    CloseLoc = T.getCloseLocation();
959
960  return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
961                                   Stmts, isStmtExpr);
962}
963
964/// ParseParenExprOrCondition:
965/// [C  ]     '(' expression ')'
966/// [C++]     '(' condition ')'       [not allowed if OnlyAllowCondition=true]
967///
968/// This function parses and performs error recovery on the specified condition
969/// or expression (depending on whether we're in C++ or C mode).  This function
970/// goes out of its way to recover well.  It returns true if there was a parser
971/// error (the right paren couldn't be found), which indicates that the caller
972/// should try to recover harder.  It returns false if the condition is
973/// successfully parsed.  Note that a successful parse can still have semantic
974/// errors in the condition.
975bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
976                                       Decl *&DeclResult,
977                                       SourceLocation Loc,
978                                       bool ConvertToBoolean) {
979  BalancedDelimiterTracker T(*this, tok::l_paren);
980  T.consumeOpen();
981
982  if (getLangOpts().CPlusPlus)
983    ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
984  else {
985    ExprResult = ParseExpression();
986    DeclResult = 0;
987
988    // If required, convert to a boolean value.
989    if (!ExprResult.isInvalid() && ConvertToBoolean)
990      ExprResult
991        = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
992  }
993
994  // If the parser was confused by the condition and we don't have a ')', try to
995  // recover by skipping ahead to a semi and bailing out.  If condexp is
996  // semantically invalid but we have well formed code, keep going.
997  if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
998    SkipUntil(tok::semi);
999    // Skipping may have stopped if it found the containing ')'.  If so, we can
1000    // continue parsing the if statement.
1001    if (Tok.isNot(tok::r_paren))
1002      return true;
1003  }
1004
1005  // Otherwise the condition is valid or the rparen is present.
1006  T.consumeClose();
1007
1008  // Check for extraneous ')'s to catch things like "if (foo())) {".  We know
1009  // that all callers are looking for a statement after the condition, so ")"
1010  // isn't valid.
1011  while (Tok.is(tok::r_paren)) {
1012    Diag(Tok, diag::err_extraneous_rparen_in_condition)
1013      << FixItHint::CreateRemoval(Tok.getLocation());
1014    ConsumeParen();
1015  }
1016
1017  return false;
1018}
1019
1020
1021/// ParseIfStatement
1022///       if-statement: [C99 6.8.4.1]
1023///         'if' '(' expression ')' statement
1024///         'if' '(' expression ')' statement 'else' statement
1025/// [C++]   'if' '(' condition ')' statement
1026/// [C++]   'if' '(' condition ')' statement 'else' statement
1027///
1028StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1029  assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1030  SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
1031
1032  if (Tok.isNot(tok::l_paren)) {
1033    Diag(Tok, diag::err_expected_lparen_after) << "if";
1034    SkipUntil(tok::semi);
1035    return StmtError();
1036  }
1037
1038  bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1039
1040  // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
1041  // the case for C90.
1042  //
1043  // C++ 6.4p3:
1044  // A name introduced by a declaration in a condition is in scope from its
1045  // point of declaration until the end of the substatements controlled by the
1046  // condition.
1047  // C++ 3.3.2p4:
1048  // Names declared in the for-init-statement, and in the condition of if,
1049  // while, for, and switch statements are local to the if, while, for, or
1050  // switch statement (including the controlled statement).
1051  //
1052  ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1053
1054  // Parse the condition.
1055  ExprResult CondExp;
1056  Decl *CondVar = 0;
1057  if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
1058    return StmtError();
1059
1060  FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
1061
1062  // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1063  // there is no compound stmt.  C90 does not have this clause.  We only do this
1064  // if the body isn't a compound statement to avoid push/pop in common cases.
1065  //
1066  // C++ 6.4p1:
1067  // The substatement in a selection-statement (each substatement, in the else
1068  // form of the if statement) implicitly defines a local scope.
1069  //
1070  // For C++ we create a scope for the condition and a new scope for
1071  // substatements because:
1072  // -When the 'then' scope exits, we want the condition declaration to still be
1073  //    active for the 'else' scope too.
1074  // -Sema will detect name clashes by considering declarations of a
1075  //    'ControlScope' as part of its direct subscope.
1076  // -If we wanted the condition and substatement to be in the same scope, we
1077  //    would have to notify ParseStatement not to create a new scope. It's
1078  //    simpler to let it create a new scope.
1079  //
1080  ParseScope InnerScope(this, Scope::DeclScope,
1081                        C99orCXX && Tok.isNot(tok::l_brace));
1082
1083  // Read the 'then' stmt.
1084  SourceLocation ThenStmtLoc = Tok.getLocation();
1085
1086  SourceLocation InnerStatementTrailingElseLoc;
1087  StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
1088
1089  // Pop the 'if' scope if needed.
1090  InnerScope.Exit();
1091
1092  // If it has an else, parse it.
1093  SourceLocation ElseLoc;
1094  SourceLocation ElseStmtLoc;
1095  StmtResult ElseStmt;
1096
1097  if (Tok.is(tok::kw_else)) {
1098    if (TrailingElseLoc)
1099      *TrailingElseLoc = Tok.getLocation();
1100
1101    ElseLoc = ConsumeToken();
1102    ElseStmtLoc = Tok.getLocation();
1103
1104    // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1105    // there is no compound stmt.  C90 does not have this clause.  We only do
1106    // this if the body isn't a compound statement to avoid push/pop in common
1107    // cases.
1108    //
1109    // C++ 6.4p1:
1110    // The substatement in a selection-statement (each substatement, in the else
1111    // form of the if statement) implicitly defines a local scope.
1112    //
1113    ParseScope InnerScope(this, Scope::DeclScope,
1114                          C99orCXX && Tok.isNot(tok::l_brace));
1115
1116    ElseStmt = ParseStatement();
1117
1118    // Pop the 'else' scope if needed.
1119    InnerScope.Exit();
1120  } else if (Tok.is(tok::code_completion)) {
1121    Actions.CodeCompleteAfterIf(getCurScope());
1122    cutOffParsing();
1123    return StmtError();
1124  } else if (InnerStatementTrailingElseLoc.isValid()) {
1125    Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1126  }
1127
1128  IfScope.Exit();
1129
1130  // If the then or else stmt is invalid and the other is valid (and present),
1131  // make turn the invalid one into a null stmt to avoid dropping the other
1132  // part.  If both are invalid, return error.
1133  if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1134      (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1135      (ThenStmt.get() == 0  && ElseStmt.isInvalid())) {
1136    // Both invalid, or one is invalid and other is non-present: return error.
1137    return StmtError();
1138  }
1139
1140  // Now if either are invalid, replace with a ';'.
1141  if (ThenStmt.isInvalid())
1142    ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1143  if (ElseStmt.isInvalid())
1144    ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1145
1146  return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
1147                             ElseLoc, ElseStmt.get());
1148}
1149
1150/// ParseSwitchStatement
1151///       switch-statement:
1152///         'switch' '(' expression ')' statement
1153/// [C++]   'switch' '(' condition ')' statement
1154StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1155  assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1156  SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
1157
1158  if (Tok.isNot(tok::l_paren)) {
1159    Diag(Tok, diag::err_expected_lparen_after) << "switch";
1160    SkipUntil(tok::semi);
1161    return StmtError();
1162  }
1163
1164  bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1165
1166  // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
1167  // not the case for C90.  Start the switch scope.
1168  //
1169  // C++ 6.4p3:
1170  // A name introduced by a declaration in a condition is in scope from its
1171  // point of declaration until the end of the substatements controlled by the
1172  // condition.
1173  // C++ 3.3.2p4:
1174  // Names declared in the for-init-statement, and in the condition of if,
1175  // while, for, and switch statements are local to the if, while, for, or
1176  // switch statement (including the controlled statement).
1177  //
1178  unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
1179  if (C99orCXX)
1180    ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1181  ParseScope SwitchScope(this, ScopeFlags);
1182
1183  // Parse the condition.
1184  ExprResult Cond;
1185  Decl *CondVar = 0;
1186  if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1187    return StmtError();
1188
1189  StmtResult Switch
1190    = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1191
1192  if (Switch.isInvalid()) {
1193    // Skip the switch body.
1194    // FIXME: This is not optimal recovery, but parsing the body is more
1195    // dangerous due to the presence of case and default statements, which
1196    // will have no place to connect back with the switch.
1197    if (Tok.is(tok::l_brace)) {
1198      ConsumeBrace();
1199      SkipUntil(tok::r_brace);
1200    } else
1201      SkipUntil(tok::semi);
1202    return Switch;
1203  }
1204
1205  // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1206  // there is no compound stmt.  C90 does not have this clause.  We only do this
1207  // if the body isn't a compound statement to avoid push/pop in common cases.
1208  //
1209  // C++ 6.4p1:
1210  // The substatement in a selection-statement (each substatement, in the else
1211  // form of the if statement) implicitly defines a local scope.
1212  //
1213  // See comments in ParseIfStatement for why we create a scope for the
1214  // condition and a new scope for substatement in C++.
1215  //
1216  ParseScope InnerScope(this, Scope::DeclScope,
1217                        C99orCXX && Tok.isNot(tok::l_brace));
1218
1219  // Read the body statement.
1220  StmtResult Body(ParseStatement(TrailingElseLoc));
1221
1222  // Pop the scopes.
1223  InnerScope.Exit();
1224  SwitchScope.Exit();
1225
1226  if (Body.isInvalid()) {
1227    // FIXME: Remove the case statement list from the Switch statement.
1228
1229    // Put the synthesized null statement on the same line as the end of switch
1230    // condition.
1231    SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1232    Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1233  }
1234
1235  return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1236}
1237
1238/// ParseWhileStatement
1239///       while-statement: [C99 6.8.5.1]
1240///         'while' '(' expression ')' statement
1241/// [C++]   'while' '(' condition ')' statement
1242StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1243  assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1244  SourceLocation WhileLoc = Tok.getLocation();
1245  ConsumeToken();  // eat the 'while'.
1246
1247  if (Tok.isNot(tok::l_paren)) {
1248    Diag(Tok, diag::err_expected_lparen_after) << "while";
1249    SkipUntil(tok::semi);
1250    return StmtError();
1251  }
1252
1253  bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1254
1255  // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
1256  // the case for C90.  Start the loop scope.
1257  //
1258  // C++ 6.4p3:
1259  // A name introduced by a declaration in a condition is in scope from its
1260  // point of declaration until the end of the substatements controlled by the
1261  // condition.
1262  // C++ 3.3.2p4:
1263  // Names declared in the for-init-statement, and in the condition of if,
1264  // while, for, and switch statements are local to the if, while, for, or
1265  // switch statement (including the controlled statement).
1266  //
1267  unsigned ScopeFlags;
1268  if (C99orCXX)
1269    ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1270                 Scope::DeclScope  | Scope::ControlScope;
1271  else
1272    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1273  ParseScope WhileScope(this, ScopeFlags);
1274
1275  // Parse the condition.
1276  ExprResult Cond;
1277  Decl *CondVar = 0;
1278  if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1279    return StmtError();
1280
1281  FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
1282
1283  // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1284  // there is no compound stmt.  C90 does not have this clause.  We only do this
1285  // if the body isn't a compound statement to avoid push/pop in common cases.
1286  //
1287  // C++ 6.5p2:
1288  // The substatement in an iteration-statement implicitly defines a local scope
1289  // which is entered and exited each time through the loop.
1290  //
1291  // See comments in ParseIfStatement for why we create a scope for the
1292  // condition and a new scope for substatement in C++.
1293  //
1294  ParseScope InnerScope(this, Scope::DeclScope,
1295                        C99orCXX && Tok.isNot(tok::l_brace));
1296
1297  // Read the body statement.
1298  StmtResult Body(ParseStatement(TrailingElseLoc));
1299
1300  // Pop the body scope if needed.
1301  InnerScope.Exit();
1302  WhileScope.Exit();
1303
1304  if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1305    return StmtError();
1306
1307  return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1308}
1309
1310/// ParseDoStatement
1311///       do-statement: [C99 6.8.5.2]
1312///         'do' statement 'while' '(' expression ')' ';'
1313/// Note: this lets the caller parse the end ';'.
1314StmtResult Parser::ParseDoStatement() {
1315  assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1316  SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
1317
1318  // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
1319  // the case for C90.  Start the loop scope.
1320  unsigned ScopeFlags;
1321  if (getLangOpts().C99)
1322    ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1323  else
1324    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1325
1326  ParseScope DoScope(this, ScopeFlags);
1327
1328  // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1329  // there is no compound stmt.  C90 does not have this clause. We only do this
1330  // if the body isn't a compound statement to avoid push/pop in common cases.
1331  //
1332  // C++ 6.5p2:
1333  // The substatement in an iteration-statement implicitly defines a local scope
1334  // which is entered and exited each time through the loop.
1335  //
1336  ParseScope InnerScope(this, Scope::DeclScope,
1337                        (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
1338                        Tok.isNot(tok::l_brace));
1339
1340  // Read the body statement.
1341  StmtResult Body(ParseStatement());
1342
1343  // Pop the body scope if needed.
1344  InnerScope.Exit();
1345
1346  if (Tok.isNot(tok::kw_while)) {
1347    if (!Body.isInvalid()) {
1348      Diag(Tok, diag::err_expected_while);
1349      Diag(DoLoc, diag::note_matching) << "do";
1350      SkipUntil(tok::semi, StopBeforeMatch);
1351    }
1352    return StmtError();
1353  }
1354  SourceLocation WhileLoc = ConsumeToken();
1355
1356  if (Tok.isNot(tok::l_paren)) {
1357    Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1358    SkipUntil(tok::semi, StopBeforeMatch);
1359    return StmtError();
1360  }
1361
1362  // Parse the parenthesized expression.
1363  BalancedDelimiterTracker T(*this, tok::l_paren);
1364  T.consumeOpen();
1365
1366  // A do-while expression is not a condition, so can't have attributes.
1367  DiagnoseAndSkipCXX11Attributes();
1368
1369  ExprResult Cond = ParseExpression();
1370  T.consumeClose();
1371  DoScope.Exit();
1372
1373  if (Cond.isInvalid() || Body.isInvalid())
1374    return StmtError();
1375
1376  return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1377                             Cond.get(), T.getCloseLocation());
1378}
1379
1380/// ParseForStatement
1381///       for-statement: [C99 6.8.5.3]
1382///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1383///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1384/// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1385/// [C++]       statement
1386/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
1387/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1388/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1389///
1390/// [C++] for-init-statement:
1391/// [C++]   expression-statement
1392/// [C++]   simple-declaration
1393///
1394/// [C++0x] for-range-declaration:
1395/// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
1396/// [C++0x] for-range-initializer:
1397/// [C++0x]   expression
1398/// [C++0x]   braced-init-list            [TODO]
1399StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1400  assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1401  SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
1402
1403  if (Tok.isNot(tok::l_paren)) {
1404    Diag(Tok, diag::err_expected_lparen_after) << "for";
1405    SkipUntil(tok::semi);
1406    return StmtError();
1407  }
1408
1409  bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1410    getLangOpts().ObjC1;
1411
1412  // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1413  // the case for C90.  Start the loop scope.
1414  //
1415  // C++ 6.4p3:
1416  // A name introduced by a declaration in a condition is in scope from its
1417  // point of declaration until the end of the substatements controlled by the
1418  // condition.
1419  // C++ 3.3.2p4:
1420  // Names declared in the for-init-statement, and in the condition of if,
1421  // while, for, and switch statements are local to the if, while, for, or
1422  // switch statement (including the controlled statement).
1423  // C++ 6.5.3p1:
1424  // Names declared in the for-init-statement are in the same declarative-region
1425  // as those declared in the condition.
1426  //
1427  unsigned ScopeFlags;
1428  if (C99orCXXorObjC)
1429    ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1430                 Scope::DeclScope  | Scope::ControlScope;
1431  else
1432    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1433
1434  ParseScope ForScope(this, ScopeFlags);
1435
1436  BalancedDelimiterTracker T(*this, tok::l_paren);
1437  T.consumeOpen();
1438
1439  ExprResult Value;
1440
1441  bool ForEach = false, ForRange = false;
1442  StmtResult FirstPart;
1443  bool SecondPartIsInvalid = false;
1444  FullExprArg SecondPart(Actions);
1445  ExprResult Collection;
1446  ForRangeInit ForRangeInit;
1447  FullExprArg ThirdPart(Actions);
1448  Decl *SecondVar = 0;
1449
1450  if (Tok.is(tok::code_completion)) {
1451    Actions.CodeCompleteOrdinaryName(getCurScope(),
1452                                     C99orCXXorObjC? Sema::PCC_ForInit
1453                                                   : Sema::PCC_Expression);
1454    cutOffParsing();
1455    return StmtError();
1456  }
1457
1458  ParsedAttributesWithRange attrs(AttrFactory);
1459  MaybeParseCXX11Attributes(attrs);
1460
1461  // Parse the first part of the for specifier.
1462  if (Tok.is(tok::semi)) {  // for (;
1463    ProhibitAttributes(attrs);
1464    // no first part, eat the ';'.
1465    ConsumeToken();
1466  } else if (isForInitDeclaration()) {  // for (int X = 4;
1467    // Parse declaration, which eats the ';'.
1468    if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
1469      Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1470
1471    // In C++0x, "for (T NS:a" might not be a typo for ::
1472    bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1473    ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1474
1475    SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1476    StmtVector Stmts;
1477    DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1478                                               DeclEnd, attrs, false,
1479                                               MightBeForRangeStmt ?
1480                                                 &ForRangeInit : 0);
1481    FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1482
1483    if (ForRangeInit.ParsedForRangeDecl()) {
1484      Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1485           diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1486
1487      ForRange = true;
1488    } else if (Tok.is(tok::semi)) {  // for (int x = 4;
1489      ConsumeToken();
1490    } else if ((ForEach = isTokIdentifier_in())) {
1491      Actions.ActOnForEachDeclStmt(DG);
1492      // ObjC: for (id x in expr)
1493      ConsumeToken(); // consume 'in'
1494
1495      if (Tok.is(tok::code_completion)) {
1496        Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1497        cutOffParsing();
1498        return StmtError();
1499      }
1500      Collection = ParseExpression();
1501    } else {
1502      Diag(Tok, diag::err_expected_semi_for);
1503    }
1504  } else {
1505    ProhibitAttributes(attrs);
1506    Value = ParseExpression();
1507
1508    ForEach = isTokIdentifier_in();
1509
1510    // Turn the expression into a stmt.
1511    if (!Value.isInvalid()) {
1512      if (ForEach)
1513        FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1514      else
1515        FirstPart = Actions.ActOnExprStmt(Value);
1516    }
1517
1518    if (Tok.is(tok::semi)) {
1519      ConsumeToken();
1520    } else if (ForEach) {
1521      ConsumeToken(); // consume 'in'
1522
1523      if (Tok.is(tok::code_completion)) {
1524        Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1525        cutOffParsing();
1526        return StmtError();
1527      }
1528      Collection = ParseExpression();
1529    } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1530      // User tried to write the reasonable, but ill-formed, for-range-statement
1531      //   for (expr : expr) { ... }
1532      Diag(Tok, diag::err_for_range_expected_decl)
1533        << FirstPart.get()->getSourceRange();
1534      SkipUntil(tok::r_paren, StopBeforeMatch);
1535      SecondPartIsInvalid = true;
1536    } else {
1537      if (!Value.isInvalid()) {
1538        Diag(Tok, diag::err_expected_semi_for);
1539      } else {
1540        // Skip until semicolon or rparen, don't consume it.
1541        SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1542        if (Tok.is(tok::semi))
1543          ConsumeToken();
1544      }
1545    }
1546  }
1547  if (!ForEach && !ForRange) {
1548    assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1549    // Parse the second part of the for specifier.
1550    if (Tok.is(tok::semi)) {  // for (...;;
1551      // no second part.
1552    } else if (Tok.is(tok::r_paren)) {
1553      // missing both semicolons.
1554    } else {
1555      ExprResult Second;
1556      if (getLangOpts().CPlusPlus)
1557        ParseCXXCondition(Second, SecondVar, ForLoc, true);
1558      else {
1559        Second = ParseExpression();
1560        if (!Second.isInvalid())
1561          Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1562                                                 Second.get());
1563      }
1564      SecondPartIsInvalid = Second.isInvalid();
1565      SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
1566    }
1567
1568    if (Tok.isNot(tok::semi)) {
1569      if (!SecondPartIsInvalid || SecondVar)
1570        Diag(Tok, diag::err_expected_semi_for);
1571      else
1572        // Skip until semicolon or rparen, don't consume it.
1573        SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1574    }
1575
1576    if (Tok.is(tok::semi)) {
1577      ConsumeToken();
1578    }
1579
1580    // Parse the third part of the for specifier.
1581    if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
1582      ExprResult Third = ParseExpression();
1583      // FIXME: The C++11 standard doesn't actually say that this is a
1584      // discarded-value expression, but it clearly should be.
1585      ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
1586    }
1587  }
1588  // Match the ')'.
1589  T.consumeClose();
1590
1591  // We need to perform most of the semantic analysis for a C++0x for-range
1592  // statememt before parsing the body, in order to be able to deduce the type
1593  // of an auto-typed loop variable.
1594  StmtResult ForRangeStmt;
1595  StmtResult ForEachStmt;
1596
1597  if (ForRange) {
1598    ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
1599                                                ForRangeInit.ColonLoc,
1600                                                ForRangeInit.RangeExpr.get(),
1601                                                T.getCloseLocation(),
1602                                                Sema::BFRK_Build);
1603
1604
1605  // Similarly, we need to do the semantic analysis for a for-range
1606  // statement immediately in order to close over temporaries correctly.
1607  } else if (ForEach) {
1608    ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1609                                                     FirstPart.take(),
1610                                                     Collection.take(),
1611                                                     T.getCloseLocation());
1612  }
1613
1614  // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1615  // there is no compound stmt.  C90 does not have this clause.  We only do this
1616  // if the body isn't a compound statement to avoid push/pop in common cases.
1617  //
1618  // C++ 6.5p2:
1619  // The substatement in an iteration-statement implicitly defines a local scope
1620  // which is entered and exited each time through the loop.
1621  //
1622  // See comments in ParseIfStatement for why we create a scope for
1623  // for-init-statement/condition and a new scope for substatement in C++.
1624  //
1625  ParseScope InnerScope(this, Scope::DeclScope,
1626                        C99orCXXorObjC && Tok.isNot(tok::l_brace));
1627
1628  // Read the body statement.
1629  StmtResult Body(ParseStatement(TrailingElseLoc));
1630
1631  // Pop the body scope if needed.
1632  InnerScope.Exit();
1633
1634  // Leave the for-scope.
1635  ForScope.Exit();
1636
1637  if (Body.isInvalid())
1638    return StmtError();
1639
1640  if (ForEach)
1641   return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1642                                              Body.take());
1643
1644  if (ForRange)
1645    return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1646
1647  return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1648                              SecondPart, SecondVar, ThirdPart,
1649                              T.getCloseLocation(), Body.take());
1650}
1651
1652/// ParseGotoStatement
1653///       jump-statement:
1654///         'goto' identifier ';'
1655/// [GNU]   'goto' '*' expression ';'
1656///
1657/// Note: this lets the caller parse the end ';'.
1658///
1659StmtResult Parser::ParseGotoStatement() {
1660  assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1661  SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
1662
1663  StmtResult Res;
1664  if (Tok.is(tok::identifier)) {
1665    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1666                                                Tok.getLocation());
1667    Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1668    ConsumeToken();
1669  } else if (Tok.is(tok::star)) {
1670    // GNU indirect goto extension.
1671    Diag(Tok, diag::ext_gnu_indirect_goto);
1672    SourceLocation StarLoc = ConsumeToken();
1673    ExprResult R(ParseExpression());
1674    if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1675      SkipUntil(tok::semi, StopBeforeMatch);
1676      return StmtError();
1677    }
1678    Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1679  } else {
1680    Diag(Tok, diag::err_expected_ident);
1681    return StmtError();
1682  }
1683
1684  return Res;
1685}
1686
1687/// ParseContinueStatement
1688///       jump-statement:
1689///         'continue' ';'
1690///
1691/// Note: this lets the caller parse the end ';'.
1692///
1693StmtResult Parser::ParseContinueStatement() {
1694  SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
1695  return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1696}
1697
1698/// ParseBreakStatement
1699///       jump-statement:
1700///         'break' ';'
1701///
1702/// Note: this lets the caller parse the end ';'.
1703///
1704StmtResult Parser::ParseBreakStatement() {
1705  SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
1706  return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1707}
1708
1709/// ParseReturnStatement
1710///       jump-statement:
1711///         'return' expression[opt] ';'
1712StmtResult Parser::ParseReturnStatement() {
1713  assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1714  SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
1715
1716  ExprResult R;
1717  if (Tok.isNot(tok::semi)) {
1718    if (Tok.is(tok::code_completion)) {
1719      Actions.CodeCompleteReturn(getCurScope());
1720      cutOffParsing();
1721      return StmtError();
1722    }
1723
1724    if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1725      R = ParseInitializer();
1726      if (R.isUsable())
1727        Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1728             diag::warn_cxx98_compat_generalized_initializer_lists :
1729             diag::ext_generalized_initializer_lists)
1730          << R.get()->getSourceRange();
1731    } else
1732        R = ParseExpression();
1733    if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1734      SkipUntil(tok::semi, StopBeforeMatch);
1735      return StmtError();
1736    }
1737  }
1738  return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1739}
1740
1741namespace {
1742  class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1743    Parser &TheParser;
1744    SourceLocation AsmLoc;
1745    StringRef AsmString;
1746
1747    /// The tokens we streamed into AsmString and handed off to MC.
1748    ArrayRef<Token> AsmToks;
1749
1750    /// The offset of each token in AsmToks within AsmString.
1751    ArrayRef<unsigned> AsmTokOffsets;
1752
1753  public:
1754    ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1755                           StringRef AsmString,
1756                           ArrayRef<Token> Toks,
1757                           ArrayRef<unsigned> Offsets)
1758      : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1759        AsmToks(Toks), AsmTokOffsets(Offsets) {
1760      assert(AsmToks.size() == AsmTokOffsets.size());
1761    }
1762
1763    void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1764                                    InlineAsmIdentifierInfo &Info,
1765                                    bool IsUnevaluatedContext) {
1766      // Collect the desired tokens.
1767      SmallVector<Token, 16> LineToks;
1768      const Token *FirstOrigToken = 0;
1769      findTokensForString(LineBuf, LineToks, FirstOrigToken);
1770
1771      unsigned NumConsumedToks;
1772      ExprResult Result =
1773        TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1774                                       IsUnevaluatedContext);
1775
1776      // If we consumed the entire line, tell MC that.
1777      // Also do this if we consumed nothing as a way of reporting failure.
1778      if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1779        // By not modifying LineBuf, we're implicitly consuming it all.
1780
1781      // Otherwise, consume up to the original tokens.
1782      } else {
1783        assert(FirstOrigToken && "not using original tokens?");
1784
1785        // Since we're using original tokens, apply that offset.
1786        assert(FirstOrigToken[NumConsumedToks].getLocation()
1787                  == LineToks[NumConsumedToks].getLocation());
1788        unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1789        unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1790
1791        // The total length we've consumed is the relative offset
1792        // of the last token we consumed plus its length.
1793        unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1794                                + AsmToks[LastIndex].getLength()
1795                                - AsmTokOffsets[FirstIndex]);
1796        LineBuf = LineBuf.substr(0, TotalOffset);
1797      }
1798
1799      // Initialize the "decl" with the lookup result.
1800      Info.OpDecl = static_cast<void*>(Result.take());
1801      return Info.OpDecl;
1802    }
1803
1804    bool LookupInlineAsmField(StringRef Base, StringRef Member,
1805                              unsigned &Offset) {
1806      return TheParser.getActions().LookupInlineAsmField(Base, Member,
1807                                                         Offset, AsmLoc);
1808    }
1809
1810    static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1811                                    void *Context) {
1812      ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1813    }
1814
1815  private:
1816    /// Collect the appropriate tokens for the given string.
1817    void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1818                             const Token *&FirstOrigToken) const {
1819      // For now, assert that the string we're working with is a substring
1820      // of what we gave to MC.  This lets us use the original tokens.
1821      assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1822             !std::less<const char*>()(AsmString.end(), Str.end()));
1823
1824      // Try to find a token whose offset matches the first token.
1825      unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1826      const unsigned *FirstTokOffset
1827        = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1828                           FirstCharOffset);
1829
1830      // For now, assert that the start of the string exactly
1831      // corresponds to the start of a token.
1832      assert(*FirstTokOffset == FirstCharOffset);
1833
1834      // Use all the original tokens for this line.  (We assume the
1835      // end of the line corresponds cleanly to a token break.)
1836      unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1837      FirstOrigToken = &AsmToks[FirstTokIndex];
1838      unsigned LastCharOffset = Str.end() - AsmString.begin();
1839      for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1840        if (AsmTokOffsets[i] >= LastCharOffset) break;
1841        TempToks.push_back(AsmToks[i]);
1842      }
1843    }
1844
1845    void handleDiagnostic(const llvm::SMDiagnostic &D) {
1846      // Compute an offset into the inline asm buffer.
1847      // FIXME: This isn't right if .macro is involved (but hopefully, no
1848      // real-world code does that).
1849      const llvm::SourceMgr &LSM = *D.getSourceMgr();
1850      const llvm::MemoryBuffer *LBuf =
1851        LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1852      unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1853
1854      // Figure out which token that offset points into.
1855      const unsigned *TokOffsetPtr =
1856        std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1857      unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1858      unsigned TokOffset = *TokOffsetPtr;
1859
1860      // If we come up with an answer which seems sane, use it; otherwise,
1861      // just point at the __asm keyword.
1862      // FIXME: Assert the answer is sane once we handle .macro correctly.
1863      SourceLocation Loc = AsmLoc;
1864      if (TokIndex < AsmToks.size()) {
1865        const Token &Tok = AsmToks[TokIndex];
1866        Loc = Tok.getLocation();
1867        Loc = Loc.getLocWithOffset(Offset - TokOffset);
1868      }
1869      TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1870        << D.getMessage();
1871    }
1872  };
1873}
1874
1875/// Parse an identifier in an MS-style inline assembly block.
1876///
1877/// \param CastInfo - a void* so that we don't have to teach Parser.h
1878///   about the actual type.
1879ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1880                                        unsigned &NumLineToksConsumed,
1881                                        void *CastInfo,
1882                                        bool IsUnevaluatedContext) {
1883  llvm::InlineAsmIdentifierInfo &Info =
1884    *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1885
1886  // Push a fake token on the end so that we don't overrun the token
1887  // stream.  We use ';' because it expression-parsing should never
1888  // overrun it.
1889  const tok::TokenKind EndOfStream = tok::semi;
1890  Token EndOfStreamTok;
1891  EndOfStreamTok.startToken();
1892  EndOfStreamTok.setKind(EndOfStream);
1893  LineToks.push_back(EndOfStreamTok);
1894
1895  // Also copy the current token over.
1896  LineToks.push_back(Tok);
1897
1898  PP.EnterTokenStream(LineToks.begin(),
1899                      LineToks.size(),
1900                      /*disable macros*/ true,
1901                      /*owns tokens*/ false);
1902
1903  // Clear the current token and advance to the first token in LineToks.
1904  ConsumeAnyToken();
1905
1906  // Parse an optional scope-specifier if we're in C++.
1907  CXXScopeSpec SS;
1908  if (getLangOpts().CPlusPlus) {
1909    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1910  }
1911
1912  // Require an identifier here.
1913  SourceLocation TemplateKWLoc;
1914  UnqualifiedId Id;
1915  bool Invalid = ParseUnqualifiedId(SS,
1916                                    /*EnteringContext=*/false,
1917                                    /*AllowDestructorName=*/false,
1918                                    /*AllowConstructorName=*/false,
1919                                    /*ObjectType=*/ ParsedType(),
1920                                    TemplateKWLoc,
1921                                    Id);
1922
1923  // If we've run into the poison token we inserted before, or there
1924  // was a parsing error, then claim the entire line.
1925  if (Invalid || Tok.is(EndOfStream)) {
1926    NumLineToksConsumed = LineToks.size() - 2;
1927
1928    // Otherwise, claim up to the start of the next token.
1929  } else {
1930    // Figure out how many tokens we are into LineToks.
1931    unsigned LineIndex = 0;
1932    while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1933      LineIndex++;
1934      assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1935    }
1936
1937    NumLineToksConsumed = LineIndex;
1938  }
1939
1940  // Finally, restore the old parsing state by consuming all the
1941  // tokens we staged before, implicitly killing off the
1942  // token-lexer we pushed.
1943  for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1944    ConsumeAnyToken();
1945  }
1946  ConsumeToken(EndOfStream);
1947
1948  // Leave LineToks in its original state.
1949  LineToks.pop_back();
1950  LineToks.pop_back();
1951
1952  // Perform the lookup.
1953  return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1954                                           IsUnevaluatedContext);
1955}
1956
1957/// Turn a sequence of our tokens back into a string that we can hand
1958/// to the MC asm parser.
1959static bool buildMSAsmString(Preprocessor &PP,
1960                             SourceLocation AsmLoc,
1961                             ArrayRef<Token> AsmToks,
1962                             SmallVectorImpl<unsigned> &TokOffsets,
1963                             SmallString<512> &Asm) {
1964  assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1965
1966  // Is this the start of a new assembly statement?
1967  bool isNewStatement = true;
1968
1969  for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1970    const Token &Tok = AsmToks[i];
1971
1972    // Start each new statement with a newline and a tab.
1973    if (!isNewStatement &&
1974        (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1975      Asm += "\n\t";
1976      isNewStatement = true;
1977    }
1978
1979    // Preserve the existence of leading whitespace except at the
1980    // start of a statement.
1981    if (!isNewStatement && Tok.hasLeadingSpace())
1982      Asm += ' ';
1983
1984    // Remember the offset of this token.
1985    TokOffsets.push_back(Asm.size());
1986
1987    // Don't actually write '__asm' into the assembly stream.
1988    if (Tok.is(tok::kw_asm)) {
1989      // Complain about __asm at the end of the stream.
1990      if (i + 1 == e) {
1991        PP.Diag(AsmLoc, diag::err_asm_empty);
1992        return true;
1993      }
1994
1995      continue;
1996    }
1997
1998    // Append the spelling of the token.
1999    SmallString<32> SpellingBuffer;
2000    bool SpellingInvalid = false;
2001    Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
2002    assert(!SpellingInvalid && "spelling was invalid after correct parse?");
2003
2004    // We are no longer at the start of a statement.
2005    isNewStatement = false;
2006  }
2007
2008  // Ensure that the buffer is null-terminated.
2009  Asm.push_back('\0');
2010  Asm.pop_back();
2011
2012  assert(TokOffsets.size() == AsmToks.size());
2013  return false;
2014}
2015
2016/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
2017/// this routine is called to collect the tokens for an MS asm statement.
2018///
2019/// [MS]  ms-asm-statement:
2020///         ms-asm-block
2021///         ms-asm-block ms-asm-statement
2022///
2023/// [MS]  ms-asm-block:
2024///         '__asm' ms-asm-line '\n'
2025///         '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
2026///
2027/// [MS]  ms-asm-instruction-block
2028///         ms-asm-line
2029///         ms-asm-line '\n' ms-asm-instruction-block
2030///
2031StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
2032  SourceManager &SrcMgr = PP.getSourceManager();
2033  SourceLocation EndLoc = AsmLoc;
2034  SmallVector<Token, 4> AsmToks;
2035
2036  bool InBraces = false;
2037  unsigned short savedBraceCount = 0;
2038  bool InAsmComment = false;
2039  FileID FID;
2040  unsigned LineNo = 0;
2041  unsigned NumTokensRead = 0;
2042  SourceLocation LBraceLoc;
2043
2044  if (Tok.is(tok::l_brace)) {
2045    // Braced inline asm: consume the opening brace.
2046    InBraces = true;
2047    savedBraceCount = BraceCount;
2048    EndLoc = LBraceLoc = ConsumeBrace();
2049    ++NumTokensRead;
2050  } else {
2051    // Single-line inline asm; compute which line it is on.
2052    std::pair<FileID, unsigned> ExpAsmLoc =
2053      SrcMgr.getDecomposedExpansionLoc(EndLoc);
2054    FID = ExpAsmLoc.first;
2055    LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2056  }
2057
2058  SourceLocation TokLoc = Tok.getLocation();
2059  do {
2060    // If we hit EOF, we're done, period.
2061    if (Tok.is(tok::eof))
2062      break;
2063
2064    if (!InAsmComment && Tok.is(tok::semi)) {
2065      // A semicolon in an asm is the start of a comment.
2066      InAsmComment = true;
2067      if (InBraces) {
2068        // Compute which line the comment is on.
2069        std::pair<FileID, unsigned> ExpSemiLoc =
2070          SrcMgr.getDecomposedExpansionLoc(TokLoc);
2071        FID = ExpSemiLoc.first;
2072        LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2073      }
2074    } else if (!InBraces || InAsmComment) {
2075      // If end-of-line is significant, check whether this token is on a
2076      // new line.
2077      std::pair<FileID, unsigned> ExpLoc =
2078        SrcMgr.getDecomposedExpansionLoc(TokLoc);
2079      if (ExpLoc.first != FID ||
2080          SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2081        // If this is a single-line __asm, we're done.
2082        if (!InBraces)
2083          break;
2084        // We're no longer in a comment.
2085        InAsmComment = false;
2086      } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2087        // Single-line asm always ends when a closing brace is seen.
2088        // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2089        // does MSVC do here?
2090        break;
2091      }
2092    }
2093    if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2094        BraceCount == (savedBraceCount + 1)) {
2095      // Consume the closing brace, and finish
2096      EndLoc = ConsumeBrace();
2097      break;
2098    }
2099
2100    // Consume the next token; make sure we don't modify the brace count etc.
2101    // if we are in a comment.
2102    EndLoc = TokLoc;
2103    if (InAsmComment)
2104      PP.Lex(Tok);
2105    else {
2106      AsmToks.push_back(Tok);
2107      ConsumeAnyToken();
2108    }
2109    TokLoc = Tok.getLocation();
2110    ++NumTokensRead;
2111  } while (1);
2112
2113  if (InBraces && BraceCount != savedBraceCount) {
2114    // __asm without closing brace (this can happen at EOF).
2115    Diag(Tok, diag::err_expected_rbrace);
2116    Diag(LBraceLoc, diag::note_matching) << "{";
2117    return StmtError();
2118  } else if (NumTokensRead == 0) {
2119    // Empty __asm.
2120    Diag(Tok, diag::err_expected_lbrace);
2121    return StmtError();
2122  }
2123
2124  // Okay, prepare to use MC to parse the assembly.
2125  SmallVector<StringRef, 4> ConstraintRefs;
2126  SmallVector<Expr*, 4> Exprs;
2127  SmallVector<StringRef, 4> ClobberRefs;
2128
2129  // We need an actual supported target.
2130  llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2131  llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2132  const std::string &TT = TheTriple.getTriple();
2133  const llvm::Target *TheTarget = 0;
2134  bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2135                          ArchTy != llvm::Triple::x86_64);
2136  if (UnsupportedArch) {
2137    Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2138  } else {
2139    std::string Error;
2140    TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2141    if (!TheTarget)
2142      Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
2143  }
2144
2145  // If we don't support assembly, or the assembly is empty, we don't
2146  // need to instantiate the AsmParser, etc.
2147  if (!TheTarget || AsmToks.empty()) {
2148    return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2149                                  /*NumOutputs*/ 0, /*NumInputs*/ 0,
2150                                  ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2151  }
2152
2153  // Expand the tokens into a string buffer.
2154  SmallString<512> AsmString;
2155  SmallVector<unsigned, 8> TokOffsets;
2156  if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2157    return StmtError();
2158
2159  OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2160  OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
2161  // Get the instruction descriptor.
2162  const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
2163  OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2164  OwningPtr<llvm::MCSubtargetInfo>
2165    STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2166
2167  llvm::SourceMgr TempSrcMgr;
2168  llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
2169  llvm::MemoryBuffer *Buffer =
2170    llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2171
2172  // Tell SrcMgr about this buffer, which is what the parser will pick up.
2173  TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2174
2175  OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2176  OwningPtr<llvm::MCAsmParser>
2177    Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2178  OwningPtr<llvm::MCTargetAsmParser>
2179    TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
2180
2181  llvm::MCInstPrinter *IP =
2182    TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2183
2184  // Change to the Intel dialect.
2185  Parser->setAssemblerDialect(1);
2186  Parser->setTargetParser(*TargetParser.get());
2187  Parser->setParsingInlineAsm(true);
2188  TargetParser->setParsingInlineAsm(true);
2189
2190  ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2191                                  AsmToks, TokOffsets);
2192  TargetParser->setSemaCallback(&Callback);
2193  TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2194                            &Callback);
2195
2196  unsigned NumOutputs;
2197  unsigned NumInputs;
2198  std::string AsmStringIR;
2199  SmallVector<std::pair<void *, bool>, 4> OpExprs;
2200  SmallVector<std::string, 4> Constraints;
2201  SmallVector<std::string, 4> Clobbers;
2202  if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2203                               NumOutputs, NumInputs, OpExprs, Constraints,
2204                               Clobbers, MII, IP, Callback))
2205    return StmtError();
2206
2207  // Build the vector of clobber StringRefs.
2208  unsigned NumClobbers = Clobbers.size();
2209  ClobberRefs.resize(NumClobbers);
2210  for (unsigned i = 0; i != NumClobbers; ++i)
2211    ClobberRefs[i] = StringRef(Clobbers[i]);
2212
2213  // Recast the void pointers and build the vector of constraint StringRefs.
2214  unsigned NumExprs = NumOutputs + NumInputs;
2215  ConstraintRefs.resize(NumExprs);
2216  Exprs.resize(NumExprs);
2217  for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2218    Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2219    if (!OpExpr)
2220      return StmtError();
2221
2222    // Need address of variable.
2223    if (OpExprs[i].second)
2224      OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2225        .take();
2226
2227    ConstraintRefs[i] = StringRef(Constraints[i]);
2228    Exprs[i] = OpExpr;
2229  }
2230
2231  // FIXME: We should be passing source locations for better diagnostics.
2232  return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2233                                NumOutputs, NumInputs,
2234                                ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2235}
2236
2237/// ParseAsmStatement - Parse a GNU extended asm statement.
2238///       asm-statement:
2239///         gnu-asm-statement
2240///         ms-asm-statement
2241///
2242/// [GNU] gnu-asm-statement:
2243///         'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2244///
2245/// [GNU] asm-argument:
2246///         asm-string-literal
2247///         asm-string-literal ':' asm-operands[opt]
2248///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2249///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2250///                 ':' asm-clobbers
2251///
2252/// [GNU] asm-clobbers:
2253///         asm-string-literal
2254///         asm-clobbers ',' asm-string-literal
2255///
2256StmtResult Parser::ParseAsmStatement(bool &msAsm) {
2257  assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
2258  SourceLocation AsmLoc = ConsumeToken();
2259
2260  if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
2261      !isTypeQualifier()) {
2262    msAsm = true;
2263    return ParseMicrosoftAsmStatement(AsmLoc);
2264  }
2265  DeclSpec DS(AttrFactory);
2266  SourceLocation Loc = Tok.getLocation();
2267  ParseTypeQualifierListOpt(DS, true, false);
2268
2269  // GNU asms accept, but warn, about type-qualifiers other than volatile.
2270  if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2271    Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
2272  if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2273    Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
2274  // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2275  if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2276    Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
2277
2278  // Remember if this was a volatile asm.
2279  bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
2280  if (Tok.isNot(tok::l_paren)) {
2281    Diag(Tok, diag::err_expected_lparen_after) << "asm";
2282    SkipUntil(tok::r_paren, StopAtSemi);
2283    return StmtError();
2284  }
2285  BalancedDelimiterTracker T(*this, tok::l_paren);
2286  T.consumeOpen();
2287
2288  ExprResult AsmString(ParseAsmStringLiteral());
2289  if (AsmString.isInvalid()) {
2290    // Consume up to and including the closing paren.
2291    T.skipToEnd();
2292    return StmtError();
2293  }
2294
2295  SmallVector<IdentifierInfo *, 4> Names;
2296  ExprVector Constraints;
2297  ExprVector Exprs;
2298  ExprVector Clobbers;
2299
2300  if (Tok.is(tok::r_paren)) {
2301    // We have a simple asm expression like 'asm("foo")'.
2302    T.consumeClose();
2303    return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2304                                   /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2305                                   Constraints, Exprs, AsmString.take(),
2306                                   Clobbers, T.getCloseLocation());
2307  }
2308
2309  // Parse Outputs, if present.
2310  bool AteExtraColon = false;
2311  if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2312    // In C++ mode, parse "::" like ": :".
2313    AteExtraColon = Tok.is(tok::coloncolon);
2314    ConsumeToken();
2315
2316    if (!AteExtraColon &&
2317        ParseAsmOperandsOpt(Names, Constraints, Exprs))
2318      return StmtError();
2319  }
2320
2321  unsigned NumOutputs = Names.size();
2322
2323  // Parse Inputs, if present.
2324  if (AteExtraColon ||
2325      Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2326    // In C++ mode, parse "::" like ": :".
2327    if (AteExtraColon)
2328      AteExtraColon = false;
2329    else {
2330      AteExtraColon = Tok.is(tok::coloncolon);
2331      ConsumeToken();
2332    }
2333
2334    if (!AteExtraColon &&
2335        ParseAsmOperandsOpt(Names, Constraints, Exprs))
2336      return StmtError();
2337  }
2338
2339  assert(Names.size() == Constraints.size() &&
2340         Constraints.size() == Exprs.size() &&
2341         "Input operand size mismatch!");
2342
2343  unsigned NumInputs = Names.size() - NumOutputs;
2344
2345  // Parse the clobbers, if present.
2346  if (AteExtraColon || Tok.is(tok::colon)) {
2347    if (!AteExtraColon)
2348      ConsumeToken();
2349
2350    // Parse the asm-string list for clobbers if present.
2351    if (Tok.isNot(tok::r_paren)) {
2352      while (1) {
2353        ExprResult Clobber(ParseAsmStringLiteral());
2354
2355        if (Clobber.isInvalid())
2356          break;
2357
2358        Clobbers.push_back(Clobber.release());
2359
2360        if (Tok.isNot(tok::comma)) break;
2361        ConsumeToken();
2362      }
2363    }
2364  }
2365
2366  T.consumeClose();
2367  return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2368                                 NumInputs, Names.data(), Constraints, Exprs,
2369                                 AsmString.take(), Clobbers,
2370                                 T.getCloseLocation());
2371}
2372
2373/// ParseAsmOperands - Parse the asm-operands production as used by
2374/// asm-statement, assuming the leading ':' token was eaten.
2375///
2376/// [GNU] asm-operands:
2377///         asm-operand
2378///         asm-operands ',' asm-operand
2379///
2380/// [GNU] asm-operand:
2381///         asm-string-literal '(' expression ')'
2382///         '[' identifier ']' asm-string-literal '(' expression ')'
2383///
2384//
2385// FIXME: Avoid unnecessary std::string trashing.
2386bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2387                                 SmallVectorImpl<Expr *> &Constraints,
2388                                 SmallVectorImpl<Expr *> &Exprs) {
2389  // 'asm-operands' isn't present?
2390  if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
2391    return false;
2392
2393  while (1) {
2394    // Read the [id] if present.
2395    if (Tok.is(tok::l_square)) {
2396      BalancedDelimiterTracker T(*this, tok::l_square);
2397      T.consumeOpen();
2398
2399      if (Tok.isNot(tok::identifier)) {
2400        Diag(Tok, diag::err_expected_ident);
2401        SkipUntil(tok::r_paren, StopAtSemi);
2402        return true;
2403      }
2404
2405      IdentifierInfo *II = Tok.getIdentifierInfo();
2406      ConsumeToken();
2407
2408      Names.push_back(II);
2409      T.consumeClose();
2410    } else
2411      Names.push_back(0);
2412
2413    ExprResult Constraint(ParseAsmStringLiteral());
2414    if (Constraint.isInvalid()) {
2415        SkipUntil(tok::r_paren, StopAtSemi);
2416        return true;
2417    }
2418    Constraints.push_back(Constraint.release());
2419
2420    if (Tok.isNot(tok::l_paren)) {
2421      Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
2422      SkipUntil(tok::r_paren, StopAtSemi);
2423      return true;
2424    }
2425
2426    // Read the parenthesized expression.
2427    BalancedDelimiterTracker T(*this, tok::l_paren);
2428    T.consumeOpen();
2429    ExprResult Res(ParseExpression());
2430    T.consumeClose();
2431    if (Res.isInvalid()) {
2432      SkipUntil(tok::r_paren, StopAtSemi);
2433      return true;
2434    }
2435    Exprs.push_back(Res.release());
2436    // Eat the comma and continue parsing if it exists.
2437    if (Tok.isNot(tok::comma)) return false;
2438    ConsumeToken();
2439  }
2440}
2441
2442Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2443  assert(Tok.is(tok::l_brace));
2444  SourceLocation LBraceLoc = Tok.getLocation();
2445
2446  if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
2447      trySkippingFunctionBody()) {
2448    BodyScope.Exit();
2449    return Actions.ActOnSkippedFunctionBody(Decl);
2450  }
2451
2452  PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2453                                      "parsing function body");
2454
2455  // Do not enter a scope for the brace, as the arguments are in the same scope
2456  // (the function body) as the body itself.  Instead, just read the statement
2457  // list and put it into a CompoundStmt for safe keeping.
2458  StmtResult FnBody(ParseCompoundStatementBody());
2459
2460  // If the function body could not be parsed, make a bogus compoundstmt.
2461  if (FnBody.isInvalid()) {
2462    Sema::CompoundScopeRAII CompoundScope(Actions);
2463    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2464  }
2465
2466  BodyScope.Exit();
2467  return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2468}
2469
2470/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2471///
2472///       function-try-block:
2473///         'try' ctor-initializer[opt] compound-statement handler-seq
2474///
2475Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2476  assert(Tok.is(tok::kw_try) && "Expected 'try'");
2477  SourceLocation TryLoc = ConsumeToken();
2478
2479  PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2480                                      "parsing function try block");
2481
2482  // Constructor initializer list?
2483  if (Tok.is(tok::colon))
2484    ParseConstructorInitializer(Decl);
2485  else
2486    Actions.ActOnDefaultCtorInitializers(Decl);
2487
2488  if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2489      trySkippingFunctionBody()) {
2490    BodyScope.Exit();
2491    return Actions.ActOnSkippedFunctionBody(Decl);
2492  }
2493
2494  SourceLocation LBraceLoc = Tok.getLocation();
2495  StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2496  // If we failed to parse the try-catch, we just give the function an empty
2497  // compound statement as the body.
2498  if (FnBody.isInvalid()) {
2499    Sema::CompoundScopeRAII CompoundScope(Actions);
2500    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2501  }
2502
2503  BodyScope.Exit();
2504  return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2505}
2506
2507bool Parser::trySkippingFunctionBody() {
2508  assert(Tok.is(tok::l_brace));
2509  assert(SkipFunctionBodies &&
2510         "Should only be called when SkipFunctionBodies is enabled");
2511
2512  if (!PP.isCodeCompletionEnabled()) {
2513    ConsumeBrace();
2514    SkipUntil(tok::r_brace);
2515    return true;
2516  }
2517
2518  // We're in code-completion mode. Skip parsing for all function bodies unless
2519  // the body contains the code-completion point.
2520  TentativeParsingAction PA(*this);
2521  ConsumeBrace();
2522  if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2523    PA.Commit();
2524    return true;
2525  }
2526
2527  PA.Revert();
2528  return false;
2529}
2530
2531/// ParseCXXTryBlock - Parse a C++ try-block.
2532///
2533///       try-block:
2534///         'try' compound-statement handler-seq
2535///
2536StmtResult Parser::ParseCXXTryBlock() {
2537  assert(Tok.is(tok::kw_try) && "Expected 'try'");
2538
2539  SourceLocation TryLoc = ConsumeToken();
2540  return ParseCXXTryBlockCommon(TryLoc);
2541}
2542
2543/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2544/// function-try-block.
2545///
2546///       try-block:
2547///         'try' compound-statement handler-seq
2548///
2549///       function-try-block:
2550///         'try' ctor-initializer[opt] compound-statement handler-seq
2551///
2552///       handler-seq:
2553///         handler handler-seq[opt]
2554///
2555///       [Borland] try-block:
2556///         'try' compound-statement seh-except-block
2557///         'try' compound-statment  seh-finally-block
2558///
2559StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2560  if (Tok.isNot(tok::l_brace))
2561    return StmtError(Diag(Tok, diag::err_expected_lbrace));
2562  // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2563
2564  StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2565                      Scope::DeclScope | Scope::TryScope |
2566                        (FnTry ? Scope::FnTryCatchScope : 0)));
2567  if (TryBlock.isInvalid())
2568    return TryBlock;
2569
2570  // Borland allows SEH-handlers with 'try'
2571
2572  if ((Tok.is(tok::identifier) &&
2573       Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2574      Tok.is(tok::kw___finally)) {
2575    // TODO: Factor into common return ParseSEHHandlerCommon(...)
2576    StmtResult Handler;
2577    if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2578      SourceLocation Loc = ConsumeToken();
2579      Handler = ParseSEHExceptBlock(Loc);
2580    }
2581    else {
2582      SourceLocation Loc = ConsumeToken();
2583      Handler = ParseSEHFinallyBlock(Loc);
2584    }
2585    if(Handler.isInvalid())
2586      return Handler;
2587
2588    return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2589                                    TryLoc,
2590                                    TryBlock.take(),
2591                                    Handler.take());
2592  }
2593  else {
2594    StmtVector Handlers;
2595
2596    // C++11 attributes can't appear here, despite this context seeming
2597    // statement-like.
2598    DiagnoseAndSkipCXX11Attributes();
2599
2600    if (Tok.isNot(tok::kw_catch))
2601      return StmtError(Diag(Tok, diag::err_expected_catch));
2602    while (Tok.is(tok::kw_catch)) {
2603      StmtResult Handler(ParseCXXCatchBlock(FnTry));
2604      if (!Handler.isInvalid())
2605        Handlers.push_back(Handler.release());
2606    }
2607    // Don't bother creating the full statement if we don't have any usable
2608    // handlers.
2609    if (Handlers.empty())
2610      return StmtError();
2611
2612    return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
2613  }
2614}
2615
2616/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2617///
2618///   handler:
2619///     'catch' '(' exception-declaration ')' compound-statement
2620///
2621///   exception-declaration:
2622///     attribute-specifier-seq[opt] type-specifier-seq declarator
2623///     attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2624///     '...'
2625///
2626StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2627  assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2628
2629  SourceLocation CatchLoc = ConsumeToken();
2630
2631  BalancedDelimiterTracker T(*this, tok::l_paren);
2632  if (T.expectAndConsume(diag::err_expected_lparen))
2633    return StmtError();
2634
2635  // C++ 3.3.2p3:
2636  // The name in a catch exception-declaration is local to the handler and
2637  // shall not be redeclared in the outermost block of the handler.
2638  ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2639                          (FnCatch ? Scope::FnTryCatchScope : 0));
2640
2641  // exception-declaration is equivalent to '...' or a parameter-declaration
2642  // without default arguments.
2643  Decl *ExceptionDecl = 0;
2644  if (Tok.isNot(tok::ellipsis)) {
2645    ParsedAttributesWithRange Attributes(AttrFactory);
2646    MaybeParseCXX11Attributes(Attributes);
2647
2648    DeclSpec DS(AttrFactory);
2649    DS.takeAttributesFrom(Attributes);
2650
2651    if (ParseCXXTypeSpecifierSeq(DS))
2652      return StmtError();
2653
2654    Declarator ExDecl(DS, Declarator::CXXCatchContext);
2655    ParseDeclarator(ExDecl);
2656    ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2657  } else
2658    ConsumeToken();
2659
2660  T.consumeClose();
2661  if (T.getCloseLocation().isInvalid())
2662    return StmtError();
2663
2664  if (Tok.isNot(tok::l_brace))
2665    return StmtError(Diag(Tok, diag::err_expected_lbrace));
2666
2667  // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2668  StmtResult Block(ParseCompoundStatement());
2669  if (Block.isInvalid())
2670    return Block;
2671
2672  return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
2673}
2674
2675void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2676  IfExistsCondition Result;
2677  if (ParseMicrosoftIfExistsCondition(Result))
2678    return;
2679
2680  // Handle dependent statements by parsing the braces as a compound statement.
2681  // This is not the same behavior as Visual C++, which don't treat this as a
2682  // compound statement, but for Clang's type checking we can't have anything
2683  // inside these braces escaping to the surrounding code.
2684  if (Result.Behavior == IEB_Dependent) {
2685    if (!Tok.is(tok::l_brace)) {
2686      Diag(Tok, diag::err_expected_lbrace);
2687      return;
2688    }
2689
2690    StmtResult Compound = ParseCompoundStatement();
2691    if (Compound.isInvalid())
2692      return;
2693
2694    StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2695                                                              Result.IsIfExists,
2696                                                              Result.SS,
2697                                                              Result.Name,
2698                                                              Compound.get());
2699    if (DepResult.isUsable())
2700      Stmts.push_back(DepResult.get());
2701    return;
2702  }
2703
2704  BalancedDelimiterTracker Braces(*this, tok::l_brace);
2705  if (Braces.consumeOpen()) {
2706    Diag(Tok, diag::err_expected_lbrace);
2707    return;
2708  }
2709
2710  switch (Result.Behavior) {
2711  case IEB_Parse:
2712    // Parse the statements below.
2713    break;
2714
2715  case IEB_Dependent:
2716    llvm_unreachable("Dependent case handled above");
2717
2718  case IEB_Skip:
2719    Braces.skipToEnd();
2720    return;
2721  }
2722
2723  // Condition is true, parse the statements.
2724  while (Tok.isNot(tok::r_brace)) {
2725    StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2726    if (R.isUsable())
2727      Stmts.push_back(R.release());
2728  }
2729  Braces.consumeClose();
2730}
2731