blob: 22c154ad1e2660da1025c8f5cb9988a62e39d805 [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.
Benjamin Kramer89cf2e32010-05-23 20:57:46 +000082 // We can't erase blocks with an associated cleanup size here since the
83 // memory might be reused, leaving the old cleanup info pointing at a new
84 // block.
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000085 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
Benjamin Kramer92b9bd92010-05-23 20:00:44 +000086 if (CurBB->empty() && CurBB->use_empty() && !BlockScopes.count(CurBB)) {
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000087 CurBB->eraseFromParent();
88 Builder.ClearInsertionPoint();
89 }
Reid Spencer5f016e22007-07-11 17:01:13 +000090 }
91 break;
Mike Stump1eb44332009-09-09 15:08:12 +000092 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000093 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000094
95 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
96 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
97 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
98 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +0000101
Devang Patel51b09f22007-10-04 23:45:31 +0000102 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000103 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000104
105 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000106 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000107 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000108 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000109 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
110 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000111 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000112 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000113 break;
114 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000115 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000116 break;
117 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000118 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000119 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000120 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000121 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000122 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000123
124 case Stmt::CXXTryStmtClass:
125 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
126 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 }
128}
129
Daniel Dunbar09124252008-11-12 08:21:33 +0000130bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
131 switch (S->getStmtClass()) {
132 default: return false;
133 case Stmt::NullStmtClass: break;
134 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000135 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000136 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
137 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
138 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
139 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
140 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
141 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
142 }
143
144 return true;
145}
146
Chris Lattner33793202007-08-31 22:09:40 +0000147/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
148/// this captures the expression result of the last sub-statement and returns it
149/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000150RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
151 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000152 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
153 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Anders Carlssone896d982009-02-13 08:11:52 +0000155 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000156 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000157 DI->setLocation(S.getLBracLoc());
158 DI->EmitRegionStart(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000159 }
160
Anders Carlssonc71c8452009-02-07 23:50:39 +0000161 // Keep track of the current cleanup stack depth.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000162 CleanupScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattner33793202007-08-31 22:09:40 +0000164 for (CompoundStmt::const_body_iterator I = S.body_begin(),
165 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000167
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000168 if (DI) {
Devang Patelcd9199e2010-04-13 00:08:43 +0000169 DI->setLocation(S.getRBracLoc());
Devang Patelbbd9fa42009-10-06 18:36:08 +0000170 DI->EmitRegionEnd(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000171 }
172
Anders Carlsson17d28a32008-12-12 05:52:00 +0000173 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000174 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000175 RV = RValue::get(0);
176 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000177 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000178 // at the end of a statement expression, they yield the value of their
179 // subexpression. Handle this by walking through all labels we encounter,
180 // emitting them before we evaluate the subexpr.
181 const Stmt *LastStmt = S.body_back();
182 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
183 EmitLabel(*LS);
184 LastStmt = LS->getSubStmt();
185 }
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Anders Carlsson17d28a32008-12-12 05:52:00 +0000187 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Anders Carlsson17d28a32008-12-12 05:52:00 +0000189 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
190 }
191
Anders Carlsson17d28a32008-12-12 05:52:00 +0000192 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000193}
194
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000195void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
196 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000198 // If there is a cleanup stack, then we it isn't worth trying to
199 // simplify this block (we would need to remove it from the scope map
200 // and cleanup entry).
201 if (!CleanupEntries.empty())
202 return;
203
204 // Can only simplify direct branches.
205 if (!BI || !BI->isUnconditional())
206 return;
207
208 BB->replaceAllUsesWith(BI->getSuccessor(0));
209 BI->eraseFromParent();
210 BB->eraseFromParent();
211}
212
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000213void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000214 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
215
Daniel Dunbard57a8712008-11-11 09:41:28 +0000216 // Fall out of the current block (if necessary).
217 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000218
219 if (IsFinished && BB->use_empty()) {
220 delete BB;
221 return;
222 }
223
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000224 // If necessary, associate the block with the cleanup stack size.
225 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000226 // Check if the basic block has already been inserted.
227 BlockScopeMap::iterator I = BlockScopes.find(BB);
228 if (I != BlockScopes.end()) {
229 assert(I->second == CleanupEntries.size() - 1);
230 } else {
231 BlockScopes[BB] = CleanupEntries.size() - 1;
232 CleanupEntries.back().Blocks.push_back(BB);
233 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000234 }
Mike Stump1eb44332009-09-09 15:08:12 +0000235
John McCall839cbaa2010-04-21 10:29:06 +0000236 // Place the block after the current block, if possible, or else at
237 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000238 if (CurBB && CurBB->getParent())
239 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
John McCall839cbaa2010-04-21 10:29:06 +0000240 else
241 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 Builder.SetInsertPoint(BB);
243}
244
Daniel Dunbard57a8712008-11-11 09:41:28 +0000245void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
246 // Emit a branch from the current block to the target one if this
247 // was a real block. If this was just a fall-through block after a
248 // terminator, don't emit it.
249 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
250
251 if (!CurBB || CurBB->getTerminator()) {
252 // If there is no insert point or the previous block is already
253 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000254 } else {
255 // Otherwise, create a fall-through branch.
256 Builder.CreateBr(Target);
257 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000258
259 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000260}
261
Mike Stumpec9771d2009-02-08 09:22:19 +0000262void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000263 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000264}
265
266
267void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
268 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000269 EmitStmt(S.getSubStmt());
270}
271
272void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000273 // If this code is reachable then emit a stop point (if generating
274 // debug info). We have to do this ourselves because we are on the
275 // "simple" statement path.
276 if (HaveInsertPoint())
277 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000278
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000279 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000280}
281
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000282
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000283void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattner49c952f2009-11-06 18:10:47 +0000284 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000285 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
286 llvm::Type::getInt8PtrTy(VMContext),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000287 "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000288 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
289
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000290
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000291 // Get the basic block for the indirect goto.
292 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
293
294 // The first instruction in the block has to be the PHI for the switch dest,
295 // add an entry for this branch.
296 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
297
298 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000299}
300
Chris Lattner62b72f62008-11-11 07:24:28 +0000301void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 // C99 6.8.4.1: The first substatement is executed if the expression compares
303 // unequal to 0. The condition must be a scalar type.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000304 CleanupScope ConditionScope(*this);
305
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000306 if (S.getConditionVariable())
Douglas Gregor01234bb2009-11-24 16:43:22 +0000307 EmitLocalBlockVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner9bc47e22008-11-12 07:46:33 +0000309 // If the condition constant folds and can be elided, try to avoid emitting
310 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000311 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000312 // Figure out which block (then or else) is executed.
313 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000314 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000315 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chris Lattner62b72f62008-11-11 07:24:28 +0000317 // If the skipped block has no labels in it, just emit the executed block.
318 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000319 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000320 if (Executed) {
321 CleanupScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000322 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000323 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000324 return;
325 }
326 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000327
328 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
329 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000330 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
331 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
332 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000334 ElseBlock = createBasicBlock("if.else");
335 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000338 EmitBlock(ThenBlock);
339 {
340 CleanupScope ThenScope(*this);
341 EmitStmt(S.getThen());
342 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000343 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 // Emit the 'else' code if present.
346 if (const Stmt *Else = S.getElse()) {
347 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000348 {
349 CleanupScope ElseScope(*this);
350 EmitStmt(Else);
351 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000352 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 }
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000356 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000357}
358
359void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Emit the header for the loop, insert it, which will create an uncond br to
361 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000362 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000364
365 // Create an exit block for when the condition fails, create a block for the
366 // body of the loop.
367 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
368 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Douglas Gregor5656e142009-11-24 21:15:44 +0000369 llvm::BasicBlock *CleanupBlock = 0;
370 llvm::BasicBlock *EffectiveExitBlock = ExitBlock;
Mike Stump72cac2c2009-02-07 18:08:12 +0000371
372 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000373 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregor5656e142009-11-24 21:15:44 +0000375 // C++ [stmt.while]p2:
376 // When the condition of a while statement is a declaration, the
377 // scope of the variable that is declared extends from its point
378 // of declaration (3.3.2) to the end of the while statement.
379 // [...]
380 // The object created in a condition is destroyed and created
381 // with each iteration of the loop.
382 CleanupScope ConditionScope(*this);
383
384 if (S.getConditionVariable()) {
385 EmitLocalBlockVarDecl(*S.getConditionVariable());
386
387 // If this condition variable requires cleanups, create a basic
388 // block to handle those cleanups.
389 if (ConditionScope.requiresCleanups()) {
390 CleanupBlock = createBasicBlock("while.cleanup");
391 EffectiveExitBlock = CleanupBlock;
392 }
393 }
394
Mike Stump16b16202009-02-07 17:18:33 +0000395 // Evaluate the conditional in the while header. C99 6.8.5.1: The
396 // evaluation of the controlling expression takes place before each
397 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000399
Devang Patel2c30d8f2007-10-09 20:51:27 +0000400 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000402 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000403 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000404 if (C->isOne())
405 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000408 if (EmitBoolCondBranch)
Douglas Gregor5656e142009-11-24 21:15:44 +0000409 Builder.CreateCondBr(BoolCondVal, LoopBody, EffectiveExitBlock);
410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 // Emit the loop body.
Douglas Gregor5656e142009-11-24 21:15:44 +0000412 {
413 CleanupScope BodyScope(*this);
414 EmitBlock(LoopBody);
415 EmitStmt(S.getBody());
416 }
Chris Lattnerda138702007-07-16 21:28:45 +0000417
Mike Stump1eb44332009-09-09 15:08:12 +0000418 BreakContinueStack.pop_back();
419
Douglas Gregor5656e142009-11-24 21:15:44 +0000420 if (CleanupBlock) {
421 // If we have a cleanup block, jump there to perform cleanups
422 // before looping.
423 EmitBranch(CleanupBlock);
424
425 // Emit the cleanup block, performing cleanups for the condition
426 // and then jumping to either the loop header or the exit block.
427 EmitBlock(CleanupBlock);
428 ConditionScope.ForceCleanup();
429 Builder.CreateCondBr(BoolCondVal, LoopHeader, ExitBlock);
430 } else {
431 // Cycle to the condition.
432 EmitBranch(LoopHeader);
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000436 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000437
Douglas Gregor5656e142009-11-24 21:15:44 +0000438
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000439 // The LoopHeader typically is just a branch if we skipped emitting
440 // a branch, try to erase it.
Douglas Gregor5656e142009-11-24 21:15:44 +0000441 if (!EmitBoolCondBranch && !CleanupBlock)
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000442 SimplifyForwardingBlocks(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000443}
444
445void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // Emit the body for the loop, insert it, which will create an uncond br to
447 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000448 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
449 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000451
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000452 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Chris Lattnerda138702007-07-16 21:28:45 +0000454 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000455 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // Emit the body of the loop into the block.
458 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Anders Carlssone4b6d342009-02-10 05:52:02 +0000460 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattnerda138702007-07-16 21:28:45 +0000462 EmitBlock(DoCond);
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
465 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // Evaluate the conditional in the while header.
468 // C99 6.8.5p2/p4: The first substatement is executed if the expression
469 // compares unequal to 0. The condition must be a scalar type.
470 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000471
472 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
473 // to correctly handle break/continue though.
474 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000475 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000476 if (C->isZero())
477 EmitBoolCondBranch = false;
478
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000480 if (EmitBoolCondBranch)
481 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 // Emit the exit block.
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000484 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000485
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000486 // The DoCond block typically is just a branch if we skipped
487 // emitting a branch, try to erase it.
488 if (!EmitBoolCondBranch)
489 SimplifyForwardingBlocks(DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490}
491
492void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000493 CleanupScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 // Evaluate the first part before the loop.
496 if (S.getInit())
497 EmitStmt(S.getInit());
498
499 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000500 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
501 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Douglas Gregord9752062009-11-25 01:51:31 +0000502 llvm::BasicBlock *IncBlock = 0;
503 llvm::BasicBlock *CondCleanup = 0;
504 llvm::BasicBlock *EffectiveExitBlock = AfterFor;
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 EmitBlock(CondBlock);
506
Douglas Gregord9752062009-11-25 01:51:31 +0000507 // Create a cleanup scope for the condition variable cleanups.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000508 CleanupScope ConditionScope(*this);
509
Douglas Gregord9752062009-11-25 01:51:31 +0000510 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000512 // If the for statement has a condition scope, emit the local variable
513 // declaration.
Douglas Gregord9752062009-11-25 01:51:31 +0000514 if (S.getConditionVariable()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000515 EmitLocalBlockVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000516
517 if (ConditionScope.requiresCleanups()) {
518 CondCleanup = createBasicBlock("for.cond.cleanup");
519 EffectiveExitBlock = CondCleanup;
520 }
521 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000522
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000524 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner31a09842008-11-12 08:04:58 +0000526 // C99 6.8.5p2/p4: The first substatement is executed if the expression
527 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000528 BoolCondVal = EvaluateExprAsBool(S.getCond());
529 Builder.CreateCondBr(BoolCondVal, ForBody, EffectiveExitBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
531 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 } else {
533 // Treat it as a non-zero constant. Don't even create a new block for the
534 // body, just fall into it.
535 }
536
Mike Stump1eb44332009-09-09 15:08:12 +0000537 // If the for loop doesn't have an increment we can just use the
Chris Lattnerda138702007-07-16 21:28:45 +0000538 // condition as the continue block.
539 llvm::BasicBlock *ContinueBlock;
540 if (S.getInc())
Douglas Gregord9752062009-11-25 01:51:31 +0000541 ContinueBlock = IncBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000542 else
Mike Stump1eb44332009-09-09 15:08:12 +0000543 ContinueBlock = CondBlock;
544
Chris Lattnerda138702007-07-16 21:28:45 +0000545 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000546 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000547
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 // If the condition is true, execute the body of the for stmt.
Devang Patelbbd9fa42009-10-06 18:36:08 +0000549 CGDebugInfo *DI = getDebugInfo();
550 if (DI) {
551 DI->setLocation(S.getSourceRange().getBegin());
552 DI->EmitRegionStart(CurFn, Builder);
553 }
Douglas Gregord9752062009-11-25 01:51:31 +0000554
555 {
556 // Create a separate cleanup scope for the body, in case it is not
557 // a compound statement.
558 CleanupScope BodyScope(*this);
559 EmitStmt(S.getBody());
560 }
Chris Lattnerda138702007-07-16 21:28:45 +0000561
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000563 if (S.getInc()) {
Douglas Gregord9752062009-11-25 01:51:31 +0000564 EmitBlock(IncBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000565 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Douglas Gregor45d3fe12010-05-21 18:36:48 +0000568 BreakContinueStack.pop_back();
569
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 // Finally, branch back up to the condition for the next iteration.
Douglas Gregord9752062009-11-25 01:51:31 +0000571 if (CondCleanup) {
572 // Branch to the cleanup block.
573 EmitBranch(CondCleanup);
574
575 // Emit the cleanup block, which branches back to the loop body or
576 // outside of the for statement once it is done.
577 EmitBlock(CondCleanup);
578 ConditionScope.ForceCleanup();
579 Builder.CreateCondBr(BoolCondVal, CondBlock, AfterFor);
580 } else
581 EmitBranch(CondBlock);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000582 if (DI) {
583 DI->setLocation(S.getSourceRange().getEnd());
584 DI->EmitRegionEnd(CurFn, Builder);
585 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000586
Chris Lattnerda138702007-07-16 21:28:45 +0000587 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000588 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000589}
590
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000591void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
592 if (RV.isScalar()) {
593 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
594 } else if (RV.isAggregate()) {
595 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
596 } else {
597 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
598 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000599 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000600}
601
Reid Spencer5f016e22007-07-11 17:01:13 +0000602/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
603/// if the function returns void, or may be missing one if the function returns
604/// non-void. Fun stuff :).
605void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 // Emit the result value, even if unused, to evalute the side effects.
607 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000609 // FIXME: Clean this up by using an LValue for ReturnTemp,
610 // EmitStoreThroughLValue, and EmitAnyExpr.
Douglas Gregord86c4772010-05-15 06:46:45 +0000611 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
612 !Target.useGlobalsForAutomaticVariables()) {
613 // Apply the named return value optimization for this return statement,
614 // which means doing nothing: the appropriate result has already been
615 // constructed into the NRVO variable.
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000616
617 // If there is an NRVO flag for this variable, set it to 1 into indicate
618 // that the cleanup code should not destroy the variable.
619 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) {
620 const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext);
621 llvm::Value *One = llvm::ConstantInt::get(BoolTy, 1);
622 Builder.CreateStore(One, NRVOFlag);
623 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000624 } else if (!ReturnValue) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000625 // Make sure not to return anything, but evaluate the expression
626 // for side effects.
627 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000628 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000630 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000631 } else if (FnRetTy->isReferenceType()) {
632 // If this function returns a reference, take the address of the expression
633 // rather than the value.
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000634 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
Douglas Gregor33fd1fc2010-03-24 23:14:04 +0000635 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000636 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000637 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000638 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000639 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000641 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 }
Eli Friedman144ac612008-05-22 01:22:33 +0000643
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000644 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000645}
646
647void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000648 // As long as debug info is modeled with instructions, we have to ensure we
649 // have a place to insert here and write the stop point here.
650 if (getDebugInfo()) {
651 EnsureInsertPoint();
652 EmitStopPoint(&S);
653 }
654
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000655 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
656 I != E; ++I)
657 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000658}
Chris Lattnerda138702007-07-16 21:28:45 +0000659
Daniel Dunbar09124252008-11-12 08:21:33 +0000660void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000661 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
662
Daniel Dunbar09124252008-11-12 08:21:33 +0000663 // If this code is reachable then emit a stop point (if generating
664 // debug info). We have to do this ourselves because we are on the
665 // "simple" statement path.
666 if (HaveInsertPoint())
667 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000668
Chris Lattnerda138702007-07-16 21:28:45 +0000669 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000670 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000671}
672
Daniel Dunbar09124252008-11-12 08:21:33 +0000673void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000674 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
675
Daniel Dunbar09124252008-11-12 08:21:33 +0000676 // If this code is reachable then emit a stop point (if generating
677 // debug info). We have to do this ourselves because we are on the
678 // "simple" statement path.
679 if (HaveInsertPoint())
680 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000681
Chris Lattnerda138702007-07-16 21:28:45 +0000682 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000683 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000684}
Devang Patel51b09f22007-10-04 23:45:31 +0000685
Devang Patelc049e4f2007-10-08 20:57:48 +0000686/// EmitCaseStmtRange - If case statement range is not too big then
687/// add multiple cases to switch instruction, one for each value within
688/// the range. If range is too big then emit "if" condition check.
689void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000690 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000691
Anders Carlsson51fe9962008-11-22 21:04:56 +0000692 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
693 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000694
Daniel Dunbar16f23572008-07-25 01:11:38 +0000695 // Emit the code for this case. We do this first to make sure it is
696 // properly chained from our predecessor before generating the
697 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000698 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000699 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
700 EmitStmt(S.getSubStmt());
701
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000702 // If range is empty, do nothing.
703 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
704 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000705
706 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000707 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000708 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
709 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000710 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000711 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000712 LHS++;
713 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000714 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000715 }
716
Daniel Dunbar16f23572008-07-25 01:11:38 +0000717 // The range is too big. Emit "if" condition into a new block,
718 // making sure to save and restore the current insertion point.
719 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000720
Daniel Dunbar16f23572008-07-25 01:11:38 +0000721 // Push this test onto the chain of range checks (which terminates
722 // in the default basic block). The switch's default will be changed
723 // to the top of this chain after switch emission is complete.
724 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000725 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000726
Daniel Dunbar16f23572008-07-25 01:11:38 +0000727 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
728 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000729
730 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000731 llvm::Value *Diff =
732 Builder.CreateSub(SwitchInsn->getCondition(),
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000733 llvm::ConstantInt::get(VMContext, LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000734 llvm::Value *Cond =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000735 Builder.CreateICmpULE(Diff,
736 llvm::ConstantInt::get(VMContext, Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000737 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
738
Daniel Dunbar16f23572008-07-25 01:11:38 +0000739 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000740 if (RestoreBB)
741 Builder.SetInsertPoint(RestoreBB);
742 else
743 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000744}
745
746void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
747 if (S.getRHS()) {
748 EmitCaseStmtRange(S);
749 return;
750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000752 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000753 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000754 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000755 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Chris Lattner5512f282009-03-04 04:46:18 +0000757 // Recursively emitting the statement is acceptable, but is not wonderful for
758 // code where we have many case statements nested together, i.e.:
759 // case 1:
760 // case 2:
761 // case 3: etc.
762 // Handling this recursively will create a new block for each case statement
763 // that falls through to the next case which is IR intensive. It also causes
764 // deep recursion which can run into stack depth limitations. Handle
765 // sequential non-range case statements specially.
766 const CaseStmt *CurCase = &S;
767 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
768
769 // Otherwise, iteratively add consequtive cases to this switch stmt.
770 while (NextCase && NextCase->getRHS() == 0) {
771 CurCase = NextCase;
772 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000773 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000774
775 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattner5512f282009-03-04 04:46:18 +0000778 // Normal default recursion for non-cases.
779 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000780}
781
782void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000783 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000784 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000785 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000786 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000787 EmitStmt(S.getSubStmt());
788}
789
790void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
Douglas Gregord3d53012009-11-24 17:07:59 +0000791 CleanupScope ConditionScope(*this);
792
793 if (S.getConditionVariable())
794 EmitLocalBlockVarDecl(*S.getConditionVariable());
795
Devang Patel51b09f22007-10-04 23:45:31 +0000796 llvm::Value *CondV = EmitScalarExpr(S.getCond());
797
798 // Handle nested switch statements.
799 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000800 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000801
Daniel Dunbar16f23572008-07-25 01:11:38 +0000802 // Create basic block to hold stuff that comes after switch
803 // statement. We also need to create a default block now so that
804 // explicit case ranges tests can have a place to jump to on
805 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000806 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
807 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000808 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
809 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000810
Daniel Dunbar09124252008-11-12 08:21:33 +0000811 // Clear the insertion point to indicate we are in unreachable code.
812 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000813
Devang Patele9b8c0a2007-10-30 20:59:40 +0000814 // All break statements jump to NextBlock. If BreakContinueStack is non empty
815 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000816 llvm::BasicBlock *ContinueBlock = 0;
817 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000818 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000819
Mike Stump3e9da662009-02-07 23:02:10 +0000820 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000821 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000822
823 // Emit switch body.
824 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Anders Carlssone4b6d342009-02-10 05:52:02 +0000826 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000827
Daniel Dunbar16f23572008-07-25 01:11:38 +0000828 // Update the default block in case explicit case range tests have
829 // been chained on top.
830 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Daniel Dunbar16f23572008-07-25 01:11:38 +0000832 // If a default was never emitted then reroute any jumps to it and
833 // discard.
834 if (!DefaultBlock->getParent()) {
835 DefaultBlock->replaceAllUsesWith(NextBlock);
836 delete DefaultBlock;
837 }
Devang Patel51b09f22007-10-04 23:45:31 +0000838
Daniel Dunbar16f23572008-07-25 01:11:38 +0000839 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000840 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000841
Devang Patel51b09f22007-10-04 23:45:31 +0000842 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000843 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000844}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000845
Chris Lattner2819fa82009-04-26 17:57:12 +0000846static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +0000847SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000848 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000849 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000851 while (*Constraint) {
852 switch (*Constraint) {
853 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000854 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000855 break;
856 // Ignore these
857 case '*':
858 case '?':
859 case '!':
860 break;
861 case 'g':
862 Result += "imr";
863 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000864 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000865 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000866 "Must pass output names to constraints with a symbolic name");
867 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +0000868 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000869 &(*OutCons)[0],
870 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000871 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000872 Result += llvm::utostr(Index);
873 break;
874 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000875 }
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000877 Constraint++;
878 }
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000880 return Result;
881}
882
Anders Carlsson63471722009-01-11 19:32:54 +0000883llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
Daniel Dunbarb84e8a62009-05-04 06:56:16 +0000884 const TargetInfo::ConstraintInfo &Info,
Anders Carlsson63471722009-01-11 19:32:54 +0000885 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000886 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000887 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +0000888 if (Info.allowsRegister() || !Info.allowsMemory()) {
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000889 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType())) {
Anders Carlsson63471722009-01-11 19:32:54 +0000890 Arg = EmitScalarExpr(InputExpr);
891 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000892 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000893 LValue Dest = EmitLValue(InputExpr);
894
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000895 const llvm::Type *Ty = ConvertType(InputExpr->getType());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000896 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
897 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000898 Ty = llvm::IntegerType::get(VMContext, Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000899 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000901 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
902 } else {
903 Arg = Dest.getAddress();
904 ConstraintStr += '*';
905 }
Anders Carlsson63471722009-01-11 19:32:54 +0000906 }
907 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000908 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000909 LValue Dest = EmitLValue(InputExpr);
910 Arg = Dest.getAddress();
911 ConstraintStr += '*';
912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Anders Carlsson63471722009-01-11 19:32:54 +0000914 return Arg;
915}
916
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000917void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000918 // Analyze the asm string to decompose it into its pieces. We know that Sema
919 // has already done this, so it is guaranteed to be successful.
920 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000921 unsigned DiagOffs;
922 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattner458cd9c2009-03-10 23:21:44 +0000924 // Assemble the pieces into the final asm string.
925 std::string AsmString;
926 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
927 if (Pieces[i].isString())
928 AsmString += Pieces[i].getString();
929 else if (Pieces[i].getModifier() == '\0')
930 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
931 else
932 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
933 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner481fef92009-05-03 07:05:00 +0000936 // Get all the output and input constraints together.
937 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
938 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
939
Mike Stump1eb44332009-09-09 15:08:12 +0000940 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000941 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
942 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000943 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
944 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +0000945 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +0000946 }
947
Chris Lattner481fef92009-05-03 07:05:00 +0000948 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
949 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
950 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000951 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
952 S.getNumOutputs(), Info);
953 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +0000954 InputConstraintInfos.push_back(Info);
955 }
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000957 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Chris Lattnerede9d902009-05-03 07:53:25 +0000959 std::vector<LValue> ResultRegDests;
960 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000961 std::vector<const llvm::Type *> ResultRegTypes;
962 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000963 std::vector<const llvm::Type*> ArgTypes;
964 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000965
966 // Keep track of inout constraints.
967 std::string InOutConstraints;
968 std::vector<llvm::Value*> InOutArgs;
969 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000970
Mike Stump1eb44332009-09-09 15:08:12 +0000971 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000972 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +0000973
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000974 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000975 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000976 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Chris Lattner810f6d52009-03-13 17:38:01 +0000978 const Expr *OutExpr = S.getOutputExpr(i);
979 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner810f6d52009-03-13 17:38:01 +0000981 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +0000982 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000983 Constraints += ',';
984
Chris Lattnera077b5c2009-05-03 08:21:20 +0000985 // If this is a register output, then make the inline asm return it
986 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +0000987 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000988 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +0000989 ResultRegQualTys.push_back(OutExpr->getType());
990 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000991 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
992 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattnera077b5c2009-05-03 08:21:20 +0000994 // If this output is tied to an input, and if the input is larger, then
995 // we need to set the actual result type of the inline asm node to be the
996 // same as the input type.
997 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +0000998 unsigned InputNo;
999 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1000 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001001 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001002 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001003 }
1004 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattnera077b5c2009-05-03 08:21:20 +00001006 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001007 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattnera077b5c2009-05-03 08:21:20 +00001009 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001010 if (getContext().getTypeSize(OutputType) < InputSize) {
1011 // Form the asm to return the value as a larger integer or fp type.
1012 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001013 }
1014 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001015 } else {
1016 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001017 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001018 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001019 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001020 }
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattner44def072009-04-26 07:16:29 +00001022 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001023 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001024
Anders Carlssonfca93612009-08-04 18:18:36 +00001025 const Expr *InputExpr = S.getOutputExpr(i);
1026 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner44def072009-04-26 07:16:29 +00001028 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001029 InOutConstraints += llvm::utostr(i);
1030 else
1031 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001032
Anders Carlssonfca93612009-08-04 18:18:36 +00001033 InOutArgTypes.push_back(Arg->getType());
1034 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001035 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001038 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001040 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1041 const Expr *InputExpr = S.getInputExpr(i);
1042
Chris Lattner481fef92009-05-03 07:05:00 +00001043 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1044
Chris Lattnerede9d902009-05-03 07:53:25 +00001045 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001046 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001048 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001049 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001050 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001051 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001052
Anders Carlsson63471722009-01-11 19:32:54 +00001053 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Chris Lattner4df4ee02009-05-03 07:27:51 +00001055 // If this input argument is tied to a larger output result, extend the
1056 // input to be the same size as the output. The LLVM backend wants to see
1057 // the input and output of a matching constraint be the same size. Note
1058 // that GCC does not define what the top bits are here. We use zext because
1059 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1060 if (Info.hasTiedOperand()) {
1061 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001062 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001063 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chris Lattneraab64d02010-04-23 17:27:29 +00001065 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001066 getContext().getTypeSize(InputTy)) {
1067 // Use ptrtoint as appropriate so that we can do our extension.
1068 if (isa<llvm::PointerType>(Arg->getType()))
1069 Arg = Builder.CreatePtrToInt(Arg,
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001070 llvm::IntegerType::get(VMContext, LLVMPointerWidth));
Chris Lattneraab64d02010-04-23 17:27:29 +00001071 const llvm::Type *OutputTy = ConvertType(OutputType);
1072 if (isa<llvm::IntegerType>(OutputTy))
1073 Arg = Builder.CreateZExt(Arg, OutputTy);
1074 else
1075 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001076 }
1077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
1079
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001080 ArgTypes.push_back(Arg->getType());
1081 Args.push_back(Arg);
1082 Constraints += InputConstraint;
1083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Anders Carlssonf39a4212008-02-05 20:01:53 +00001085 // Append the "input" part of inout constraints last.
1086 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1087 ArgTypes.push_back(InOutArgTypes[i]);
1088 Args.push_back(InOutArgs[i]);
1089 }
1090 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001092 // Clobbers
1093 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001094 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001095
Anders Carlsson83c021c2010-01-30 19:12:25 +00001096 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Anders Carlssonea041752008-02-06 00:11:32 +00001098 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001099 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Anders Carlssonea041752008-02-06 00:11:32 +00001101 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001102 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001103 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001104 }
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001106 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001107 std::string MachineClobbers = Target.getClobbers();
1108 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001109 if (!Constraints.empty())
1110 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001111 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001112 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001113
1114 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001115 if (ResultRegTypes.empty())
Owen Anderson0032b272009-08-13 21:57:51 +00001116 ResultType = llvm::Type::getVoidTy(VMContext);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001117 else if (ResultRegTypes.size() == 1)
1118 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001119 else
Owen Anderson47a434f2009-08-05 23:18:46 +00001120 ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001121
1122 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001123 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001124
1125 llvm::InlineAsm *IA =
1126 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001127 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001128 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001129 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001131 // Slap the source location of the inline asm into a !srcloc metadata on the
1132 // call.
1133 unsigned LocID = S.getAsmString()->getLocStart().getRawEncoding();
1134 llvm::Value *LocIDC =
1135 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LocID);
1136 Result->setMetadata("srcloc", llvm::MDNode::get(VMContext, &LocIDC, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Chris Lattnera077b5c2009-05-03 08:21:20 +00001138 // Extract all of the register value results from the asm.
1139 std::vector<llvm::Value*> RegResults;
1140 if (ResultRegTypes.size() == 1) {
1141 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001142 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001143 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001144 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001145 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001146 }
1147 }
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattnera077b5c2009-05-03 08:21:20 +00001149 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1150 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Chris Lattnera077b5c2009-05-03 08:21:20 +00001152 // If the result type of the LLVM IR asm doesn't match the result type of
1153 // the expression, do the conversion.
1154 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1155 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001156
1157 // Truncate the integer result to the right size, note that TruncTy can be
1158 // a pointer.
1159 if (TruncTy->isFloatingPointTy())
1160 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001161 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001162 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1163 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext,
1164 (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001165 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001166 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1167 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1168 Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext,
1169 (unsigned)TmpSize));
1170 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1171 } else if (TruncTy->isIntegerTy()) {
1172 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001173 }
1174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattnera077b5c2009-05-03 08:21:20 +00001176 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1177 ResultRegQualTys[i]);
1178 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001179}