blob: 85a6ca8705ed9792cc3579721993c907857b2931 [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "clang/AST/AST.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19using namespace clang;
20using namespace CodeGen;
21
22//===----------------------------------------------------------------------===//
23// Statement Emission
24//===----------------------------------------------------------------------===//
25
26void CodeGenFunction::EmitStmt(const Stmt *S) {
27 assert(S && "Null statement?");
28
29 switch (S->getStmtClass()) {
30 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000031 // Must be an expression in a stmt context. Emit the value (to get
32 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000033 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000034 if (!hasAggregateLLVMType(E->getType()))
35 EmitScalarExpr(E);
36 else if (E->getType()->isComplexType())
37 EmitComplexExpr(E);
38 else
39 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000040 } else {
41 printf("Unimplemented stmt!\n");
42 S->dump();
43 }
44 break;
45 case Stmt::NullStmtClass: break;
46 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
47 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
48 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
49
50 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
51 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
52 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
53 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
54
55 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
56 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000057
58 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
59 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000060 }
61}
62
Chris Lattner33793202007-08-31 22:09:40 +000063/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
64/// this captures the expression result of the last sub-statement and returns it
65/// (for use by the statement expression extension).
66RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast) {
Reid Spencer5f016e22007-07-11 17:01:13 +000067 // FIXME: handle vla's etc.
Chris Lattner33793202007-08-31 22:09:40 +000068 if (S.body_empty() || !isa<Expr>(S.body_back())) GetLast = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000069
Chris Lattner33793202007-08-31 22:09:40 +000070 for (CompoundStmt::const_body_iterator I = S.body_begin(),
71 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +000072 EmitStmt(*I);
Chris Lattner33793202007-08-31 22:09:40 +000073
74
75 if (!GetLast)
76 return RValue::get(0);
77
78 const Expr *Last = cast<Expr>(S.body_back());
79 if (!hasAggregateLLVMType(Last->getType()))
80 return RValue::get(EmitScalarExpr(Last));
81 assert(0 && "Unimp");
82 //else if (Last->getType()->isComplexType())
83 // EmitComplexExpr(Last);
84 //else
85 // EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
87
88void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
89 // Emit a branch from this block to the next one if this was a real block. If
90 // this was just a fall-through block after a terminator, don't emit it.
91 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
92
93 if (LastBB->getTerminator()) {
94 // If the previous block is already terminated, don't touch it.
95 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
96 // If the last block was an empty placeholder, remove it now.
97 // TODO: cache and reuse these.
98 Builder.GetInsertBlock()->eraseFromParent();
99 } else {
100 // Otherwise, create a fall-through branch.
101 Builder.CreateBr(BB);
102 }
103 CurFn->getBasicBlockList().push_back(BB);
104 Builder.SetInsertPoint(BB);
105}
106
107void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
108 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
109
110 EmitBlock(NextBB);
111 EmitStmt(S.getSubStmt());
112}
113
114void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
115 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
116
117 // Emit a block after the branch so that dead code after a goto has some place
118 // to go.
119 Builder.SetInsertPoint(new llvm::BasicBlock("", CurFn));
120}
121
122void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
123 // C99 6.8.4.1: The first substatement is executed if the expression compares
124 // unequal to 0. The condition must be a scalar type.
125 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
126
127 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("ifend");
128 llvm::BasicBlock *ThenBlock = new llvm::BasicBlock("ifthen");
129 llvm::BasicBlock *ElseBlock = ContBlock;
130
131 if (S.getElse())
132 ElseBlock = new llvm::BasicBlock("ifelse");
133
134 // Insert the conditional branch.
135 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
136
137 // Emit the 'then' code.
138 EmitBlock(ThenBlock);
139 EmitStmt(S.getThen());
140 Builder.CreateBr(ContBlock);
141
142 // Emit the 'else' code if present.
143 if (const Stmt *Else = S.getElse()) {
144 EmitBlock(ElseBlock);
145 EmitStmt(Else);
146 Builder.CreateBr(ContBlock);
147 }
148
149 // Emit the continuation block for code after the if.
150 EmitBlock(ContBlock);
151}
152
153void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 // Emit the header for the loop, insert it, which will create an uncond br to
155 // it.
156 llvm::BasicBlock *LoopHeader = new llvm::BasicBlock("whilecond");
157 EmitBlock(LoopHeader);
158
159 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
160 // of the controlling expression takes place before each execution of the loop
161 // body.
162 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
163
164 // TODO: while(1) is common, avoid extra exit blocks, etc. Be sure
165 // to correctly handle break/continue though.
166
167 // Create an exit block for when the condition fails, create a block for the
168 // body of the loop.
169 llvm::BasicBlock *ExitBlock = new llvm::BasicBlock("whileexit");
170 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("whilebody");
171
172 // As long as the condition is true, go to the loop body.
173 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000174
175 // Store the blocks to use for break and continue.
176 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000177
178 // Emit the loop body.
179 EmitBlock(LoopBody);
180 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000181
182 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000183
184 // Cycle to the condition.
185 Builder.CreateBr(LoopHeader);
186
187 // Emit the exit block.
188 EmitBlock(ExitBlock);
189}
190
191void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 // TODO: "do {} while (0)" is common in macros, avoid extra blocks. Be sure
193 // to correctly handle break/continue though.
194
195 // Emit the body for the loop, insert it, which will create an uncond br to
196 // it.
197 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("dobody");
198 llvm::BasicBlock *AfterDo = new llvm::BasicBlock("afterdo");
199 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000200
201 llvm::BasicBlock *DoCond = new llvm::BasicBlock("docond");
202
203 // Store the blocks to use for break and continue.
204 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000205
206 // Emit the body of the loop into the block.
207 EmitStmt(S.getBody());
208
Chris Lattnerda138702007-07-16 21:28:45 +0000209 BreakContinueStack.pop_back();
210
211 EmitBlock(DoCond);
212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
214 // after each execution of the loop body."
215
216 // Evaluate the conditional in the while header.
217 // C99 6.8.5p2/p4: The first substatement is executed if the expression
218 // compares unequal to 0. The condition must be a scalar type.
219 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
220
221 // As long as the condition is true, iterate the loop.
222 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
223
224 // Emit the exit block.
225 EmitBlock(AfterDo);
226}
227
228void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
230 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000231 // TODO: We could keep track of whether the loop body contains any
232 // break/continue statements and not create unnecessary blocks (like
233 // "afterfor" for a condless loop) if it doesn't.
234
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 // Evaluate the first part before the loop.
236 if (S.getInit())
237 EmitStmt(S.getInit());
238
239 // Start the loop with a block that tests the condition.
240 llvm::BasicBlock *CondBlock = new llvm::BasicBlock("forcond");
Chris Lattnerda138702007-07-16 21:28:45 +0000241 llvm::BasicBlock *AfterFor = new llvm::BasicBlock("afterfor");
242
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 EmitBlock(CondBlock);
244
245 // Evaluate the condition if present. If not, treat it as a non-zero-constant
246 // according to 6.8.5.3p2, aka, true.
247 if (S.getCond()) {
248 // C99 6.8.5p2/p4: The first substatement is executed if the expression
249 // compares unequal to 0. The condition must be a scalar type.
250 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
251
252 // As long as the condition is true, iterate the loop.
253 llvm::BasicBlock *ForBody = new llvm::BasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
255 EmitBlock(ForBody);
256 } else {
257 // Treat it as a non-zero constant. Don't even create a new block for the
258 // body, just fall into it.
259 }
260
Chris Lattnerda138702007-07-16 21:28:45 +0000261 // If the for loop doesn't have an increment we can just use the
262 // condition as the continue block.
263 llvm::BasicBlock *ContinueBlock;
264 if (S.getInc())
265 ContinueBlock = new llvm::BasicBlock("forinc");
266 else
267 ContinueBlock = CondBlock;
268
269 // Store the blocks to use for break and continue.
270 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 // If the condition is true, execute the body of the for stmt.
273 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000274
275 BreakContinueStack.pop_back();
276
277 if (S.getInc())
278 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279
280 // If there is an increment, emit it next.
281 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000282 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000283
284 // Finally, branch back up to the condition for the next iteration.
285 Builder.CreateBr(CondBlock);
286
Chris Lattnerda138702007-07-16 21:28:45 +0000287 // Emit the fall-through block.
288 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000289}
290
291/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
292/// if the function returns void, or may be missing one if the function returns
293/// non-void. Fun stuff :).
294void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 // Emit the result value, even if unused, to evalute the side effects.
296 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000297
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 QualType FnRetTy = CurFuncDecl->getType().getCanonicalType();
299 FnRetTy = cast<FunctionType>(FnRetTy)->getResultType();
300
301 if (FnRetTy->isVoidType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000302 // If the function returns void, emit ret void.
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 Builder.CreateRetVoid();
304 } else if (RV == 0) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000305 // Handle "return;" in a function that returns a value.
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
307 if (RetTy == llvm::Type::VoidTy)
308 Builder.CreateRetVoid(); // struct return etc.
309 else
310 Builder.CreateRet(llvm::UndefValue::get(RetTy));
Chris Lattner4b0029d2007-08-26 07:14:44 +0000311 } else if (!hasAggregateLLVMType(RV->getType())) {
312 Builder.CreateRet(EmitScalarExpr(RV));
313 } else if (RV->getType()->isComplexType()) {
314 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000315 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000317 llvm::Value *SRetPtr = CurFn->arg_begin();
318 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 }
320
321 // Emit a block after the branch so that dead code after a return has some
322 // place to go.
323 EmitBlock(new llvm::BasicBlock());
324}
325
326void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
327 for (const Decl *Decl = S.getDecl(); Decl; Decl = Decl->getNextDeclarator())
328 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000329}
Chris Lattnerda138702007-07-16 21:28:45 +0000330
331void CodeGenFunction::EmitBreakStmt() {
332 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
333
334 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
335 Builder.CreateBr(Block);
336 EmitBlock(new llvm::BasicBlock());
337}
338
339void CodeGenFunction::EmitContinueStmt() {
340 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
341
342 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
343 Builder.CreateBr(Block);
344 EmitBlock(new llvm::BasicBlock());
345}