1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
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 contains code to emit Stmt nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/PrettyStackTrace.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Intrinsics.h"
25 using namespace clang;
26 using namespace CodeGen;
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
33 if (CGDebugInfo *DI = getDebugInfo()) {
38 Loc = S->getLocStart();
39 DI->EmitLocation(Builder, Loc);
41 //if (++NumStopPoints == 1)
46 void CodeGenFunction::EmitStmt(const Stmt *S) {
47 assert(S && "Null statement?");
49 // These statements have their own debug info handling.
50 if (EmitSimpleStmt(S))
53 // Check if we are generating unreachable code.
54 if (!HaveInsertPoint()) {
55 // If so, and the statement doesn't contain a label, then we do not need to
56 // generate actual code. This is safe because (1) the current point is
57 // unreachable, so we don't need to execute the code, and (2) we've already
58 // handled the statements which update internal data structures (like the
59 // local variable map) which could be used by subsequent statements.
60 if (!ContainsLabel(S)) {
61 // Verify that any decl statements were handled as simple, they may be in
62 // scope of subsequent reachable statements.
63 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
67 // Otherwise, make a new block to hold the code.
71 // Generate a stoppoint if we are emitting debug info.
74 switch (S->getStmtClass()) {
75 case Stmt::NoStmtClass:
76 case Stmt::CXXCatchStmtClass:
77 case Stmt::SEHExceptStmtClass:
78 case Stmt::SEHFinallyStmtClass:
79 case Stmt::MSDependentExistsStmtClass:
80 llvm_unreachable("invalid statement class to emit generically");
81 case Stmt::NullStmtClass:
82 case Stmt::CompoundStmtClass:
83 case Stmt::DeclStmtClass:
84 case Stmt::LabelStmtClass:
85 case Stmt::AttributedStmtClass:
86 case Stmt::GotoStmtClass:
87 case Stmt::BreakStmtClass:
88 case Stmt::ContinueStmtClass:
89 case Stmt::DefaultStmtClass:
90 case Stmt::CaseStmtClass:
91 llvm_unreachable("should have emitted these statements as simple");
93 #define STMT(Type, Base)
94 #define ABSTRACT_STMT(Op)
95 #define EXPR(Type, Base) \
96 case Stmt::Type##Class:
97 #include "clang/AST/StmtNodes.inc"
99 // Remember the block we came in on.
100 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
101 assert(incoming && "expression emission must have an insertion point");
103 EmitIgnoredExpr(cast<Expr>(S));
105 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
106 assert(outgoing && "expression emission cleared block!");
108 // The expression emitters assume (reasonably!) that the insertion
109 // point is always set. To maintain that, the call-emission code
110 // for noreturn functions has to enter a new block with no
111 // predecessors. We want to kill that block and mark the current
112 // insertion point unreachable in the common case of a call like
113 // "exit();". Since expression emission doesn't otherwise create
114 // blocks with no predecessors, we can just test for that.
115 // However, we must be careful not to do this to our incoming
116 // block, because *statement* emission does sometimes create
117 // reachable blocks which will have no predecessors until later in
118 // the function. This occurs with, e.g., labels that are not
119 // reachable by fallthrough.
120 if (incoming != outgoing && outgoing->use_empty()) {
121 outgoing->eraseFromParent();
122 Builder.ClearInsertionPoint();
127 case Stmt::IndirectGotoStmtClass:
128 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
130 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
131 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
132 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
133 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
135 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
137 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
138 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
139 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
140 case Stmt::CapturedStmtClass:
141 EmitCapturedStmt(cast<CapturedStmt>(*S));
143 case Stmt::ObjCAtTryStmtClass:
144 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
146 case Stmt::ObjCAtCatchStmtClass:
148 "@catch statements should be handled by EmitObjCAtTryStmt");
149 case Stmt::ObjCAtFinallyStmtClass:
151 "@finally statements should be handled by EmitObjCAtTryStmt");
152 case Stmt::ObjCAtThrowStmtClass:
153 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
155 case Stmt::ObjCAtSynchronizedStmtClass:
156 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
158 case Stmt::ObjCForCollectionStmtClass:
159 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
161 case Stmt::ObjCAutoreleasePoolStmtClass:
162 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
165 case Stmt::CXXTryStmtClass:
166 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
168 case Stmt::CXXForRangeStmtClass:
169 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
170 case Stmt::SEHTryStmtClass:
171 // FIXME Not yet implemented
176 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
177 switch (S->getStmtClass()) {
178 default: return false;
179 case Stmt::NullStmtClass: break;
180 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
181 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
182 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
183 case Stmt::AttributedStmtClass:
184 EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
185 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
186 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
187 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
188 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
189 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
195 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
196 /// this captures the expression result of the last sub-statement and returns it
197 /// (for use by the statement expression extension).
198 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
199 AggValueSlot AggSlot) {
200 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
201 "LLVM IR generation of compound statement ('{}')");
203 // Keep track of the current cleanup stack depth, including debug scopes.
204 LexicalScope Scope(*this, S.getSourceRange());
206 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
209 RValue CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast,
210 AggValueSlot AggSlot) {
212 for (CompoundStmt::const_body_iterator I = S.body_begin(),
213 E = S.body_end()-GetLast; I != E; ++I)
220 // We have to special case labels here. They are statements, but when put
221 // at the end of a statement expression, they yield the value of their
222 // subexpression. Handle this by walking through all labels we encounter,
223 // emitting them before we evaluate the subexpr.
224 const Stmt *LastStmt = S.body_back();
225 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
226 EmitLabel(LS->getDecl());
227 LastStmt = LS->getSubStmt();
232 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
238 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
239 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
241 // If there is a cleanup stack, then we it isn't worth trying to
242 // simplify this block (we would need to remove it from the scope map
243 // and cleanup entry).
244 if (!EHStack.empty())
247 // Can only simplify direct branches.
248 if (!BI || !BI->isUnconditional())
251 // Can only simplify empty blocks.
252 if (BI != BB->begin())
255 BB->replaceAllUsesWith(BI->getSuccessor(0));
256 BI->eraseFromParent();
257 BB->eraseFromParent();
260 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
261 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
263 // Fall out of the current block (if necessary).
266 if (IsFinished && BB->use_empty()) {
271 // Place the block after the current block, if possible, or else at
272 // the end of the function.
273 if (CurBB && CurBB->getParent())
274 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
276 CurFn->getBasicBlockList().push_back(BB);
277 Builder.SetInsertPoint(BB);
280 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
281 // Emit a branch from the current block to the target one if this
282 // was a real block. If this was just a fall-through block after a
283 // terminator, don't emit it.
284 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
286 if (!CurBB || CurBB->getTerminator()) {
287 // If there is no insert point or the previous block is already
288 // terminated, don't touch it.
290 // Otherwise, create a fall-through branch.
291 Builder.CreateBr(Target);
294 Builder.ClearInsertionPoint();
297 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
298 bool inserted = false;
299 for (llvm::BasicBlock::use_iterator
300 i = block->use_begin(), e = block->use_end(); i != e; ++i) {
301 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) {
302 CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
309 CurFn->getBasicBlockList().push_back(block);
311 Builder.SetInsertPoint(block);
314 CodeGenFunction::JumpDest
315 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
316 JumpDest &Dest = LabelMap[D];
317 if (Dest.isValid()) return Dest;
319 // Create, but don't insert, the new block.
320 Dest = JumpDest(createBasicBlock(D->getName()),
321 EHScopeStack::stable_iterator::invalid(),
322 NextCleanupDestIndex++);
326 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
327 // Add this label to the current lexical scope if we're within any
328 // normal cleanups. Jumps "in" to this label --- when permitted by
329 // the language --- may need to be routed around such cleanups.
330 if (EHStack.hasNormalCleanups() && CurLexicalScope)
331 CurLexicalScope->addLabel(D);
333 JumpDest &Dest = LabelMap[D];
335 // If we didn't need a forward reference to this label, just go
336 // ahead and create a destination at the current scope.
337 if (!Dest.isValid()) {
338 Dest = getJumpDestInCurrentScope(D->getName());
340 // Otherwise, we need to give this label a target depth and remove
341 // it from the branch-fixups list.
343 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
344 Dest.setScopeDepth(EHStack.stable_begin());
345 ResolveBranchFixups(Dest.getBlock());
348 EmitBlock(Dest.getBlock());
351 /// Change the cleanup scope of the labels in this lexical scope to
352 /// match the scope of the enclosing context.
353 void CodeGenFunction::LexicalScope::rescopeLabels() {
354 assert(!Labels.empty());
355 EHScopeStack::stable_iterator innermostScope
356 = CGF.EHStack.getInnermostNormalCleanup();
358 // Change the scope depth of all the labels.
359 for (SmallVectorImpl<const LabelDecl*>::const_iterator
360 i = Labels.begin(), e = Labels.end(); i != e; ++i) {
361 assert(CGF.LabelMap.count(*i));
362 JumpDest &dest = CGF.LabelMap.find(*i)->second;
363 assert(dest.getScopeDepth().isValid());
364 assert(innermostScope.encloses(dest.getScopeDepth()));
365 dest.setScopeDepth(innermostScope);
368 // Reparent the labels if the new scope also has cleanups.
369 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
370 ParentScope->Labels.append(Labels.begin(), Labels.end());
375 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
376 EmitLabel(S.getDecl());
377 EmitStmt(S.getSubStmt());
380 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
381 EmitStmt(S.getSubStmt());
384 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
385 // If this code is reachable then emit a stop point (if generating
386 // debug info). We have to do this ourselves because we are on the
387 // "simple" statement path.
388 if (HaveInsertPoint())
391 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
395 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
396 if (const LabelDecl *Target = S.getConstantTarget()) {
397 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
401 // Ensure that we have an i8* for our PHI node.
402 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
404 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
406 // Get the basic block for the indirect goto.
407 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
409 // The first instruction in the block has to be the PHI for the switch dest,
410 // add an entry for this branch.
411 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
413 EmitBranch(IndGotoBB);
416 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
417 // C99 6.8.4.1: The first substatement is executed if the expression compares
418 // unequal to 0. The condition must be a scalar type.
419 RunCleanupsScope ConditionScope(*this);
421 if (S.getConditionVariable())
422 EmitAutoVarDecl(*S.getConditionVariable());
424 // If the condition constant folds and can be elided, try to avoid emitting
425 // the condition and the dead arm of the if/else.
427 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
428 // Figure out which block (then or else) is executed.
429 const Stmt *Executed = S.getThen();
430 const Stmt *Skipped = S.getElse();
431 if (!CondConstant) // Condition false?
432 std::swap(Executed, Skipped);
434 // If the skipped block has no labels in it, just emit the executed block.
435 // This avoids emitting dead code and simplifies the CFG substantially.
436 if (!ContainsLabel(Skipped)) {
438 RunCleanupsScope ExecutedScope(*this);
445 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
446 // the conditional branch.
447 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
448 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
449 llvm::BasicBlock *ElseBlock = ContBlock;
451 ElseBlock = createBasicBlock("if.else");
452 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
454 // Emit the 'then' code.
455 EmitBlock(ThenBlock);
457 RunCleanupsScope ThenScope(*this);
458 EmitStmt(S.getThen());
460 EmitBranch(ContBlock);
462 // Emit the 'else' code if present.
463 if (const Stmt *Else = S.getElse()) {
464 // There is no need to emit line number for unconditional branch.
466 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
467 EmitBlock(ElseBlock);
469 RunCleanupsScope ElseScope(*this);
472 // There is no need to emit line number for unconditional branch.
474 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
475 EmitBranch(ContBlock);
478 // Emit the continuation block for code after the if.
479 EmitBlock(ContBlock, true);
482 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
483 // Emit the header for the loop, which will also become
484 // the continue target.
485 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
486 EmitBlock(LoopHeader.getBlock());
488 // Create an exit block for when the condition fails, which will
489 // also become the break target.
490 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
492 // Store the blocks to use for break and continue.
493 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
495 // C++ [stmt.while]p2:
496 // When the condition of a while statement is a declaration, the
497 // scope of the variable that is declared extends from its point
498 // of declaration (3.3.2) to the end of the while statement.
500 // The object created in a condition is destroyed and created
501 // with each iteration of the loop.
502 RunCleanupsScope ConditionScope(*this);
504 if (S.getConditionVariable())
505 EmitAutoVarDecl(*S.getConditionVariable());
507 // Evaluate the conditional in the while header. C99 6.8.5.1: The
508 // evaluation of the controlling expression takes place before each
509 // execution of the loop body.
510 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
512 // while(1) is common, avoid extra exit blocks. Be sure
513 // to correctly handle break/continue though.
514 bool EmitBoolCondBranch = true;
515 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
517 EmitBoolCondBranch = false;
519 // As long as the condition is true, go to the loop body.
520 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
521 if (EmitBoolCondBranch) {
522 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
523 if (ConditionScope.requiresCleanups())
524 ExitBlock = createBasicBlock("while.exit");
526 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
528 if (ExitBlock != LoopExit.getBlock()) {
529 EmitBlock(ExitBlock);
530 EmitBranchThroughCleanup(LoopExit);
534 // Emit the loop body. We have to emit this in a cleanup scope
535 // because it might be a singleton DeclStmt.
537 RunCleanupsScope BodyScope(*this);
539 EmitStmt(S.getBody());
542 BreakContinueStack.pop_back();
544 // Immediately force cleanup.
545 ConditionScope.ForceCleanup();
547 // Branch to the loop header again.
548 EmitBranch(LoopHeader.getBlock());
550 // Emit the exit block.
551 EmitBlock(LoopExit.getBlock(), true);
553 // The LoopHeader typically is just a branch if we skipped emitting
554 // a branch, try to erase it.
555 if (!EmitBoolCondBranch)
556 SimplifyForwardingBlocks(LoopHeader.getBlock());
559 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
560 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
561 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
563 // Store the blocks to use for break and continue.
564 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
566 // Emit the body of the loop.
567 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
570 RunCleanupsScope BodyScope(*this);
571 EmitStmt(S.getBody());
574 BreakContinueStack.pop_back();
576 EmitBlock(LoopCond.getBlock());
578 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
579 // after each execution of the loop body."
581 // Evaluate the conditional in the while header.
582 // C99 6.8.5p2/p4: The first substatement is executed if the expression
583 // compares unequal to 0. The condition must be a scalar type.
584 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
586 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
587 // to correctly handle break/continue though.
588 bool EmitBoolCondBranch = true;
589 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
591 EmitBoolCondBranch = false;
593 // As long as the condition is true, iterate the loop.
594 if (EmitBoolCondBranch)
595 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
597 // Emit the exit block.
598 EmitBlock(LoopExit.getBlock());
600 // The DoCond block typically is just a branch if we skipped
601 // emitting a branch, try to erase it.
602 if (!EmitBoolCondBranch)
603 SimplifyForwardingBlocks(LoopCond.getBlock());
606 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
607 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
609 RunCleanupsScope ForScope(*this);
611 CGDebugInfo *DI = getDebugInfo();
613 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
615 // Evaluate the first part before the loop.
617 EmitStmt(S.getInit());
619 // Start the loop with a block that tests the condition.
620 // If there's an increment, the continue scope will be overwritten
622 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
623 llvm::BasicBlock *CondBlock = Continue.getBlock();
624 EmitBlock(CondBlock);
626 // Create a cleanup scope for the condition variable cleanups.
627 RunCleanupsScope ConditionScope(*this);
629 llvm::Value *BoolCondVal = 0;
631 // If the for statement has a condition scope, emit the local variable
633 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
634 if (S.getConditionVariable()) {
635 EmitAutoVarDecl(*S.getConditionVariable());
638 // If there are any cleanups between here and the loop-exit scope,
639 // create a block to stage a loop exit along.
640 if (ForScope.requiresCleanups())
641 ExitBlock = createBasicBlock("for.cond.cleanup");
643 // As long as the condition is true, iterate the loop.
644 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
646 // C99 6.8.5p2/p4: The first substatement is executed if the expression
647 // compares unequal to 0. The condition must be a scalar type.
648 BoolCondVal = EvaluateExprAsBool(S.getCond());
649 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
651 if (ExitBlock != LoopExit.getBlock()) {
652 EmitBlock(ExitBlock);
653 EmitBranchThroughCleanup(LoopExit);
658 // Treat it as a non-zero constant. Don't even create a new block for the
659 // body, just fall into it.
662 // If the for loop doesn't have an increment we can just use the
663 // condition as the continue block. Otherwise we'll need to create
664 // a block for it (in the current scope, i.e. in the scope of the
665 // condition), and that we will become our continue block.
667 Continue = getJumpDestInCurrentScope("for.inc");
669 // Store the blocks to use for break and continue.
670 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
673 // Create a separate cleanup scope for the body, in case it is not
674 // a compound statement.
675 RunCleanupsScope BodyScope(*this);
676 EmitStmt(S.getBody());
679 // If there is an increment, emit it next.
681 EmitBlock(Continue.getBlock());
682 EmitStmt(S.getInc());
685 BreakContinueStack.pop_back();
687 ConditionScope.ForceCleanup();
688 EmitBranch(CondBlock);
690 ForScope.ForceCleanup();
693 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
695 // Emit the fall-through block.
696 EmitBlock(LoopExit.getBlock(), true);
699 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
700 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
702 RunCleanupsScope ForScope(*this);
704 CGDebugInfo *DI = getDebugInfo();
706 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
708 // Evaluate the first pieces before the loop.
709 EmitStmt(S.getRangeStmt());
710 EmitStmt(S.getBeginEndStmt());
712 // Start the loop with a block that tests the condition.
713 // If there's an increment, the continue scope will be overwritten
715 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
716 EmitBlock(CondBlock);
718 // If there are any cleanups between here and the loop-exit scope,
719 // create a block to stage a loop exit along.
720 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
721 if (ForScope.requiresCleanups())
722 ExitBlock = createBasicBlock("for.cond.cleanup");
724 // The loop body, consisting of the specified body and the loop variable.
725 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
727 // The body is executed if the expression, contextually converted
729 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
730 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
732 if (ExitBlock != LoopExit.getBlock()) {
733 EmitBlock(ExitBlock);
734 EmitBranchThroughCleanup(LoopExit);
739 // Create a block for the increment. In case of a 'continue', we jump there.
740 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
742 // Store the blocks to use for break and continue.
743 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
746 // Create a separate cleanup scope for the loop variable and body.
747 RunCleanupsScope BodyScope(*this);
748 EmitStmt(S.getLoopVarStmt());
749 EmitStmt(S.getBody());
752 // If there is an increment, emit it next.
753 EmitBlock(Continue.getBlock());
754 EmitStmt(S.getInc());
756 BreakContinueStack.pop_back();
758 EmitBranch(CondBlock);
760 ForScope.ForceCleanup();
763 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
765 // Emit the fall-through block.
766 EmitBlock(LoopExit.getBlock(), true);
769 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
771 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
772 } else if (RV.isAggregate()) {
773 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
775 EmitStoreOfComplex(RV.getComplexVal(),
776 MakeNaturalAlignAddrLValue(ReturnValue, Ty),
779 EmitBranchThroughCleanup(ReturnBlock);
782 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
783 /// if the function returns void, or may be missing one if the function returns
784 /// non-void. Fun stuff :).
785 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
786 // Emit the result value, even if unused, to evalute the side effects.
787 const Expr *RV = S.getRetValue();
789 // Treat block literals in a return expression as if they appeared
790 // in their own scope. This permits a small, easily-implemented
791 // exception to our over-conservative rules about not jumping to
792 // statements following block literals with non-trivial cleanups.
793 RunCleanupsScope cleanupScope(*this);
794 if (const ExprWithCleanups *cleanups =
795 dyn_cast_or_null<ExprWithCleanups>(RV)) {
796 enterFullExpression(cleanups);
797 RV = cleanups->getSubExpr();
800 // FIXME: Clean this up by using an LValue for ReturnTemp,
801 // EmitStoreThroughLValue, and EmitAnyExpr.
802 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
803 // Apply the named return value optimization for this return statement,
804 // which means doing nothing: the appropriate result has already been
805 // constructed into the NRVO variable.
807 // If there is an NRVO flag for this variable, set it to 1 into indicate
808 // that the cleanup code should not destroy the variable.
809 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
810 Builder.CreateStore(Builder.getTrue(), NRVOFlag);
811 } else if (!ReturnValue) {
812 // Make sure not to return anything, but evaluate the expression
816 } else if (RV == 0) {
817 // Do nothing (return value is left uninitialized)
818 } else if (FnRetTy->isReferenceType()) {
819 // If this function returns a reference, take the address of the expression
820 // rather than the value.
821 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
822 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
824 switch (getEvaluationKind(RV->getType())) {
826 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
829 EmitComplexExprIntoLValue(RV,
830 MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
833 case TEK_Aggregate: {
834 CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
835 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
837 AggValueSlot::IsDestructed,
838 AggValueSlot::DoesNotNeedGCBarriers,
839 AggValueSlot::IsNotAliased));
846 if (RV == 0 || RV->isEvaluatable(getContext()))
847 NumSimpleReturnExprs += 1;
849 cleanupScope.ForceCleanup();
850 EmitBranchThroughCleanup(ReturnBlock);
853 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
854 // As long as debug info is modeled with instructions, we have to ensure we
855 // have a place to insert here and write the stop point here.
856 if (HaveInsertPoint())
859 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
864 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
865 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
867 // If this code is reachable then emit a stop point (if generating
868 // debug info). We have to do this ourselves because we are on the
869 // "simple" statement path.
870 if (HaveInsertPoint())
873 JumpDest Block = BreakContinueStack.back().BreakBlock;
874 EmitBranchThroughCleanup(Block);
877 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
878 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
880 // If this code is reachable then emit a stop point (if generating
881 // debug info). We have to do this ourselves because we are on the
882 // "simple" statement path.
883 if (HaveInsertPoint())
886 JumpDest Block = BreakContinueStack.back().ContinueBlock;
887 EmitBranchThroughCleanup(Block);
890 /// EmitCaseStmtRange - If case statement range is not too big then
891 /// add multiple cases to switch instruction, one for each value within
892 /// the range. If range is too big then emit "if" condition check.
893 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
894 assert(S.getRHS() && "Expected RHS value in CaseStmt");
896 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
897 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
899 // Emit the code for this case. We do this first to make sure it is
900 // properly chained from our predecessor before generating the
901 // switch machinery to enter this block.
902 EmitBlock(createBasicBlock("sw.bb"));
903 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
904 EmitStmt(S.getSubStmt());
906 // If range is empty, do nothing.
907 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
910 llvm::APInt Range = RHS - LHS;
911 // FIXME: parameters such as this should not be hardcoded.
912 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
913 // Range is small enough to add multiple switch instruction cases.
914 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
915 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
921 // The range is too big. Emit "if" condition into a new block,
922 // making sure to save and restore the current insertion point.
923 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
925 // Push this test onto the chain of range checks (which terminates
926 // in the default basic block). The switch's default will be changed
927 // to the top of this chain after switch emission is complete.
928 llvm::BasicBlock *FalseDest = CaseRangeBlock;
929 CaseRangeBlock = createBasicBlock("sw.caserange");
931 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
932 Builder.SetInsertPoint(CaseRangeBlock);
936 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
938 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
939 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
941 // Restore the appropriate insertion point.
943 Builder.SetInsertPoint(RestoreBB);
945 Builder.ClearInsertionPoint();
948 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
949 // If there is no enclosing switch instance that we're aware of, then this
950 // case statement and its block can be elided. This situation only happens
951 // when we've constant-folded the switch, are emitting the constant case,
952 // and part of the constant case includes another case statement. For
953 // instance: switch (4) { case 4: do { case 5: } while (1); }
955 EmitStmt(S.getSubStmt());
959 // Handle case ranges.
961 EmitCaseStmtRange(S);
965 llvm::ConstantInt *CaseVal =
966 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
968 // If the body of the case is just a 'break', and if there was no fallthrough,
969 // try to not emit an empty block.
970 if ((CGM.getCodeGenOpts().OptimizationLevel > 0) &&
971 isa<BreakStmt>(S.getSubStmt())) {
972 JumpDest Block = BreakContinueStack.back().BreakBlock;
974 // Only do this optimization if there are no cleanups that need emitting.
975 if (isObviouslyBranchWithoutCleanups(Block)) {
976 SwitchInsn->addCase(CaseVal, Block.getBlock());
978 // If there was a fallthrough into this case, make sure to redirect it to
979 // the end of the switch as well.
980 if (Builder.GetInsertBlock()) {
981 Builder.CreateBr(Block.getBlock());
982 Builder.ClearInsertionPoint();
988 EmitBlock(createBasicBlock("sw.bb"));
989 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
990 SwitchInsn->addCase(CaseVal, CaseDest);
992 // Recursively emitting the statement is acceptable, but is not wonderful for
993 // code where we have many case statements nested together, i.e.:
997 // Handling this recursively will create a new block for each case statement
998 // that falls through to the next case which is IR intensive. It also causes
999 // deep recursion which can run into stack depth limitations. Handle
1000 // sequential non-range case statements specially.
1001 const CaseStmt *CurCase = &S;
1002 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1004 // Otherwise, iteratively add consecutive cases to this switch stmt.
1005 while (NextCase && NextCase->getRHS() == 0) {
1007 llvm::ConstantInt *CaseVal =
1008 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1009 SwitchInsn->addCase(CaseVal, CaseDest);
1010 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1013 // Normal default recursion for non-cases.
1014 EmitStmt(CurCase->getSubStmt());
1017 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1018 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1019 assert(DefaultBlock->empty() &&
1020 "EmitDefaultStmt: Default block already defined?");
1021 EmitBlock(DefaultBlock);
1022 EmitStmt(S.getSubStmt());
1025 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1026 /// constant value that is being switched on, see if we can dead code eliminate
1027 /// the body of the switch to a simple series of statements to emit. Basically,
1028 /// on a switch (5) we want to find these statements:
1030 /// printf(...); <--
1034 /// and add them to the ResultStmts vector. If it is unsafe to do this
1035 /// transformation (for example, one of the elided statements contains a label
1036 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1037 /// should include statements after it (e.g. the printf() line is a substmt of
1038 /// the case) then return CSFC_FallThrough. If we handled it and found a break
1039 /// statement, then return CSFC_Success.
1041 /// If Case is non-null, then we are looking for the specified case, checking
1042 /// that nothing we jump over contains labels. If Case is null, then we found
1043 /// the case and are looking for the break.
1045 /// If the recursive walk actually finds our Case, then we set FoundCase to
1048 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1049 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1050 const SwitchCase *Case,
1052 SmallVectorImpl<const Stmt*> &ResultStmts) {
1053 // If this is a null statement, just succeed.
1055 return Case ? CSFC_Success : CSFC_FallThrough;
1057 // If this is the switchcase (case 4: or default) that we're looking for, then
1058 // we're in business. Just add the substatement.
1059 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1062 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
1066 // Otherwise, this is some other case or default statement, just ignore it.
1067 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1071 // If we are in the live part of the code and we found our break statement,
1072 // return a success!
1073 if (Case == 0 && isa<BreakStmt>(S))
1074 return CSFC_Success;
1076 // If this is a switch statement, then it might contain the SwitchCase, the
1077 // break, or neither.
1078 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1079 // Handle this as two cases: we might be looking for the SwitchCase (if so
1080 // the skipped statements must be skippable) or we might already have it.
1081 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1083 // Keep track of whether we see a skipped declaration. The code could be
1084 // using the declaration even if it is skipped, so we can't optimize out
1085 // the decl if the kept statements might refer to it.
1086 bool HadSkippedDecl = false;
1088 // If we're looking for the case, just see if we can skip each of the
1090 for (; Case && I != E; ++I) {
1091 HadSkippedDecl |= isa<DeclStmt>(*I);
1093 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1094 case CSFC_Failure: return CSFC_Failure;
1096 // A successful result means that either 1) that the statement doesn't
1097 // have the case and is skippable, or 2) does contain the case value
1098 // and also contains the break to exit the switch. In the later case,
1099 // we just verify the rest of the statements are elidable.
1101 // If we found the case and skipped declarations, we can't do the
1104 return CSFC_Failure;
1106 for (++I; I != E; ++I)
1107 if (CodeGenFunction::ContainsLabel(*I, true))
1108 return CSFC_Failure;
1109 return CSFC_Success;
1112 case CSFC_FallThrough:
1113 // If we have a fallthrough condition, then we must have found the
1114 // case started to include statements. Consider the rest of the
1115 // statements in the compound statement as candidates for inclusion.
1116 assert(FoundCase && "Didn't find case but returned fallthrough?");
1117 // We recursively found Case, so we're not looking for it anymore.
1120 // If we found the case and skipped declarations, we can't do the
1123 return CSFC_Failure;
1129 // If we have statements in our range, then we know that the statements are
1130 // live and need to be added to the set of statements we're tracking.
1131 for (; I != E; ++I) {
1132 switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1133 case CSFC_Failure: return CSFC_Failure;
1134 case CSFC_FallThrough:
1135 // A fallthrough result means that the statement was simple and just
1136 // included in ResultStmt, keep adding them afterwards.
1139 // A successful result means that we found the break statement and
1140 // stopped statement inclusion. We just ensure that any leftover stmts
1141 // are skippable and return success ourselves.
1142 for (++I; I != E; ++I)
1143 if (CodeGenFunction::ContainsLabel(*I, true))
1144 return CSFC_Failure;
1145 return CSFC_Success;
1149 return Case ? CSFC_Success : CSFC_FallThrough;
1152 // Okay, this is some other statement that we don't handle explicitly, like a
1153 // for statement or increment etc. If we are skipping over this statement,
1154 // just verify it doesn't have labels, which would make it invalid to elide.
1156 if (CodeGenFunction::ContainsLabel(S, true))
1157 return CSFC_Failure;
1158 return CSFC_Success;
1161 // Otherwise, we want to include this statement. Everything is cool with that
1162 // so long as it doesn't contain a break out of the switch we're in.
1163 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1165 // Otherwise, everything is great. Include the statement and tell the caller
1166 // that we fall through and include the next statement as well.
1167 ResultStmts.push_back(S);
1168 return CSFC_FallThrough;
1171 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1172 /// then invoke CollectStatementsForCase to find the list of statements to emit
1173 /// for a switch on constant. See the comment above CollectStatementsForCase
1174 /// for more details.
1175 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1176 const llvm::APSInt &ConstantCondValue,
1177 SmallVectorImpl<const Stmt*> &ResultStmts,
1179 // First step, find the switch case that is being branched to. We can do this
1180 // efficiently by scanning the SwitchCase list.
1181 const SwitchCase *Case = S.getSwitchCaseList();
1182 const DefaultStmt *DefaultCase = 0;
1184 for (; Case; Case = Case->getNextSwitchCase()) {
1185 // It's either a default or case. Just remember the default statement in
1186 // case we're not jumping to any numbered cases.
1187 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1192 // Check to see if this case is the one we're looking for.
1193 const CaseStmt *CS = cast<CaseStmt>(Case);
1194 // Don't handle case ranges yet.
1195 if (CS->getRHS()) return false;
1197 // If we found our case, remember it as 'case'.
1198 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1202 // If we didn't find a matching case, we use a default if it exists, or we
1203 // elide the whole switch body!
1205 // It is safe to elide the body of the switch if it doesn't contain labels
1206 // etc. If it is safe, return successfully with an empty ResultStmts list.
1207 if (DefaultCase == 0)
1208 return !CodeGenFunction::ContainsLabel(&S);
1212 // Ok, we know which case is being jumped to, try to collect all the
1213 // statements that follow it. This can fail for a variety of reasons. Also,
1214 // check to see that the recursive walk actually found our case statement.
1215 // Insane cases like this can fail to find it in the recursive walk since we
1216 // don't handle every stmt kind:
1220 bool FoundCase = false;
1221 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1222 ResultStmts) != CSFC_Failure &&
1226 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1227 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1229 RunCleanupsScope ConditionScope(*this);
1231 if (S.getConditionVariable())
1232 EmitAutoVarDecl(*S.getConditionVariable());
1234 // Handle nested switch statements.
1235 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1236 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1238 // See if we can constant fold the condition of the switch and therefore only
1239 // emit the live case statement (if any) of the switch.
1240 llvm::APSInt ConstantCondValue;
1241 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1242 SmallVector<const Stmt*, 4> CaseStmts;
1243 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1245 RunCleanupsScope ExecutedScope(*this);
1247 // At this point, we are no longer "within" a switch instance, so
1248 // we can temporarily enforce this to ensure that any embedded case
1249 // statements are not emitted.
1252 // Okay, we can dead code eliminate everything except this case. Emit the
1253 // specified series of statements and we're good.
1254 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1255 EmitStmt(CaseStmts[i]);
1257 // Now we want to restore the saved switch instance so that nested
1258 // switches continue to function properly
1259 SwitchInsn = SavedSwitchInsn;
1265 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1267 // Create basic block to hold stuff that comes after switch
1268 // statement. We also need to create a default block now so that
1269 // explicit case ranges tests can have a place to jump to on
1271 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1272 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1273 CaseRangeBlock = DefaultBlock;
1275 // Clear the insertion point to indicate we are in unreachable code.
1276 Builder.ClearInsertionPoint();
1278 // All break statements jump to NextBlock. If BreakContinueStack is non empty
1279 // then reuse last ContinueBlock.
1280 JumpDest OuterContinue;
1281 if (!BreakContinueStack.empty())
1282 OuterContinue = BreakContinueStack.back().ContinueBlock;
1284 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1286 // Emit switch body.
1287 EmitStmt(S.getBody());
1289 BreakContinueStack.pop_back();
1291 // Update the default block in case explicit case range tests have
1292 // been chained on top.
1293 SwitchInsn->setDefaultDest(CaseRangeBlock);
1295 // If a default was never emitted:
1296 if (!DefaultBlock->getParent()) {
1297 // If we have cleanups, emit the default block so that there's a
1298 // place to jump through the cleanups from.
1299 if (ConditionScope.requiresCleanups()) {
1300 EmitBlock(DefaultBlock);
1302 // Otherwise, just forward the default block to the switch end.
1304 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1305 delete DefaultBlock;
1309 ConditionScope.ForceCleanup();
1311 // Emit continuation.
1312 EmitBlock(SwitchExit.getBlock(), true);
1314 SwitchInsn = SavedSwitchInsn;
1315 CaseRangeBlock = SavedCRBlock;
1319 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1320 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
1323 while (*Constraint) {
1324 switch (*Constraint) {
1326 Result += Target.convertConstraint(Constraint);
1332 case '=': // Will see this and the following in mult-alt constraints.
1335 case '#': // Ignore the rest of the constraint alternative.
1336 while (Constraint[1] && Constraint[1] != ',')
1347 "Must pass output names to constraints with a symbolic name");
1349 bool result = Target.resolveSymbolicName(Constraint,
1351 OutCons->size(), Index);
1352 assert(result && "Could not resolve symbolic name"); (void)result;
1353 Result += llvm::utostr(Index);
1364 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1365 /// as using a particular register add that as a constraint that will be used
1366 /// in this asm stmt.
1368 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1369 const TargetInfo &Target, CodeGenModule &CGM,
1370 const AsmStmt &Stmt) {
1371 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1374 const ValueDecl &Value = *AsmDeclRef->getDecl();
1375 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1378 if (Variable->getStorageClass() != SC_Register)
1380 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1383 StringRef Register = Attr->getLabel();
1384 assert(Target.isValidGCCRegisterName(Register));
1385 // We're using validateOutputConstraint here because we only care if
1386 // this is a register constraint.
1387 TargetInfo::ConstraintInfo Info(Constraint, "");
1388 if (Target.validateOutputConstraint(Info) &&
1389 !Info.allowsRegister()) {
1390 CGM.ErrorUnsupported(&Stmt, "__asm__");
1393 // Canonicalize the register here before returning it.
1394 Register = Target.getNormalizedGCCRegisterName(Register);
1395 return "{" + Register.str() + "}";
1399 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1400 LValue InputValue, QualType InputType,
1401 std::string &ConstraintStr) {
1403 if (Info.allowsRegister() || !Info.allowsMemory()) {
1404 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1405 Arg = EmitLoadOfLValue(InputValue).getScalarVal();
1407 llvm::Type *Ty = ConvertType(InputType);
1408 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1409 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1410 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1411 Ty = llvm::PointerType::getUnqual(Ty);
1413 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1416 Arg = InputValue.getAddress();
1417 ConstraintStr += '*';
1421 Arg = InputValue.getAddress();
1422 ConstraintStr += '*';
1428 llvm::Value* CodeGenFunction::EmitAsmInput(
1429 const TargetInfo::ConstraintInfo &Info,
1430 const Expr *InputExpr,
1431 std::string &ConstraintStr) {
1432 if (Info.allowsRegister() || !Info.allowsMemory())
1433 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1434 return EmitScalarExpr(InputExpr);
1436 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1437 LValue Dest = EmitLValue(InputExpr);
1438 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr);
1441 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1442 /// asm call instruction. The !srcloc MDNode contains a list of constant
1443 /// integers which are the source locations of the start of each line in the
1445 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1446 CodeGenFunction &CGF) {
1447 SmallVector<llvm::Value *, 8> Locs;
1448 // Add the location of the first line to the MDNode.
1449 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1450 Str->getLocStart().getRawEncoding()));
1451 StringRef StrVal = Str->getString();
1452 if (!StrVal.empty()) {
1453 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1454 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1456 // Add the location of the start of each subsequent line of the asm to the
1458 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1459 if (StrVal[i] != '\n') continue;
1460 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1462 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1463 LineLoc.getRawEncoding()));
1467 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1470 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1471 // Assemble the final asm string.
1472 std::string AsmString = S.generateAsmString(getContext());
1474 // Get all the output and input constraints together.
1475 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1476 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1478 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1480 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1481 Name = GAS->getOutputName(i);
1482 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1483 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1484 assert(IsValid && "Failed to parse output constraint");
1485 OutputConstraintInfos.push_back(Info);
1488 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1490 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1491 Name = GAS->getInputName(i);
1492 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1494 getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1495 S.getNumOutputs(), Info);
1496 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1497 InputConstraintInfos.push_back(Info);
1500 std::string Constraints;
1502 std::vector<LValue> ResultRegDests;
1503 std::vector<QualType> ResultRegQualTys;
1504 std::vector<llvm::Type *> ResultRegTypes;
1505 std::vector<llvm::Type *> ResultTruncRegTypes;
1506 std::vector<llvm::Type *> ArgTypes;
1507 std::vector<llvm::Value*> Args;
1509 // Keep track of inout constraints.
1510 std::string InOutConstraints;
1511 std::vector<llvm::Value*> InOutArgs;
1512 std::vector<llvm::Type*> InOutArgTypes;
1514 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1515 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1517 // Simplify the output constraint.
1518 std::string OutputConstraint(S.getOutputConstraint(i));
1519 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1522 const Expr *OutExpr = S.getOutputExpr(i);
1523 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1525 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1526 getTarget(), CGM, S);
1528 LValue Dest = EmitLValue(OutExpr);
1529 if (!Constraints.empty())
1532 // If this is a register output, then make the inline asm return it
1533 // by-value. If this is a memory result, return the value by-reference.
1534 if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1535 Constraints += "=" + OutputConstraint;
1536 ResultRegQualTys.push_back(OutExpr->getType());
1537 ResultRegDests.push_back(Dest);
1538 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1539 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1541 // If this output is tied to an input, and if the input is larger, then
1542 // we need to set the actual result type of the inline asm node to be the
1543 // same as the input type.
1544 if (Info.hasMatchingInput()) {
1546 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1547 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1548 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1551 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1553 QualType InputTy = S.getInputExpr(InputNo)->getType();
1554 QualType OutputType = OutExpr->getType();
1556 uint64_t InputSize = getContext().getTypeSize(InputTy);
1557 if (getContext().getTypeSize(OutputType) < InputSize) {
1558 // Form the asm to return the value as a larger integer or fp type.
1559 ResultRegTypes.back() = ConvertType(InputTy);
1562 if (llvm::Type* AdjTy =
1563 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1564 ResultRegTypes.back()))
1565 ResultRegTypes.back() = AdjTy;
1567 ArgTypes.push_back(Dest.getAddress()->getType());
1568 Args.push_back(Dest.getAddress());
1569 Constraints += "=*";
1570 Constraints += OutputConstraint;
1573 if (Info.isReadWrite()) {
1574 InOutConstraints += ',';
1576 const Expr *InputExpr = S.getOutputExpr(i);
1577 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1580 if (llvm::Type* AdjTy =
1581 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1583 Arg = Builder.CreateBitCast(Arg, AdjTy);
1585 if (Info.allowsRegister())
1586 InOutConstraints += llvm::utostr(i);
1588 InOutConstraints += OutputConstraint;
1590 InOutArgTypes.push_back(Arg->getType());
1591 InOutArgs.push_back(Arg);
1595 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1597 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1598 const Expr *InputExpr = S.getInputExpr(i);
1600 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1602 if (!Constraints.empty())
1605 // Simplify the input constraint.
1606 std::string InputConstraint(S.getInputConstraint(i));
1607 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1608 &OutputConstraintInfos);
1611 AddVariableConstraints(InputConstraint,
1612 *InputExpr->IgnoreParenNoopCasts(getContext()),
1613 getTarget(), CGM, S);
1615 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1617 // If this input argument is tied to a larger output result, extend the
1618 // input to be the same size as the output. The LLVM backend wants to see
1619 // the input and output of a matching constraint be the same size. Note
1620 // that GCC does not define what the top bits are here. We use zext because
1621 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1622 if (Info.hasTiedOperand()) {
1623 unsigned Output = Info.getTiedOperand();
1624 QualType OutputType = S.getOutputExpr(Output)->getType();
1625 QualType InputTy = InputExpr->getType();
1627 if (getContext().getTypeSize(OutputType) >
1628 getContext().getTypeSize(InputTy)) {
1629 // Use ptrtoint as appropriate so that we can do our extension.
1630 if (isa<llvm::PointerType>(Arg->getType()))
1631 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1632 llvm::Type *OutputTy = ConvertType(OutputType);
1633 if (isa<llvm::IntegerType>(OutputTy))
1634 Arg = Builder.CreateZExt(Arg, OutputTy);
1635 else if (isa<llvm::PointerType>(OutputTy))
1636 Arg = Builder.CreateZExt(Arg, IntPtrTy);
1638 assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1639 Arg = Builder.CreateFPExt(Arg, OutputTy);
1643 if (llvm::Type* AdjTy =
1644 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1646 Arg = Builder.CreateBitCast(Arg, AdjTy);
1648 ArgTypes.push_back(Arg->getType());
1649 Args.push_back(Arg);
1650 Constraints += InputConstraint;
1653 // Append the "input" part of inout constraints last.
1654 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1655 ArgTypes.push_back(InOutArgTypes[i]);
1656 Args.push_back(InOutArgs[i]);
1658 Constraints += InOutConstraints;
1661 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1662 StringRef Clobber = S.getClobber(i);
1664 if (Clobber != "memory" && Clobber != "cc")
1665 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
1667 if (i != 0 || NumConstraints != 0)
1670 Constraints += "~{";
1671 Constraints += Clobber;
1675 // Add machine specific clobbers
1676 std::string MachineClobbers = getTarget().getClobbers();
1677 if (!MachineClobbers.empty()) {
1678 if (!Constraints.empty())
1680 Constraints += MachineClobbers;
1683 llvm::Type *ResultType;
1684 if (ResultRegTypes.empty())
1685 ResultType = VoidTy;
1686 else if (ResultRegTypes.size() == 1)
1687 ResultType = ResultRegTypes[0];
1689 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1691 llvm::FunctionType *FTy =
1692 llvm::FunctionType::get(ResultType, ArgTypes, false);
1694 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
1695 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
1696 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
1697 llvm::InlineAsm *IA =
1698 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
1699 /* IsAlignStack */ false, AsmDialect);
1700 llvm::CallInst *Result = Builder.CreateCall(IA, Args);
1701 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
1702 llvm::Attribute::NoUnwind);
1704 // Slap the source location of the inline asm into a !srcloc metadata on the
1705 // call. FIXME: Handle metadata for MS-style inline asms.
1706 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
1707 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
1710 // Extract all of the register value results from the asm.
1711 std::vector<llvm::Value*> RegResults;
1712 if (ResultRegTypes.size() == 1) {
1713 RegResults.push_back(Result);
1715 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1716 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1717 RegResults.push_back(Tmp);
1721 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1722 llvm::Value *Tmp = RegResults[i];
1724 // If the result type of the LLVM IR asm doesn't match the result type of
1725 // the expression, do the conversion.
1726 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1727 llvm::Type *TruncTy = ResultTruncRegTypes[i];
1729 // Truncate the integer result to the right size, note that TruncTy can be
1731 if (TruncTy->isFloatingPointTy())
1732 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1733 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1734 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
1735 Tmp = Builder.CreateTrunc(Tmp,
1736 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
1737 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1738 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1739 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
1740 Tmp = Builder.CreatePtrToInt(Tmp,
1741 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
1742 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1743 } else if (TruncTy->isIntegerTy()) {
1744 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1745 } else if (TruncTy->isVectorTy()) {
1746 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1750 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
1754 void CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S) {
1755 llvm_unreachable("not implemented yet");