blob: ece4aeeff897bdf82c2e80d9aa137ef9bfe5ca02 [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"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "llvm/InlineAsm.h"
20#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22using namespace CodeGen;
23
24//===----------------------------------------------------------------------===//
25// Statement Emission
26//===----------------------------------------------------------------------===//
27
28void CodeGenFunction::EmitStmt(const Stmt *S) {
29 assert(S && "Null statement?");
30
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000031 // Generate stoppoints if we are emitting debug info.
32 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
33 // executable code. So do not generate a stoppoint for that.
34 CGDebugInfo *DI = CGM.getDebugInfo();
35 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
Daniel Dunbar66031a52008-10-17 16:15:48 +000036 DI->setLocation(S->getLocStart());
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000037 DI->EmitStopPoint(CurFn, Builder);
38 }
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040 switch (S->getStmtClass()) {
41 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000042 // Must be an expression in a stmt context. Emit the value (to get
43 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000044 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000045 if (!hasAggregateLLVMType(E->getType()))
46 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000047 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000048 EmitComplexExpr(E);
49 else
50 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000051 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000052 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000053 }
54 break;
55 case Stmt::NullStmtClass: break;
56 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
57 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
58 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000059 case Stmt::IndirectGotoStmtClass:
60 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000061
62 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
63 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
64 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
65 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
66
67 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
68 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000069
Daniel Dunbara4275d12008-10-02 18:02:06 +000070 case Stmt::BreakStmtClass:
71 // FIXME: Implement break in @try or @catch blocks.
72 if (!ObjCEHStack.empty()) {
73 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
74 return;
75 }
76 EmitBreakStmt();
77 break;
78
79 case Stmt::ContinueStmtClass:
80 // FIXME: Implement continue in @try or @catch blocks.
81 if (!ObjCEHStack.empty()) {
82 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
83 return;
84 }
85 EmitContinueStmt();
86 break;
87
Devang Patel51b09f22007-10-04 23:45:31 +000088 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
89 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
90 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000091 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000092
93 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000094 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
95 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000096 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000097 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
98 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000100 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101 break;
102 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000103 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000104 break;
105 case Stmt::ObjCAtSynchronizedStmtClass:
106 ErrorUnsupported(S, "@synchronized statement");
107 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000108 case Stmt::ObjCForCollectionStmtClass:
109 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000110 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
112}
113
Chris Lattner33793202007-08-31 22:09:40 +0000114/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
115/// this captures the expression result of the last sub-statement and returns it
116/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000117RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
118 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000120 CGDebugInfo *DI = CGM.getDebugInfo();
121 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000122 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000123 DI->EmitRegionStart(CurFn, Builder);
124 }
125
Chris Lattner33793202007-08-31 22:09:40 +0000126 for (CompoundStmt::const_body_iterator I = S.body_begin(),
127 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000129
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000130 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000131 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Chris Lattner33793202007-08-31 22:09:40 +0000135 if (!GetLast)
136 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000137
Chris Lattner91d723d2008-07-26 20:23:23 +0000138 // We have to special case labels here. They are statements, but when put at
139 // the end of a statement expression, they yield the value of their
140 // subexpression. Handle this by walking through all labels we encounter,
141 // emitting them before we evaluate the subexpr.
142 const Stmt *LastStmt = S.body_back();
143 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
144 EmitLabel(*LS);
145 LastStmt = LS->getSubStmt();
146 }
147
148 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000149}
150
151void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
152 // Emit a branch from this block to the next one if this was a real block. If
153 // this was just a fall-through block after a terminator, don't emit it.
154 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
155
156 if (LastBB->getTerminator()) {
157 // If the previous block is already terminated, don't touch it.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000158 } else if (LastBB->empty() && isDummyBlock(LastBB)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 // If the last block was an empty placeholder, remove it now.
160 // TODO: cache and reuse these.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000161 LastBB->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 } else {
163 // Otherwise, create a fall-through branch.
164 Builder.CreateBr(BB);
165 }
166 CurFn->getBasicBlockList().push_back(BB);
167 Builder.SetInsertPoint(BB);
168}
169
Chris Lattner91d723d2008-07-26 20:23:23 +0000170void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000173}
174
175
176void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
177 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 EmitStmt(S.getSubStmt());
179}
180
181void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000182 // FIXME: Implement goto out in @try or @catch blocks.
183 if (!ObjCEHStack.empty()) {
184 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
185 return;
186 }
187
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
189
190 // Emit a block after the branch so that dead code after a goto has some place
191 // to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000192 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Reid Spencer5f016e22007-07-11 17:01:13 +0000193}
194
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000195void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000196 // FIXME: Implement indirect goto in @try or @catch blocks.
197 if (!ObjCEHStack.empty()) {
198 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
199 return;
200 }
201
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000202 // Emit initial switch which will be patched up later by
203 // EmitIndirectSwitches(). We need a default dest, so we use the
204 // current BB, but this is overwritten.
205 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
206 llvm::Type::Int32Ty,
207 "addr");
208 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
209 IndirectSwitches.push_back(I);
210
211 // Emit a block after the branch so that dead code after a goto has some place
212 // to go.
213 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
214}
215
Reid Spencer5f016e22007-07-11 17:01:13 +0000216void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000217 // FIXME: It would probably be nice for us to skip emission of if
218 // (0) code here.
219
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // C99 6.8.4.1: The first substatement is executed if the expression compares
221 // unequal to 0. The condition must be a scalar type.
222 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
223
Gabor Greif984d0b42008-04-06 20:42:52 +0000224 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
225 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000226 llvm::BasicBlock *ElseBlock = ContBlock;
227
228 if (S.getElse())
Gabor Greif984d0b42008-04-06 20:42:52 +0000229 ElseBlock = llvm::BasicBlock::Create("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000230
231 // Insert the conditional branch.
232 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
233
234 // Emit the 'then' code.
235 EmitBlock(ThenBlock);
236 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000237 llvm::BasicBlock *BB = Builder.GetInsertBlock();
238 if (isDummyBlock(BB)) {
239 BB->eraseFromParent();
240 Builder.SetInsertPoint(ThenBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000241 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000242 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000243 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000244
245 // Emit the 'else' code if present.
246 if (const Stmt *Else = S.getElse()) {
247 EmitBlock(ElseBlock);
248 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000249 llvm::BasicBlock *BB = Builder.GetInsertBlock();
250 if (isDummyBlock(BB)) {
251 BB->eraseFromParent();
252 Builder.SetInsertPoint(ElseBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000253 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000254 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000255 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 }
257
258 // Emit the continuation block for code after the if.
259 EmitBlock(ContBlock);
260}
261
262void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 // Emit the header for the loop, insert it, which will create an uncond br to
264 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000265 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 EmitBlock(LoopHeader);
267
268 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
269 // of the controlling expression takes place before each execution of the loop
270 // body.
271 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000272
273 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000275 bool EmitBoolCondBranch = true;
276 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
277 if (C->isOne())
278 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000279
280 // Create an exit block for when the condition fails, create a block for the
281 // body of the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000282 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
283 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000284
285 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000286 if (EmitBoolCondBranch)
287 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000288
289 // Store the blocks to use for break and continue.
290 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000291
292 // Emit the loop body.
293 EmitBlock(LoopBody);
294 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000295
296 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000297
298 // Cycle to the condition.
299 Builder.CreateBr(LoopHeader);
300
301 // Emit the exit block.
302 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000303
304 // If LoopHeader is a simple forwarding block then eliminate it.
305 if (!EmitBoolCondBranch
306 && &LoopHeader->front() == LoopHeader->getTerminator()) {
307 LoopHeader->replaceAllUsesWith(LoopBody);
308 LoopHeader->getTerminator()->eraseFromParent();
309 LoopHeader->eraseFromParent();
310 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000311}
312
313void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // Emit the body for the loop, insert it, which will create an uncond br to
315 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000316 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
317 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000319
Gabor Greif984d0b42008-04-06 20:42:52 +0000320 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000321
322 // Store the blocks to use for break and continue.
323 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000324
325 // Emit the body of the loop into the block.
326 EmitStmt(S.getBody());
327
Chris Lattnerda138702007-07-16 21:28:45 +0000328 BreakContinueStack.pop_back();
329
330 EmitBlock(DoCond);
331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
333 // after each execution of the loop body."
334
335 // Evaluate the conditional in the while header.
336 // C99 6.8.5p2/p4: The first substatement is executed if the expression
337 // compares unequal to 0. The condition must be a scalar type.
338 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000339
340 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
341 // to correctly handle break/continue though.
342 bool EmitBoolCondBranch = true;
343 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
344 if (C->isZero())
345 EmitBoolCondBranch = false;
346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000348 if (EmitBoolCondBranch)
349 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000350
351 // Emit the exit block.
352 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000353
354 // If DoCond is a simple forwarding block then eliminate it.
355 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
356 DoCond->replaceAllUsesWith(AfterDo);
357 DoCond->getTerminator()->eraseFromParent();
358 DoCond->eraseFromParent();
359 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000360}
361
362void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
364 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000365 // TODO: We could keep track of whether the loop body contains any
366 // break/continue statements and not create unnecessary blocks (like
367 // "afterfor" for a condless loop) if it doesn't.
368
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // Evaluate the first part before the loop.
370 if (S.getInit())
371 EmitStmt(S.getInit());
372
373 // Start the loop with a block that tests the condition.
Gabor Greif984d0b42008-04-06 20:42:52 +0000374 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
375 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000376
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 EmitBlock(CondBlock);
378
379 // Evaluate the condition if present. If not, treat it as a non-zero-constant
380 // according to 6.8.5.3p2, aka, true.
381 if (S.getCond()) {
382 // C99 6.8.5p2/p4: The first substatement is executed if the expression
383 // compares unequal to 0. The condition must be a scalar type.
384 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
385
386 // As long as the condition is true, iterate the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000387 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
389 EmitBlock(ForBody);
390 } else {
391 // Treat it as a non-zero constant. Don't even create a new block for the
392 // body, just fall into it.
393 }
394
Chris Lattnerda138702007-07-16 21:28:45 +0000395 // If the for loop doesn't have an increment we can just use the
396 // condition as the continue block.
397 llvm::BasicBlock *ContinueBlock;
398 if (S.getInc())
Gabor Greif984d0b42008-04-06 20:42:52 +0000399 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000400 else
401 ContinueBlock = CondBlock;
402
403 // Store the blocks to use for break and continue.
404 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
405
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 // If the condition is true, execute the body of the for stmt.
407 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000408
409 BreakContinueStack.pop_back();
410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000412 if (S.getInc()) {
413 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000414 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000415 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000416
417 // Finally, branch back up to the condition for the next iteration.
418 Builder.CreateBr(CondBlock);
419
Chris Lattnerda138702007-07-16 21:28:45 +0000420 // Emit the fall-through block.
421 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000422}
423
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000424void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
425 if (RV.isScalar()) {
426 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
427 } else if (RV.isAggregate()) {
428 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
429 } else {
430 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
431 }
432 Builder.CreateBr(ReturnBlock);
433
434 // Emit a block after the branch so that dead code after a return has some
435 // place to go.
436 EmitBlock(llvm::BasicBlock::Create());
437}
438
Reid Spencer5f016e22007-07-11 17:01:13 +0000439/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
440/// if the function returns void, or may be missing one if the function returns
441/// non-void. Fun stuff :).
442void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // Emit the result value, even if unused, to evalute the side effects.
444 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000445
446 // FIXME: Clean this up by using an LValue for ReturnTemp,
447 // EmitStoreThroughLValue, and EmitAnyExpr.
448 if (!ReturnValue) {
449 // Make sure not to return anything, but evaluate the expression
450 // for side effects.
451 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000452 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000454 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000455 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000456 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000457 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000458 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000460 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 }
Eli Friedman144ac612008-05-22 01:22:33 +0000462
Daniel Dunbar898d5082008-09-30 01:06:03 +0000463 if (!ObjCEHStack.empty()) {
464 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
465 e = ObjCEHStack.rend(); i != e; ++i) {
466 llvm::BasicBlock *ReturnPad = llvm::BasicBlock::Create("return.pad");
467 EmitJumpThroughFinally(*i, ReturnPad);
468 EmitBlock(ReturnPad);
469 }
470 }
471
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000472 Builder.CreateBr(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000473
474 // Emit a block after the branch so that dead code after a return has some
475 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000476 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000477}
478
479void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000480 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
481 I != E; ++I)
482 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000483}
Chris Lattnerda138702007-07-16 21:28:45 +0000484
485void CodeGenFunction::EmitBreakStmt() {
486 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
487
488 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
489 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000490 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000491}
492
493void CodeGenFunction::EmitContinueStmt() {
494 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
495
496 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
497 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000498 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000499}
Devang Patel51b09f22007-10-04 23:45:31 +0000500
Devang Patelc049e4f2007-10-08 20:57:48 +0000501/// EmitCaseStmtRange - If case statement range is not too big then
502/// add multiple cases to switch instruction, one for each value within
503/// the range. If range is too big then emit "if" condition check.
504void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000505 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000506
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000507 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
508 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
509
Daniel Dunbar16f23572008-07-25 01:11:38 +0000510 // Emit the code for this case. We do this first to make sure it is
511 // properly chained from our predecessor before generating the
512 // switch machinery to enter this block.
513 StartBlock("sw.bb");
514 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
515 EmitStmt(S.getSubStmt());
516
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000517 // If range is empty, do nothing.
518 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
519 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000520
521 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000522 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000523 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
524 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000525 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000526 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
527 LHS++;
528 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000529 return;
530 }
531
Daniel Dunbar16f23572008-07-25 01:11:38 +0000532 // The range is too big. Emit "if" condition into a new block,
533 // making sure to save and restore the current insertion point.
534 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000535
Daniel Dunbar16f23572008-07-25 01:11:38 +0000536 // Push this test onto the chain of range checks (which terminates
537 // in the default basic block). The switch's default will be changed
538 // to the top of this chain after switch emission is complete.
539 llvm::BasicBlock *FalseDest = CaseRangeBlock;
540 CaseRangeBlock = llvm::BasicBlock::Create("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000541
Daniel Dunbar16f23572008-07-25 01:11:38 +0000542 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
543 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000544
545 // Emit range check.
546 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000547 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
548 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000549 llvm::Value *Cond =
550 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
551 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
552
Daniel Dunbar16f23572008-07-25 01:11:38 +0000553 // Restore the appropriate insertion point.
554 Builder.SetInsertPoint(RestoreBB);
Devang Patelc049e4f2007-10-08 20:57:48 +0000555}
556
557void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
558 if (S.getRHS()) {
559 EmitCaseStmtRange(S);
560 return;
561 }
562
563 StartBlock("sw.bb");
564 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000565 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
566 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal),
567 CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000568 EmitStmt(S.getSubStmt());
569}
570
571void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000572 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
573 assert(DefaultBlock->empty() && "EmitDefaultStmt: Default block already defined?");
574 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000575 EmitStmt(S.getSubStmt());
576}
577
578void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
579 llvm::Value *CondV = EmitScalarExpr(S.getCond());
580
581 // Handle nested switch statements.
582 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000583 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000584
Daniel Dunbar16f23572008-07-25 01:11:38 +0000585 // Create basic block to hold stuff that comes after switch
586 // statement. We also need to create a default block now so that
587 // explicit case ranges tests can have a place to jump to on
588 // failure.
589 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("sw.epilog");
590 llvm::BasicBlock *DefaultBlock = llvm::BasicBlock::Create("sw.default");
591 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
592 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000593
Eli Friedmand28a80d2008-05-12 16:08:04 +0000594 // Create basic block for body of switch
Daniel Dunbar16f23572008-07-25 01:11:38 +0000595 StartBlock("sw.body");
Eli Friedmand28a80d2008-05-12 16:08:04 +0000596
Devang Patele9b8c0a2007-10-30 20:59:40 +0000597 // All break statements jump to NextBlock. If BreakContinueStack is non empty
598 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000599 llvm::BasicBlock *ContinueBlock = NULL;
600 if (!BreakContinueStack.empty())
601 ContinueBlock = BreakContinueStack.back().ContinueBlock;
602 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
603
604 // Emit switch body.
605 EmitStmt(S.getBody());
606 BreakContinueStack.pop_back();
607
Daniel Dunbar16f23572008-07-25 01:11:38 +0000608 // Update the default block in case explicit case range tests have
609 // been chained on top.
610 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000611
Daniel Dunbar16f23572008-07-25 01:11:38 +0000612 // If a default was never emitted then reroute any jumps to it and
613 // discard.
614 if (!DefaultBlock->getParent()) {
615 DefaultBlock->replaceAllUsesWith(NextBlock);
616 delete DefaultBlock;
617 }
Devang Patel51b09f22007-10-04 23:45:31 +0000618
Daniel Dunbar16f23572008-07-25 01:11:38 +0000619 // Emit continuation.
620 EmitBlock(NextBlock);
621
Devang Patel51b09f22007-10-04 23:45:31 +0000622 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000623 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000624}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000625
Chris Lattner345f7202008-07-26 20:15:14 +0000626static std::string ConvertAsmString(const char *Start, unsigned NumOperands,
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000627 bool IsSimple, bool &Failed) {
628 Failed = false;
629
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000630 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000631 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000632 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000633 if (IsSimple) {
634 while (*Start) {
635 switch (*Start) {
636 default:
637 Result += *Start;
638 break;
639 case '$':
640 Result += "$$";
641 break;
642 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000643 Start++;
644 }
645
646 return Result;
647 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000648
649 while (*Start) {
650 switch (*Start) {
651 default:
652 Result += *Start;
653 break;
654 case '$':
655 Result += "$$";
656 break;
657 case '%':
658 // Escaped character
659 Start++;
660 if (!*Start) {
661 // FIXME: This should be caught during Sema.
662 assert(0 && "Trailing '%' in asm string.");
663 }
664
665 char EscapedChar = *Start;
666 if (EscapedChar == '%') {
667 // Escaped percentage sign.
668 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000669 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000670 // Generate an unique ID.
671 Result += llvm::utostr(AsmCounter);
672 } else if (isdigit(EscapedChar)) {
673 // %n - Assembler operand n
674 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000675 unsigned long n = strtoul(Start, &End, 10);
676 if (Start == End) {
677 // FIXME: This should be caught during Sema.
678 assert(0 && "Missing operand!");
679 } else if (n >= NumOperands) {
680 // FIXME: This should be caught during Sema.
681 assert(0 && "Operand number out of range!");
682 }
683
684 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000685 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000686 } else if (isalpha(EscapedChar)) {
687 char *End;
688
689 unsigned long n = strtoul(Start + 1, &End, 10);
690 if (Start == End) {
691 // FIXME: This should be caught during Sema.
692 assert(0 && "Missing operand!");
693 } else if (n >= NumOperands) {
694 // FIXME: This should be caught during Sema.
695 assert(0 && "Operand number out of range!");
696 }
697
698 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000699 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000700 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000701 Failed = true;
702 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000703 }
704 }
705 Start++;
706 }
707
708 return Result;
709}
710
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000711static std::string SimplifyConstraint(const char* Constraint,
712 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000713 std::string Result;
714
715 while (*Constraint) {
716 switch (*Constraint) {
717 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000718 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000719 break;
720 // Ignore these
721 case '*':
722 case '?':
723 case '!':
724 break;
725 case 'g':
726 Result += "imr";
727 break;
728 }
729
730 Constraint++;
731 }
732
733 return Result;
734}
735
736void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000737 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000738 std::string AsmString =
739 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
740 S.getAsmString()->getByteLength()).c_str(),
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000741 S.getNumOutputs() + S.getNumInputs(), S.isSimple(),
742 Failed);
743
744 if (Failed) {
745 ErrorUnsupported(&S, "asm string");
746 return;
747 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000748
749 std::string Constraints;
750
751 llvm::Value *ResultAddr = 0;
752 const llvm::Type *ResultType = llvm::Type::VoidTy;
753
754 std::vector<const llvm::Type*> ArgTypes;
755 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000756
757 // Keep track of inout constraints.
758 std::string InOutConstraints;
759 std::vector<llvm::Value*> InOutArgs;
760 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000761
762 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
763 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
764 S.getOutputConstraint(i)->getByteLength());
765
766 TargetInfo::ConstraintInfo Info;
767 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
768 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000769 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000770
771 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000772 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000773
774 LValue Dest = EmitLValue(S.getOutputExpr(i));
775 const llvm::Type *DestValueType =
776 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
777
778 // If the first output operand is not a memory dest, we'll
779 // make it the return value.
780 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000781 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000782 ResultAddr = Dest.getAddress();
783 ResultType = DestValueType;
784 Constraints += "=" + OutputConstraint;
785 } else {
786 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000787 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000788 if (i != 0)
789 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000790 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000791 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000792 }
793
794 if (Info & TargetInfo::CI_ReadWrite) {
795 // FIXME: This code should be shared with the code that handles inputs.
796 InOutConstraints += ',';
797
798 const Expr *InputExpr = S.getOutputExpr(i);
799 llvm::Value *Arg;
800 if ((Info & TargetInfo::CI_AllowsRegister) ||
801 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000802 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000803 Arg = EmitScalarExpr(InputExpr);
804 } else {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000805 ErrorUnsupported(&S, "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000806 }
807 } else {
808 LValue Dest = EmitLValue(InputExpr);
809 Arg = Dest.getAddress();
810 InOutConstraints += '*';
811 }
812
813 InOutArgTypes.push_back(Arg->getType());
814 InOutArgs.push_back(Arg);
815 InOutConstraints += OutputConstraint;
816 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000817 }
818
819 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
820
821 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
822 const Expr *InputExpr = S.getInputExpr(i);
823
824 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
825 S.getInputConstraint(i)->getByteLength());
826
827 TargetInfo::ConstraintInfo Info;
828 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000829 NumConstraints, Info);
830 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000831
832 if (i != 0 || S.getNumOutputs() > 0)
833 Constraints += ',';
834
835 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000836 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000837
838 llvm::Value *Arg;
839
840 if ((Info & TargetInfo::CI_AllowsRegister) ||
841 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000842 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000843 Arg = EmitScalarExpr(InputExpr);
844 } else {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000845 ErrorUnsupported(&S, "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000846 }
847 } else {
848 LValue Dest = EmitLValue(InputExpr);
849 Arg = Dest.getAddress();
850 Constraints += '*';
851 }
852
853 ArgTypes.push_back(Arg->getType());
854 Args.push_back(Arg);
855 Constraints += InputConstraint;
856 }
857
Anders Carlssonf39a4212008-02-05 20:01:53 +0000858 // Append the "input" part of inout constraints last.
859 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
860 ArgTypes.push_back(InOutArgTypes[i]);
861 Args.push_back(InOutArgs[i]);
862 }
863 Constraints += InOutConstraints;
864
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000865 // Clobbers
866 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
867 std::string Clobber(S.getClobber(i)->getStrData(),
868 S.getClobber(i)->getByteLength());
869
870 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
871
Anders Carlssonea041752008-02-06 00:11:32 +0000872 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000873 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000874
875 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000876 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000877 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000878 }
879
880 // Add machine specific clobbers
881 if (const char *C = Target.getClobbers()) {
882 if (!Constraints.empty())
883 Constraints += ',';
884 Constraints += C;
885 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000886
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000887 const llvm::FunctionType *FTy =
888 llvm::FunctionType::get(ResultType, ArgTypes, false);
889
890 llvm::InlineAsm *IA =
891 llvm::InlineAsm::get(FTy, AsmString, Constraints,
892 S.isVolatile() || S.getNumOutputs() == 0);
893 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000894 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000895 Builder.CreateStore(Result, ResultAddr);
896}