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));
155 case Stmt::CXXTryStmtClass:
156 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
158 case Stmt::CXXForRangeStmtClass:
159 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
160 case Stmt::SEHTryStmtClass:
161 // FIXME Not yet implemented
166 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
167 switch (S->getStmtClass()) {
168 default: return false;
169 case Stmt::NullStmtClass: break;
170 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
171 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
172 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
173 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
174 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
175 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
176 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
177 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
183 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
184 /// this captures the expression result of the last sub-statement and returns it
185 /// (for use by the statement expression extension).
186 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
187 AggValueSlot AggSlot) {
188 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
189 "LLVM IR generation of compound statement ('{}')");
191 CGDebugInfo *DI = getDebugInfo();
193 DI->setLocation(S.getLBracLoc());
194 DI->EmitRegionStart(Builder);
197 // Keep track of the current cleanup stack depth.
198 RunCleanupsScope Scope(*this);
200 for (CompoundStmt::const_body_iterator I = S.body_begin(),
201 E = S.body_end()-GetLast; I != E; ++I)
205 DI->setLocation(S.getRBracLoc());
206 DI->EmitRegionEnd(Builder);
213 // We have to special case labels here. They are statements, but when put
214 // at the end of a statement expression, they yield the value of their
215 // subexpression. Handle this by walking through all labels we encounter,
216 // emitting them before we evaluate the subexpr.
217 const Stmt *LastStmt = S.body_back();
218 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
219 EmitLabel(LS->getDecl());
220 LastStmt = LS->getSubStmt();
225 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
231 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
232 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
234 // If there is a cleanup stack, then we it isn't worth trying to
235 // simplify this block (we would need to remove it from the scope map
236 // and cleanup entry).
237 if (!EHStack.empty())
240 // Can only simplify direct branches.
241 if (!BI || !BI->isUnconditional())
244 BB->replaceAllUsesWith(BI->getSuccessor(0));
245 BI->eraseFromParent();
246 BB->eraseFromParent();
249 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
250 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
252 // Fall out of the current block (if necessary).
255 if (IsFinished && BB->use_empty()) {
260 // Place the block after the current block, if possible, or else at
261 // the end of the function.
262 if (CurBB && CurBB->getParent())
263 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
265 CurFn->getBasicBlockList().push_back(BB);
266 Builder.SetInsertPoint(BB);
269 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
270 // Emit a branch from the current block to the target one if this
271 // was a real block. If this was just a fall-through block after a
272 // terminator, don't emit it.
273 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
275 if (!CurBB || CurBB->getTerminator()) {
276 // If there is no insert point or the previous block is already
277 // terminated, don't touch it.
279 // Otherwise, create a fall-through branch.
280 Builder.CreateBr(Target);
283 Builder.ClearInsertionPoint();
286 CodeGenFunction::JumpDest
287 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
288 JumpDest &Dest = LabelMap[D];
289 if (Dest.isValid()) return Dest;
291 // Create, but don't insert, the new block.
292 Dest = JumpDest(createBasicBlock(D->getName()),
293 EHScopeStack::stable_iterator::invalid(),
294 NextCleanupDestIndex++);
298 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
299 JumpDest &Dest = LabelMap[D];
301 // If we didn't need a forward reference to this label, just go
302 // ahead and create a destination at the current scope.
303 if (!Dest.isValid()) {
304 Dest = getJumpDestInCurrentScope(D->getName());
306 // Otherwise, we need to give this label a target depth and remove
307 // it from the branch-fixups list.
309 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
310 Dest = JumpDest(Dest.getBlock(),
311 EHStack.stable_begin(),
312 Dest.getDestIndex());
314 ResolveBranchFixups(Dest.getBlock());
317 EmitBlock(Dest.getBlock());
321 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
322 EmitLabel(S.getDecl());
323 EmitStmt(S.getSubStmt());
326 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
327 // If this code is reachable then emit a stop point (if generating
328 // debug info). We have to do this ourselves because we are on the
329 // "simple" statement path.
330 if (HaveInsertPoint())
333 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
337 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
338 if (const LabelDecl *Target = S.getConstantTarget()) {
339 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
343 // Ensure that we have an i8* for our PHI node.
344 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
346 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
349 // Get the basic block for the indirect goto.
350 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
352 // The first instruction in the block has to be the PHI for the switch dest,
353 // add an entry for this branch.
354 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
356 EmitBranch(IndGotoBB);
359 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
360 // C99 6.8.4.1: The first substatement is executed if the expression compares
361 // unequal to 0. The condition must be a scalar type.
362 RunCleanupsScope ConditionScope(*this);
364 if (S.getConditionVariable())
365 EmitAutoVarDecl(*S.getConditionVariable());
367 // If the condition constant folds and can be elided, try to avoid emitting
368 // the condition and the dead arm of the if/else.
370 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
371 // Figure out which block (then or else) is executed.
372 const Stmt *Executed = S.getThen();
373 const Stmt *Skipped = S.getElse();
374 if (!CondConstant) // Condition false?
375 std::swap(Executed, Skipped);
377 // If the skipped block has no labels in it, just emit the executed block.
378 // This avoids emitting dead code and simplifies the CFG substantially.
379 if (!ContainsLabel(Skipped)) {
381 RunCleanupsScope ExecutedScope(*this);
388 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
389 // the conditional branch.
390 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
391 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
392 llvm::BasicBlock *ElseBlock = ContBlock;
394 ElseBlock = createBasicBlock("if.else");
395 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
397 // Emit the 'then' code.
398 EmitBlock(ThenBlock);
400 RunCleanupsScope ThenScope(*this);
401 EmitStmt(S.getThen());
403 EmitBranch(ContBlock);
405 // Emit the 'else' code if present.
406 if (const Stmt *Else = S.getElse()) {
407 // There is no need to emit line number for unconditional branch.
409 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
410 EmitBlock(ElseBlock);
412 RunCleanupsScope ElseScope(*this);
415 // There is no need to emit line number for unconditional branch.
417 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
418 EmitBranch(ContBlock);
421 // Emit the continuation block for code after the if.
422 EmitBlock(ContBlock, true);
425 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
426 // Emit the header for the loop, which will also become
427 // the continue target.
428 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
429 EmitBlock(LoopHeader.getBlock());
431 // Create an exit block for when the condition fails, which will
432 // also become the break target.
433 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
435 // Store the blocks to use for break and continue.
436 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
438 // C++ [stmt.while]p2:
439 // When the condition of a while statement is a declaration, the
440 // scope of the variable that is declared extends from its point
441 // of declaration (3.3.2) to the end of the while statement.
443 // The object created in a condition is destroyed and created
444 // with each iteration of the loop.
445 RunCleanupsScope ConditionScope(*this);
447 if (S.getConditionVariable())
448 EmitAutoVarDecl(*S.getConditionVariable());
450 // Evaluate the conditional in the while header. C99 6.8.5.1: The
451 // evaluation of the controlling expression takes place before each
452 // execution of the loop body.
453 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
455 // while(1) is common, avoid extra exit blocks. Be sure
456 // to correctly handle break/continue though.
457 bool EmitBoolCondBranch = true;
458 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
460 EmitBoolCondBranch = false;
462 // As long as the condition is true, go to the loop body.
463 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
464 if (EmitBoolCondBranch) {
465 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
466 if (ConditionScope.requiresCleanups())
467 ExitBlock = createBasicBlock("while.exit");
469 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
471 if (ExitBlock != LoopExit.getBlock()) {
472 EmitBlock(ExitBlock);
473 EmitBranchThroughCleanup(LoopExit);
477 // Emit the loop body. We have to emit this in a cleanup scope
478 // because it might be a singleton DeclStmt.
480 RunCleanupsScope BodyScope(*this);
482 EmitStmt(S.getBody());
485 BreakContinueStack.pop_back();
487 // Immediately force cleanup.
488 ConditionScope.ForceCleanup();
490 // Branch to the loop header again.
491 EmitBranch(LoopHeader.getBlock());
493 // Emit the exit block.
494 EmitBlock(LoopExit.getBlock(), true);
496 // The LoopHeader typically is just a branch if we skipped emitting
497 // a branch, try to erase it.
498 if (!EmitBoolCondBranch)
499 SimplifyForwardingBlocks(LoopHeader.getBlock());
502 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
503 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
504 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
506 // Store the blocks to use for break and continue.
507 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
509 // Emit the body of the loop.
510 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
513 RunCleanupsScope BodyScope(*this);
514 EmitStmt(S.getBody());
517 BreakContinueStack.pop_back();
519 EmitBlock(LoopCond.getBlock());
521 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
522 // after each execution of the loop body."
524 // Evaluate the conditional in the while header.
525 // C99 6.8.5p2/p4: The first substatement is executed if the expression
526 // compares unequal to 0. The condition must be a scalar type.
527 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
529 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
530 // to correctly handle break/continue though.
531 bool EmitBoolCondBranch = true;
532 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
534 EmitBoolCondBranch = false;
536 // As long as the condition is true, iterate the loop.
537 if (EmitBoolCondBranch)
538 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
540 // Emit the exit block.
541 EmitBlock(LoopExit.getBlock());
543 // The DoCond block typically is just a branch if we skipped
544 // emitting a branch, try to erase it.
545 if (!EmitBoolCondBranch)
546 SimplifyForwardingBlocks(LoopCond.getBlock());
549 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
550 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
552 RunCleanupsScope ForScope(*this);
554 CGDebugInfo *DI = getDebugInfo();
556 DI->setLocation(S.getSourceRange().getBegin());
557 DI->EmitRegionStart(Builder);
560 // Evaluate the first part before the loop.
562 EmitStmt(S.getInit());
564 // Start the loop with a block that tests the condition.
565 // If there's an increment, the continue scope will be overwritten
567 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
568 llvm::BasicBlock *CondBlock = Continue.getBlock();
569 EmitBlock(CondBlock);
571 // Create a cleanup scope for the condition variable cleanups.
572 RunCleanupsScope ConditionScope(*this);
574 llvm::Value *BoolCondVal = 0;
576 // If the for statement has a condition scope, emit the local variable
578 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
579 if (S.getConditionVariable()) {
580 EmitAutoVarDecl(*S.getConditionVariable());
583 // If there are any cleanups between here and the loop-exit scope,
584 // create a block to stage a loop exit along.
585 if (ForScope.requiresCleanups())
586 ExitBlock = createBasicBlock("for.cond.cleanup");
588 // As long as the condition is true, iterate the loop.
589 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
591 // C99 6.8.5p2/p4: The first substatement is executed if the expression
592 // compares unequal to 0. The condition must be a scalar type.
593 BoolCondVal = EvaluateExprAsBool(S.getCond());
594 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
596 if (ExitBlock != LoopExit.getBlock()) {
597 EmitBlock(ExitBlock);
598 EmitBranchThroughCleanup(LoopExit);
603 // Treat it as a non-zero constant. Don't even create a new block for the
604 // body, just fall into it.
607 // If the for loop doesn't have an increment we can just use the
608 // condition as the continue block. Otherwise we'll need to create
609 // a block for it (in the current scope, i.e. in the scope of the
610 // condition), and that we will become our continue block.
612 Continue = getJumpDestInCurrentScope("for.inc");
614 // Store the blocks to use for break and continue.
615 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
618 // Create a separate cleanup scope for the body, in case it is not
619 // a compound statement.
620 RunCleanupsScope BodyScope(*this);
621 EmitStmt(S.getBody());
624 // If there is an increment, emit it next.
626 EmitBlock(Continue.getBlock());
627 EmitStmt(S.getInc());
630 BreakContinueStack.pop_back();
632 ConditionScope.ForceCleanup();
633 EmitBranch(CondBlock);
635 ForScope.ForceCleanup();
638 DI->setLocation(S.getSourceRange().getEnd());
639 DI->EmitRegionEnd(Builder);
642 // Emit the fall-through block.
643 EmitBlock(LoopExit.getBlock(), true);
646 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
647 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
649 RunCleanupsScope ForScope(*this);
651 CGDebugInfo *DI = getDebugInfo();
653 DI->setLocation(S.getSourceRange().getBegin());
654 DI->EmitRegionStart(Builder);
657 // Evaluate the first pieces before the loop.
658 EmitStmt(S.getRangeStmt());
659 EmitStmt(S.getBeginEndStmt());
661 // Start the loop with a block that tests the condition.
662 // If there's an increment, the continue scope will be overwritten
664 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
665 EmitBlock(CondBlock);
667 // If there are any cleanups between here and the loop-exit scope,
668 // create a block to stage a loop exit along.
669 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
670 if (ForScope.requiresCleanups())
671 ExitBlock = createBasicBlock("for.cond.cleanup");
673 // The loop body, consisting of the specified body and the loop variable.
674 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
676 // The body is executed if the expression, contextually converted
678 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
679 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
681 if (ExitBlock != LoopExit.getBlock()) {
682 EmitBlock(ExitBlock);
683 EmitBranchThroughCleanup(LoopExit);
688 // Create a block for the increment. In case of a 'continue', we jump there.
689 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
691 // Store the blocks to use for break and continue.
692 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
695 // Create a separate cleanup scope for the loop variable and body.
696 RunCleanupsScope BodyScope(*this);
697 EmitStmt(S.getLoopVarStmt());
698 EmitStmt(S.getBody());
701 // If there is an increment, emit it next.
702 EmitBlock(Continue.getBlock());
703 EmitStmt(S.getInc());
705 BreakContinueStack.pop_back();
707 EmitBranch(CondBlock);
709 ForScope.ForceCleanup();
712 DI->setLocation(S.getSourceRange().getEnd());
713 DI->EmitRegionEnd(Builder);
716 // Emit the fall-through block.
717 EmitBlock(LoopExit.getBlock(), true);
720 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
722 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
723 } else if (RV.isAggregate()) {
724 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
726 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
728 EmitBranchThroughCleanup(ReturnBlock);
731 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
732 /// if the function returns void, or may be missing one if the function returns
733 /// non-void. Fun stuff :).
734 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
735 // Emit the result value, even if unused, to evalute the side effects.
736 const Expr *RV = S.getRetValue();
738 // FIXME: Clean this up by using an LValue for ReturnTemp,
739 // EmitStoreThroughLValue, and EmitAnyExpr.
740 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
741 !Target.useGlobalsForAutomaticVariables()) {
742 // Apply the named return value optimization for this return statement,
743 // which means doing nothing: the appropriate result has already been
744 // constructed into the NRVO variable.
746 // If there is an NRVO flag for this variable, set it to 1 into indicate
747 // that the cleanup code should not destroy the variable.
748 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
749 Builder.CreateStore(Builder.getTrue(), NRVOFlag);
750 } else if (!ReturnValue) {
751 // Make sure not to return anything, but evaluate the expression
755 } else if (RV == 0) {
756 // Do nothing (return value is left uninitialized)
757 } else if (FnRetTy->isReferenceType()) {
758 // If this function returns a reference, take the address of the expression
759 // rather than the value.
760 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
761 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
762 } else if (!hasAggregateLLVMType(RV->getType())) {
763 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
764 } else if (RV->getType()->isAnyComplexType()) {
765 EmitComplexExprIntoAddr(RV, ReturnValue, false);
767 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, false, true));
770 EmitBranchThroughCleanup(ReturnBlock);
773 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
774 // As long as debug info is modeled with instructions, we have to ensure we
775 // have a place to insert here and write the stop point here.
776 if (getDebugInfo() && HaveInsertPoint())
779 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
784 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
785 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
787 // If this code is reachable then emit a stop point (if generating
788 // debug info). We have to do this ourselves because we are on the
789 // "simple" statement path.
790 if (HaveInsertPoint())
793 JumpDest Block = BreakContinueStack.back().BreakBlock;
794 EmitBranchThroughCleanup(Block);
797 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
798 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
800 // If this code is reachable then emit a stop point (if generating
801 // debug info). We have to do this ourselves because we are on the
802 // "simple" statement path.
803 if (HaveInsertPoint())
806 JumpDest Block = BreakContinueStack.back().ContinueBlock;
807 EmitBranchThroughCleanup(Block);
810 /// EmitCaseStmtRange - If case statement range is not too big then
811 /// add multiple cases to switch instruction, one for each value within
812 /// the range. If range is too big then emit "if" condition check.
813 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
814 assert(S.getRHS() && "Expected RHS value in CaseStmt");
816 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
817 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
819 // Emit the code for this case. We do this first to make sure it is
820 // properly chained from our predecessor before generating the
821 // switch machinery to enter this block.
822 EmitBlock(createBasicBlock("sw.bb"));
823 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
824 EmitStmt(S.getSubStmt());
826 // If range is empty, do nothing.
827 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
830 llvm::APInt Range = RHS - LHS;
831 // FIXME: parameters such as this should not be hardcoded.
832 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
833 // Range is small enough to add multiple switch instruction cases.
834 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
835 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
841 // The range is too big. Emit "if" condition into a new block,
842 // making sure to save and restore the current insertion point.
843 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
845 // Push this test onto the chain of range checks (which terminates
846 // in the default basic block). The switch's default will be changed
847 // to the top of this chain after switch emission is complete.
848 llvm::BasicBlock *FalseDest = CaseRangeBlock;
849 CaseRangeBlock = createBasicBlock("sw.caserange");
851 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
852 Builder.SetInsertPoint(CaseRangeBlock);
856 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS), "tmp");
858 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
859 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
861 // Restore the appropriate insertion point.
863 Builder.SetInsertPoint(RestoreBB);
865 Builder.ClearInsertionPoint();
868 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
869 // Handle case ranges.
871 EmitCaseStmtRange(S);
875 llvm::ConstantInt *CaseVal =
876 Builder.getInt(S.getLHS()->EvaluateAsInt(getContext()));
878 // If the body of the case is just a 'break', and if there was no fallthrough,
879 // try to not emit an empty block.
880 if (isa<BreakStmt>(S.getSubStmt())) {
881 JumpDest Block = BreakContinueStack.back().BreakBlock;
883 // Only do this optimization if there are no cleanups that need emitting.
884 if (isObviouslyBranchWithoutCleanups(Block)) {
885 SwitchInsn->addCase(CaseVal, Block.getBlock());
887 // If there was a fallthrough into this case, make sure to redirect it to
888 // the end of the switch as well.
889 if (Builder.GetInsertBlock()) {
890 Builder.CreateBr(Block.getBlock());
891 Builder.ClearInsertionPoint();
897 EmitBlock(createBasicBlock("sw.bb"));
898 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
899 SwitchInsn->addCase(CaseVal, CaseDest);
901 // Recursively emitting the statement is acceptable, but is not wonderful for
902 // code where we have many case statements nested together, i.e.:
906 // Handling this recursively will create a new block for each case statement
907 // that falls through to the next case which is IR intensive. It also causes
908 // deep recursion which can run into stack depth limitations. Handle
909 // sequential non-range case statements specially.
910 const CaseStmt *CurCase = &S;
911 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
913 // Otherwise, iteratively add consecutive cases to this switch stmt.
914 while (NextCase && NextCase->getRHS() == 0) {
916 llvm::ConstantInt *CaseVal =
917 Builder.getInt(CurCase->getLHS()->EvaluateAsInt(getContext()));
918 SwitchInsn->addCase(CaseVal, CaseDest);
919 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
922 // Normal default recursion for non-cases.
923 EmitStmt(CurCase->getSubStmt());
926 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
927 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
928 assert(DefaultBlock->empty() &&
929 "EmitDefaultStmt: Default block already defined?");
930 EmitBlock(DefaultBlock);
931 EmitStmt(S.getSubStmt());
934 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
935 /// constant value that is being switched on, see if we can dead code eliminate
936 /// the body of the switch to a simple series of statements to emit. Basically,
937 /// on a switch (5) we want to find these statements:
943 /// and add them to the ResultStmts vector. If it is unsafe to do this
944 /// transformation (for example, one of the elided statements contains a label
945 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
946 /// should include statements after it (e.g. the printf() line is a substmt of
947 /// the case) then return CSFC_FallThrough. If we handled it and found a break
948 /// statement, then return CSFC_Success.
950 /// If Case is non-null, then we are looking for the specified case, checking
951 /// that nothing we jump over contains labels. If Case is null, then we found
952 /// the case and are looking for the break.
954 /// If the recursive walk actually finds our Case, then we set FoundCase to
957 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
958 static CSFC_Result CollectStatementsForCase(const Stmt *S,
959 const SwitchCase *Case,
961 llvm::SmallVectorImpl<const Stmt*> &ResultStmts) {
962 // If this is a null statement, just succeed.
964 return Case ? CSFC_Success : CSFC_FallThrough;
966 // If this is the switchcase (case 4: or default) that we're looking for, then
967 // we're in business. Just add the substatement.
968 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
971 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
975 // Otherwise, this is some other case or default statement, just ignore it.
976 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
980 // If we are in the live part of the code and we found our break statement,
982 if (Case == 0 && isa<BreakStmt>(S))
985 // If this is a switch statement, then it might contain the SwitchCase, the
986 // break, or neither.
987 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
988 // Handle this as two cases: we might be looking for the SwitchCase (if so
989 // the skipped statements must be skippable) or we might already have it.
990 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
992 // Keep track of whether we see a skipped declaration. The code could be
993 // using the declaration even if it is skipped, so we can't optimize out
994 // the decl if the kept statements might refer to it.
995 bool HadSkippedDecl = false;
997 // If we're looking for the case, just see if we can skip each of the
999 for (; Case && I != E; ++I) {
1000 HadSkippedDecl |= isa<DeclStmt>(*I);
1002 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1003 case CSFC_Failure: return CSFC_Failure;
1005 // A successful result means that either 1) that the statement doesn't
1006 // have the case and is skippable, or 2) does contain the case value
1007 // and also contains the break to exit the switch. In the later case,
1008 // we just verify the rest of the statements are elidable.
1010 // If we found the case and skipped declarations, we can't do the
1013 return CSFC_Failure;
1015 for (++I; I != E; ++I)
1016 if (CodeGenFunction::ContainsLabel(*I, true))
1017 return CSFC_Failure;
1018 return CSFC_Success;
1021 case CSFC_FallThrough:
1022 // If we have a fallthrough condition, then we must have found the
1023 // case started to include statements. Consider the rest of the
1024 // statements in the compound statement as candidates for inclusion.
1025 assert(FoundCase && "Didn't find case but returned fallthrough?");
1026 // We recursively found Case, so we're not looking for it anymore.
1029 // If we found the case and skipped declarations, we can't do the
1032 return CSFC_Failure;
1038 // If we have statements in our range, then we know that the statements are
1039 // live and need to be added to the set of statements we're tracking.
1040 for (; I != E; ++I) {
1041 switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1042 case CSFC_Failure: return CSFC_Failure;
1043 case CSFC_FallThrough:
1044 // A fallthrough result means that the statement was simple and just
1045 // included in ResultStmt, keep adding them afterwards.
1048 // A successful result means that we found the break statement and
1049 // stopped statement inclusion. We just ensure that any leftover stmts
1050 // are skippable and return success ourselves.
1051 for (++I; I != E; ++I)
1052 if (CodeGenFunction::ContainsLabel(*I, true))
1053 return CSFC_Failure;
1054 return CSFC_Success;
1058 return Case ? CSFC_Success : CSFC_FallThrough;
1061 // Okay, this is some other statement that we don't handle explicitly, like a
1062 // for statement or increment etc. If we are skipping over this statement,
1063 // just verify it doesn't have labels, which would make it invalid to elide.
1065 if (CodeGenFunction::ContainsLabel(S, true))
1066 return CSFC_Failure;
1067 return CSFC_Success;
1070 // Otherwise, we want to include this statement. Everything is cool with that
1071 // so long as it doesn't contain a break out of the switch we're in.
1072 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1074 // Otherwise, everything is great. Include the statement and tell the caller
1075 // that we fall through and include the next statement as well.
1076 ResultStmts.push_back(S);
1077 return CSFC_FallThrough;
1080 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1081 /// then invoke CollectStatementsForCase to find the list of statements to emit
1082 /// for a switch on constant. See the comment above CollectStatementsForCase
1083 /// for more details.
1084 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1085 const llvm::APInt &ConstantCondValue,
1086 llvm::SmallVectorImpl<const Stmt*> &ResultStmts,
1088 // First step, find the switch case that is being branched to. We can do this
1089 // efficiently by scanning the SwitchCase list.
1090 const SwitchCase *Case = S.getSwitchCaseList();
1091 const DefaultStmt *DefaultCase = 0;
1093 for (; Case; Case = Case->getNextSwitchCase()) {
1094 // It's either a default or case. Just remember the default statement in
1095 // case we're not jumping to any numbered cases.
1096 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1101 // Check to see if this case is the one we're looking for.
1102 const CaseStmt *CS = cast<CaseStmt>(Case);
1103 // Don't handle case ranges yet.
1104 if (CS->getRHS()) return false;
1106 // If we found our case, remember it as 'case'.
1107 if (CS->getLHS()->EvaluateAsInt(C) == ConstantCondValue)
1111 // If we didn't find a matching case, we use a default if it exists, or we
1112 // elide the whole switch body!
1114 // It is safe to elide the body of the switch if it doesn't contain labels
1115 // etc. If it is safe, return successfully with an empty ResultStmts list.
1116 if (DefaultCase == 0)
1117 return !CodeGenFunction::ContainsLabel(&S);
1121 // Ok, we know which case is being jumped to, try to collect all the
1122 // statements that follow it. This can fail for a variety of reasons. Also,
1123 // check to see that the recursive walk actually found our case statement.
1124 // Insane cases like this can fail to find it in the recursive walk since we
1125 // don't handle every stmt kind:
1129 bool FoundCase = false;
1130 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1131 ResultStmts) != CSFC_Failure &&
1135 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1136 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1138 RunCleanupsScope ConditionScope(*this);
1140 if (S.getConditionVariable())
1141 EmitAutoVarDecl(*S.getConditionVariable());
1143 // See if we can constant fold the condition of the switch and therefore only
1144 // emit the live case statement (if any) of the switch.
1145 llvm::APInt ConstantCondValue;
1146 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1147 llvm::SmallVector<const Stmt*, 4> CaseStmts;
1148 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1150 RunCleanupsScope ExecutedScope(*this);
1152 // Okay, we can dead code eliminate everything except this case. Emit the
1153 // specified series of statements and we're good.
1154 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1155 EmitStmt(CaseStmts[i]);
1160 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1162 // Handle nested switch statements.
1163 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1164 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1166 // Create basic block to hold stuff that comes after switch
1167 // statement. We also need to create a default block now so that
1168 // explicit case ranges tests can have a place to jump to on
1170 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1171 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1172 CaseRangeBlock = DefaultBlock;
1174 // Clear the insertion point to indicate we are in unreachable code.
1175 Builder.ClearInsertionPoint();
1177 // All break statements jump to NextBlock. If BreakContinueStack is non empty
1178 // then reuse last ContinueBlock.
1179 JumpDest OuterContinue;
1180 if (!BreakContinueStack.empty())
1181 OuterContinue = BreakContinueStack.back().ContinueBlock;
1183 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1185 // Emit switch body.
1186 EmitStmt(S.getBody());
1188 BreakContinueStack.pop_back();
1190 // Update the default block in case explicit case range tests have
1191 // been chained on top.
1192 SwitchInsn->setSuccessor(0, CaseRangeBlock);
1194 // If a default was never emitted:
1195 if (!DefaultBlock->getParent()) {
1196 // If we have cleanups, emit the default block so that there's a
1197 // place to jump through the cleanups from.
1198 if (ConditionScope.requiresCleanups()) {
1199 EmitBlock(DefaultBlock);
1201 // Otherwise, just forward the default block to the switch end.
1203 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1204 delete DefaultBlock;
1208 ConditionScope.ForceCleanup();
1210 // Emit continuation.
1211 EmitBlock(SwitchExit.getBlock(), true);
1213 SwitchInsn = SavedSwitchInsn;
1214 CaseRangeBlock = SavedCRBlock;
1218 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1219 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
1222 while (*Constraint) {
1223 switch (*Constraint) {
1225 Result += Target.convertConstraint(Constraint);
1231 case '=': // Will see this and the following in mult-alt constraints.
1242 "Must pass output names to constraints with a symbolic name");
1244 bool result = Target.resolveSymbolicName(Constraint,
1246 OutCons->size(), Index);
1247 assert(result && "Could not resolve symbolic name"); (void)result;
1248 Result += llvm::utostr(Index);
1259 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1260 /// as using a particular register add that as a constraint that will be used
1261 /// in this asm stmt.
1263 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1264 const TargetInfo &Target, CodeGenModule &CGM,
1265 const AsmStmt &Stmt) {
1266 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1269 const ValueDecl &Value = *AsmDeclRef->getDecl();
1270 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1273 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1276 llvm::StringRef Register = Attr->getLabel();
1277 assert(Target.isValidGCCRegisterName(Register));
1278 // FIXME: We should check which registers are compatible with "r" or "x".
1279 if (Constraint != "r" && Constraint != "x") {
1280 CGM.ErrorUnsupported(&Stmt, "__asm__");
1283 return "{" + Register.str() + "}";
1287 CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
1288 const TargetInfo::ConstraintInfo &Info,
1289 LValue InputValue, QualType InputType,
1290 std::string &ConstraintStr) {
1292 if (Info.allowsRegister() || !Info.allowsMemory()) {
1293 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
1294 Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
1296 const llvm::Type *Ty = ConvertType(InputType);
1297 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
1298 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1299 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1300 Ty = llvm::PointerType::getUnqual(Ty);
1302 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1305 Arg = InputValue.getAddress();
1306 ConstraintStr += '*';
1310 Arg = InputValue.getAddress();
1311 ConstraintStr += '*';
1317 llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
1318 const TargetInfo::ConstraintInfo &Info,
1319 const Expr *InputExpr,
1320 std::string &ConstraintStr) {
1321 if (Info.allowsRegister() || !Info.allowsMemory())
1322 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
1323 return EmitScalarExpr(InputExpr);
1325 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1326 LValue Dest = EmitLValue(InputExpr);
1327 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
1330 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1331 /// asm call instruction. The !srcloc MDNode contains a list of constant
1332 /// integers which are the source locations of the start of each line in the
1334 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1335 CodeGenFunction &CGF) {
1336 llvm::SmallVector<llvm::Value *, 8> Locs;
1337 // Add the location of the first line to the MDNode.
1338 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1339 Str->getLocStart().getRawEncoding()));
1340 llvm::StringRef StrVal = Str->getString();
1341 if (!StrVal.empty()) {
1342 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1343 const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1345 // Add the location of the start of each subsequent line of the asm to the
1347 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1348 if (StrVal[i] != '\n') continue;
1349 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1351 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1352 LineLoc.getRawEncoding()));
1356 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1359 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1360 // Analyze the asm string to decompose it into its pieces. We know that Sema
1361 // has already done this, so it is guaranteed to be successful.
1362 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
1364 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
1366 // Assemble the pieces into the final asm string.
1367 std::string AsmString;
1368 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1369 if (Pieces[i].isString())
1370 AsmString += Pieces[i].getString();
1371 else if (Pieces[i].getModifier() == '\0')
1372 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1374 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1375 Pieces[i].getModifier() + '}';
1378 // Get all the output and input constraints together.
1379 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1380 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1382 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1383 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1384 S.getOutputName(i));
1385 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1386 assert(IsValid && "Failed to parse output constraint");
1387 OutputConstraintInfos.push_back(Info);
1390 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1391 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1393 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1394 S.getNumOutputs(), Info);
1395 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1396 InputConstraintInfos.push_back(Info);
1399 std::string Constraints;
1401 std::vector<LValue> ResultRegDests;
1402 std::vector<QualType> ResultRegQualTys;
1403 std::vector<const llvm::Type *> ResultRegTypes;
1404 std::vector<const llvm::Type *> ResultTruncRegTypes;
1405 std::vector<const llvm::Type*> ArgTypes;
1406 std::vector<llvm::Value*> Args;
1408 // Keep track of inout constraints.
1409 std::string InOutConstraints;
1410 std::vector<llvm::Value*> InOutArgs;
1411 std::vector<const llvm::Type*> InOutArgTypes;
1413 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1414 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1416 // Simplify the output constraint.
1417 std::string OutputConstraint(S.getOutputConstraint(i));
1418 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
1420 const Expr *OutExpr = S.getOutputExpr(i);
1421 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1423 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1426 LValue Dest = EmitLValue(OutExpr);
1427 if (!Constraints.empty())
1430 // If this is a register output, then make the inline asm return it
1431 // by-value. If this is a memory result, return the value by-reference.
1432 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
1433 Constraints += "=" + OutputConstraint;
1434 ResultRegQualTys.push_back(OutExpr->getType());
1435 ResultRegDests.push_back(Dest);
1436 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1437 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1439 // If this output is tied to an input, and if the input is larger, then
1440 // we need to set the actual result type of the inline asm node to be the
1441 // same as the input type.
1442 if (Info.hasMatchingInput()) {
1444 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1445 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1446 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1449 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1451 QualType InputTy = S.getInputExpr(InputNo)->getType();
1452 QualType OutputType = OutExpr->getType();
1454 uint64_t InputSize = getContext().getTypeSize(InputTy);
1455 if (getContext().getTypeSize(OutputType) < InputSize) {
1456 // Form the asm to return the value as a larger integer or fp type.
1457 ResultRegTypes.back() = ConvertType(InputTy);
1460 if (const llvm::Type* AdjTy =
1461 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1462 ResultRegTypes.back()))
1463 ResultRegTypes.back() = AdjTy;
1465 ArgTypes.push_back(Dest.getAddress()->getType());
1466 Args.push_back(Dest.getAddress());
1467 Constraints += "=*";
1468 Constraints += OutputConstraint;
1471 if (Info.isReadWrite()) {
1472 InOutConstraints += ',';
1474 const Expr *InputExpr = S.getOutputExpr(i);
1475 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1478 if (Info.allowsRegister())
1479 InOutConstraints += llvm::utostr(i);
1481 InOutConstraints += OutputConstraint;
1483 InOutArgTypes.push_back(Arg->getType());
1484 InOutArgs.push_back(Arg);
1488 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1490 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1491 const Expr *InputExpr = S.getInputExpr(i);
1493 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1495 if (!Constraints.empty())
1498 // Simplify the input constraint.
1499 std::string InputConstraint(S.getInputConstraint(i));
1500 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1501 &OutputConstraintInfos);
1504 AddVariableConstraints(InputConstraint,
1505 *InputExpr->IgnoreParenNoopCasts(getContext()),
1508 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
1510 // If this input argument is tied to a larger output result, extend the
1511 // input to be the same size as the output. The LLVM backend wants to see
1512 // the input and output of a matching constraint be the same size. Note
1513 // that GCC does not define what the top bits are here. We use zext because
1514 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1515 if (Info.hasTiedOperand()) {
1516 unsigned Output = Info.getTiedOperand();
1517 QualType OutputType = S.getOutputExpr(Output)->getType();
1518 QualType InputTy = InputExpr->getType();
1520 if (getContext().getTypeSize(OutputType) >
1521 getContext().getTypeSize(InputTy)) {
1522 // Use ptrtoint as appropriate so that we can do our extension.
1523 if (isa<llvm::PointerType>(Arg->getType()))
1524 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1525 const llvm::Type *OutputTy = ConvertType(OutputType);
1526 if (isa<llvm::IntegerType>(OutputTy))
1527 Arg = Builder.CreateZExt(Arg, OutputTy);
1529 Arg = Builder.CreateFPExt(Arg, OutputTy);
1532 if (const llvm::Type* AdjTy =
1533 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1535 Arg = Builder.CreateBitCast(Arg, AdjTy);
1537 ArgTypes.push_back(Arg->getType());
1538 Args.push_back(Arg);
1539 Constraints += InputConstraint;
1542 // Append the "input" part of inout constraints last.
1543 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1544 ArgTypes.push_back(InOutArgTypes[i]);
1545 Args.push_back(InOutArgs[i]);
1547 Constraints += InOutConstraints;
1550 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1551 llvm::StringRef Clobber = S.getClobber(i)->getString();
1553 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
1555 if (i != 0 || NumConstraints != 0)
1558 Constraints += "~{";
1559 Constraints += Clobber;
1563 // Add machine specific clobbers
1564 std::string MachineClobbers = Target.getClobbers();
1565 if (!MachineClobbers.empty()) {
1566 if (!Constraints.empty())
1568 Constraints += MachineClobbers;
1571 const llvm::Type *ResultType;
1572 if (ResultRegTypes.empty())
1573 ResultType = llvm::Type::getVoidTy(getLLVMContext());
1574 else if (ResultRegTypes.size() == 1)
1575 ResultType = ResultRegTypes[0];
1577 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1579 const llvm::FunctionType *FTy =
1580 llvm::FunctionType::get(ResultType, ArgTypes, false);
1582 llvm::InlineAsm *IA =
1583 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1584 S.isVolatile() || S.getNumOutputs() == 0);
1585 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
1586 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1588 // Slap the source location of the inline asm into a !srcloc metadata on the
1590 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
1592 // Extract all of the register value results from the asm.
1593 std::vector<llvm::Value*> RegResults;
1594 if (ResultRegTypes.size() == 1) {
1595 RegResults.push_back(Result);
1597 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1598 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1599 RegResults.push_back(Tmp);
1603 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1604 llvm::Value *Tmp = RegResults[i];
1606 // If the result type of the LLVM IR asm doesn't match the result type of
1607 // the expression, do the conversion.
1608 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1609 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1611 // Truncate the integer result to the right size, note that TruncTy can be
1613 if (TruncTy->isFloatingPointTy())
1614 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1615 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1616 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1617 Tmp = Builder.CreateTrunc(Tmp,
1618 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
1619 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1620 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1621 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1622 Tmp = Builder.CreatePtrToInt(Tmp,
1623 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
1624 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1625 } else if (TruncTy->isIntegerTy()) {
1626 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1627 } else if (TruncTy->isVectorTy()) {
1628 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1632 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1633 ResultRegQualTys[i]);