blob: b72725edca7ef5c0fa80e62d45b8db21bed94ef7 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner7d22bf02009-03-05 08:04:57 +000018#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000020#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000021#include "llvm/InlineAsm.h"
22#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000023#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
Daniel Dunbar09124252008-11-12 08:21:33 +000031void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000032 if (CGDebugInfo *DI = getDebugInfo()) {
Devang Patel60e4fd92010-05-12 00:39:34 +000033 if (isa<DeclStmt>(S))
34 DI->setLocation(S->getLocEnd());
35 else
36 DI->setLocation(S->getLocStart());
Daniel Dunbar09124252008-11-12 08:21:33 +000037 DI->EmitStopPoint(CurFn, Builder);
38 }
39}
40
Reid Spencer5f016e22007-07-11 17:01:13 +000041void CodeGenFunction::EmitStmt(const Stmt *S) {
42 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000043
Daniel Dunbar09124252008-11-12 08:21:33 +000044 // Check if we can handle this without bothering to generate an
45 // insert point or debug info.
46 if (EmitSimpleStmt(S))
47 return;
48
Daniel Dunbard286f052009-07-19 06:58:07 +000049 // Check if we are generating unreachable code.
50 if (!HaveInsertPoint()) {
51 // If so, and the statement doesn't contain a label, then we do not need to
52 // generate actual code. This is safe because (1) the current point is
53 // unreachable, so we don't need to execute the code, and (2) we've already
54 // handled the statements which update internal data structures (like the
55 // local variable map) which could be used by subsequent statements.
56 if (!ContainsLabel(S)) {
57 // Verify that any decl statements were handled as simple, they may be in
58 // scope of subsequent reachable statements.
59 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
60 return;
61 }
62
63 // Otherwise, make a new block to hold the code.
64 EnsureInsertPoint();
65 }
66
Daniel Dunbar09124252008-11-12 08:21:33 +000067 // Generate a stoppoint if we are emitting debug info.
68 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000069
Reid Spencer5f016e22007-07-11 17:01:13 +000070 switch (S->getStmtClass()) {
71 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000072 // Must be an expression in a stmt context. Emit the value (to get
73 // side-effects) and ignore the result.
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000074 if (!isa<Expr>(S))
Daniel Dunbar488e9932008-08-16 00:56:44 +000075 ErrorUnsupported(S, "statement");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000076
77 EmitAnyExpr(cast<Expr>(S), 0, false, true);
Mike Stump1eb44332009-09-09 15:08:12 +000078
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000079 // Expression emitters don't handle unreachable blocks yet, so look for one
80 // explicitly here. This handles the common case of a call to a noreturn
81 // function.
82 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
John McCallf1549f62010-07-06 01:34:17 +000083 if (CurBB->empty() && CurBB->use_empty()) {
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000084 CurBB->eraseFromParent();
85 Builder.ClearInsertionPoint();
86 }
Reid Spencer5f016e22007-07-11 17:01:13 +000087 }
88 break;
Mike Stump1eb44332009-09-09 15:08:12 +000089 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000090 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000091
92 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
93 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
94 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
95 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Reid Spencer5f016e22007-07-11 17:01:13 +000097 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000098
Devang Patel51b09f22007-10-04 23:45:31 +000099 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000100 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101
102 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000103 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000104 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000105 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000106 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
107 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000108 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000109 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000110 break;
111 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000112 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000113 break;
114 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000115 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000116 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000117 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000118 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000119 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000120
121 case Stmt::CXXTryStmtClass:
122 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
123 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 }
125}
126
Daniel Dunbar09124252008-11-12 08:21:33 +0000127bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
128 switch (S->getStmtClass()) {
129 default: return false;
130 case Stmt::NullStmtClass: break;
131 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000132 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000133 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
134 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
135 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
136 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
137 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
138 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
139 }
140
141 return true;
142}
143
Chris Lattner33793202007-08-31 22:09:40 +0000144/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
145/// this captures the expression result of the last sub-statement and returns it
146/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000147RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
148 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000149 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
150 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Anders Carlssone896d982009-02-13 08:11:52 +0000152 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000153 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000154 DI->setLocation(S.getLBracLoc());
155 DI->EmitRegionStart(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000156 }
157
Anders Carlssonc71c8452009-02-07 23:50:39 +0000158 // Keep track of the current cleanup stack depth.
John McCallf1549f62010-07-06 01:34:17 +0000159 RunCleanupsScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattner33793202007-08-31 22:09:40 +0000161 for (CompoundStmt::const_body_iterator I = S.body_begin(),
162 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000164
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000165 if (DI) {
Devang Patelcd9199e2010-04-13 00:08:43 +0000166 DI->setLocation(S.getRBracLoc());
Devang Patelbbd9fa42009-10-06 18:36:08 +0000167 DI->EmitRegionEnd(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000168 }
169
Anders Carlsson17d28a32008-12-12 05:52:00 +0000170 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000171 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000172 RV = RValue::get(0);
173 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000174 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000175 // at the end of a statement expression, they yield the value of their
176 // subexpression. Handle this by walking through all labels we encounter,
177 // emitting them before we evaluate the subexpr.
178 const Stmt *LastStmt = S.body_back();
179 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
180 EmitLabel(*LS);
181 LastStmt = LS->getSubStmt();
182 }
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Anders Carlsson17d28a32008-12-12 05:52:00 +0000184 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Anders Carlsson17d28a32008-12-12 05:52:00 +0000186 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
187 }
188
Anders Carlsson17d28a32008-12-12 05:52:00 +0000189 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000190}
191
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000192void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
193 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000195 // If there is a cleanup stack, then we it isn't worth trying to
196 // simplify this block (we would need to remove it from the scope map
197 // and cleanup entry).
John McCallf1549f62010-07-06 01:34:17 +0000198 if (!EHStack.empty())
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000199 return;
200
201 // Can only simplify direct branches.
202 if (!BI || !BI->isUnconditional())
203 return;
204
205 BB->replaceAllUsesWith(BI->getSuccessor(0));
206 BI->eraseFromParent();
207 BB->eraseFromParent();
208}
209
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000210void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000211 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
212
Daniel Dunbard57a8712008-11-11 09:41:28 +0000213 // Fall out of the current block (if necessary).
214 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000215
216 if (IsFinished && BB->use_empty()) {
217 delete BB;
218 return;
219 }
220
John McCall839cbaa2010-04-21 10:29:06 +0000221 // Place the block after the current block, if possible, or else at
222 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000223 if (CurBB && CurBB->getParent())
224 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
John McCall839cbaa2010-04-21 10:29:06 +0000225 else
226 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 Builder.SetInsertPoint(BB);
228}
229
Daniel Dunbard57a8712008-11-11 09:41:28 +0000230void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
231 // Emit a branch from the current block to the target one if this
232 // was a real block. If this was just a fall-through block after a
233 // terminator, don't emit it.
234 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
235
236 if (!CurBB || CurBB->getTerminator()) {
237 // If there is no insert point or the previous block is already
238 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000239 } else {
240 // Otherwise, create a fall-through branch.
241 Builder.CreateBr(Target);
242 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000243
244 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000245}
246
John McCallf1549f62010-07-06 01:34:17 +0000247CodeGenFunction::JumpDest
248CodeGenFunction::getJumpDestForLabel(const LabelStmt *S) {
249 JumpDest &Dest = LabelMap[S];
250 if (Dest.Block) return Dest;
251
252 // Create, but don't insert, the new block.
253 Dest.Block = createBasicBlock(S->getName());
254 Dest.ScopeDepth = EHScopeStack::stable_iterator::invalid();
255 return Dest;
256}
257
Mike Stumpec9771d2009-02-08 09:22:19 +0000258void CodeGenFunction::EmitLabel(const LabelStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000259 JumpDest &Dest = LabelMap[&S];
260
261 // If we didn't needed a forward reference to this label, just go
262 // ahead and create a destination at the current scope.
263 if (!Dest.Block) {
264 Dest = getJumpDestInCurrentScope(S.getName());
265
266 // Otherwise, we need to give this label a target depth and remove
267 // it from the branch-fixups list.
268 } else {
269 assert(!Dest.ScopeDepth.isValid() && "already emitted label!");
270 Dest.ScopeDepth = EHStack.stable_begin();
271
272 EHStack.resolveBranchFixups(Dest.Block);
273 }
274
275 EmitBlock(Dest.Block);
Chris Lattner91d723d2008-07-26 20:23:23 +0000276}
277
278
279void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
280 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 EmitStmt(S.getSubStmt());
282}
283
284void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000285 // If this code is reachable then emit a stop point (if generating
286 // debug info). We have to do this ourselves because we are on the
287 // "simple" statement path.
288 if (HaveInsertPoint())
289 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000290
John McCallf1549f62010-07-06 01:34:17 +0000291 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000292}
293
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000294
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000295void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattner49c952f2009-11-06 18:10:47 +0000296 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000297 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
298 llvm::Type::getInt8PtrTy(VMContext),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000299 "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000300 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
301
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000302
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000303 // Get the basic block for the indirect goto.
304 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
305
306 // The first instruction in the block has to be the PHI for the switch dest,
307 // add an entry for this branch.
308 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
309
310 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000311}
312
Chris Lattner62b72f62008-11-11 07:24:28 +0000313void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // C99 6.8.4.1: The first substatement is executed if the expression compares
315 // unequal to 0. The condition must be a scalar type.
John McCallf1549f62010-07-06 01:34:17 +0000316 RunCleanupsScope ConditionScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000317
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000318 if (S.getConditionVariable())
Douglas Gregor01234bb2009-11-24 16:43:22 +0000319 EmitLocalBlockVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner9bc47e22008-11-12 07:46:33 +0000321 // If the condition constant folds and can be elided, try to avoid emitting
322 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000323 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000324 // Figure out which block (then or else) is executed.
325 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000326 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000327 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattner62b72f62008-11-11 07:24:28 +0000329 // If the skipped block has no labels in it, just emit the executed block.
330 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000331 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000332 if (Executed) {
John McCallf1549f62010-07-06 01:34:17 +0000333 RunCleanupsScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000334 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000335 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000336 return;
337 }
338 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000339
340 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
341 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000342 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
343 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
344 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000346 ElseBlock = createBasicBlock("if.else");
347 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000350 EmitBlock(ThenBlock);
351 {
John McCallf1549f62010-07-06 01:34:17 +0000352 RunCleanupsScope ThenScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000353 EmitStmt(S.getThen());
354 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000355 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // Emit the 'else' code if present.
358 if (const Stmt *Else = S.getElse()) {
359 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000360 {
John McCallf1549f62010-07-06 01:34:17 +0000361 RunCleanupsScope ElseScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000362 EmitStmt(Else);
363 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000364 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 }
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000368 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000369}
370
371void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000372 // Emit the header for the loop, which will also become
373 // the continue target.
374 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
375 EmitBlock(LoopHeader.Block);
Mike Stump72cac2c2009-02-07 18:08:12 +0000376
John McCallf1549f62010-07-06 01:34:17 +0000377 // Create an exit block for when the condition fails, which will
378 // also become the break target.
379 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
Mike Stump72cac2c2009-02-07 18:08:12 +0000380
381 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000382 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor5656e142009-11-24 21:15:44 +0000384 // C++ [stmt.while]p2:
385 // When the condition of a while statement is a declaration, the
386 // scope of the variable that is declared extends from its point
387 // of declaration (3.3.2) to the end of the while statement.
388 // [...]
389 // The object created in a condition is destroyed and created
390 // with each iteration of the loop.
John McCallf1549f62010-07-06 01:34:17 +0000391 RunCleanupsScope ConditionScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000392
John McCallf1549f62010-07-06 01:34:17 +0000393 if (S.getConditionVariable())
Douglas Gregor5656e142009-11-24 21:15:44 +0000394 EmitLocalBlockVarDecl(*S.getConditionVariable());
Douglas Gregor5656e142009-11-24 21:15:44 +0000395
Mike Stump16b16202009-02-07 17:18:33 +0000396 // Evaluate the conditional in the while header. C99 6.8.5.1: The
397 // evaluation of the controlling expression takes place before each
398 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000400
Devang Patel2c30d8f2007-10-09 20:51:27 +0000401 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000403 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000404 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000405 if (C->isOne())
406 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // As long as the condition is true, go to the loop body.
John McCallf1549f62010-07-06 01:34:17 +0000409 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
410 if (EmitBoolCondBranch) {
411 llvm::BasicBlock *ExitBlock = LoopExit.Block;
412 if (ConditionScope.requiresCleanups())
413 ExitBlock = createBasicBlock("while.exit");
414
415 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
416
417 if (ExitBlock != LoopExit.Block) {
418 EmitBlock(ExitBlock);
419 EmitBranchThroughCleanup(LoopExit);
420 }
421 }
Douglas Gregor5656e142009-11-24 21:15:44 +0000422
John McCallf1549f62010-07-06 01:34:17 +0000423 // Emit the loop body. We have to emit this in a cleanup scope
424 // because it might be a singleton DeclStmt.
Douglas Gregor5656e142009-11-24 21:15:44 +0000425 {
John McCallf1549f62010-07-06 01:34:17 +0000426 RunCleanupsScope BodyScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000427 EmitBlock(LoopBody);
428 EmitStmt(S.getBody());
429 }
Chris Lattnerda138702007-07-16 21:28:45 +0000430
Mike Stump1eb44332009-09-09 15:08:12 +0000431 BreakContinueStack.pop_back();
432
John McCallf1549f62010-07-06 01:34:17 +0000433 // Immediately force cleanup.
434 ConditionScope.ForceCleanup();
Douglas Gregor5656e142009-11-24 21:15:44 +0000435
John McCallf1549f62010-07-06 01:34:17 +0000436 // Branch to the loop header again.
437 EmitBranch(LoopHeader.Block);
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 // Emit the exit block.
John McCallf1549f62010-07-06 01:34:17 +0000440 EmitBlock(LoopExit.Block, true);
Douglas Gregor5656e142009-11-24 21:15:44 +0000441
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000442 // The LoopHeader typically is just a branch if we skipped emitting
443 // a branch, try to erase it.
John McCallf1549f62010-07-06 01:34:17 +0000444 if (!EmitBoolCondBranch)
445 SimplifyForwardingBlocks(LoopHeader.Block);
Reid Spencer5f016e22007-07-11 17:01:13 +0000446}
447
448void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000449 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
450 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattnerda138702007-07-16 21:28:45 +0000452 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000453 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000454
John McCallf1549f62010-07-06 01:34:17 +0000455 // Emit the body of the loop.
456 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
457 EmitBlock(LoopBody);
458 {
459 RunCleanupsScope BodyScope(*this);
460 EmitStmt(S.getBody());
461 }
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Anders Carlssone4b6d342009-02-10 05:52:02 +0000463 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000464
John McCallf1549f62010-07-06 01:34:17 +0000465 EmitBlock(LoopCond.Block);
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
468 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 // Evaluate the conditional in the while header.
471 // C99 6.8.5p2/p4: The first substatement is executed if the expression
472 // compares unequal to 0. The condition must be a scalar type.
473 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000474
475 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
476 // to correctly handle break/continue though.
477 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000478 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000479 if (C->isZero())
480 EmitBoolCondBranch = false;
481
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000483 if (EmitBoolCondBranch)
John McCallf1549f62010-07-06 01:34:17 +0000484 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.Block);
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 // Emit the exit block.
John McCallf1549f62010-07-06 01:34:17 +0000487 EmitBlock(LoopExit.Block);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000488
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000489 // The DoCond block typically is just a branch if we skipped
490 // emitting a branch, try to erase it.
491 if (!EmitBoolCondBranch)
John McCallf1549f62010-07-06 01:34:17 +0000492 SimplifyForwardingBlocks(LoopCond.Block);
Reid Spencer5f016e22007-07-11 17:01:13 +0000493}
494
495void CodeGenFunction::EmitForStmt(const ForStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000496 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
497
498 RunCleanupsScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 // Evaluate the first part before the loop.
501 if (S.getInit())
502 EmitStmt(S.getInit());
503
504 // Start the loop with a block that tests the condition.
John McCallf1549f62010-07-06 01:34:17 +0000505 // If there's an increment, the continue scope will be overwritten
506 // later.
507 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
508 llvm::BasicBlock *CondBlock = Continue.Block;
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 EmitBlock(CondBlock);
510
Douglas Gregord9752062009-11-25 01:51:31 +0000511 // Create a cleanup scope for the condition variable cleanups.
John McCallf1549f62010-07-06 01:34:17 +0000512 RunCleanupsScope ConditionScope(*this);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000513
Douglas Gregord9752062009-11-25 01:51:31 +0000514 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000516 // If the for statement has a condition scope, emit the local variable
517 // declaration.
John McCallf1549f62010-07-06 01:34:17 +0000518 llvm::BasicBlock *ExitBlock = LoopExit.Block;
Douglas Gregord9752062009-11-25 01:51:31 +0000519 if (S.getConditionVariable()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000520 EmitLocalBlockVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000521 }
John McCallf1549f62010-07-06 01:34:17 +0000522
523 // If there are any cleanups between here and the loop-exit scope,
524 // create a block to stage a loop exit along.
525 if (ForScope.requiresCleanups())
526 ExitBlock = createBasicBlock("for.cond.cleanup");
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000527
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000529 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner31a09842008-11-12 08:04:58 +0000531 // C99 6.8.5p2/p4: The first substatement is executed if the expression
532 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000533 BoolCondVal = EvaluateExprAsBool(S.getCond());
John McCallf1549f62010-07-06 01:34:17 +0000534 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
535
536 if (ExitBlock != LoopExit.Block) {
537 EmitBlock(ExitBlock);
538 EmitBranchThroughCleanup(LoopExit);
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
541 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 } else {
543 // Treat it as a non-zero constant. Don't even create a new block for the
544 // body, just fall into it.
545 }
546
Mike Stump1eb44332009-09-09 15:08:12 +0000547 // If the for loop doesn't have an increment we can just use the
John McCallf1549f62010-07-06 01:34:17 +0000548 // condition as the continue block. Otherwise we'll need to create
549 // a block for it (in the current scope, i.e. in the scope of the
550 // condition), and that we will become our continue block.
Chris Lattnerda138702007-07-16 21:28:45 +0000551 if (S.getInc())
John McCallf1549f62010-07-06 01:34:17 +0000552 Continue = getJumpDestInCurrentScope("for.inc");
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Chris Lattnerda138702007-07-16 21:28:45 +0000554 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000555 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Mike Stump3e9da662009-02-07 23:02:10 +0000556
Devang Patelbbd9fa42009-10-06 18:36:08 +0000557 CGDebugInfo *DI = getDebugInfo();
558 if (DI) {
559 DI->setLocation(S.getSourceRange().getBegin());
560 DI->EmitRegionStart(CurFn, Builder);
561 }
Douglas Gregord9752062009-11-25 01:51:31 +0000562
563 {
564 // Create a separate cleanup scope for the body, in case it is not
565 // a compound statement.
John McCallf1549f62010-07-06 01:34:17 +0000566 RunCleanupsScope BodyScope(*this);
Douglas Gregord9752062009-11-25 01:51:31 +0000567 EmitStmt(S.getBody());
568 }
Chris Lattnerda138702007-07-16 21:28:45 +0000569
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000571 if (S.getInc()) {
John McCallf1549f62010-07-06 01:34:17 +0000572 EmitBlock(Continue.Block);
Chris Lattner883f6a72007-08-11 00:04:45 +0000573 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000574 }
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor45d3fe12010-05-21 18:36:48 +0000576 BreakContinueStack.pop_back();
Douglas Gregord9752062009-11-25 01:51:31 +0000577
John McCallf1549f62010-07-06 01:34:17 +0000578 ConditionScope.ForceCleanup();
579 EmitBranch(CondBlock);
580
581 ForScope.ForceCleanup();
582
Devang Patelbbd9fa42009-10-06 18:36:08 +0000583 if (DI) {
584 DI->setLocation(S.getSourceRange().getEnd());
585 DI->EmitRegionEnd(CurFn, Builder);
586 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000587
Chris Lattnerda138702007-07-16 21:28:45 +0000588 // Emit the fall-through block.
John McCallf1549f62010-07-06 01:34:17 +0000589 EmitBlock(LoopExit.Block, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000590}
591
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000592void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
593 if (RV.isScalar()) {
594 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
595 } else if (RV.isAggregate()) {
596 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
597 } else {
598 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
599 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000600 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000601}
602
Reid Spencer5f016e22007-07-11 17:01:13 +0000603/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
604/// if the function returns void, or may be missing one if the function returns
605/// non-void. Fun stuff :).
606void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 // Emit the result value, even if unused, to evalute the side effects.
608 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000610 // FIXME: Clean this up by using an LValue for ReturnTemp,
611 // EmitStoreThroughLValue, and EmitAnyExpr.
Douglas Gregord86c4772010-05-15 06:46:45 +0000612 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
613 !Target.useGlobalsForAutomaticVariables()) {
614 // Apply the named return value optimization for this return statement,
615 // which means doing nothing: the appropriate result has already been
616 // constructed into the NRVO variable.
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000617
618 // If there is an NRVO flag for this variable, set it to 1 into indicate
619 // that the cleanup code should not destroy the variable.
620 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) {
621 const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext);
622 llvm::Value *One = llvm::ConstantInt::get(BoolTy, 1);
623 Builder.CreateStore(One, NRVOFlag);
624 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000625 } else if (!ReturnValue) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000626 // Make sure not to return anything, but evaluate the expression
627 // for side effects.
628 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000629 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000631 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000632 } else if (FnRetTy->isReferenceType()) {
633 // If this function returns a reference, take the address of the expression
634 // rather than the value.
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000635 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
Douglas Gregor33fd1fc2010-03-24 23:14:04 +0000636 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000637 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000638 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000639 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000640 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000642 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 }
Eli Friedman144ac612008-05-22 01:22:33 +0000644
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000645 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000646}
647
648void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000649 // As long as debug info is modeled with instructions, we have to ensure we
650 // have a place to insert here and write the stop point here.
651 if (getDebugInfo()) {
652 EnsureInsertPoint();
653 EmitStopPoint(&S);
654 }
655
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000656 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
657 I != E; ++I)
658 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000659}
Chris Lattnerda138702007-07-16 21:28:45 +0000660
Daniel Dunbar09124252008-11-12 08:21:33 +0000661void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000662 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
663
Daniel Dunbar09124252008-11-12 08:21:33 +0000664 // If this code is reachable then emit a stop point (if generating
665 // debug info). We have to do this ourselves because we are on the
666 // "simple" statement path.
667 if (HaveInsertPoint())
668 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000669
John McCallf1549f62010-07-06 01:34:17 +0000670 JumpDest Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000671 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000672}
673
Daniel Dunbar09124252008-11-12 08:21:33 +0000674void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000675 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
676
Daniel Dunbar09124252008-11-12 08:21:33 +0000677 // If this code is reachable then emit a stop point (if generating
678 // debug info). We have to do this ourselves because we are on the
679 // "simple" statement path.
680 if (HaveInsertPoint())
681 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000682
John McCallf1549f62010-07-06 01:34:17 +0000683 JumpDest Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000684 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000685}
Devang Patel51b09f22007-10-04 23:45:31 +0000686
Devang Patelc049e4f2007-10-08 20:57:48 +0000687/// EmitCaseStmtRange - If case statement range is not too big then
688/// add multiple cases to switch instruction, one for each value within
689/// the range. If range is too big then emit "if" condition check.
690void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000691 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000692
Anders Carlsson51fe9962008-11-22 21:04:56 +0000693 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
694 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000695
Daniel Dunbar16f23572008-07-25 01:11:38 +0000696 // Emit the code for this case. We do this first to make sure it is
697 // properly chained from our predecessor before generating the
698 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000699 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000700 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
701 EmitStmt(S.getSubStmt());
702
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000703 // If range is empty, do nothing.
704 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
705 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000706
707 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000708 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000709 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
710 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000711 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000712 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000713 LHS++;
714 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000715 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000716 }
717
Daniel Dunbar16f23572008-07-25 01:11:38 +0000718 // The range is too big. Emit "if" condition into a new block,
719 // making sure to save and restore the current insertion point.
720 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000721
Daniel Dunbar16f23572008-07-25 01:11:38 +0000722 // Push this test onto the chain of range checks (which terminates
723 // in the default basic block). The switch's default will be changed
724 // to the top of this chain after switch emission is complete.
725 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000726 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000727
Daniel Dunbar16f23572008-07-25 01:11:38 +0000728 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
729 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000730
731 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000732 llvm::Value *Diff =
733 Builder.CreateSub(SwitchInsn->getCondition(),
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000734 llvm::ConstantInt::get(VMContext, LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000735 llvm::Value *Cond =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000736 Builder.CreateICmpULE(Diff,
737 llvm::ConstantInt::get(VMContext, Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000738 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
739
Daniel Dunbar16f23572008-07-25 01:11:38 +0000740 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000741 if (RestoreBB)
742 Builder.SetInsertPoint(RestoreBB);
743 else
744 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000745}
746
747void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
748 if (S.getRHS()) {
749 EmitCaseStmtRange(S);
750 return;
751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000753 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000754 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000755 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000756 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Chris Lattner5512f282009-03-04 04:46:18 +0000758 // Recursively emitting the statement is acceptable, but is not wonderful for
759 // code where we have many case statements nested together, i.e.:
760 // case 1:
761 // case 2:
762 // case 3: etc.
763 // Handling this recursively will create a new block for each case statement
764 // that falls through to the next case which is IR intensive. It also causes
765 // deep recursion which can run into stack depth limitations. Handle
766 // sequential non-range case statements specially.
767 const CaseStmt *CurCase = &S;
768 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
769
770 // Otherwise, iteratively add consequtive cases to this switch stmt.
771 while (NextCase && NextCase->getRHS() == 0) {
772 CurCase = NextCase;
773 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000774 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000775
776 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
777 }
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner5512f282009-03-04 04:46:18 +0000779 // Normal default recursion for non-cases.
780 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000781}
782
783void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000784 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000785 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000786 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000787 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000788 EmitStmt(S.getSubStmt());
789}
790
791void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000792 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
793
794 RunCleanupsScope ConditionScope(*this);
Douglas Gregord3d53012009-11-24 17:07:59 +0000795
796 if (S.getConditionVariable())
797 EmitLocalBlockVarDecl(*S.getConditionVariable());
798
Devang Patel51b09f22007-10-04 23:45:31 +0000799 llvm::Value *CondV = EmitScalarExpr(S.getCond());
800
801 // Handle nested switch statements.
802 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000803 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000804
Daniel Dunbar16f23572008-07-25 01:11:38 +0000805 // Create basic block to hold stuff that comes after switch
806 // statement. We also need to create a default block now so that
807 // explicit case ranges tests can have a place to jump to on
808 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000809 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000810 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
811 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000812
Daniel Dunbar09124252008-11-12 08:21:33 +0000813 // Clear the insertion point to indicate we are in unreachable code.
814 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000815
Devang Patele9b8c0a2007-10-30 20:59:40 +0000816 // All break statements jump to NextBlock. If BreakContinueStack is non empty
817 // then reuse last ContinueBlock.
John McCallf1549f62010-07-06 01:34:17 +0000818 JumpDest OuterContinue;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000819 if (!BreakContinueStack.empty())
John McCallf1549f62010-07-06 01:34:17 +0000820 OuterContinue = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000821
John McCallf1549f62010-07-06 01:34:17 +0000822 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
Devang Patel51b09f22007-10-04 23:45:31 +0000823
824 // Emit switch body.
825 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Anders Carlssone4b6d342009-02-10 05:52:02 +0000827 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000828
Daniel Dunbar16f23572008-07-25 01:11:38 +0000829 // Update the default block in case explicit case range tests have
830 // been chained on top.
831 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000832
John McCallf1549f62010-07-06 01:34:17 +0000833 // If a default was never emitted:
Daniel Dunbar16f23572008-07-25 01:11:38 +0000834 if (!DefaultBlock->getParent()) {
John McCallf1549f62010-07-06 01:34:17 +0000835 // If we have cleanups, emit the default block so that there's a
836 // place to jump through the cleanups from.
837 if (ConditionScope.requiresCleanups()) {
838 EmitBlock(DefaultBlock);
839
840 // Otherwise, just forward the default block to the switch end.
841 } else {
842 DefaultBlock->replaceAllUsesWith(SwitchExit.Block);
843 delete DefaultBlock;
844 }
Daniel Dunbar16f23572008-07-25 01:11:38 +0000845 }
Devang Patel51b09f22007-10-04 23:45:31 +0000846
Daniel Dunbar16f23572008-07-25 01:11:38 +0000847 // Emit continuation.
John McCallf1549f62010-07-06 01:34:17 +0000848 EmitBlock(SwitchExit.Block, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000849
Devang Patel51b09f22007-10-04 23:45:31 +0000850 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000851 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000852}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000853
Chris Lattner2819fa82009-04-26 17:57:12 +0000854static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +0000855SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000856 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000857 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000859 while (*Constraint) {
860 switch (*Constraint) {
861 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000862 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000863 break;
864 // Ignore these
865 case '*':
866 case '?':
867 case '!':
868 break;
869 case 'g':
870 Result += "imr";
871 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000872 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000873 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000874 "Must pass output names to constraints with a symbolic name");
875 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +0000876 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000877 &(*OutCons)[0],
878 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000879 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000880 Result += llvm::utostr(Index);
881 break;
882 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000883 }
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000885 Constraint++;
886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000888 return Result;
889}
890
Anders Carlsson63471722009-01-11 19:32:54 +0000891llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
Daniel Dunbarb84e8a62009-05-04 06:56:16 +0000892 const TargetInfo::ConstraintInfo &Info,
Anders Carlsson63471722009-01-11 19:32:54 +0000893 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000894 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000895 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +0000896 if (Info.allowsRegister() || !Info.allowsMemory()) {
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000897 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType())) {
Anders Carlsson63471722009-01-11 19:32:54 +0000898 Arg = EmitScalarExpr(InputExpr);
899 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000900 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000901 LValue Dest = EmitLValue(InputExpr);
902
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000903 const llvm::Type *Ty = ConvertType(InputExpr->getType());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000904 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
905 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000906 Ty = llvm::IntegerType::get(VMContext, Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000907 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000909 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
910 } else {
911 Arg = Dest.getAddress();
912 ConstraintStr += '*';
913 }
Anders Carlsson63471722009-01-11 19:32:54 +0000914 }
915 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000916 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000917 LValue Dest = EmitLValue(InputExpr);
918 Arg = Dest.getAddress();
919 ConstraintStr += '*';
920 }
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Anders Carlsson63471722009-01-11 19:32:54 +0000922 return Arg;
923}
924
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000925void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000926 // Analyze the asm string to decompose it into its pieces. We know that Sema
927 // has already done this, so it is guaranteed to be successful.
928 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000929 unsigned DiagOffs;
930 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Chris Lattner458cd9c2009-03-10 23:21:44 +0000932 // Assemble the pieces into the final asm string.
933 std::string AsmString;
934 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
935 if (Pieces[i].isString())
936 AsmString += Pieces[i].getString();
937 else if (Pieces[i].getModifier() == '\0')
938 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
939 else
940 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
941 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Chris Lattner481fef92009-05-03 07:05:00 +0000944 // Get all the output and input constraints together.
945 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
946 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
947
Mike Stump1eb44332009-09-09 15:08:12 +0000948 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000949 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
950 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000951 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
952 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +0000953 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +0000954 }
955
Chris Lattner481fef92009-05-03 07:05:00 +0000956 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
957 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
958 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000959 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
960 S.getNumOutputs(), Info);
961 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +0000962 InputConstraintInfos.push_back(Info);
963 }
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000965 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattnerede9d902009-05-03 07:53:25 +0000967 std::vector<LValue> ResultRegDests;
968 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000969 std::vector<const llvm::Type *> ResultRegTypes;
970 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000971 std::vector<const llvm::Type*> ArgTypes;
972 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000973
974 // Keep track of inout constraints.
975 std::string InOutConstraints;
976 std::vector<llvm::Value*> InOutArgs;
977 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000978
Mike Stump1eb44332009-09-09 15:08:12 +0000979 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000980 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +0000981
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000982 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000983 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000984 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner810f6d52009-03-13 17:38:01 +0000986 const Expr *OutExpr = S.getOutputExpr(i);
987 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chris Lattner810f6d52009-03-13 17:38:01 +0000989 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +0000990 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000991 Constraints += ',';
992
Chris Lattnera077b5c2009-05-03 08:21:20 +0000993 // If this is a register output, then make the inline asm return it
994 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +0000995 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000996 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +0000997 ResultRegQualTys.push_back(OutExpr->getType());
998 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000999 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1000 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattnera077b5c2009-05-03 08:21:20 +00001002 // If this output is tied to an input, and if the input is larger, then
1003 // we need to set the actual result type of the inline asm node to be the
1004 // same as the input type.
1005 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +00001006 unsigned InputNo;
1007 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1008 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001009 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001010 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001011 }
1012 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattnera077b5c2009-05-03 08:21:20 +00001014 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001015 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattnera077b5c2009-05-03 08:21:20 +00001017 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001018 if (getContext().getTypeSize(OutputType) < InputSize) {
1019 // Form the asm to return the value as a larger integer or fp type.
1020 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001021 }
1022 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001023 } else {
1024 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001025 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001026 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001027 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Chris Lattner44def072009-04-26 07:16:29 +00001030 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001031 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001032
Anders Carlssonfca93612009-08-04 18:18:36 +00001033 const Expr *InputExpr = S.getOutputExpr(i);
1034 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattner44def072009-04-26 07:16:29 +00001036 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001037 InOutConstraints += llvm::utostr(i);
1038 else
1039 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001040
Anders Carlssonfca93612009-08-04 18:18:36 +00001041 InOutArgTypes.push_back(Arg->getType());
1042 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001043 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001046 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001048 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1049 const Expr *InputExpr = S.getInputExpr(i);
1050
Chris Lattner481fef92009-05-03 07:05:00 +00001051 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1052
Chris Lattnerede9d902009-05-03 07:53:25 +00001053 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001054 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001056 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001057 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001058 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001059 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001060
Anders Carlsson63471722009-01-11 19:32:54 +00001061 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Chris Lattner4df4ee02009-05-03 07:27:51 +00001063 // If this input argument is tied to a larger output result, extend the
1064 // input to be the same size as the output. The LLVM backend wants to see
1065 // the input and output of a matching constraint be the same size. Note
1066 // that GCC does not define what the top bits are here. We use zext because
1067 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1068 if (Info.hasTiedOperand()) {
1069 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001070 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001071 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Chris Lattneraab64d02010-04-23 17:27:29 +00001073 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001074 getContext().getTypeSize(InputTy)) {
1075 // Use ptrtoint as appropriate so that we can do our extension.
1076 if (isa<llvm::PointerType>(Arg->getType()))
Chris Lattner77b89b82010-06-27 07:15:29 +00001077 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001078 const llvm::Type *OutputTy = ConvertType(OutputType);
1079 if (isa<llvm::IntegerType>(OutputTy))
1080 Arg = Builder.CreateZExt(Arg, OutputTy);
1081 else
1082 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001083 }
1084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
1086
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001087 ArgTypes.push_back(Arg->getType());
1088 Args.push_back(Arg);
1089 Constraints += InputConstraint;
1090 }
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Anders Carlssonf39a4212008-02-05 20:01:53 +00001092 // Append the "input" part of inout constraints last.
1093 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1094 ArgTypes.push_back(InOutArgTypes[i]);
1095 Args.push_back(InOutArgs[i]);
1096 }
1097 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001099 // Clobbers
1100 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001101 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001102
Anders Carlsson83c021c2010-01-30 19:12:25 +00001103 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Anders Carlssonea041752008-02-06 00:11:32 +00001105 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001106 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Anders Carlssonea041752008-02-06 00:11:32 +00001108 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001109 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001110 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001111 }
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001113 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001114 std::string MachineClobbers = Target.getClobbers();
1115 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001116 if (!Constraints.empty())
1117 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001118 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001119 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001120
1121 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001122 if (ResultRegTypes.empty())
Owen Anderson0032b272009-08-13 21:57:51 +00001123 ResultType = llvm::Type::getVoidTy(VMContext);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001124 else if (ResultRegTypes.size() == 1)
1125 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001126 else
Owen Anderson47a434f2009-08-05 23:18:46 +00001127 ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
1129 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001130 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001131
1132 llvm::InlineAsm *IA =
1133 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001134 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001135 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001136 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001138 // Slap the source location of the inline asm into a !srcloc metadata on the
1139 // call.
1140 unsigned LocID = S.getAsmString()->getLocStart().getRawEncoding();
1141 llvm::Value *LocIDC =
Chris Lattner77b89b82010-06-27 07:15:29 +00001142 llvm::ConstantInt::get(Int32Ty, LocID);
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001143 Result->setMetadata("srcloc", llvm::MDNode::get(VMContext, &LocIDC, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Chris Lattnera077b5c2009-05-03 08:21:20 +00001145 // Extract all of the register value results from the asm.
1146 std::vector<llvm::Value*> RegResults;
1147 if (ResultRegTypes.size() == 1) {
1148 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001149 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001150 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001151 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001152 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001153 }
1154 }
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Chris Lattnera077b5c2009-05-03 08:21:20 +00001156 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1157 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Chris Lattnera077b5c2009-05-03 08:21:20 +00001159 // If the result type of the LLVM IR asm doesn't match the result type of
1160 // the expression, do the conversion.
1161 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1162 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001163
1164 // Truncate the integer result to the right size, note that TruncTy can be
1165 // a pointer.
1166 if (TruncTy->isFloatingPointTy())
1167 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001168 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001169 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1170 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext,
1171 (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001172 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001173 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1174 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1175 Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext,
1176 (unsigned)TmpSize));
1177 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1178 } else if (TruncTy->isIntegerTy()) {
1179 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001180 }
1181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Chris Lattnera077b5c2009-05-03 08:21:20 +00001183 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1184 ResultRegQualTys[i]);
1185 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001186}