blob: daad06261961f98e1995abb5a7775fd3904b0f29 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "CodeGenFunction.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000019#include "llvm/InlineAsm.h"
20#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Gupta40e56a12008-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) {
36 if (S->getLocStart().isValid()) {
37 DI->setLocation(S->getLocStart());
38 }
39
40 DI->EmitStopPoint(CurFn, Builder);
41 }
42
Chris Lattner4b009652007-07-25 00:24:17 +000043 switch (S->getStmtClass()) {
44 default:
Chris Lattner35055b82007-08-26 22:58:05 +000045 // Must be an expression in a stmt context. Emit the value (to get
46 // side-effects) and ignore the result.
Chris Lattner4b009652007-07-25 00:24:17 +000047 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner35055b82007-08-26 22:58:05 +000048 if (!hasAggregateLLVMType(E->getType()))
49 EmitScalarExpr(E);
Chris Lattnerde0908b2008-04-04 16:54:41 +000050 else if (E->getType()->isAnyComplexType())
Chris Lattner35055b82007-08-26 22:58:05 +000051 EmitComplexExpr(E);
52 else
53 EmitAggExpr(E, 0, false);
Chris Lattner4b009652007-07-25 00:24:17 +000054 } else {
Daniel Dunbar9503b782008-08-16 00:56:44 +000055 ErrorUnsupported(S, "statement");
Chris Lattner4b009652007-07-25 00:24:17 +000056 }
57 break;
58 case Stmt::NullStmtClass: break;
59 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
60 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
61 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar879788d2008-08-04 16:51:22 +000062 case Stmt::IndirectGotoStmtClass:
63 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Chris Lattner4b009652007-07-25 00:24:17 +000064
65 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
66 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
67 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
68 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
69
70 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
71 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
72
73 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
74 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Devang Patele58e0802007-10-04 23:45:31 +000075 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
76 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
77 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000078 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Chris Lattner4b009652007-07-25 00:24:17 +000079 }
80}
81
Chris Lattnerea6cdd72007-08-31 22:09:40 +000082/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
83/// this captures the expression result of the last sub-statement and returns it
84/// (for use by the statement expression extension).
Chris Lattnere24c4cf2007-08-31 22:49:20 +000085RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
86 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner4b009652007-07-25 00:24:17 +000087 // FIXME: handle vla's etc.
Sanjiv Gupta93eb8252008-05-25 05:15:42 +000088 CGDebugInfo *DI = CGM.getDebugInfo();
89 if (DI) {
Chris Lattnera23eb7b2008-07-26 20:15:14 +000090 if (S.getLBracLoc().isValid())
Sanjiv Gupta93eb8252008-05-25 05:15:42 +000091 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +000092 DI->EmitRegionStart(CurFn, Builder);
93 }
94
Chris Lattnerea6cdd72007-08-31 22:09:40 +000095 for (CompoundStmt::const_body_iterator I = S.body_begin(),
96 E = S.body_end()-GetLast; I != E; ++I)
Chris Lattner4b009652007-07-25 00:24:17 +000097 EmitStmt(*I);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000098
Sanjiv Gupta93eb8252008-05-25 05:15:42 +000099 if (DI) {
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000100 if (S.getRBracLoc().isValid())
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000101 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000102 DI->EmitRegionEnd(CurFn, Builder);
103 }
104
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000105 if (!GetLast)
106 return RValue::get(0);
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000107
Chris Lattner09cee852008-07-26 20:23:23 +0000108 // We have to special case labels here. They are statements, but when put at
109 // the end of a statement expression, they yield the value of their
110 // subexpression. Handle this by walking through all labels we encounter,
111 // emitting them before we evaluate the subexpr.
112 const Stmt *LastStmt = S.body_back();
113 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
114 EmitLabel(*LS);
115 LastStmt = LS->getSubStmt();
116 }
117
118 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000119}
120
121void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
122 // Emit a branch from this block to the next one if this was a real block. If
123 // this was just a fall-through block after a terminator, don't emit it.
124 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
125
126 if (LastBB->getTerminator()) {
127 // If the previous block is already terminated, don't touch it.
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000128 } else if (LastBB->empty() && isDummyBlock(LastBB)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000129 // If the last block was an empty placeholder, remove it now.
130 // TODO: cache and reuse these.
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000131 LastBB->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000132 } else {
133 // Otherwise, create a fall-through branch.
134 Builder.CreateBr(BB);
135 }
136 CurFn->getBasicBlockList().push_back(BB);
137 Builder.SetInsertPoint(BB);
138}
139
Chris Lattner09cee852008-07-26 20:23:23 +0000140void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000141 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Chris Lattner4b009652007-07-25 00:24:17 +0000142 EmitBlock(NextBB);
Chris Lattner09cee852008-07-26 20:23:23 +0000143}
144
145
146void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
147 EmitLabel(S);
Chris Lattner4b009652007-07-25 00:24:17 +0000148 EmitStmt(S.getSubStmt());
149}
150
151void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
152 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
153
154 // Emit a block after the branch so that dead code after a goto has some place
155 // to go.
Gabor Greif815e2c12008-04-06 20:42:52 +0000156 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Chris Lattner4b009652007-07-25 00:24:17 +0000157}
158
Daniel Dunbar879788d2008-08-04 16:51:22 +0000159void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
160 // Emit initial switch which will be patched up later by
161 // EmitIndirectSwitches(). We need a default dest, so we use the
162 // current BB, but this is overwritten.
163 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
164 llvm::Type::Int32Ty,
165 "addr");
166 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
167 IndirectSwitches.push_back(I);
168
169 // Emit a block after the branch so that dead code after a goto has some place
170 // to go.
171 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
172}
173
Chris Lattner4b009652007-07-25 00:24:17 +0000174void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Daniel Dunbar879788d2008-08-04 16:51:22 +0000175 // FIXME: It would probably be nice for us to skip emission of if
176 // (0) code here.
177
Chris Lattner4b009652007-07-25 00:24:17 +0000178 // C99 6.8.4.1: The first substatement is executed if the expression compares
179 // unequal to 0. The condition must be a scalar type.
180 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
181
Gabor Greif815e2c12008-04-06 20:42:52 +0000182 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
183 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Chris Lattner4b009652007-07-25 00:24:17 +0000184 llvm::BasicBlock *ElseBlock = ContBlock;
185
186 if (S.getElse())
Gabor Greif815e2c12008-04-06 20:42:52 +0000187 ElseBlock = llvm::BasicBlock::Create("ifelse");
Chris Lattner4b009652007-07-25 00:24:17 +0000188
189 // Insert the conditional branch.
190 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
191
192 // Emit the 'then' code.
193 EmitBlock(ThenBlock);
194 EmitStmt(S.getThen());
Devang Patel97299362007-09-28 21:49:18 +0000195 llvm::BasicBlock *BB = Builder.GetInsertBlock();
196 if (isDummyBlock(BB)) {
197 BB->eraseFromParent();
198 Builder.SetInsertPoint(ThenBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000199 } else {
Devang Patel97299362007-09-28 21:49:18 +0000200 Builder.CreateBr(ContBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000201 }
Chris Lattner4b009652007-07-25 00:24:17 +0000202
203 // Emit the 'else' code if present.
204 if (const Stmt *Else = S.getElse()) {
205 EmitBlock(ElseBlock);
206 EmitStmt(Else);
Devang Patel97299362007-09-28 21:49:18 +0000207 llvm::BasicBlock *BB = Builder.GetInsertBlock();
208 if (isDummyBlock(BB)) {
209 BB->eraseFromParent();
210 Builder.SetInsertPoint(ElseBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000211 } else {
Devang Patel97299362007-09-28 21:49:18 +0000212 Builder.CreateBr(ContBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000213 }
Chris Lattner4b009652007-07-25 00:24:17 +0000214 }
215
216 // Emit the continuation block for code after the if.
217 EmitBlock(ContBlock);
218}
219
220void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
221 // Emit the header for the loop, insert it, which will create an uncond br to
222 // it.
Gabor Greif815e2c12008-04-06 20:42:52 +0000223 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Chris Lattner4b009652007-07-25 00:24:17 +0000224 EmitBlock(LoopHeader);
225
226 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
227 // of the controlling expression takes place before each execution of the loop
228 // body.
229 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel706f8442007-10-09 20:51:27 +0000230
231 // while(1) is common, avoid extra exit blocks. Be sure
Chris Lattner4b009652007-07-25 00:24:17 +0000232 // to correctly handle break/continue though.
Devang Patel706f8442007-10-09 20:51:27 +0000233 bool EmitBoolCondBranch = true;
234 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
235 if (C->isOne())
236 EmitBoolCondBranch = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000237
238 // Create an exit block for when the condition fails, create a block for the
239 // body of the loop.
Gabor Greif815e2c12008-04-06 20:42:52 +0000240 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
241 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Chris Lattner4b009652007-07-25 00:24:17 +0000242
243 // As long as the condition is true, go to the loop body.
Devang Patel706f8442007-10-09 20:51:27 +0000244 if (EmitBoolCondBranch)
245 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000246
247 // Store the blocks to use for break and continue.
248 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
249
250 // Emit the loop body.
251 EmitBlock(LoopBody);
252 EmitStmt(S.getBody());
253
254 BreakContinueStack.pop_back();
255
256 // Cycle to the condition.
257 Builder.CreateBr(LoopHeader);
258
259 // Emit the exit block.
260 EmitBlock(ExitBlock);
Devang Patel706f8442007-10-09 20:51:27 +0000261
262 // If LoopHeader is a simple forwarding block then eliminate it.
263 if (!EmitBoolCondBranch
264 && &LoopHeader->front() == LoopHeader->getTerminator()) {
265 LoopHeader->replaceAllUsesWith(LoopBody);
266 LoopHeader->getTerminator()->eraseFromParent();
267 LoopHeader->eraseFromParent();
268 }
Chris Lattner4b009652007-07-25 00:24:17 +0000269}
270
271void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000272 // Emit the body for the loop, insert it, which will create an uncond br to
273 // it.
Gabor Greif815e2c12008-04-06 20:42:52 +0000274 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
275 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Chris Lattner4b009652007-07-25 00:24:17 +0000276 EmitBlock(LoopBody);
277
Gabor Greif815e2c12008-04-06 20:42:52 +0000278 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattner4b009652007-07-25 00:24:17 +0000279
280 // Store the blocks to use for break and continue.
281 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
282
283 // Emit the body of the loop into the block.
284 EmitStmt(S.getBody());
285
286 BreakContinueStack.pop_back();
287
288 EmitBlock(DoCond);
289
290 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
291 // after each execution of the loop body."
292
293 // Evaluate the conditional in the while header.
294 // C99 6.8.5p2/p4: The first substatement is executed if the expression
295 // compares unequal to 0. The condition must be a scalar type.
296 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel716d02c2007-10-09 20:33:39 +0000297
298 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
299 // to correctly handle break/continue though.
300 bool EmitBoolCondBranch = true;
301 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
302 if (C->isZero())
303 EmitBoolCondBranch = false;
304
Chris Lattner4b009652007-07-25 00:24:17 +0000305 // As long as the condition is true, iterate the loop.
Devang Patel716d02c2007-10-09 20:33:39 +0000306 if (EmitBoolCondBranch)
307 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Chris Lattner4b009652007-07-25 00:24:17 +0000308
309 // Emit the exit block.
310 EmitBlock(AfterDo);
Devang Patel716d02c2007-10-09 20:33:39 +0000311
312 // If DoCond is a simple forwarding block then eliminate it.
313 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
314 DoCond->replaceAllUsesWith(AfterDo);
315 DoCond->getTerminator()->eraseFromParent();
316 DoCond->eraseFromParent();
317 }
Chris Lattner4b009652007-07-25 00:24:17 +0000318}
319
320void CodeGenFunction::EmitForStmt(const ForStmt &S) {
321 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
322 // which contains a continue/break?
323 // TODO: We could keep track of whether the loop body contains any
324 // break/continue statements and not create unnecessary blocks (like
325 // "afterfor" for a condless loop) if it doesn't.
326
327 // Evaluate the first part before the loop.
328 if (S.getInit())
329 EmitStmt(S.getInit());
330
331 // Start the loop with a block that tests the condition.
Gabor Greif815e2c12008-04-06 20:42:52 +0000332 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
333 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattner4b009652007-07-25 00:24:17 +0000334
335 EmitBlock(CondBlock);
336
337 // Evaluate the condition if present. If not, treat it as a non-zero-constant
338 // according to 6.8.5.3p2, aka, true.
339 if (S.getCond()) {
340 // C99 6.8.5p2/p4: The first substatement is executed if the expression
341 // compares unequal to 0. The condition must be a scalar type.
342 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
343
344 // As long as the condition is true, iterate the loop.
Gabor Greif815e2c12008-04-06 20:42:52 +0000345 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Chris Lattner4b009652007-07-25 00:24:17 +0000346 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
347 EmitBlock(ForBody);
348 } else {
349 // Treat it as a non-zero constant. Don't even create a new block for the
350 // body, just fall into it.
351 }
352
353 // If the for loop doesn't have an increment we can just use the
354 // condition as the continue block.
355 llvm::BasicBlock *ContinueBlock;
356 if (S.getInc())
Gabor Greif815e2c12008-04-06 20:42:52 +0000357 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattner4b009652007-07-25 00:24:17 +0000358 else
359 ContinueBlock = CondBlock;
360
361 // Store the blocks to use for break and continue.
362 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
363
364 // If the condition is true, execute the body of the for stmt.
365 EmitStmt(S.getBody());
366
367 BreakContinueStack.pop_back();
368
369 if (S.getInc())
370 EmitBlock(ContinueBlock);
371
372 // If there is an increment, emit it next.
373 if (S.getInc())
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000374 EmitStmt(S.getInc());
Chris Lattner4b009652007-07-25 00:24:17 +0000375
376 // Finally, branch back up to the condition for the next iteration.
377 Builder.CreateBr(CondBlock);
378
379 // Emit the fall-through block.
380 EmitBlock(AfterFor);
381}
382
383/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
384/// if the function returns void, or may be missing one if the function returns
385/// non-void. Fun stuff :).
386void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000387 // Emit the result value, even if unused, to evalute the side effects.
388 const Expr *RV = S.getRetValue();
Chris Lattner74b93032007-08-26 07:14:44 +0000389
Eli Friedman56977312008-05-22 01:22:33 +0000390 llvm::Value* RetValue = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000391 if (FnRetTy->isVoidType()) {
Eli Friedman56977312008-05-22 01:22:33 +0000392 // Make sure not to return anything
393 if (RV) {
394 // Evaluate the expression for side effects
395 EmitAnyExpr(RV);
396 }
Chris Lattner4b009652007-07-25 00:24:17 +0000397 } else if (RV == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000398 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
Eli Friedman56977312008-05-22 01:22:33 +0000399 if (RetTy != llvm::Type::VoidTy) {
400 // Handle "return;" in a function that returns a value.
401 RetValue = llvm::UndefValue::get(RetTy);
402 }
Chris Lattner74b93032007-08-26 07:14:44 +0000403 } else if (!hasAggregateLLVMType(RV->getType())) {
Eli Friedman56977312008-05-22 01:22:33 +0000404 RetValue = EmitScalarExpr(RV);
Chris Lattnerde0908b2008-04-04 16:54:41 +0000405 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000406 EmitComplexExprIntoAddr(RV, CurFn->arg_begin(), false);
Chris Lattner4b009652007-07-25 00:24:17 +0000407 } else {
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000408 EmitAggExpr(RV, CurFn->arg_begin(), false);
Chris Lattner4b009652007-07-25 00:24:17 +0000409 }
Eli Friedman56977312008-05-22 01:22:33 +0000410
411 if (RetValue) {
412 Builder.CreateRet(RetValue);
413 } else {
414 Builder.CreateRetVoid();
415 }
Chris Lattner4b009652007-07-25 00:24:17 +0000416
417 // Emit a block after the branch so that dead code after a return has some
418 // place to go.
Gabor Greif815e2c12008-04-06 20:42:52 +0000419 EmitBlock(llvm::BasicBlock::Create());
Chris Lattner4b009652007-07-25 00:24:17 +0000420}
421
422void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000423 for (const ScopedDecl *Decl = S.getDecl(); Decl;
424 Decl = Decl->getNextDeclarator())
Chris Lattner4b009652007-07-25 00:24:17 +0000425 EmitDecl(*Decl);
426}
427
428void CodeGenFunction::EmitBreakStmt() {
429 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
430
431 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
432 Builder.CreateBr(Block);
Gabor Greif815e2c12008-04-06 20:42:52 +0000433 EmitBlock(llvm::BasicBlock::Create());
Chris Lattner4b009652007-07-25 00:24:17 +0000434}
435
436void CodeGenFunction::EmitContinueStmt() {
437 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
438
439 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
440 Builder.CreateBr(Block);
Gabor Greif815e2c12008-04-06 20:42:52 +0000441 EmitBlock(llvm::BasicBlock::Create());
Chris Lattner4b009652007-07-25 00:24:17 +0000442}
Devang Patele58e0802007-10-04 23:45:31 +0000443
Devang Patel347ca322007-10-08 20:57:48 +0000444/// EmitCaseStmtRange - If case statement range is not too big then
445/// add multiple cases to switch instruction, one for each value within
446/// the range. If range is too big then emit "if" condition check.
447void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000448 // XXX kill me with param - ddunbar
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000449 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patel347ca322007-10-08 20:57:48 +0000450
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000451 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
452 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
453
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000454 // Emit the code for this case. We do this first to make sure it is
455 // properly chained from our predecessor before generating the
456 // switch machinery to enter this block.
457 StartBlock("sw.bb");
458 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
459 EmitStmt(S.getSubStmt());
460
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000461 // If range is empty, do nothing.
462 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
463 return;
Devang Patel347ca322007-10-08 20:57:48 +0000464
465 llvm::APInt Range = RHS - LHS;
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000466 // FIXME: parameters such as this should not be hardcoded.
Devang Patel347ca322007-10-08 20:57:48 +0000467 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
468 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000469 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patelcf9dbf22007-10-05 20:54:07 +0000470 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
471 LHS++;
472 }
Devang Patel347ca322007-10-08 20:57:48 +0000473 return;
474 }
475
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000476 // The range is too big. Emit "if" condition into a new block,
477 // making sure to save and restore the current insertion point.
478 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patelcf9dbf22007-10-05 20:54:07 +0000479
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000480 // Push this test onto the chain of range checks (which terminates
481 // in the default basic block). The switch's default will be changed
482 // to the top of this chain after switch emission is complete.
483 llvm::BasicBlock *FalseDest = CaseRangeBlock;
484 CaseRangeBlock = llvm::BasicBlock::Create("sw.caserange");
Devang Patel347ca322007-10-08 20:57:48 +0000485
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000486 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
487 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000488
489 // Emit range check.
490 llvm::Value *Diff =
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000491 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
492 "tmp");
Devang Patel347ca322007-10-08 20:57:48 +0000493 llvm::Value *Cond =
494 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
495 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
496
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000497 // Restore the appropriate insertion point.
498 Builder.SetInsertPoint(RestoreBB);
Devang Patel347ca322007-10-08 20:57:48 +0000499}
500
501void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
502 if (S.getRHS()) {
503 EmitCaseStmtRange(S);
504 return;
505 }
506
507 StartBlock("sw.bb");
508 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000509 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
510 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal),
511 CaseDest);
Devang Patele58e0802007-10-04 23:45:31 +0000512 EmitStmt(S.getSubStmt());
513}
514
515void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000516 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
517 assert(DefaultBlock->empty() && "EmitDefaultStmt: Default block already defined?");
518 EmitBlock(DefaultBlock);
Devang Patele58e0802007-10-04 23:45:31 +0000519 EmitStmt(S.getSubStmt());
520}
521
522void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
523 llvm::Value *CondV = EmitScalarExpr(S.getCond());
524
525 // Handle nested switch statements.
526 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000527 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000528
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000529 // Create basic block to hold stuff that comes after switch
530 // statement. We also need to create a default block now so that
531 // explicit case ranges tests can have a place to jump to on
532 // failure.
533 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("sw.epilog");
534 llvm::BasicBlock *DefaultBlock = llvm::BasicBlock::Create("sw.default");
535 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
536 CaseRangeBlock = DefaultBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000537
Eli Friedman51eaf1b2008-05-12 16:08:04 +0000538 // Create basic block for body of switch
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000539 StartBlock("sw.body");
Eli Friedman51eaf1b2008-05-12 16:08:04 +0000540
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000541 // All break statements jump to NextBlock. If BreakContinueStack is non empty
542 // then reuse last ContinueBlock.
Devang Patele58e0802007-10-04 23:45:31 +0000543 llvm::BasicBlock *ContinueBlock = NULL;
544 if (!BreakContinueStack.empty())
545 ContinueBlock = BreakContinueStack.back().ContinueBlock;
546 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
547
548 // Emit switch body.
549 EmitStmt(S.getBody());
550 BreakContinueStack.pop_back();
551
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000552 // Update the default block in case explicit case range tests have
553 // been chained on top.
554 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000555
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000556 // If a default was never emitted then reroute any jumps to it and
557 // discard.
558 if (!DefaultBlock->getParent()) {
559 DefaultBlock->replaceAllUsesWith(NextBlock);
560 delete DefaultBlock;
561 }
Devang Patele58e0802007-10-04 23:45:31 +0000562
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000563 // Emit continuation.
564 EmitBlock(NextBlock);
565
Devang Patele58e0802007-10-04 23:45:31 +0000566 SwitchInsn = SavedSwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000567 CaseRangeBlock = SavedCRBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000568}
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000569
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000570static std::string ConvertAsmString(const char *Start, unsigned NumOperands,
571 bool IsSimple) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000572 static unsigned AsmCounter = 0;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000573 AsmCounter++;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000574 std::string Result;
Anders Carlsson52234522008-02-05 23:18:57 +0000575 if (IsSimple) {
576 while (*Start) {
577 switch (*Start) {
578 default:
579 Result += *Start;
580 break;
581 case '$':
582 Result += "$$";
583 break;
584 }
Anders Carlsson52234522008-02-05 23:18:57 +0000585 Start++;
586 }
587
588 return Result;
589 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000590
591 while (*Start) {
592 switch (*Start) {
593 default:
594 Result += *Start;
595 break;
596 case '$':
597 Result += "$$";
598 break;
599 case '%':
600 // Escaped character
601 Start++;
602 if (!*Start) {
603 // FIXME: This should be caught during Sema.
604 assert(0 && "Trailing '%' in asm string.");
605 }
606
607 char EscapedChar = *Start;
608 if (EscapedChar == '%') {
609 // Escaped percentage sign.
610 Result += '%';
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000611 } else if (EscapedChar == '=') {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000612 // Generate an unique ID.
613 Result += llvm::utostr(AsmCounter);
614 } else if (isdigit(EscapedChar)) {
615 // %n - Assembler operand n
616 char *End;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000617 unsigned long n = strtoul(Start, &End, 10);
618 if (Start == End) {
619 // FIXME: This should be caught during Sema.
620 assert(0 && "Missing operand!");
621 } else if (n >= NumOperands) {
622 // FIXME: This should be caught during Sema.
623 assert(0 && "Operand number out of range!");
624 }
625
626 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000627 Start = End - 1;
Anders Carlsson52234522008-02-05 23:18:57 +0000628 } else if (isalpha(EscapedChar)) {
629 char *End;
630
631 unsigned long n = strtoul(Start + 1, &End, 10);
632 if (Start == End) {
633 // FIXME: This should be caught during Sema.
634 assert(0 && "Missing operand!");
635 } else if (n >= NumOperands) {
636 // FIXME: This should be caught during Sema.
637 assert(0 && "Operand number out of range!");
638 }
639
640 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000641 Start = End - 1;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000642 } else {
643 assert(0 && "Unhandled asm escaped character!");
644 }
645 }
646 Start++;
647 }
648
649 return Result;
650}
651
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000652static std::string SimplifyConstraint(const char* Constraint,
653 TargetInfo &Target) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000654 std::string Result;
655
656 while (*Constraint) {
657 switch (*Constraint) {
658 default:
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000659 Result += Target.convertConstraint(*Constraint);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000660 break;
661 // Ignore these
662 case '*':
663 case '?':
664 case '!':
665 break;
666 case 'g':
667 Result += "imr";
668 break;
669 }
670
671 Constraint++;
672 }
673
674 return Result;
675}
676
677void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
678 std::string AsmString =
679 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
680 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson52234522008-02-05 23:18:57 +0000681 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000682
683 std::string Constraints;
684
685 llvm::Value *ResultAddr = 0;
686 const llvm::Type *ResultType = llvm::Type::VoidTy;
687
688 std::vector<const llvm::Type*> ArgTypes;
689 std::vector<llvm::Value*> Args;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000690
691 // Keep track of inout constraints.
692 std::string InOutConstraints;
693 std::vector<llvm::Value*> InOutArgs;
694 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000695
696 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
697 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
698 S.getOutputConstraint(i)->getByteLength());
699
700 TargetInfo::ConstraintInfo Info;
701 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
702 Info);
703 assert(result && "Failed to parse output constraint");
704
705 // Simplify the output constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000706 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000707
708 LValue Dest = EmitLValue(S.getOutputExpr(i));
709 const llvm::Type *DestValueType =
710 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
711
712 // If the first output operand is not a memory dest, we'll
713 // make it the return value.
714 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohman377ba9f2008-05-22 22:12:56 +0000715 DestValueType->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000716 ResultAddr = Dest.getAddress();
717 ResultType = DestValueType;
718 Constraints += "=" + OutputConstraint;
719 } else {
720 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlsson78725072008-02-05 16:57:38 +0000721 Args.push_back(Dest.getAddress());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000722 if (i != 0)
723 Constraints += ',';
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000724 Constraints += "=*";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000725 Constraints += OutputConstraint;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000726 }
727
728 if (Info & TargetInfo::CI_ReadWrite) {
729 // FIXME: This code should be shared with the code that handles inputs.
730 InOutConstraints += ',';
731
732 const Expr *InputExpr = S.getOutputExpr(i);
733 llvm::Value *Arg;
734 if ((Info & TargetInfo::CI_AllowsRegister) ||
735 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000736 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000737 Arg = EmitScalarExpr(InputExpr);
738 } else {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000739 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000740 }
741 } else {
742 LValue Dest = EmitLValue(InputExpr);
743 Arg = Dest.getAddress();
744 InOutConstraints += '*';
745 }
746
747 InOutArgTypes.push_back(Arg->getType());
748 InOutArgs.push_back(Arg);
749 InOutConstraints += OutputConstraint;
750 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000751 }
752
753 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
754
755 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
756 const Expr *InputExpr = S.getInputExpr(i);
757
758 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
759 S.getInputConstraint(i)->getByteLength());
760
761 TargetInfo::ConstraintInfo Info;
762 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
763 NumConstraints,
764 Info);
765 assert(result && "Failed to parse input constraint");
766
767 if (i != 0 || S.getNumOutputs() > 0)
768 Constraints += ',';
769
770 // Simplify the input constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000771 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000772
773 llvm::Value *Arg;
774
775 if ((Info & TargetInfo::CI_AllowsRegister) ||
776 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000777 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000778 Arg = EmitScalarExpr(InputExpr);
779 } else {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000780 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000781 }
782 } else {
783 LValue Dest = EmitLValue(InputExpr);
784 Arg = Dest.getAddress();
785 Constraints += '*';
786 }
787
788 ArgTypes.push_back(Arg->getType());
789 Args.push_back(Arg);
790 Constraints += InputConstraint;
791 }
792
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000793 // Append the "input" part of inout constraints last.
794 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
795 ArgTypes.push_back(InOutArgTypes[i]);
796 Args.push_back(InOutArgs[i]);
797 }
798 Constraints += InOutConstraints;
799
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000800 // Clobbers
801 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
802 std::string Clobber(S.getClobber(i)->getStrData(),
803 S.getClobber(i)->getByteLength());
804
805 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
806
Anders Carlsson74385982008-02-06 00:11:32 +0000807 if (i != 0 || NumConstraints != 0)
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000808 Constraints += ',';
Anders Carlsson74385982008-02-06 00:11:32 +0000809
810 Constraints += "~{";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000811 Constraints += Clobber;
Anders Carlsson74385982008-02-06 00:11:32 +0000812 Constraints += '}';
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000813 }
814
815 // Add machine specific clobbers
816 if (const char *C = Target.getClobbers()) {
817 if (!Constraints.empty())
818 Constraints += ',';
819 Constraints += C;
820 }
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000821
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000822 const llvm::FunctionType *FTy =
823 llvm::FunctionType::get(ResultType, ArgTypes, false);
824
825 llvm::InlineAsm *IA =
826 llvm::InlineAsm::get(FTy, AsmString, Constraints,
827 S.isVolatile() || S.getNumOutputs() == 0);
828 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman2e630542008-06-13 23:01:12 +0000829 if (ResultAddr) // FIXME: volatility
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000830 Builder.CreateStore(Result, ResultAddr);
831}