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 "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "CodeGenFunction.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/InlineAsm.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Target/TargetData.h"
25 using namespace clang;
26 using namespace CodeGen;
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
33 if (CGDebugInfo *DI = getDebugInfo()) {
35 DI->setLocation(S->getLocEnd());
37 DI->setLocation(S->getLocStart());
38 DI->UpdateLineDirectiveRegion(Builder);
39 DI->EmitStopPoint(Builder);
43 void CodeGenFunction::EmitStmt(const Stmt *S) {
44 assert(S && "Null statement?");
46 // Check if we can handle this without bothering to generate an
47 // insert point or debug info.
48 if (EmitSimpleStmt(S))
51 // Check if we are generating unreachable code.
52 if (!HaveInsertPoint()) {
53 // If so, and the statement doesn't contain a label, then we do not need to
54 // generate actual code. This is safe because (1) the current point is
55 // unreachable, so we don't need to execute the code, and (2) we've already
56 // handled the statements which update internal data structures (like the
57 // local variable map) which could be used by subsequent statements.
58 if (!ContainsLabel(S)) {
59 // Verify that any decl statements were handled as simple, they may be in
60 // scope of subsequent reachable statements.
61 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
65 // Otherwise, make a new block to hold the code.
69 // Generate a stoppoint if we are emitting debug info.
72 switch (S->getStmtClass()) {
73 case Stmt::NoStmtClass:
74 case Stmt::CXXCatchStmtClass:
75 case Stmt::SEHExceptStmtClass:
76 case Stmt::SEHFinallyStmtClass:
77 llvm_unreachable("invalid statement class to emit generically");
78 case Stmt::NullStmtClass:
79 case Stmt::CompoundStmtClass:
80 case Stmt::DeclStmtClass:
81 case Stmt::LabelStmtClass:
82 case Stmt::GotoStmtClass:
83 case Stmt::BreakStmtClass:
84 case Stmt::ContinueStmtClass:
85 case Stmt::DefaultStmtClass:
86 case Stmt::CaseStmtClass:
87 llvm_unreachable("should have emitted these statements as simple");
89 #define STMT(Type, Base)
90 #define ABSTRACT_STMT(Op)
91 #define EXPR(Type, Base) \
92 case Stmt::Type##Class:
93 #include "clang/AST/StmtNodes.inc"
95 // Remember the block we came in on.
96 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
97 assert(incoming && "expression emission must have an insertion point");
99 EmitIgnoredExpr(cast<Expr>(S));
101 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
102 assert(outgoing && "expression emission cleared block!");
104 // The expression emitters assume (reasonably!) that the insertion
105 // point is always set. To maintain that, the call-emission code
106 // for noreturn functions has to enter a new block with no
107 // predecessors. We want to kill that block and mark the current
108 // insertion point unreachable in the common case of a call like
109 // "exit();". Since expression emission doesn't otherwise create
110 // blocks with no predecessors, we can just test for that.
111 // However, we must be careful not to do this to our incoming
112 // block, because *statement* emission does sometimes create
113 // reachable blocks which will have no predecessors until later in
114 // the function. This occurs with, e.g., labels that are not
115 // reachable by fallthrough.
116 if (incoming != outgoing && outgoing->use_empty()) {
117 outgoing->eraseFromParent();
118 Builder.ClearInsertionPoint();
123 case Stmt::IndirectGotoStmtClass:
124 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
126 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
127 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
128 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
129 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
131 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
133 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
134 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
136 case Stmt::ObjCAtTryStmtClass:
137 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
139 case Stmt::ObjCAtCatchStmtClass:
140 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
142 case Stmt::ObjCAtFinallyStmtClass:
143 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
145 case Stmt::ObjCAtThrowStmtClass:
146 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
148 case Stmt::ObjCAtSynchronizedStmtClass:
149 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
151 case Stmt::ObjCForCollectionStmtClass:
152 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
154 case Stmt::ObjCAutoreleasePoolStmtClass:
155 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
158 case Stmt::CXXTryStmtClass:
159 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
161 case Stmt::CXXForRangeStmtClass:
162 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
163 case Stmt::SEHTryStmtClass:
164 // FIXME Not yet implemented
169 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
170 switch (S->getStmtClass()) {
171 default: return false;
172 case Stmt::NullStmtClass: break;
173 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
174 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
175 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
176 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
177 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
178 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
179 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
180 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
186 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
187 /// this captures the expression result of the last sub-statement and returns it
188 /// (for use by the statement expression extension).
189 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
190 AggValueSlot AggSlot) {
191 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
192 "LLVM IR generation of compound statement ('{}')");
194 CGDebugInfo *DI = getDebugInfo();
196 DI->setLocation(S.getLBracLoc());
197 DI->EmitRegionStart(Builder);
200 // Keep track of the current cleanup stack depth.
201 RunCleanupsScope Scope(*this);
203 for (CompoundStmt::const_body_iterator I = S.body_begin(),
204 E = S.body_end()-GetLast; I != E; ++I)
208 DI->setLocation(S.getRBracLoc());
209 DI->EmitRegionEnd(Builder);
216 // We have to special case labels here. They are statements, but when put
217 // at the end of a statement expression, they yield the value of their
218 // subexpression. Handle this by walking through all labels we encounter,
219 // emitting them before we evaluate the subexpr.
220 const Stmt *LastStmt = S.body_back();
221 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
222 EmitLabel(LS->getDecl());
223 LastStmt = LS->getSubStmt();
228 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
234 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
235 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
237 // If there is a cleanup stack, then we it isn't worth trying to
238 // simplify this block (we would need to remove it from the scope map
239 // and cleanup entry).
240 if (!EHStack.empty())
243 // Can only simplify direct branches.
244 if (!BI || !BI->isUnconditional())
247 BB->replaceAllUsesWith(BI->getSuccessor(0));
248 BI->eraseFromParent();
249 BB->eraseFromParent();
252 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
253 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
255 // Fall out of the current block (if necessary).
258 if (IsFinished && BB->use_empty()) {
263 // Place the block after the current block, if possible, or else at
264 // the end of the function.
265 if (CurBB && CurBB->getParent())
266 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
268 CurFn->getBasicBlockList().push_back(BB);
269 Builder.SetInsertPoint(BB);
272 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
273 // Emit a branch from the current block to the target one if this
274 // was a real block. If this was just a fall-through block after a
275 // terminator, don't emit it.
276 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
278 if (!CurBB || CurBB->getTerminator()) {
279 // If there is no insert point or the previous block is already
280 // terminated, don't touch it.
282 // Otherwise, create a fall-through branch.
283 Builder.CreateBr(Target);
286 Builder.ClearInsertionPoint();
289 CodeGenFunction::JumpDest
290 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
291 JumpDest &Dest = LabelMap[D];
292 if (Dest.isValid()) return Dest;
294 // Create, but don't insert, the new block.
295 Dest = JumpDest(createBasicBlock(D->getName()),
296 EHScopeStack::stable_iterator::invalid(),
297 NextCleanupDestIndex++);
301 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
302 JumpDest &Dest = LabelMap[D];
304 // If we didn't need a forward reference to this label, just go
305 // ahead and create a destination at the current scope.
306 if (!Dest.isValid()) {
307 Dest = getJumpDestInCurrentScope(D->getName());
309 // Otherwise, we need to give this label a target depth and remove
310 // it from the branch-fixups list.
312 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
313 Dest = JumpDest(Dest.getBlock(),
314 EHStack.stable_begin(),
315 Dest.getDestIndex());
317 ResolveBranchFixups(Dest.getBlock());
320 EmitBlock(Dest.getBlock());
324 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
325 EmitLabel(S.getDecl());
326 EmitStmt(S.getSubStmt());
329 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
330 // If this code is reachable then emit a stop point (if generating
331 // debug info). We have to do this ourselves because we are on the
332 // "simple" statement path.
333 if (HaveInsertPoint())
336 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
340 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
341 if (const LabelDecl *Target = S.getConstantTarget()) {
342 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
346 // Ensure that we have an i8* for our PHI node.
347 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
349 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
352 // Get the basic block for the indirect goto.
353 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
355 // The first instruction in the block has to be the PHI for the switch dest,
356 // add an entry for this branch.
357 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
359 EmitBranch(IndGotoBB);
362 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
363 // C99 6.8.4.1: The first substatement is executed if the expression compares
364 // unequal to 0. The condition must be a scalar type.
365 RunCleanupsScope ConditionScope(*this);
367 if (S.getConditionVariable())
368 EmitAutoVarDecl(*S.getConditionVariable());
370 // If the condition constant folds and can be elided, try to avoid emitting
371 // the condition and the dead arm of the if/else.
373 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
374 // Figure out which block (then or else) is executed.
375 const Stmt *Executed = S.getThen();
376 const Stmt *Skipped = S.getElse();
377 if (!CondConstant) // Condition false?
378 std::swap(Executed, Skipped);
380 // If the skipped block has no labels in it, just emit the executed block.
381 // This avoids emitting dead code and simplifies the CFG substantially.
382 if (!ContainsLabel(Skipped)) {
384 RunCleanupsScope ExecutedScope(*this);
391 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
392 // the conditional branch.
393 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
394 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
395 llvm::BasicBlock *ElseBlock = ContBlock;
397 ElseBlock = createBasicBlock("if.else");
398 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
400 // Emit the 'then' code.
401 EmitBlock(ThenBlock);
403 RunCleanupsScope ThenScope(*this);
404 EmitStmt(S.getThen());
406 EmitBranch(ContBlock);
408 // Emit the 'else' code if present.
409 if (const Stmt *Else = S.getElse()) {
410 // There is no need to emit line number for unconditional branch.
412 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
413 EmitBlock(ElseBlock);
415 RunCleanupsScope ElseScope(*this);
418 // There is no need to emit line number for unconditional branch.
420 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
421 EmitBranch(ContBlock);
424 // Emit the continuation block for code after the if.
425 EmitBlock(ContBlock, true);
428 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
429 // Emit the header for the loop, which will also become
430 // the continue target.
431 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
432 EmitBlock(LoopHeader.getBlock());
434 // Create an exit block for when the condition fails, which will
435 // also become the break target.
436 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
438 // Store the blocks to use for break and continue.
439 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
441 // C++ [stmt.while]p2:
442 // When the condition of a while statement is a declaration, the
443 // scope of the variable that is declared extends from its point
444 // of declaration (3.3.2) to the end of the while statement.
446 // The object created in a condition is destroyed and created
447 // with each iteration of the loop.
448 RunCleanupsScope ConditionScope(*this);
450 if (S.getConditionVariable())
451 EmitAutoVarDecl(*S.getConditionVariable());
453 // Evaluate the conditional in the while header. C99 6.8.5.1: The
454 // evaluation of the controlling expression takes place before each
455 // execution of the loop body.
456 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
458 // while(1) is common, avoid extra exit blocks. Be sure
459 // to correctly handle break/continue though.
460 bool EmitBoolCondBranch = true;
461 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
463 EmitBoolCondBranch = false;
465 // As long as the condition is true, go to the loop body.
466 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
467 if (EmitBoolCondBranch) {
468 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
469 if (ConditionScope.requiresCleanups())
470 ExitBlock = createBasicBlock("while.exit");
472 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
474 if (ExitBlock != LoopExit.getBlock()) {
475 EmitBlock(ExitBlock);
476 EmitBranchThroughCleanup(LoopExit);
480 // Emit the loop body. We have to emit this in a cleanup scope
481 // because it might be a singleton DeclStmt.
483 RunCleanupsScope BodyScope(*this);
485 EmitStmt(S.getBody());
488 BreakContinueStack.pop_back();
490 // Immediately force cleanup.
491 ConditionScope.ForceCleanup();
493 // Branch to the loop header again.
494 EmitBranch(LoopHeader.getBlock());
496 // Emit the exit block.
497 EmitBlock(LoopExit.getBlock(), true);
499 // The LoopHeader typically is just a branch if we skipped emitting
500 // a branch, try to erase it.
501 if (!EmitBoolCondBranch)
502 SimplifyForwardingBlocks(LoopHeader.getBlock());
505 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
506 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
507 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
509 // Store the blocks to use for break and continue.
510 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
512 // Emit the body of the loop.
513 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
516 RunCleanupsScope BodyScope(*this);
517 EmitStmt(S.getBody());
520 BreakContinueStack.pop_back();
522 EmitBlock(LoopCond.getBlock());
524 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
525 // after each execution of the loop body."
527 // Evaluate the conditional in the while header.
528 // C99 6.8.5p2/p4: The first substatement is executed if the expression
529 // compares unequal to 0. The condition must be a scalar type.
530 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
532 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
533 // to correctly handle break/continue though.
534 bool EmitBoolCondBranch = true;
535 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
537 EmitBoolCondBranch = false;
539 // As long as the condition is true, iterate the loop.
540 if (EmitBoolCondBranch)
541 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
543 // Emit the exit block.
544 EmitBlock(LoopExit.getBlock());
546 // The DoCond block typically is just a branch if we skipped
547 // emitting a branch, try to erase it.
548 if (!EmitBoolCondBranch)
549 SimplifyForwardingBlocks(LoopCond.getBlock());
552 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
553 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
555 RunCleanupsScope ForScope(*this);
557 CGDebugInfo *DI = getDebugInfo();
559 DI->setLocation(S.getSourceRange().getBegin());
560 DI->EmitRegionStart(Builder);
563 // Evaluate the first part before the loop.
565 EmitStmt(S.getInit());
567 // Start the loop with a block that tests the condition.
568 // If there's an increment, the continue scope will be overwritten
570 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
571 llvm::BasicBlock *CondBlock = Continue.getBlock();
572 EmitBlock(CondBlock);
574 // Create a cleanup scope for the condition variable cleanups.
575 RunCleanupsScope ConditionScope(*this);
577 llvm::Value *BoolCondVal = 0;
579 // If the for statement has a condition scope, emit the local variable
581 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
582 if (S.getConditionVariable()) {
583 EmitAutoVarDecl(*S.getConditionVariable());
586 // If there are any cleanups between here and the loop-exit scope,
587 // create a block to stage a loop exit along.
588 if (ForScope.requiresCleanups())
589 ExitBlock = createBasicBlock("for.cond.cleanup");
591 // As long as the condition is true, iterate the loop.
592 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
594 // C99 6.8.5p2/p4: The first substatement is executed if the expression
595 // compares unequal to 0. The condition must be a scalar type.
596 BoolCondVal = EvaluateExprAsBool(S.getCond());
597 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
599 if (ExitBlock != LoopExit.getBlock()) {
600 EmitBlock(ExitBlock);
601 EmitBranchThroughCleanup(LoopExit);
606 // Treat it as a non-zero constant. Don't even create a new block for the
607 // body, just fall into it.
610 // If the for loop doesn't have an increment we can just use the
611 // condition as the continue block. Otherwise we'll need to create
612 // a block for it (in the current scope, i.e. in the scope of the
613 // condition), and that we will become our continue block.
615 Continue = getJumpDestInCurrentScope("for.inc");
617 // Store the blocks to use for break and continue.
618 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
621 // Create a separate cleanup scope for the body, in case it is not
622 // a compound statement.
623 RunCleanupsScope BodyScope(*this);
624 EmitStmt(S.getBody());
627 // If there is an increment, emit it next.
629 EmitBlock(Continue.getBlock());
630 EmitStmt(S.getInc());
633 BreakContinueStack.pop_back();
635 ConditionScope.ForceCleanup();
636 EmitBranch(CondBlock);
638 ForScope.ForceCleanup();
641 DI->setLocation(S.getSourceRange().getEnd());
642 DI->EmitRegionEnd(Builder);
645 // Emit the fall-through block.
646 EmitBlock(LoopExit.getBlock(), true);
649 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
650 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
652 RunCleanupsScope ForScope(*this);
654 CGDebugInfo *DI = getDebugInfo();
656 DI->setLocation(S.getSourceRange().getBegin());
657 DI->EmitRegionStart(Builder);
660 // Evaluate the first pieces before the loop.
661 EmitStmt(S.getRangeStmt());
662 EmitStmt(S.getBeginEndStmt());
664 // Start the loop with a block that tests the condition.
665 // If there's an increment, the continue scope will be overwritten
667 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
668 EmitBlock(CondBlock);
670 // If there are any cleanups between here and the loop-exit scope,
671 // create a block to stage a loop exit along.
672 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
673 if (ForScope.requiresCleanups())
674 ExitBlock = createBasicBlock("for.cond.cleanup");
676 // The loop body, consisting of the specified body and the loop variable.
677 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
679 // The body is executed if the expression, contextually converted
681 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
682 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
684 if (ExitBlock != LoopExit.getBlock()) {
685 EmitBlock(ExitBlock);
686 EmitBranchThroughCleanup(LoopExit);
691 // Create a block for the increment. In case of a 'continue', we jump there.
692 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
694 // Store the blocks to use for break and continue.
695 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
698 // Create a separate cleanup scope for the loop variable and body.
699 RunCleanupsScope BodyScope(*this);
700 EmitStmt(S.getLoopVarStmt());
701 EmitStmt(S.getBody());
704 // If there is an increment, emit it next.
705 EmitBlock(Continue.getBlock());
706 EmitStmt(S.getInc());
708 BreakContinueStack.pop_back();
710 EmitBranch(CondBlock);
712 ForScope.ForceCleanup();
715 DI->setLocation(S.getSourceRange().getEnd());
716 DI->EmitRegionEnd(Builder);
719 // Emit the fall-through block.
720 EmitBlock(LoopExit.getBlock(), true);
723 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
725 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
726 } else if (RV.isAggregate()) {
727 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
729 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
731 EmitBranchThroughCleanup(ReturnBlock);
734 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
735 /// if the function returns void, or may be missing one if the function returns
736 /// non-void. Fun stuff :).
737 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
738 // Emit the result value, even if unused, to evalute the side effects.
739 const Expr *RV = S.getRetValue();
741 // FIXME: Clean this up by using an LValue for ReturnTemp,
742 // EmitStoreThroughLValue, and EmitAnyExpr.
743 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
744 !Target.useGlobalsForAutomaticVariables()) {
745 // Apply the named return value optimization for this return statement,
746 // which means doing nothing: the appropriate result has already been
747 // constructed into the NRVO variable.
749 // If there is an NRVO flag for this variable, set it to 1 into indicate
750 // that the cleanup code should not destroy the variable.
751 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
752 Builder.CreateStore(Builder.getTrue(), NRVOFlag);
753 } else if (!ReturnValue) {
754 // Make sure not to return anything, but evaluate the expression
758 } else if (RV == 0) {
759 // Do nothing (return value is left uninitialized)
760 } else if (FnRetTy->isReferenceType()) {
761 // If this function returns a reference, take the address of the expression
762 // rather than the value.
763 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
764 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
765 } else if (!hasAggregateLLVMType(RV->getType())) {
766 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
767 } else if (RV->getType()->isAnyComplexType()) {
768 EmitComplexExprIntoAddr(RV, ReturnValue, false);
770 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Qualifiers(), true));
773 EmitBranchThroughCleanup(ReturnBlock);
776 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
777 // As long as debug info is modeled with instructions, we have to ensure we
778 // have a place to insert here and write the stop point here.
779 if (getDebugInfo() && HaveInsertPoint())
782 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
787 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
788 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
790 // If this code is reachable then emit a stop point (if generating
791 // debug info). We have to do this ourselves because we are on the
792 // "simple" statement path.
793 if (HaveInsertPoint())
796 JumpDest Block = BreakContinueStack.back().BreakBlock;
797 EmitBranchThroughCleanup(Block);
800 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
801 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
803 // If this code is reachable then emit a stop point (if generating
804 // debug info). We have to do this ourselves because we are on the
805 // "simple" statement path.
806 if (HaveInsertPoint())
809 JumpDest Block = BreakContinueStack.back().ContinueBlock;
810 EmitBranchThroughCleanup(Block);
813 /// EmitCaseStmtRange - If case statement range is not too big then
814 /// add multiple cases to switch instruction, one for each value within
815 /// the range. If range is too big then emit "if" condition check.
816 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
817 assert(S.getRHS() && "Expected RHS value in CaseStmt");
819 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
820 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
822 // Emit the code for this case. We do this first to make sure it is
823 // properly chained from our predecessor before generating the
824 // switch machinery to enter this block.
825 EmitBlock(createBasicBlock("sw.bb"));
826 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
827 EmitStmt(S.getSubStmt());
829 // If range is empty, do nothing.
830 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
833 llvm::APInt Range = RHS - LHS;
834 // FIXME: parameters such as this should not be hardcoded.
835 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
836 // Range is small enough to add multiple switch instruction cases.
837 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
838 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
844 // The range is too big. Emit "if" condition into a new block,
845 // making sure to save and restore the current insertion point.
846 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
848 // Push this test onto the chain of range checks (which terminates
849 // in the default basic block). The switch's default will be changed
850 // to the top of this chain after switch emission is complete.
851 llvm::BasicBlock *FalseDest = CaseRangeBlock;
852 CaseRangeBlock = createBasicBlock("sw.caserange");
854 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
855 Builder.SetInsertPoint(CaseRangeBlock);
859 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS), "tmp");
861 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
862 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
864 // Restore the appropriate insertion point.
866 Builder.SetInsertPoint(RestoreBB);
868 Builder.ClearInsertionPoint();
871 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
872 // Handle case ranges.
874 EmitCaseStmtRange(S);
878 llvm::ConstantInt *CaseVal =
879 Builder.getInt(S.getLHS()->EvaluateAsInt(getContext()));
881 // If the body of the case is just a 'break', and if there was no fallthrough,
882 // try to not emit an empty block.
883 if (isa<BreakStmt>(S.getSubStmt())) {
884 JumpDest Block = BreakContinueStack.back().BreakBlock;
886 // Only do this optimization if there are no cleanups that need emitting.
887 if (isObviouslyBranchWithoutCleanups(Block)) {
888 SwitchInsn->addCase(CaseVal, Block.getBlock());
890 // If there was a fallthrough into this case, make sure to redirect it to
891 // the end of the switch as well.
892 if (Builder.GetInsertBlock()) {
893 Builder.CreateBr(Block.getBlock());
894 Builder.ClearInsertionPoint();
900 EmitBlock(createBasicBlock("sw.bb"));
901 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
902 SwitchInsn->addCase(CaseVal, CaseDest);
904 // Recursively emitting the statement is acceptable, but is not wonderful for
905 // code where we have many case statements nested together, i.e.:
909 // Handling this recursively will create a new block for each case statement
910 // that falls through to the next case which is IR intensive. It also causes
911 // deep recursion which can run into stack depth limitations. Handle
912 // sequential non-range case statements specially.
913 const CaseStmt *CurCase = &S;
914 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
916 // Otherwise, iteratively add consecutive cases to this switch stmt.
917 while (NextCase && NextCase->getRHS() == 0) {
919 llvm::ConstantInt *CaseVal =
920 Builder.getInt(CurCase->getLHS()->EvaluateAsInt(getContext()));
921 SwitchInsn->addCase(CaseVal, CaseDest);
922 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
925 // Normal default recursion for non-cases.
926 EmitStmt(CurCase->getSubStmt());
929 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
930 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
931 assert(DefaultBlock->empty() &&
932 "EmitDefaultStmt: Default block already defined?");
933 EmitBlock(DefaultBlock);
934 EmitStmt(S.getSubStmt());
937 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
938 /// constant value that is being switched on, see if we can dead code eliminate
939 /// the body of the switch to a simple series of statements to emit. Basically,
940 /// on a switch (5) we want to find these statements:
946 /// and add them to the ResultStmts vector. If it is unsafe to do this
947 /// transformation (for example, one of the elided statements contains a label
948 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
949 /// should include statements after it (e.g. the printf() line is a substmt of
950 /// the case) then return CSFC_FallThrough. If we handled it and found a break
951 /// statement, then return CSFC_Success.
953 /// If Case is non-null, then we are looking for the specified case, checking
954 /// that nothing we jump over contains labels. If Case is null, then we found
955 /// the case and are looking for the break.
957 /// If the recursive walk actually finds our Case, then we set FoundCase to
960 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
961 static CSFC_Result CollectStatementsForCase(const Stmt *S,
962 const SwitchCase *Case,
964 llvm::SmallVectorImpl<const Stmt*> &ResultStmts) {
965 // If this is a null statement, just succeed.
967 return Case ? CSFC_Success : CSFC_FallThrough;
969 // If this is the switchcase (case 4: or default) that we're looking for, then
970 // we're in business. Just add the substatement.
971 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
974 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
978 // Otherwise, this is some other case or default statement, just ignore it.
979 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
983 // If we are in the live part of the code and we found our break statement,
985 if (Case == 0 && isa<BreakStmt>(S))
988 // If this is a switch statement, then it might contain the SwitchCase, the
989 // break, or neither.
990 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
991 // Handle this as two cases: we might be looking for the SwitchCase (if so
992 // the skipped statements must be skippable) or we might already have it.
993 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
995 // Keep track of whether we see a skipped declaration. The code could be
996 // using the declaration even if it is skipped, so we can't optimize out
997 // the decl if the kept statements might refer to it.
998 bool HadSkippedDecl = false;
1000 // If we're looking for the case, just see if we can skip each of the
1002 for (; Case && I != E; ++I) {
1003 HadSkippedDecl |= isa<DeclStmt>(*I);
1005 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1006 case CSFC_Failure: return CSFC_Failure;
1008 // A successful result means that either 1) that the statement doesn't
1009 // have the case and is skippable, or 2) does contain the case value
1010 // and also contains the break to exit the switch. In the later case,
1011 // we just verify the rest of the statements are elidable.
1013 // If we found the case and skipped declarations, we can't do the
1016 return CSFC_Failure;
1018 for (++I; I != E; ++I)
1019 if (CodeGenFunction::ContainsLabel(*I, true))
1020 return CSFC_Failure;
1021 return CSFC_Success;
1024 case CSFC_FallThrough:
1025 // If we have a fallthrough condition, then we must have found the
1026 // case started to include statements. Consider the rest of the
1027 // statements in the compound statement as candidates for inclusion.
1028 assert(FoundCase && "Didn't find case but returned fallthrough?");
1029 // We recursively found Case, so we're not looking for it anymore.
1032 // If we found the case and skipped declarations, we can't do the
1035 return CSFC_Failure;
1041 // If we have statements in our range, then we know that the statements are
1042 // live and need to be added to the set of statements we're tracking.
1043 for (; I != E; ++I) {
1044 switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1045 case CSFC_Failure: return CSFC_Failure;
1046 case CSFC_FallThrough:
1047 // A fallthrough result means that the statement was simple and just
1048 // included in ResultStmt, keep adding them afterwards.
1051 // A successful result means that we found the break statement and
1052 // stopped statement inclusion. We just ensure that any leftover stmts
1053 // are skippable and return success ourselves.
1054 for (++I; I != E; ++I)
1055 if (CodeGenFunction::ContainsLabel(*I, true))
1056 return CSFC_Failure;
1057 return CSFC_Success;
1061 return Case ? CSFC_Success : CSFC_FallThrough;
1064 // Okay, this is some other statement that we don't handle explicitly, like a
1065 // for statement or increment etc. If we are skipping over this statement,
1066 // just verify it doesn't have labels, which would make it invalid to elide.
1068 if (CodeGenFunction::ContainsLabel(S, true))
1069 return CSFC_Failure;
1070 return CSFC_Success;
1073 // Otherwise, we want to include this statement. Everything is cool with that
1074 // so long as it doesn't contain a break out of the switch we're in.
1075 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1077 // Otherwise, everything is great. Include the statement and tell the caller
1078 // that we fall through and include the next statement as well.
1079 ResultStmts.push_back(S);
1080 return CSFC_FallThrough;
1083 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1084 /// then invoke CollectStatementsForCase to find the list of statements to emit
1085 /// for a switch on constant. See the comment above CollectStatementsForCase
1086 /// for more details.
1087 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1088 const llvm::APInt &ConstantCondValue,
1089 llvm::SmallVectorImpl<const Stmt*> &ResultStmts,
1091 // First step, find the switch case that is being branched to. We can do this
1092 // efficiently by scanning the SwitchCase list.
1093 const SwitchCase *Case = S.getSwitchCaseList();
1094 const DefaultStmt *DefaultCase = 0;
1096 for (; Case; Case = Case->getNextSwitchCase()) {
1097 // It's either a default or case. Just remember the default statement in
1098 // case we're not jumping to any numbered cases.
1099 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1104 // Check to see if this case is the one we're looking for.
1105 const CaseStmt *CS = cast<CaseStmt>(Case);
1106 // Don't handle case ranges yet.
1107 if (CS->getRHS()) return false;
1109 // If we found our case, remember it as 'case'.
1110 if (CS->getLHS()->EvaluateAsInt(C) == ConstantCondValue)
1114 // If we didn't find a matching case, we use a default if it exists, or we
1115 // elide the whole switch body!
1117 // It is safe to elide the body of the switch if it doesn't contain labels
1118 // etc. If it is safe, return successfully with an empty ResultStmts list.
1119 if (DefaultCase == 0)
1120 return !CodeGenFunction::ContainsLabel(&S);
1124 // Ok, we know which case is being jumped to, try to collect all the
1125 // statements that follow it. This can fail for a variety of reasons. Also,
1126 // check to see that the recursive walk actually found our case statement.
1127 // Insane cases like this can fail to find it in the recursive walk since we
1128 // don't handle every stmt kind:
1132 bool FoundCase = false;
1133 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1134 ResultStmts) != CSFC_Failure &&
1138 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1139 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1141 RunCleanupsScope ConditionScope(*this);
1143 if (S.getConditionVariable())
1144 EmitAutoVarDecl(*S.getConditionVariable());
1146 // See if we can constant fold the condition of the switch and therefore only
1147 // emit the live case statement (if any) of the switch.
1148 llvm::APInt ConstantCondValue;
1149 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1150 llvm::SmallVector<const Stmt*, 4> CaseStmts;
1151 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1153 RunCleanupsScope ExecutedScope(*this);
1155 // Okay, we can dead code eliminate everything except this case. Emit the
1156 // specified series of statements and we're good.
1157 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1158 EmitStmt(CaseStmts[i]);
1163 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1165 // Handle nested switch statements.
1166 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1167 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1169 // Create basic block to hold stuff that comes after switch
1170 // statement. We also need to create a default block now so that
1171 // explicit case ranges tests can have a place to jump to on
1173 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1174 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1175 CaseRangeBlock = DefaultBlock;
1177 // Clear the insertion point to indicate we are in unreachable code.
1178 Builder.ClearInsertionPoint();
1180 // All break statements jump to NextBlock. If BreakContinueStack is non empty
1181 // then reuse last ContinueBlock.
1182 JumpDest OuterContinue;
1183 if (!BreakContinueStack.empty())
1184 OuterContinue = BreakContinueStack.back().ContinueBlock;
1186 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1188 // Emit switch body.
1189 EmitStmt(S.getBody());
1191 BreakContinueStack.pop_back();
1193 // Update the default block in case explicit case range tests have
1194 // been chained on top.
1195 SwitchInsn->setSuccessor(0, CaseRangeBlock);
1197 // If a default was never emitted:
1198 if (!DefaultBlock->getParent()) {
1199 // If we have cleanups, emit the default block so that there's a
1200 // place to jump through the cleanups from.
1201 if (ConditionScope.requiresCleanups()) {
1202 EmitBlock(DefaultBlock);
1204 // Otherwise, just forward the default block to the switch end.
1206 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1207 delete DefaultBlock;
1211 ConditionScope.ForceCleanup();
1213 // Emit continuation.
1214 EmitBlock(SwitchExit.getBlock(), true);
1216 SwitchInsn = SavedSwitchInsn;
1217 CaseRangeBlock = SavedCRBlock;
1221 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1222 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
1225 while (*Constraint) {
1226 switch (*Constraint) {
1228 Result += Target.convertConstraint(Constraint);
1234 case '=': // Will see this and the following in mult-alt constraints.
1245 "Must pass output names to constraints with a symbolic name");
1247 bool result = Target.resolveSymbolicName(Constraint,
1249 OutCons->size(), Index);
1250 assert(result && "Could not resolve symbolic name"); (void)result;
1251 Result += llvm::utostr(Index);
1262 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1263 /// as using a particular register add that as a constraint that will be used
1264 /// in this asm stmt.
1266 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1267 const TargetInfo &Target, CodeGenModule &CGM,
1268 const AsmStmt &Stmt) {
1269 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1272 const ValueDecl &Value = *AsmDeclRef->getDecl();
1273 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1276 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1279 llvm::StringRef Register = Attr->getLabel();
1280 assert(Target.isValidGCCRegisterName(Register));
1281 // We're using validateOutputConstraint here because we only care if
1282 // this is a register constraint.
1283 TargetInfo::ConstraintInfo Info(Constraint, "");
1284 if (Target.validateOutputConstraint(Info) &&
1285 !Info.allowsRegister()) {
1286 CGM.ErrorUnsupported(&Stmt, "__asm__");
1289 // Canonicalize the register here before returning it.
1290 Register = Target.getNormalizedGCCRegisterName(Register);
1291 return "{" + Register.str() + "}";
1295 CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
1296 const TargetInfo::ConstraintInfo &Info,
1297 LValue InputValue, QualType InputType,
1298 std::string &ConstraintStr) {
1300 if (Info.allowsRegister() || !Info.allowsMemory()) {
1301 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
1302 Arg = EmitLoadOfLValue(InputValue).getScalarVal();
1304 const llvm::Type *Ty = ConvertType(InputType);
1305 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
1306 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1307 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1308 Ty = llvm::PointerType::getUnqual(Ty);
1310 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1313 Arg = InputValue.getAddress();
1314 ConstraintStr += '*';
1318 Arg = InputValue.getAddress();
1319 ConstraintStr += '*';
1325 llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
1326 const TargetInfo::ConstraintInfo &Info,
1327 const Expr *InputExpr,
1328 std::string &ConstraintStr) {
1329 if (Info.allowsRegister() || !Info.allowsMemory())
1330 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
1331 return EmitScalarExpr(InputExpr);
1333 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1334 LValue Dest = EmitLValue(InputExpr);
1335 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
1338 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1339 /// asm call instruction. The !srcloc MDNode contains a list of constant
1340 /// integers which are the source locations of the start of each line in the
1342 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1343 CodeGenFunction &CGF) {
1344 llvm::SmallVector<llvm::Value *, 8> Locs;
1345 // Add the location of the first line to the MDNode.
1346 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1347 Str->getLocStart().getRawEncoding()));
1348 llvm::StringRef StrVal = Str->getString();
1349 if (!StrVal.empty()) {
1350 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1351 const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1353 // Add the location of the start of each subsequent line of the asm to the
1355 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1356 if (StrVal[i] != '\n') continue;
1357 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1359 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1360 LineLoc.getRawEncoding()));
1364 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1367 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1368 // Analyze the asm string to decompose it into its pieces. We know that Sema
1369 // has already done this, so it is guaranteed to be successful.
1370 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
1372 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
1374 // Assemble the pieces into the final asm string.
1375 std::string AsmString;
1376 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1377 if (Pieces[i].isString())
1378 AsmString += Pieces[i].getString();
1379 else if (Pieces[i].getModifier() == '\0')
1380 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1382 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1383 Pieces[i].getModifier() + '}';
1386 // Get all the output and input constraints together.
1387 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1388 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1390 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1391 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1392 S.getOutputName(i));
1393 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1394 assert(IsValid && "Failed to parse output constraint");
1395 OutputConstraintInfos.push_back(Info);
1398 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1399 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1401 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1402 S.getNumOutputs(), Info);
1403 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1404 InputConstraintInfos.push_back(Info);
1407 std::string Constraints;
1409 std::vector<LValue> ResultRegDests;
1410 std::vector<QualType> ResultRegQualTys;
1411 std::vector<llvm::Type *> ResultRegTypes;
1412 std::vector<llvm::Type *> ResultTruncRegTypes;
1413 std::vector<llvm::Type*> ArgTypes;
1414 std::vector<llvm::Value*> Args;
1416 // Keep track of inout constraints.
1417 std::string InOutConstraints;
1418 std::vector<llvm::Value*> InOutArgs;
1419 std::vector<llvm::Type*> InOutArgTypes;
1421 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1422 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1424 // Simplify the output constraint.
1425 std::string OutputConstraint(S.getOutputConstraint(i));
1426 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
1428 const Expr *OutExpr = S.getOutputExpr(i);
1429 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1431 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1434 LValue Dest = EmitLValue(OutExpr);
1435 if (!Constraints.empty())
1438 // If this is a register output, then make the inline asm return it
1439 // by-value. If this is a memory result, return the value by-reference.
1440 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
1441 Constraints += "=" + OutputConstraint;
1442 ResultRegQualTys.push_back(OutExpr->getType());
1443 ResultRegDests.push_back(Dest);
1444 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1445 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1447 // If this output is tied to an input, and if the input is larger, then
1448 // we need to set the actual result type of the inline asm node to be the
1449 // same as the input type.
1450 if (Info.hasMatchingInput()) {
1452 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1453 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1454 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1457 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1459 QualType InputTy = S.getInputExpr(InputNo)->getType();
1460 QualType OutputType = OutExpr->getType();
1462 uint64_t InputSize = getContext().getTypeSize(InputTy);
1463 if (getContext().getTypeSize(OutputType) < InputSize) {
1464 // Form the asm to return the value as a larger integer or fp type.
1465 ResultRegTypes.back() = ConvertType(InputTy);
1468 if (llvm::Type* AdjTy =
1469 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1470 ResultRegTypes.back()))
1471 ResultRegTypes.back() = AdjTy;
1473 ArgTypes.push_back(Dest.getAddress()->getType());
1474 Args.push_back(Dest.getAddress());
1475 Constraints += "=*";
1476 Constraints += OutputConstraint;
1479 if (Info.isReadWrite()) {
1480 InOutConstraints += ',';
1482 const Expr *InputExpr = S.getOutputExpr(i);
1483 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1486 if (Info.allowsRegister())
1487 InOutConstraints += llvm::utostr(i);
1489 InOutConstraints += OutputConstraint;
1491 InOutArgTypes.push_back(Arg->getType());
1492 InOutArgs.push_back(Arg);
1496 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1498 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1499 const Expr *InputExpr = S.getInputExpr(i);
1501 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1503 if (!Constraints.empty())
1506 // Simplify the input constraint.
1507 std::string InputConstraint(S.getInputConstraint(i));
1508 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1509 &OutputConstraintInfos);
1512 AddVariableConstraints(InputConstraint,
1513 *InputExpr->IgnoreParenNoopCasts(getContext()),
1516 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
1518 // If this input argument is tied to a larger output result, extend the
1519 // input to be the same size as the output. The LLVM backend wants to see
1520 // the input and output of a matching constraint be the same size. Note
1521 // that GCC does not define what the top bits are here. We use zext because
1522 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1523 if (Info.hasTiedOperand()) {
1524 unsigned Output = Info.getTiedOperand();
1525 QualType OutputType = S.getOutputExpr(Output)->getType();
1526 QualType InputTy = InputExpr->getType();
1528 if (getContext().getTypeSize(OutputType) >
1529 getContext().getTypeSize(InputTy)) {
1530 // Use ptrtoint as appropriate so that we can do our extension.
1531 if (isa<llvm::PointerType>(Arg->getType()))
1532 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1533 const llvm::Type *OutputTy = ConvertType(OutputType);
1534 if (isa<llvm::IntegerType>(OutputTy))
1535 Arg = Builder.CreateZExt(Arg, OutputTy);
1537 Arg = Builder.CreateFPExt(Arg, OutputTy);
1540 if (const llvm::Type* AdjTy =
1541 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1543 Arg = Builder.CreateBitCast(Arg, AdjTy);
1545 ArgTypes.push_back(Arg->getType());
1546 Args.push_back(Arg);
1547 Constraints += InputConstraint;
1550 // Append the "input" part of inout constraints last.
1551 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1552 ArgTypes.push_back(InOutArgTypes[i]);
1553 Args.push_back(InOutArgs[i]);
1555 Constraints += InOutConstraints;
1558 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1559 llvm::StringRef Clobber = S.getClobber(i)->getString();
1561 if (Clobber != "memory" && Clobber != "cc")
1562 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
1564 if (i != 0 || NumConstraints != 0)
1567 Constraints += "~{";
1568 Constraints += Clobber;
1572 // Add machine specific clobbers
1573 std::string MachineClobbers = Target.getClobbers();
1574 if (!MachineClobbers.empty()) {
1575 if (!Constraints.empty())
1577 Constraints += MachineClobbers;
1580 const llvm::Type *ResultType;
1581 if (ResultRegTypes.empty())
1582 ResultType = llvm::Type::getVoidTy(getLLVMContext());
1583 else if (ResultRegTypes.size() == 1)
1584 ResultType = ResultRegTypes[0];
1586 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1588 const llvm::FunctionType *FTy =
1589 llvm::FunctionType::get(ResultType, ArgTypes, false);
1591 llvm::InlineAsm *IA =
1592 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1593 S.isVolatile() || S.getNumOutputs() == 0);
1594 llvm::CallInst *Result = Builder.CreateCall(IA, Args);
1595 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1597 // Slap the source location of the inline asm into a !srcloc metadata on the
1599 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
1601 // Extract all of the register value results from the asm.
1602 std::vector<llvm::Value*> RegResults;
1603 if (ResultRegTypes.size() == 1) {
1604 RegResults.push_back(Result);
1606 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1607 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1608 RegResults.push_back(Tmp);
1612 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1613 llvm::Value *Tmp = RegResults[i];
1615 // If the result type of the LLVM IR asm doesn't match the result type of
1616 // the expression, do the conversion.
1617 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1618 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1620 // Truncate the integer result to the right size, note that TruncTy can be
1622 if (TruncTy->isFloatingPointTy())
1623 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1624 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1625 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1626 Tmp = Builder.CreateTrunc(Tmp,
1627 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
1628 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1629 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1630 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1631 Tmp = Builder.CreatePtrToInt(Tmp,
1632 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
1633 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1634 } else if (TruncTy->isIntegerTy()) {
1635 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1636 } else if (TruncTy->isVectorTy()) {
1637 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1641 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);