1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Statement and Block portions of the Parser
13 //===----------------------------------------------------------------------===//
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"
38 using namespace clang;
40 //===----------------------------------------------------------------------===//
41 // C99 6.8: Statements and Blocks.
42 //===----------------------------------------------------------------------===//
44 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
45 /// StatementOrDeclaration:
51 /// compound-statement
52 /// expression-statement
53 /// selection-statement
54 /// iteration-statement
56 /// [C++] declaration-statement
58 /// [MS] seh-try-block
59 /// [OBC] objc-throw-statement
60 /// [OBC] objc-try-catch-statement
61 /// [OBC] objc-synchronized-statement
62 /// [GNU] asm-statement
63 /// [OMP] openmp-construct [TODO]
65 /// labeled-statement:
66 /// identifier ':' statement
67 /// 'case' constant-expression ':' statement
68 /// 'default' ':' statement
70 /// selection-statement:
74 /// iteration-statement:
79 /// expression-statement:
80 /// expression[opt] ';'
83 /// 'goto' identifier ';'
86 /// 'return' expression[opt] ';'
87 /// [GNU] 'goto' '*' expression ';'
89 /// [OBC] objc-throw-statement:
90 /// [OBC] '@' 'throw' expression ';'
91 /// [OBC] '@' 'throw' ';'
94 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
95 SourceLocation *TrailingElseLoc) {
97 ParenBraceBracketBalancer BalancerRAIIObj(*this);
99 ParsedAttributesWithRange Attrs(AttrFactory);
100 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
102 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
103 OnlyStatement, TrailingElseLoc, Attrs);
105 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
106 "attributes on empty statement");
108 if (Attrs.empty() || Res.isInvalid())
111 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
115 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
116 bool OnlyStatement, SourceLocation *TrailingElseLoc,
117 ParsedAttributesWithRange &Attrs) {
118 const char *SemiError = 0;
121 // Cases in this switch statement should fall through if the parser expects
122 // the token to end in a semicolon (in which case SemiError should be set),
123 // or they directly 'return;' if not.
125 tok::TokenKind Kind = Tok.getKind();
126 SourceLocation AtLoc;
128 case tok::at: // May be a @try or @throw statement
130 ProhibitAttributes(Attrs); // TODO: is it correct?
131 AtLoc = ConsumeToken(); // consume @
132 return ParseObjCAtStatement(AtLoc);
135 case tok::code_completion:
136 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
140 case tok::identifier: {
141 Token Next = NextToken();
142 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
143 // identifier ':' statement
144 return ParseLabeledStatement(Attrs);
147 // Look up the identifier, and typo-correct it to a keyword if it's not
149 if (Next.isNot(tok::coloncolon)) {
150 // Try to limit which sets of keywords should be included in typo
151 // correction based on what the next token is.
152 // FIXME: Pass the next token into the CorrectionCandidateCallback and
153 // do this filtering in a more fine-grained manner.
154 CorrectionCandidateCallback DefaultValidator;
155 DefaultValidator.WantTypeSpecifiers =
156 Next.is(tok::l_paren) || Next.is(tok::less) ||
157 Next.is(tok::identifier) || Next.is(tok::star) ||
158 Next.is(tok::amp) || Next.is(tok::l_square);
159 DefaultValidator.WantExpressionKeywords =
160 Next.is(tok::l_paren) || Next.is(tok::identifier) ||
161 Next.is(tok::arrow) || Next.is(tok::period);
162 DefaultValidator.WantRemainingKeywords =
163 Next.is(tok::l_paren) || Next.is(tok::semi) ||
164 Next.is(tok::identifier) || Next.is(tok::l_brace);
165 DefaultValidator.WantCXXNamedCasts = false;
166 if (TryAnnotateName(/*IsAddressOfOperand*/false, &DefaultValidator)
168 // Handle errors here by skipping up to the next semicolon or '}', and
169 // eat the semicolon if that's what stopped us.
170 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
171 if (Tok.is(tok::semi))
176 // If the identifier was typo-corrected, try again.
177 if (Tok.isNot(tok::identifier))
185 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
186 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
187 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
189 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
192 if (Tok.is(tok::r_brace)) {
193 Diag(Tok, diag::err_expected_statement);
197 return ParseExprStatement();
200 case tok::kw_case: // C99 6.8.1: labeled-statement
201 return ParseCaseStatement();
202 case tok::kw_default: // C99 6.8.1: labeled-statement
203 return ParseDefaultStatement();
205 case tok::l_brace: // C99 6.8.2: compound-statement
206 return ParseCompoundStatement();
207 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
208 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
209 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
212 case tok::kw_if: // C99 6.8.4.1: if-statement
213 return ParseIfStatement(TrailingElseLoc);
214 case tok::kw_switch: // C99 6.8.4.2: switch-statement
215 return ParseSwitchStatement(TrailingElseLoc);
217 case tok::kw_while: // C99 6.8.5.1: while-statement
218 return ParseWhileStatement(TrailingElseLoc);
219 case tok::kw_do: // C99 6.8.5.2: do-statement
220 Res = ParseDoStatement();
221 SemiError = "do/while";
223 case tok::kw_for: // C99 6.8.5.3: for-statement
224 return ParseForStatement(TrailingElseLoc);
226 case tok::kw_goto: // C99 6.8.6.1: goto-statement
227 Res = ParseGotoStatement();
230 case tok::kw_continue: // C99 6.8.6.2: continue-statement
231 Res = ParseContinueStatement();
232 SemiError = "continue";
234 case tok::kw_break: // C99 6.8.6.3: break-statement
235 Res = ParseBreakStatement();
238 case tok::kw_return: // C99 6.8.6.4: return-statement
239 Res = ParseReturnStatement();
240 SemiError = "return";
244 ProhibitAttributes(Attrs);
246 Res = ParseAsmStatement(msAsm);
247 Res = Actions.ActOnFinishFullStmt(Res.get());
248 if (msAsm) return Res;
253 case tok::kw_try: // C++ 15: try-block
254 return ParseCXXTryBlock();
257 ProhibitAttributes(Attrs); // TODO: is it correct?
258 return ParseSEHTryBlock();
260 case tok::annot_pragma_vis:
261 ProhibitAttributes(Attrs);
262 HandlePragmaVisibility();
265 case tok::annot_pragma_pack:
266 ProhibitAttributes(Attrs);
270 case tok::annot_pragma_msstruct:
271 ProhibitAttributes(Attrs);
272 HandlePragmaMSStruct();
275 case tok::annot_pragma_align:
276 ProhibitAttributes(Attrs);
280 case tok::annot_pragma_weak:
281 ProhibitAttributes(Attrs);
285 case tok::annot_pragma_weakalias:
286 ProhibitAttributes(Attrs);
287 HandlePragmaWeakAlias();
290 case tok::annot_pragma_redefine_extname:
291 ProhibitAttributes(Attrs);
292 HandlePragmaRedefineExtname();
295 case tok::annot_pragma_fp_contract:
296 Diag(Tok, diag::err_pragma_fp_contract_scope);
300 case tok::annot_pragma_opencl_extension:
301 ProhibitAttributes(Attrs);
302 HandlePragmaOpenCLExtension();
305 case tok::annot_pragma_captured:
306 return HandlePragmaCaptured();
308 case tok::annot_pragma_openmp:
309 SourceLocation DeclStart = Tok.getLocation();
310 DeclGroupPtrTy Res = ParseOpenMPDeclarativeDirective();
311 return Actions.ActOnDeclStmt(Res, DeclStart, Tok.getLocation());
314 // If we reached this code, the statement must end in a semicolon.
315 if (Tok.is(tok::semi)) {
317 } else if (!Res.isInvalid()) {
318 // If the result was valid, then we do want to diagnose this. Use
319 // ExpectAndConsume to emit the diagnostic, even though we know it won't
321 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
322 // Skip until we see a } or ;, but don't eat it.
323 SkipUntil(tok::r_brace, true, true);
329 /// \brief Parse an expression statement.
330 StmtResult Parser::ParseExprStatement() {
331 // If a case keyword is missing, this is where it should be inserted.
332 Token OldToken = Tok;
334 // expression[opt] ';'
335 ExprResult Expr(ParseExpression());
336 if (Expr.isInvalid()) {
337 // If the expression is invalid, skip ahead to the next semicolon or '}'.
338 // Not doing this opens us up to the possibility of infinite loops if
339 // ParseExpression does not consume any tokens.
340 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
341 if (Tok.is(tok::semi))
343 return Actions.ActOnExprStmtError();
346 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
347 Actions.CheckCaseExpression(Expr.get())) {
348 // If a constant expression is followed by a colon inside a switch block,
349 // suggest a missing case keyword.
350 Diag(OldToken, diag::err_expected_case_before_expression)
351 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
353 // Recover parsing as a case statement.
354 return ParseCaseStatement(/*MissingCase=*/true, Expr);
357 // Otherwise, eat the semicolon.
358 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
359 return Actions.ActOnExprStmt(Expr);
362 StmtResult Parser::ParseSEHTryBlock() {
363 assert(Tok.is(tok::kw___try) && "Expected '__try'");
364 SourceLocation Loc = ConsumeToken();
365 return ParseSEHTryBlockCommon(Loc);
368 /// ParseSEHTryBlockCommon
371 /// '__try' compound-statement seh-handler
375 /// seh-finally-block
377 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
378 if(Tok.isNot(tok::l_brace))
379 return StmtError(Diag(Tok,diag::err_expected_lbrace));
381 StmtResult TryBlock(ParseCompoundStatement());
382 if(TryBlock.isInvalid())
386 if (Tok.is(tok::identifier) &&
387 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
388 SourceLocation Loc = ConsumeToken();
389 Handler = ParseSEHExceptBlock(Loc);
390 } else if (Tok.is(tok::kw___finally)) {
391 SourceLocation Loc = ConsumeToken();
392 Handler = ParseSEHFinallyBlock(Loc);
394 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
397 if(Handler.isInvalid())
400 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
406 /// ParseSEHExceptBlock - Handle __except
408 /// seh-except-block:
409 /// '__except' '(' seh-filter-expression ')' compound-statement
411 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
412 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
413 raii2(Ident___exception_code, false),
414 raii3(Ident_GetExceptionCode, false);
416 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
419 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
421 if (getLangOpts().Borland) {
422 Ident__exception_info->setIsPoisoned(false);
423 Ident___exception_info->setIsPoisoned(false);
424 Ident_GetExceptionInfo->setIsPoisoned(false);
426 ExprResult FilterExpr(ParseExpression());
428 if (getLangOpts().Borland) {
429 Ident__exception_info->setIsPoisoned(true);
430 Ident___exception_info->setIsPoisoned(true);
431 Ident_GetExceptionInfo->setIsPoisoned(true);
434 if(FilterExpr.isInvalid())
437 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
440 StmtResult Block(ParseCompoundStatement());
442 if(Block.isInvalid())
445 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
448 /// ParseSEHFinallyBlock - Handle __finally
450 /// seh-finally-block:
451 /// '__finally' compound-statement
453 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
454 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
455 raii2(Ident___abnormal_termination, false),
456 raii3(Ident_AbnormalTermination, false);
458 StmtResult Block(ParseCompoundStatement());
459 if(Block.isInvalid())
462 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
465 /// ParseLabeledStatement - We have an identifier and a ':' after it.
467 /// labeled-statement:
468 /// identifier ':' statement
469 /// [GNU] identifier ':' attributes[opt] statement
471 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
472 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
473 "Not an identifier!");
475 Token IdentTok = Tok; // Save the whole token.
476 ConsumeToken(); // eat the identifier.
478 assert(Tok.is(tok::colon) && "Not a label!");
480 // identifier ':' statement
481 SourceLocation ColonLoc = ConsumeToken();
483 // Read label attributes, if present. attrs will contain both C++11 and GNU
484 // attributes (if present) after this point.
485 MaybeParseGNUAttributes(attrs);
487 StmtResult SubStmt(ParseStatement());
489 // Broken substmt shouldn't prevent the label from being added to the AST.
490 if (SubStmt.isInvalid())
491 SubStmt = Actions.ActOnNullStmt(ColonLoc);
493 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
494 IdentTok.getLocation());
495 if (AttributeList *Attrs = attrs.getList()) {
496 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
500 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
504 /// ParseCaseStatement
505 /// labeled-statement:
506 /// 'case' constant-expression ':' statement
507 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
509 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
510 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
512 // It is very very common for code to contain many case statements recursively
513 // nested, as in (but usually without indentation):
520 // Parsing this naively works, but is both inefficient and can cause us to run
521 // out of stack space in our recursive descent parser. As a special case,
522 // flatten this recursion into an iterative loop. This is complex and gross,
523 // but all the grossness is constrained to ParseCaseStatement (and some
524 // wierdness in the actions), so this is just local grossness :).
526 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
528 StmtResult TopLevelCase(true);
530 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
531 // gets updated each time a new case is parsed, and whose body is unset so
532 // far. When parsing 'case 4', this is the 'case 3' node.
533 Stmt *DeepestParsedCaseStmt = 0;
535 // While we have case statements, eat and stack them.
536 SourceLocation ColonLoc;
538 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
539 ConsumeToken(); // eat the 'case'.
541 if (Tok.is(tok::code_completion)) {
542 Actions.CodeCompleteCase(getCurScope());
547 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
548 /// Disable this form of error recovery while we're parsing the case
550 ColonProtectionRAIIObject ColonProtection(*this);
552 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
554 if (LHS.isInvalid()) {
555 SkipUntil(tok::colon);
559 // GNU case range extension.
560 SourceLocation DotDotDotLoc;
562 if (Tok.is(tok::ellipsis)) {
563 Diag(Tok, diag::ext_gnu_case_range);
564 DotDotDotLoc = ConsumeToken();
566 RHS = ParseConstantExpression();
567 if (RHS.isInvalid()) {
568 SkipUntil(tok::colon);
573 ColonProtection.restore();
575 if (Tok.is(tok::colon)) {
576 ColonLoc = ConsumeToken();
578 // Treat "case blah;" as a typo for "case blah:".
579 } else if (Tok.is(tok::semi)) {
580 ColonLoc = ConsumeToken();
581 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
582 << FixItHint::CreateReplacement(ColonLoc, ":");
584 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
585 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
586 << FixItHint::CreateInsertion(ExpectedLoc, ":");
587 ColonLoc = ExpectedLoc;
591 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
592 RHS.get(), ColonLoc);
594 // If we had a sema error parsing this case, then just ignore it and
595 // continue parsing the sub-stmt.
596 if (Case.isInvalid()) {
597 if (TopLevelCase.isInvalid()) // No parsed case stmts.
598 return ParseStatement();
599 // Otherwise, just don't add it as a nested case.
601 // If this is the first case statement we parsed, it becomes TopLevelCase.
602 // Otherwise we link it into the current chain.
603 Stmt *NextDeepest = Case.get();
604 if (TopLevelCase.isInvalid())
607 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
608 DeepestParsedCaseStmt = NextDeepest;
611 // Handle all case statements.
612 } while (Tok.is(tok::kw_case));
614 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
616 // If we found a non-case statement, start by parsing it.
619 if (Tok.isNot(tok::r_brace)) {
620 SubStmt = ParseStatement();
622 // Nicely diagnose the common error "switch (X) { case 4: }", which is
624 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
625 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
626 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
630 // Broken sub-stmt shouldn't prevent forming the case statement properly.
631 if (SubStmt.isInvalid())
632 SubStmt = Actions.ActOnNullStmt(SourceLocation());
634 // Install the body into the most deeply-nested case.
635 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
637 // Return the top level parsed statement tree.
641 /// ParseDefaultStatement
642 /// labeled-statement:
643 /// 'default' ':' statement
644 /// Note that this does not parse the 'statement' at the end.
646 StmtResult Parser::ParseDefaultStatement() {
647 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
648 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
650 SourceLocation ColonLoc;
651 if (Tok.is(tok::colon)) {
652 ColonLoc = ConsumeToken();
654 // Treat "default;" as a typo for "default:".
655 } else if (Tok.is(tok::semi)) {
656 ColonLoc = ConsumeToken();
657 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
658 << FixItHint::CreateReplacement(ColonLoc, ":");
660 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
661 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
662 << FixItHint::CreateInsertion(ExpectedLoc, ":");
663 ColonLoc = ExpectedLoc;
668 if (Tok.isNot(tok::r_brace)) {
669 SubStmt = ParseStatement();
671 // Diagnose the common error "switch (X) {... default: }", which is
673 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
674 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
675 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
679 // Broken sub-stmt shouldn't prevent forming the case statement properly.
680 if (SubStmt.isInvalid())
681 SubStmt = Actions.ActOnNullStmt(ColonLoc);
683 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
684 SubStmt.get(), getCurScope());
687 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
688 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
691 /// ParseCompoundStatement - Parse a "{}" block.
693 /// compound-statement: [C99 6.8.2]
694 /// { block-item-list[opt] }
695 /// [GNU] { label-declarations block-item-list } [TODO]
699 /// block-item-list block-item
703 /// [GNU] '__extension__' declaration
705 /// [OMP] openmp-directive [TODO]
707 /// [GNU] label-declarations:
708 /// [GNU] label-declaration
709 /// [GNU] label-declarations label-declaration
711 /// [GNU] label-declaration:
712 /// [GNU] '__label__' identifier-list ';'
714 /// [OMP] openmp-directive: [TODO]
715 /// [OMP] barrier-directive
716 /// [OMP] flush-directive
718 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
719 unsigned ScopeFlags) {
720 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
722 // Enter a scope to hold everything within the compound stmt. Compound
723 // statements can always hold declarations.
724 ParseScope CompoundScope(this, ScopeFlags);
726 // Parse the statements in the body.
727 return ParseCompoundStatementBody(isStmtExpr);
730 /// Parse any pragmas at the start of the compound expression. We handle these
731 /// separately since some pragmas (FP_CONTRACT) must appear before any C
732 /// statement in the compound, but may be intermingled with other pragmas.
733 void Parser::ParseCompoundStatementLeadingPragmas() {
734 bool checkForPragmas = true;
735 while (checkForPragmas) {
736 switch (Tok.getKind()) {
737 case tok::annot_pragma_vis:
738 HandlePragmaVisibility();
740 case tok::annot_pragma_pack:
743 case tok::annot_pragma_msstruct:
744 HandlePragmaMSStruct();
746 case tok::annot_pragma_align:
749 case tok::annot_pragma_weak:
752 case tok::annot_pragma_weakalias:
753 HandlePragmaWeakAlias();
755 case tok::annot_pragma_redefine_extname:
756 HandlePragmaRedefineExtname();
758 case tok::annot_pragma_opencl_extension:
759 HandlePragmaOpenCLExtension();
761 case tok::annot_pragma_fp_contract:
762 HandlePragmaFPContract();
765 checkForPragmas = false;
772 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
773 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
774 /// consume the '}' at the end of the block. It does not manipulate the scope
776 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
777 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
779 "in compound statement ('{}')");
781 // Record the state of the FP_CONTRACT pragma, restore on leaving the
782 // compound statement.
783 Sema::FPContractStateRAII SaveFPContractState(Actions);
785 InMessageExpressionRAIIObject InMessage(*this, false);
786 BalancedDelimiterTracker T(*this, tok::l_brace);
790 Sema::CompoundScopeRAII CompoundScope(Actions);
792 // Parse any pragmas at the beginning of the compound statement.
793 ParseCompoundStatementLeadingPragmas();
797 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
798 // only allowed at the start of a compound stmt regardless of the language.
799 while (Tok.is(tok::kw___label__)) {
800 SourceLocation LabelLoc = ConsumeToken();
801 Diag(LabelLoc, diag::ext_gnu_local_label);
803 SmallVector<Decl *, 8> DeclsInGroup;
805 if (Tok.isNot(tok::identifier)) {
806 Diag(Tok, diag::err_expected_ident);
810 IdentifierInfo *II = Tok.getIdentifierInfo();
811 SourceLocation IdLoc = ConsumeToken();
812 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
814 if (!Tok.is(tok::comma))
819 DeclSpec DS(AttrFactory);
820 DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
821 DeclsInGroup.data(), DeclsInGroup.size());
822 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
824 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
826 Stmts.push_back(R.release());
829 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
830 if (Tok.is(tok::annot_pragma_unused)) {
831 HandlePragmaUnused();
835 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
836 Tok.is(tok::kw___if_not_exists))) {
837 ParseMicrosoftIfExistsStatement(Stmts);
842 if (Tok.isNot(tok::kw___extension__)) {
843 R = ParseStatementOrDeclaration(Stmts, false);
845 // __extension__ can start declarations and it can also be a unary
846 // operator for expressions. Consume multiple __extension__ markers here
847 // until we can determine which is which.
848 // FIXME: This loses extension expressions in the AST!
849 SourceLocation ExtLoc = ConsumeToken();
850 while (Tok.is(tok::kw___extension__))
853 ParsedAttributesWithRange attrs(AttrFactory);
854 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
856 // If this is the start of a declaration, parse it as such.
857 if (isDeclarationStatement()) {
858 // __extension__ silences extension warnings in the subdeclaration.
859 // FIXME: Save the __extension__ on the decl as a node somehow?
860 ExtensionRAIIObject O(Diags);
862 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
863 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
864 Declarator::BlockContext, DeclEnd,
866 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
868 // Otherwise this was a unary __extension__ marker.
869 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
871 if (Res.isInvalid()) {
872 SkipUntil(tok::semi);
876 // FIXME: Use attributes?
877 // Eat the semicolon at the end of stmt and convert the expr into a
879 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
880 R = Actions.ActOnExprStmt(Res);
885 Stmts.push_back(R.release());
888 SourceLocation CloseLoc = Tok.getLocation();
890 // We broke out of the while loop because we found a '}' or EOF.
891 if (!T.consumeClose())
892 // Recover by creating a compound statement with what we parsed so far,
893 // instead of dropping everything and returning StmtError();
894 CloseLoc = T.getCloseLocation();
896 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
900 /// ParseParenExprOrCondition:
901 /// [C ] '(' expression ')'
902 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
904 /// This function parses and performs error recovery on the specified condition
905 /// or expression (depending on whether we're in C++ or C mode). This function
906 /// goes out of its way to recover well. It returns true if there was a parser
907 /// error (the right paren couldn't be found), which indicates that the caller
908 /// should try to recover harder. It returns false if the condition is
909 /// successfully parsed. Note that a successful parse can still have semantic
910 /// errors in the condition.
911 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
914 bool ConvertToBoolean) {
915 BalancedDelimiterTracker T(*this, tok::l_paren);
918 if (getLangOpts().CPlusPlus)
919 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
921 ExprResult = ParseExpression();
924 // If required, convert to a boolean value.
925 if (!ExprResult.isInvalid() && ConvertToBoolean)
927 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
930 // If the parser was confused by the condition and we don't have a ')', try to
931 // recover by skipping ahead to a semi and bailing out. If condexp is
932 // semantically invalid but we have well formed code, keep going.
933 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
934 SkipUntil(tok::semi);
935 // Skipping may have stopped if it found the containing ')'. If so, we can
936 // continue parsing the if statement.
937 if (Tok.isNot(tok::r_paren))
941 // Otherwise the condition is valid or the rparen is present.
944 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
945 // that all callers are looking for a statement after the condition, so ")"
947 while (Tok.is(tok::r_paren)) {
948 Diag(Tok, diag::err_extraneous_rparen_in_condition)
949 << FixItHint::CreateRemoval(Tok.getLocation());
958 /// if-statement: [C99 6.8.4.1]
959 /// 'if' '(' expression ')' statement
960 /// 'if' '(' expression ')' statement 'else' statement
961 /// [C++] 'if' '(' condition ')' statement
962 /// [C++] 'if' '(' condition ')' statement 'else' statement
964 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
965 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
966 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
968 if (Tok.isNot(tok::l_paren)) {
969 Diag(Tok, diag::err_expected_lparen_after) << "if";
970 SkipUntil(tok::semi);
974 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
976 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
980 // A name introduced by a declaration in a condition is in scope from its
981 // point of declaration until the end of the substatements controlled by the
984 // Names declared in the for-init-statement, and in the condition of if,
985 // while, for, and switch statements are local to the if, while, for, or
986 // switch statement (including the controlled statement).
988 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
990 // Parse the condition.
993 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
996 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
998 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
999 // there is no compound stmt. C90 does not have this clause. We only do this
1000 // if the body isn't a compound statement to avoid push/pop in common cases.
1003 // The substatement in a selection-statement (each substatement, in the else
1004 // form of the if statement) implicitly defines a local scope.
1006 // For C++ we create a scope for the condition and a new scope for
1007 // substatements because:
1008 // -When the 'then' scope exits, we want the condition declaration to still be
1009 // active for the 'else' scope too.
1010 // -Sema will detect name clashes by considering declarations of a
1011 // 'ControlScope' as part of its direct subscope.
1012 // -If we wanted the condition and substatement to be in the same scope, we
1013 // would have to notify ParseStatement not to create a new scope. It's
1014 // simpler to let it create a new scope.
1016 ParseScope InnerScope(this, Scope::DeclScope,
1017 C99orCXX && Tok.isNot(tok::l_brace));
1019 // Read the 'then' stmt.
1020 SourceLocation ThenStmtLoc = Tok.getLocation();
1022 SourceLocation InnerStatementTrailingElseLoc;
1023 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
1025 // Pop the 'if' scope if needed.
1028 // If it has an else, parse it.
1029 SourceLocation ElseLoc;
1030 SourceLocation ElseStmtLoc;
1031 StmtResult ElseStmt;
1033 if (Tok.is(tok::kw_else)) {
1034 if (TrailingElseLoc)
1035 *TrailingElseLoc = Tok.getLocation();
1037 ElseLoc = ConsumeToken();
1038 ElseStmtLoc = Tok.getLocation();
1040 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1041 // there is no compound stmt. C90 does not have this clause. We only do
1042 // this if the body isn't a compound statement to avoid push/pop in common
1046 // The substatement in a selection-statement (each substatement, in the else
1047 // form of the if statement) implicitly defines a local scope.
1049 ParseScope InnerScope(this, Scope::DeclScope,
1050 C99orCXX && Tok.isNot(tok::l_brace));
1052 ElseStmt = ParseStatement();
1054 // Pop the 'else' scope if needed.
1056 } else if (Tok.is(tok::code_completion)) {
1057 Actions.CodeCompleteAfterIf(getCurScope());
1060 } else if (InnerStatementTrailingElseLoc.isValid()) {
1061 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1066 // If the then or else stmt is invalid and the other is valid (and present),
1067 // make turn the invalid one into a null stmt to avoid dropping the other
1068 // part. If both are invalid, return error.
1069 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1070 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1071 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
1072 // Both invalid, or one is invalid and other is non-present: return error.
1076 // Now if either are invalid, replace with a ';'.
1077 if (ThenStmt.isInvalid())
1078 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1079 if (ElseStmt.isInvalid())
1080 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1082 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
1083 ElseLoc, ElseStmt.get());
1086 /// ParseSwitchStatement
1087 /// switch-statement:
1088 /// 'switch' '(' expression ')' statement
1089 /// [C++] 'switch' '(' condition ')' statement
1090 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1091 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1092 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1094 if (Tok.isNot(tok::l_paren)) {
1095 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1096 SkipUntil(tok::semi);
1100 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1102 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1103 // not the case for C90. Start the switch scope.
1106 // A name introduced by a declaration in a condition is in scope from its
1107 // point of declaration until the end of the substatements controlled by the
1110 // Names declared in the for-init-statement, and in the condition of if,
1111 // while, for, and switch statements are local to the if, while, for, or
1112 // switch statement (including the controlled statement).
1114 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
1116 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1117 ParseScope SwitchScope(this, ScopeFlags);
1119 // Parse the condition.
1122 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1126 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1128 if (Switch.isInvalid()) {
1129 // Skip the switch body.
1130 // FIXME: This is not optimal recovery, but parsing the body is more
1131 // dangerous due to the presence of case and default statements, which
1132 // will have no place to connect back with the switch.
1133 if (Tok.is(tok::l_brace)) {
1135 SkipUntil(tok::r_brace, false, false);
1137 SkipUntil(tok::semi);
1141 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1142 // there is no compound stmt. C90 does not have this clause. We only do this
1143 // if the body isn't a compound statement to avoid push/pop in common cases.
1146 // The substatement in a selection-statement (each substatement, in the else
1147 // form of the if statement) implicitly defines a local scope.
1149 // See comments in ParseIfStatement for why we create a scope for the
1150 // condition and a new scope for substatement in C++.
1152 ParseScope InnerScope(this, Scope::DeclScope,
1153 C99orCXX && Tok.isNot(tok::l_brace));
1155 // Read the body statement.
1156 StmtResult Body(ParseStatement(TrailingElseLoc));
1162 if (Body.isInvalid()) {
1163 // FIXME: Remove the case statement list from the Switch statement.
1165 // Put the synthesized null statement on the same line as the end of switch
1167 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1168 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1171 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1174 /// ParseWhileStatement
1175 /// while-statement: [C99 6.8.5.1]
1176 /// 'while' '(' expression ')' statement
1177 /// [C++] 'while' '(' condition ')' statement
1178 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1179 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1180 SourceLocation WhileLoc = Tok.getLocation();
1181 ConsumeToken(); // eat the 'while'.
1183 if (Tok.isNot(tok::l_paren)) {
1184 Diag(Tok, diag::err_expected_lparen_after) << "while";
1185 SkipUntil(tok::semi);
1189 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1191 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1192 // the case for C90. Start the loop scope.
1195 // A name introduced by a declaration in a condition is in scope from its
1196 // point of declaration until the end of the substatements controlled by the
1199 // Names declared in the for-init-statement, and in the condition of if,
1200 // while, for, and switch statements are local to the if, while, for, or
1201 // switch statement (including the controlled statement).
1203 unsigned ScopeFlags;
1205 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1206 Scope::DeclScope | Scope::ControlScope;
1208 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1209 ParseScope WhileScope(this, ScopeFlags);
1211 // Parse the condition.
1214 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1217 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
1219 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1220 // there is no compound stmt. C90 does not have this clause. We only do this
1221 // if the body isn't a compound statement to avoid push/pop in common cases.
1224 // The substatement in an iteration-statement implicitly defines a local scope
1225 // which is entered and exited each time through the loop.
1227 // See comments in ParseIfStatement for why we create a scope for the
1228 // condition and a new scope for substatement in C++.
1230 ParseScope InnerScope(this, Scope::DeclScope,
1231 C99orCXX && Tok.isNot(tok::l_brace));
1233 // Read the body statement.
1234 StmtResult Body(ParseStatement(TrailingElseLoc));
1236 // Pop the body scope if needed.
1240 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1243 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1246 /// ParseDoStatement
1247 /// do-statement: [C99 6.8.5.2]
1248 /// 'do' statement 'while' '(' expression ')' ';'
1249 /// Note: this lets the caller parse the end ';'.
1250 StmtResult Parser::ParseDoStatement() {
1251 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1252 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1254 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1255 // the case for C90. Start the loop scope.
1256 unsigned ScopeFlags;
1257 if (getLangOpts().C99)
1258 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1260 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1262 ParseScope DoScope(this, ScopeFlags);
1264 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1265 // there is no compound stmt. C90 does not have this clause. We only do this
1266 // if the body isn't a compound statement to avoid push/pop in common cases.
1269 // The substatement in an iteration-statement implicitly defines a local scope
1270 // which is entered and exited each time through the loop.
1272 ParseScope InnerScope(this, Scope::DeclScope,
1273 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
1274 Tok.isNot(tok::l_brace));
1276 // Read the body statement.
1277 StmtResult Body(ParseStatement());
1279 // Pop the body scope if needed.
1282 if (Tok.isNot(tok::kw_while)) {
1283 if (!Body.isInvalid()) {
1284 Diag(Tok, diag::err_expected_while);
1285 Diag(DoLoc, diag::note_matching) << "do";
1286 SkipUntil(tok::semi, false, true);
1290 SourceLocation WhileLoc = ConsumeToken();
1292 if (Tok.isNot(tok::l_paren)) {
1293 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1294 SkipUntil(tok::semi, false, true);
1298 // Parse the parenthesized condition.
1299 BalancedDelimiterTracker T(*this, tok::l_paren);
1302 // FIXME: Do not just parse the attribute contents and throw them away
1303 ParsedAttributesWithRange attrs(AttrFactory);
1304 MaybeParseCXX11Attributes(attrs);
1305 ProhibitAttributes(attrs);
1307 ExprResult Cond = ParseExpression();
1311 if (Cond.isInvalid() || Body.isInvalid())
1314 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1315 Cond.get(), T.getCloseLocation());
1318 /// ParseForStatement
1319 /// for-statement: [C99 6.8.5.3]
1320 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1321 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1322 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1324 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
1325 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1326 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1328 /// [C++] for-init-statement:
1329 /// [C++] expression-statement
1330 /// [C++] simple-declaration
1332 /// [C++0x] for-range-declaration:
1333 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1334 /// [C++0x] for-range-initializer:
1335 /// [C++0x] expression
1336 /// [C++0x] braced-init-list [TODO]
1337 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1338 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1339 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1341 if (Tok.isNot(tok::l_paren)) {
1342 Diag(Tok, diag::err_expected_lparen_after) << "for";
1343 SkipUntil(tok::semi);
1347 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1348 getLangOpts().ObjC1;
1350 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1351 // the case for C90. Start the loop scope.
1354 // A name introduced by a declaration in a condition is in scope from its
1355 // point of declaration until the end of the substatements controlled by the
1358 // Names declared in the for-init-statement, and in the condition of if,
1359 // while, for, and switch statements are local to the if, while, for, or
1360 // switch statement (including the controlled statement).
1362 // Names declared in the for-init-statement are in the same declarative-region
1363 // as those declared in the condition.
1365 unsigned ScopeFlags;
1367 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1368 Scope::DeclScope | Scope::ControlScope;
1370 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1372 ParseScope ForScope(this, ScopeFlags);
1374 BalancedDelimiterTracker T(*this, tok::l_paren);
1379 bool ForEach = false, ForRange = false;
1380 StmtResult FirstPart;
1381 bool SecondPartIsInvalid = false;
1382 FullExprArg SecondPart(Actions);
1383 ExprResult Collection;
1384 ForRangeInit ForRangeInit;
1385 FullExprArg ThirdPart(Actions);
1386 Decl *SecondVar = 0;
1388 if (Tok.is(tok::code_completion)) {
1389 Actions.CodeCompleteOrdinaryName(getCurScope(),
1390 C99orCXXorObjC? Sema::PCC_ForInit
1391 : Sema::PCC_Expression);
1396 ParsedAttributesWithRange attrs(AttrFactory);
1397 MaybeParseCXX11Attributes(attrs);
1399 // Parse the first part of the for specifier.
1400 if (Tok.is(tok::semi)) { // for (;
1401 ProhibitAttributes(attrs);
1402 // no first part, eat the ';'.
1404 } else if (isForInitDeclaration()) { // for (int X = 4;
1405 // Parse declaration, which eats the ';'.
1406 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1407 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1409 // In C++0x, "for (T NS:a" might not be a typo for ::
1410 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1411 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1413 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1415 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1416 DeclEnd, attrs, false,
1417 MightBeForRangeStmt ?
1419 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1421 if (ForRangeInit.ParsedForRangeDecl()) {
1422 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1423 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1426 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1428 } else if ((ForEach = isTokIdentifier_in())) {
1429 Actions.ActOnForEachDeclStmt(DG);
1430 // ObjC: for (id x in expr)
1431 ConsumeToken(); // consume 'in'
1433 if (Tok.is(tok::code_completion)) {
1434 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1438 Collection = ParseExpression();
1440 Diag(Tok, diag::err_expected_semi_for);
1443 ProhibitAttributes(attrs);
1444 Value = ParseExpression();
1446 ForEach = isTokIdentifier_in();
1448 // Turn the expression into a stmt.
1449 if (!Value.isInvalid()) {
1451 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1453 FirstPart = Actions.ActOnExprStmt(Value);
1456 if (Tok.is(tok::semi)) {
1458 } else if (ForEach) {
1459 ConsumeToken(); // consume 'in'
1461 if (Tok.is(tok::code_completion)) {
1462 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1466 Collection = ParseExpression();
1467 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1468 // User tried to write the reasonable, but ill-formed, for-range-statement
1469 // for (expr : expr) { ... }
1470 Diag(Tok, diag::err_for_range_expected_decl)
1471 << FirstPart.get()->getSourceRange();
1472 SkipUntil(tok::r_paren, false, true);
1473 SecondPartIsInvalid = true;
1475 if (!Value.isInvalid()) {
1476 Diag(Tok, diag::err_expected_semi_for);
1478 // Skip until semicolon or rparen, don't consume it.
1479 SkipUntil(tok::r_paren, true, true);
1480 if (Tok.is(tok::semi))
1485 if (!ForEach && !ForRange) {
1486 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1487 // Parse the second part of the for specifier.
1488 if (Tok.is(tok::semi)) { // for (...;;
1490 } else if (Tok.is(tok::r_paren)) {
1491 // missing both semicolons.
1494 if (getLangOpts().CPlusPlus)
1495 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1497 Second = ParseExpression();
1498 if (!Second.isInvalid())
1499 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1502 SecondPartIsInvalid = Second.isInvalid();
1503 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
1506 if (Tok.isNot(tok::semi)) {
1507 if (!SecondPartIsInvalid || SecondVar)
1508 Diag(Tok, diag::err_expected_semi_for);
1510 // Skip until semicolon or rparen, don't consume it.
1511 SkipUntil(tok::r_paren, true, true);
1514 if (Tok.is(tok::semi)) {
1518 // Parse the third part of the for specifier.
1519 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1520 ExprResult Third = ParseExpression();
1521 // FIXME: The C++11 standard doesn't actually say that this is a
1522 // discarded-value expression, but it clearly should be.
1523 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
1529 // We need to perform most of the semantic analysis for a C++0x for-range
1530 // statememt before parsing the body, in order to be able to deduce the type
1531 // of an auto-typed loop variable.
1532 StmtResult ForRangeStmt;
1533 StmtResult ForEachStmt;
1536 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
1537 ForRangeInit.ColonLoc,
1538 ForRangeInit.RangeExpr.get(),
1539 T.getCloseLocation(),
1543 // Similarly, we need to do the semantic analysis for a for-range
1544 // statement immediately in order to close over temporaries correctly.
1545 } else if (ForEach) {
1546 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1549 T.getCloseLocation());
1552 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1553 // there is no compound stmt. C90 does not have this clause. We only do this
1554 // if the body isn't a compound statement to avoid push/pop in common cases.
1557 // The substatement in an iteration-statement implicitly defines a local scope
1558 // which is entered and exited each time through the loop.
1560 // See comments in ParseIfStatement for why we create a scope for
1561 // for-init-statement/condition and a new scope for substatement in C++.
1563 ParseScope InnerScope(this, Scope::DeclScope,
1564 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1566 // Read the body statement.
1567 StmtResult Body(ParseStatement(TrailingElseLoc));
1569 // Pop the body scope if needed.
1572 // Leave the for-scope.
1575 if (Body.isInvalid())
1579 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1583 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1585 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1586 SecondPart, SecondVar, ThirdPart,
1587 T.getCloseLocation(), Body.take());
1590 /// ParseGotoStatement
1592 /// 'goto' identifier ';'
1593 /// [GNU] 'goto' '*' expression ';'
1595 /// Note: this lets the caller parse the end ';'.
1597 StmtResult Parser::ParseGotoStatement() {
1598 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1599 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1602 if (Tok.is(tok::identifier)) {
1603 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1605 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1607 } else if (Tok.is(tok::star)) {
1608 // GNU indirect goto extension.
1609 Diag(Tok, diag::ext_gnu_indirect_goto);
1610 SourceLocation StarLoc = ConsumeToken();
1611 ExprResult R(ParseExpression());
1612 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1613 SkipUntil(tok::semi, false, true);
1616 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1618 Diag(Tok, diag::err_expected_ident);
1625 /// ParseContinueStatement
1629 /// Note: this lets the caller parse the end ';'.
1631 StmtResult Parser::ParseContinueStatement() {
1632 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1633 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1636 /// ParseBreakStatement
1640 /// Note: this lets the caller parse the end ';'.
1642 StmtResult Parser::ParseBreakStatement() {
1643 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1644 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1647 /// ParseReturnStatement
1649 /// 'return' expression[opt] ';'
1650 StmtResult Parser::ParseReturnStatement() {
1651 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1652 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1655 if (Tok.isNot(tok::semi)) {
1656 if (Tok.is(tok::code_completion)) {
1657 Actions.CodeCompleteReturn(getCurScope());
1662 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1663 R = ParseInitializer();
1665 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1666 diag::warn_cxx98_compat_generalized_initializer_lists :
1667 diag::ext_generalized_initializer_lists)
1668 << R.get()->getSourceRange();
1670 R = ParseExpression();
1671 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1672 SkipUntil(tok::semi, false, true);
1676 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1680 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1682 SourceLocation AsmLoc;
1683 StringRef AsmString;
1685 /// The tokens we streamed into AsmString and handed off to MC.
1686 ArrayRef<Token> AsmToks;
1688 /// The offset of each token in AsmToks within AsmString.
1689 ArrayRef<unsigned> AsmTokOffsets;
1692 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1693 StringRef AsmString,
1694 ArrayRef<Token> Toks,
1695 ArrayRef<unsigned> Offsets)
1696 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1697 AsmToks(Toks), AsmTokOffsets(Offsets) {
1698 assert(AsmToks.size() == AsmTokOffsets.size());
1701 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1702 InlineAsmIdentifierInfo &Info,
1703 bool IsUnevaluatedContext) {
1704 // Collect the desired tokens.
1705 SmallVector<Token, 16> LineToks;
1706 const Token *FirstOrigToken = 0;
1707 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1709 unsigned NumConsumedToks;
1711 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1712 IsUnevaluatedContext);
1714 // If we consumed the entire line, tell MC that.
1715 // Also do this if we consumed nothing as a way of reporting failure.
1716 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1717 // By not modifying LineBuf, we're implicitly consuming it all.
1719 // Otherwise, consume up to the original tokens.
1721 assert(FirstOrigToken && "not using original tokens?");
1723 // Since we're using original tokens, apply that offset.
1724 assert(FirstOrigToken[NumConsumedToks].getLocation()
1725 == LineToks[NumConsumedToks].getLocation());
1726 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1727 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1729 // The total length we've consumed is the relative offset
1730 // of the last token we consumed plus its length.
1731 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1732 + AsmToks[LastIndex].getLength()
1733 - AsmTokOffsets[FirstIndex]);
1734 LineBuf = LineBuf.substr(0, TotalOffset);
1737 // Initialize the "decl" with the lookup result.
1738 Info.OpDecl = static_cast<void*>(Result.take());
1742 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1744 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1748 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1750 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1754 /// Collect the appropriate tokens for the given string.
1755 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1756 const Token *&FirstOrigToken) const {
1757 // For now, assert that the string we're working with is a substring
1758 // of what we gave to MC. This lets us use the original tokens.
1759 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1760 !std::less<const char*>()(AsmString.end(), Str.end()));
1762 // Try to find a token whose offset matches the first token.
1763 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1764 const unsigned *FirstTokOffset
1765 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1768 // For now, assert that the start of the string exactly
1769 // corresponds to the start of a token.
1770 assert(*FirstTokOffset == FirstCharOffset);
1772 // Use all the original tokens for this line. (We assume the
1773 // end of the line corresponds cleanly to a token break.)
1774 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1775 FirstOrigToken = &AsmToks[FirstTokIndex];
1776 unsigned LastCharOffset = Str.end() - AsmString.begin();
1777 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1778 if (AsmTokOffsets[i] >= LastCharOffset) break;
1779 TempToks.push_back(AsmToks[i]);
1783 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1784 // Compute an offset into the inline asm buffer.
1785 // FIXME: This isn't right if .macro is involved (but hopefully, no
1786 // real-world code does that).
1787 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1788 const llvm::MemoryBuffer *LBuf =
1789 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1790 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1792 // Figure out which token that offset points into.
1793 const unsigned *TokOffsetPtr =
1794 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1795 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1796 unsigned TokOffset = *TokOffsetPtr;
1798 // If we come up with an answer which seems sane, use it; otherwise,
1799 // just point at the __asm keyword.
1800 // FIXME: Assert the answer is sane once we handle .macro correctly.
1801 SourceLocation Loc = AsmLoc;
1802 if (TokIndex < AsmToks.size()) {
1803 const Token &Tok = AsmToks[TokIndex];
1804 Loc = Tok.getLocation();
1805 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1807 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1813 /// Parse an identifier in an MS-style inline assembly block.
1815 /// \param CastInfo - a void* so that we don't have to teach Parser.h
1816 /// about the actual type.
1817 ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1818 unsigned &NumLineToksConsumed,
1820 bool IsUnevaluatedContext) {
1821 llvm::InlineAsmIdentifierInfo &Info =
1822 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1824 // Push a fake token on the end so that we don't overrun the token
1825 // stream. We use ';' because it expression-parsing should never
1827 const tok::TokenKind EndOfStream = tok::semi;
1828 Token EndOfStreamTok;
1829 EndOfStreamTok.startToken();
1830 EndOfStreamTok.setKind(EndOfStream);
1831 LineToks.push_back(EndOfStreamTok);
1833 // Also copy the current token over.
1834 LineToks.push_back(Tok);
1836 PP.EnterTokenStream(LineToks.begin(),
1838 /*disable macros*/ true,
1839 /*owns tokens*/ false);
1841 // Clear the current token and advance to the first token in LineToks.
1844 // Parse an optional scope-specifier if we're in C++.
1846 if (getLangOpts().CPlusPlus) {
1847 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1850 // Require an identifier here.
1851 SourceLocation TemplateKWLoc;
1853 bool Invalid = ParseUnqualifiedId(SS,
1854 /*EnteringContext=*/false,
1855 /*AllowDestructorName=*/false,
1856 /*AllowConstructorName=*/false,
1857 /*ObjectType=*/ ParsedType(),
1861 // If we've run into the poison token we inserted before, or there
1862 // was a parsing error, then claim the entire line.
1863 if (Invalid || Tok.is(EndOfStream)) {
1864 NumLineToksConsumed = LineToks.size() - 2;
1866 // Otherwise, claim up to the start of the next token.
1868 // Figure out how many tokens we are into LineToks.
1869 unsigned LineIndex = 0;
1870 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1872 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1875 NumLineToksConsumed = LineIndex;
1878 // Finally, restore the old parsing state by consuming all the
1879 // tokens we staged before, implicitly killing off the
1880 // token-lexer we pushed.
1881 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1884 ConsumeToken(EndOfStream);
1886 // Leave LineToks in its original state.
1887 LineToks.pop_back();
1888 LineToks.pop_back();
1890 // Perform the lookup.
1891 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1892 IsUnevaluatedContext);
1895 /// Turn a sequence of our tokens back into a string that we can hand
1896 /// to the MC asm parser.
1897 static bool buildMSAsmString(Preprocessor &PP,
1898 SourceLocation AsmLoc,
1899 ArrayRef<Token> AsmToks,
1900 SmallVectorImpl<unsigned> &TokOffsets,
1901 SmallString<512> &Asm) {
1902 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1904 // Is this the start of a new assembly statement?
1905 bool isNewStatement = true;
1907 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1908 const Token &Tok = AsmToks[i];
1910 // Start each new statement with a newline and a tab.
1911 if (!isNewStatement &&
1912 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1914 isNewStatement = true;
1917 // Preserve the existence of leading whitespace except at the
1918 // start of a statement.
1919 if (!isNewStatement && Tok.hasLeadingSpace())
1922 // Remember the offset of this token.
1923 TokOffsets.push_back(Asm.size());
1925 // Don't actually write '__asm' into the assembly stream.
1926 if (Tok.is(tok::kw_asm)) {
1927 // Complain about __asm at the end of the stream.
1929 PP.Diag(AsmLoc, diag::err_asm_empty);
1936 // Append the spelling of the token.
1937 SmallString<32> SpellingBuffer;
1938 bool SpellingInvalid = false;
1939 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
1940 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
1942 // We are no longer at the start of a statement.
1943 isNewStatement = false;
1946 // Ensure that the buffer is null-terminated.
1947 Asm.push_back('\0');
1950 assert(TokOffsets.size() == AsmToks.size());
1954 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1955 /// this routine is called to collect the tokens for an MS asm statement.
1957 /// [MS] ms-asm-statement:
1959 /// ms-asm-block ms-asm-statement
1961 /// [MS] ms-asm-block:
1962 /// '__asm' ms-asm-line '\n'
1963 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1965 /// [MS] ms-asm-instruction-block
1967 /// ms-asm-line '\n' ms-asm-instruction-block
1969 StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1970 SourceManager &SrcMgr = PP.getSourceManager();
1971 SourceLocation EndLoc = AsmLoc;
1972 SmallVector<Token, 4> AsmToks;
1974 bool InBraces = false;
1975 unsigned short savedBraceCount = 0;
1976 bool InAsmComment = false;
1978 unsigned LineNo = 0;
1979 unsigned NumTokensRead = 0;
1980 SourceLocation LBraceLoc;
1982 if (Tok.is(tok::l_brace)) {
1983 // Braced inline asm: consume the opening brace.
1985 savedBraceCount = BraceCount;
1986 EndLoc = LBraceLoc = ConsumeBrace();
1989 // Single-line inline asm; compute which line it is on.
1990 std::pair<FileID, unsigned> ExpAsmLoc =
1991 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1992 FID = ExpAsmLoc.first;
1993 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1996 SourceLocation TokLoc = Tok.getLocation();
1998 // If we hit EOF, we're done, period.
1999 if (Tok.is(tok::eof))
2002 if (!InAsmComment && Tok.is(tok::semi)) {
2003 // A semicolon in an asm is the start of a comment.
2004 InAsmComment = true;
2006 // Compute which line the comment is on.
2007 std::pair<FileID, unsigned> ExpSemiLoc =
2008 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2009 FID = ExpSemiLoc.first;
2010 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2012 } else if (!InBraces || InAsmComment) {
2013 // If end-of-line is significant, check whether this token is on a
2015 std::pair<FileID, unsigned> ExpLoc =
2016 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2017 if (ExpLoc.first != FID ||
2018 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2019 // If this is a single-line __asm, we're done.
2022 // We're no longer in a comment.
2023 InAsmComment = false;
2024 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2025 // Single-line asm always ends when a closing brace is seen.
2026 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2027 // does MSVC do here?
2031 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2032 BraceCount == (savedBraceCount + 1)) {
2033 // Consume the closing brace, and finish
2034 EndLoc = ConsumeBrace();
2038 // Consume the next token; make sure we don't modify the brace count etc.
2039 // if we are in a comment.
2044 AsmToks.push_back(Tok);
2047 TokLoc = Tok.getLocation();
2051 if (InBraces && BraceCount != savedBraceCount) {
2052 // __asm without closing brace (this can happen at EOF).
2053 Diag(Tok, diag::err_expected_rbrace);
2054 Diag(LBraceLoc, diag::note_matching) << "{";
2056 } else if (NumTokensRead == 0) {
2058 Diag(Tok, diag::err_expected_lbrace);
2062 // Okay, prepare to use MC to parse the assembly.
2063 SmallVector<StringRef, 4> ConstraintRefs;
2064 SmallVector<Expr*, 4> Exprs;
2065 SmallVector<StringRef, 4> ClobberRefs;
2067 // We need an actual supported target.
2068 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2069 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2070 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2071 ArchTy != llvm::Triple::x86_64);
2072 if (UnsupportedArch)
2073 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2075 // If we don't support assembly, or the assembly is empty, we don't
2076 // need to instantiate the AsmParser, etc.
2077 if (UnsupportedArch || AsmToks.empty()) {
2078 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2079 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2080 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2083 // Expand the tokens into a string buffer.
2084 SmallString<512> AsmString;
2085 SmallVector<unsigned, 8> TokOffsets;
2086 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2089 // Find the target and create the target specific parser.
2091 const std::string &TT = TheTriple.getTriple();
2092 const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2094 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
2095 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2096 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2097 OwningPtr<llvm::MCSubtargetInfo>
2098 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2100 llvm::SourceMgr TempSrcMgr;
2101 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &TempSrcMgr);
2102 llvm::MemoryBuffer *Buffer =
2103 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2105 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2106 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2108 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2109 OwningPtr<llvm::MCAsmParser>
2110 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2111 OwningPtr<llvm::MCTargetAsmParser>
2112 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
2114 // Get the instruction descriptor.
2115 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
2116 llvm::MCInstPrinter *IP =
2117 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2119 // Change to the Intel dialect.
2120 Parser->setAssemblerDialect(1);
2121 Parser->setTargetParser(*TargetParser.get());
2122 Parser->setParsingInlineAsm(true);
2123 TargetParser->setParsingInlineAsm(true);
2125 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2126 AsmToks, TokOffsets);
2127 TargetParser->setSemaCallback(&Callback);
2128 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2131 unsigned NumOutputs;
2133 std::string AsmStringIR;
2134 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2135 SmallVector<std::string, 4> Constraints;
2136 SmallVector<std::string, 4> Clobbers;
2137 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2138 NumOutputs, NumInputs, OpExprs, Constraints,
2139 Clobbers, MII, IP, Callback))
2142 // Build the vector of clobber StringRefs.
2143 unsigned NumClobbers = Clobbers.size();
2144 ClobberRefs.resize(NumClobbers);
2145 for (unsigned i = 0; i != NumClobbers; ++i)
2146 ClobberRefs[i] = StringRef(Clobbers[i]);
2148 // Recast the void pointers and build the vector of constraint StringRefs.
2149 unsigned NumExprs = NumOutputs + NumInputs;
2150 ConstraintRefs.resize(NumExprs);
2151 Exprs.resize(NumExprs);
2152 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2153 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2157 // Need address of variable.
2158 if (OpExprs[i].second)
2159 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2162 ConstraintRefs[i] = StringRef(Constraints[i]);
2166 // FIXME: We should be passing source locations for better diagnostics.
2167 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2168 NumOutputs, NumInputs,
2169 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2172 /// ParseAsmStatement - Parse a GNU extended asm statement.
2174 /// gnu-asm-statement
2175 /// ms-asm-statement
2177 /// [GNU] gnu-asm-statement:
2178 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2180 /// [GNU] asm-argument:
2181 /// asm-string-literal
2182 /// asm-string-literal ':' asm-operands[opt]
2183 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2184 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2185 /// ':' asm-clobbers
2187 /// [GNU] asm-clobbers:
2188 /// asm-string-literal
2189 /// asm-clobbers ',' asm-string-literal
2191 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
2192 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
2193 SourceLocation AsmLoc = ConsumeToken();
2195 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
2196 !isTypeQualifier()) {
2198 return ParseMicrosoftAsmStatement(AsmLoc);
2200 DeclSpec DS(AttrFactory);
2201 SourceLocation Loc = Tok.getLocation();
2202 ParseTypeQualifierListOpt(DS, true, false);
2204 // GNU asms accept, but warn, about type-qualifiers other than volatile.
2205 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2206 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
2207 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2208 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
2209 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2210 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2211 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
2213 // Remember if this was a volatile asm.
2214 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
2215 if (Tok.isNot(tok::l_paren)) {
2216 Diag(Tok, diag::err_expected_lparen_after) << "asm";
2217 SkipUntil(tok::r_paren);
2220 BalancedDelimiterTracker T(*this, tok::l_paren);
2223 ExprResult AsmString(ParseAsmStringLiteral());
2224 if (AsmString.isInvalid()) {
2225 // Consume up to and including the closing paren.
2230 SmallVector<IdentifierInfo *, 4> Names;
2231 ExprVector Constraints;
2233 ExprVector Clobbers;
2235 if (Tok.is(tok::r_paren)) {
2236 // We have a simple asm expression like 'asm("foo")'.
2238 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2239 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2240 Constraints, Exprs, AsmString.take(),
2241 Clobbers, T.getCloseLocation());
2244 // Parse Outputs, if present.
2245 bool AteExtraColon = false;
2246 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2247 // In C++ mode, parse "::" like ": :".
2248 AteExtraColon = Tok.is(tok::coloncolon);
2251 if (!AteExtraColon &&
2252 ParseAsmOperandsOpt(Names, Constraints, Exprs))
2256 unsigned NumOutputs = Names.size();
2258 // Parse Inputs, if present.
2259 if (AteExtraColon ||
2260 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2261 // In C++ mode, parse "::" like ": :".
2263 AteExtraColon = false;
2265 AteExtraColon = Tok.is(tok::coloncolon);
2269 if (!AteExtraColon &&
2270 ParseAsmOperandsOpt(Names, Constraints, Exprs))
2274 assert(Names.size() == Constraints.size() &&
2275 Constraints.size() == Exprs.size() &&
2276 "Input operand size mismatch!");
2278 unsigned NumInputs = Names.size() - NumOutputs;
2280 // Parse the clobbers, if present.
2281 if (AteExtraColon || Tok.is(tok::colon)) {
2285 // Parse the asm-string list for clobbers if present.
2286 if (Tok.isNot(tok::r_paren)) {
2288 ExprResult Clobber(ParseAsmStringLiteral());
2290 if (Clobber.isInvalid())
2293 Clobbers.push_back(Clobber.release());
2295 if (Tok.isNot(tok::comma)) break;
2302 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2303 NumInputs, Names.data(), Constraints, Exprs,
2304 AsmString.take(), Clobbers,
2305 T.getCloseLocation());
2308 /// ParseAsmOperands - Parse the asm-operands production as used by
2309 /// asm-statement, assuming the leading ':' token was eaten.
2311 /// [GNU] asm-operands:
2313 /// asm-operands ',' asm-operand
2315 /// [GNU] asm-operand:
2316 /// asm-string-literal '(' expression ')'
2317 /// '[' identifier ']' asm-string-literal '(' expression ')'
2320 // FIXME: Avoid unnecessary std::string trashing.
2321 bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2322 SmallVectorImpl<Expr *> &Constraints,
2323 SmallVectorImpl<Expr *> &Exprs) {
2324 // 'asm-operands' isn't present?
2325 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
2329 // Read the [id] if present.
2330 if (Tok.is(tok::l_square)) {
2331 BalancedDelimiterTracker T(*this, tok::l_square);
2334 if (Tok.isNot(tok::identifier)) {
2335 Diag(Tok, diag::err_expected_ident);
2336 SkipUntil(tok::r_paren);
2340 IdentifierInfo *II = Tok.getIdentifierInfo();
2343 Names.push_back(II);
2348 ExprResult Constraint(ParseAsmStringLiteral());
2349 if (Constraint.isInvalid()) {
2350 SkipUntil(tok::r_paren);
2353 Constraints.push_back(Constraint.release());
2355 if (Tok.isNot(tok::l_paren)) {
2356 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
2357 SkipUntil(tok::r_paren);
2361 // Read the parenthesized expression.
2362 BalancedDelimiterTracker T(*this, tok::l_paren);
2364 ExprResult Res(ParseExpression());
2366 if (Res.isInvalid()) {
2367 SkipUntil(tok::r_paren);
2370 Exprs.push_back(Res.release());
2371 // Eat the comma and continue parsing if it exists.
2372 if (Tok.isNot(tok::comma)) return false;
2377 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2378 assert(Tok.is(tok::l_brace));
2379 SourceLocation LBraceLoc = Tok.getLocation();
2381 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
2382 trySkippingFunctionBody()) {
2384 return Actions.ActOnSkippedFunctionBody(Decl);
2387 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2388 "parsing function body");
2390 // Do not enter a scope for the brace, as the arguments are in the same scope
2391 // (the function body) as the body itself. Instead, just read the statement
2392 // list and put it into a CompoundStmt for safe keeping.
2393 StmtResult FnBody(ParseCompoundStatementBody());
2395 // If the function body could not be parsed, make a bogus compoundstmt.
2396 if (FnBody.isInvalid()) {
2397 Sema::CompoundScopeRAII CompoundScope(Actions);
2398 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
2399 MultiStmtArg(), false);
2403 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2406 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2408 /// function-try-block:
2409 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2411 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2412 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2413 SourceLocation TryLoc = ConsumeToken();
2415 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2416 "parsing function try block");
2418 // Constructor initializer list?
2419 if (Tok.is(tok::colon))
2420 ParseConstructorInitializer(Decl);
2422 Actions.ActOnDefaultCtorInitializers(Decl);
2424 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2425 trySkippingFunctionBody()) {
2427 return Actions.ActOnSkippedFunctionBody(Decl);
2430 SourceLocation LBraceLoc = Tok.getLocation();
2431 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2432 // If we failed to parse the try-catch, we just give the function an empty
2433 // compound statement as the body.
2434 if (FnBody.isInvalid()) {
2435 Sema::CompoundScopeRAII CompoundScope(Actions);
2436 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
2437 MultiStmtArg(), false);
2441 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2444 bool Parser::trySkippingFunctionBody() {
2445 assert(Tok.is(tok::l_brace));
2446 assert(SkipFunctionBodies &&
2447 "Should only be called when SkipFunctionBodies is enabled");
2449 if (!PP.isCodeCompletionEnabled()) {
2451 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2455 // We're in code-completion mode. Skip parsing for all function bodies unless
2456 // the body contains the code-completion point.
2457 TentativeParsingAction PA(*this);
2459 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
2460 /*StopAtCodeCompletion=*/true)) {
2469 /// ParseCXXTryBlock - Parse a C++ try-block.
2472 /// 'try' compound-statement handler-seq
2474 StmtResult Parser::ParseCXXTryBlock() {
2475 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2477 SourceLocation TryLoc = ConsumeToken();
2478 return ParseCXXTryBlockCommon(TryLoc);
2481 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2482 /// function-try-block.
2485 /// 'try' compound-statement handler-seq
2487 /// function-try-block:
2488 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2491 /// handler handler-seq[opt]
2493 /// [Borland] try-block:
2494 /// 'try' compound-statement seh-except-block
2495 /// 'try' compound-statment seh-finally-block
2497 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2498 if (Tok.isNot(tok::l_brace))
2499 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2500 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2502 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2503 Scope::DeclScope | Scope::TryScope |
2504 (FnTry ? Scope::FnTryCatchScope : 0)));
2505 if (TryBlock.isInvalid())
2508 // Borland allows SEH-handlers with 'try'
2510 if ((Tok.is(tok::identifier) &&
2511 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2512 Tok.is(tok::kw___finally)) {
2513 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2515 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2516 SourceLocation Loc = ConsumeToken();
2517 Handler = ParseSEHExceptBlock(Loc);
2520 SourceLocation Loc = ConsumeToken();
2521 Handler = ParseSEHFinallyBlock(Loc);
2523 if(Handler.isInvalid())
2526 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2532 StmtVector Handlers;
2533 ParsedAttributesWithRange attrs(AttrFactory);
2534 MaybeParseCXX11Attributes(attrs);
2535 ProhibitAttributes(attrs);
2537 if (Tok.isNot(tok::kw_catch))
2538 return StmtError(Diag(Tok, diag::err_expected_catch));
2539 while (Tok.is(tok::kw_catch)) {
2540 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2541 if (!Handler.isInvalid())
2542 Handlers.push_back(Handler.release());
2544 // Don't bother creating the full statement if we don't have any usable
2546 if (Handlers.empty())
2549 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(),Handlers);
2553 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2556 /// 'catch' '(' exception-declaration ')' compound-statement
2558 /// exception-declaration:
2559 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2560 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2563 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2564 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2566 SourceLocation CatchLoc = ConsumeToken();
2568 BalancedDelimiterTracker T(*this, tok::l_paren);
2569 if (T.expectAndConsume(diag::err_expected_lparen))
2573 // The name in a catch exception-declaration is local to the handler and
2574 // shall not be redeclared in the outermost block of the handler.
2575 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2576 (FnCatch ? Scope::FnTryCatchScope : 0));
2578 // exception-declaration is equivalent to '...' or a parameter-declaration
2579 // without default arguments.
2580 Decl *ExceptionDecl = 0;
2581 if (Tok.isNot(tok::ellipsis)) {
2582 ParsedAttributesWithRange Attributes(AttrFactory);
2583 MaybeParseCXX11Attributes(Attributes);
2585 DeclSpec DS(AttrFactory);
2586 DS.takeAttributesFrom(Attributes);
2588 if (ParseCXXTypeSpecifierSeq(DS))
2591 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2592 ParseDeclarator(ExDecl);
2593 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2598 if (T.getCloseLocation().isInvalid())
2601 if (Tok.isNot(tok::l_brace))
2602 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2604 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2605 StmtResult Block(ParseCompoundStatement());
2606 if (Block.isInvalid())
2609 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
2612 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2613 IfExistsCondition Result;
2614 if (ParseMicrosoftIfExistsCondition(Result))
2617 // Handle dependent statements by parsing the braces as a compound statement.
2618 // This is not the same behavior as Visual C++, which don't treat this as a
2619 // compound statement, but for Clang's type checking we can't have anything
2620 // inside these braces escaping to the surrounding code.
2621 if (Result.Behavior == IEB_Dependent) {
2622 if (!Tok.is(tok::l_brace)) {
2623 Diag(Tok, diag::err_expected_lbrace);
2627 StmtResult Compound = ParseCompoundStatement();
2628 if (Compound.isInvalid())
2631 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2636 if (DepResult.isUsable())
2637 Stmts.push_back(DepResult.get());
2641 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2642 if (Braces.consumeOpen()) {
2643 Diag(Tok, diag::err_expected_lbrace);
2647 switch (Result.Behavior) {
2649 // Parse the statements below.
2653 llvm_unreachable("Dependent case handled above");
2660 // Condition is true, parse the statements.
2661 while (Tok.isNot(tok::r_brace)) {
2662 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2664 Stmts.push_back(R.release());
2666 Braces.consumeClose();