blob: 2b9a72be531f025b7514e66fc96dab96f7a7d3dc [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");
Chris Lattner419ea7e2007-09-13 01:17:29 +000042 S->dump(getContext().SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +000043 }
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;
Devang Patel51b09f22007-10-04 23:45:31 +000060 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
61 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
62 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000063 }
64}
65
Chris Lattner33793202007-08-31 22:09:40 +000066/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
67/// this captures the expression result of the last sub-statement and returns it
68/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +000069RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
70 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +000071 // FIXME: handle vla's etc.
Chris Lattner33793202007-08-31 22:09:40 +000072 if (S.body_empty() || !isa<Expr>(S.body_back())) GetLast = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000073
Chris Lattner33793202007-08-31 22:09:40 +000074 for (CompoundStmt::const_body_iterator I = S.body_begin(),
75 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +000076 EmitStmt(*I);
Chris Lattner33793202007-08-31 22:09:40 +000077
78
79 if (!GetLast)
80 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +000081
82 return EmitAnyExpr(cast<Expr>(S.body_back()), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000083}
84
85void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
86 // Emit a branch from this block to the next one if this was a real block. If
87 // this was just a fall-through block after a terminator, don't emit it.
88 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
89
90 if (LastBB->getTerminator()) {
91 // If the previous block is already terminated, don't touch it.
92 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
93 // If the last block was an empty placeholder, remove it now.
94 // TODO: cache and reuse these.
95 Builder.GetInsertBlock()->eraseFromParent();
96 } else {
97 // Otherwise, create a fall-through branch.
98 Builder.CreateBr(BB);
99 }
100 CurFn->getBasicBlockList().push_back(BB);
101 Builder.SetInsertPoint(BB);
102}
103
104void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
105 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
106
107 EmitBlock(NextBB);
108 EmitStmt(S.getSubStmt());
109}
110
111void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
112 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
113
114 // Emit a block after the branch so that dead code after a goto has some place
115 // to go.
116 Builder.SetInsertPoint(new llvm::BasicBlock("", CurFn));
117}
118
119void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
120 // C99 6.8.4.1: The first substatement is executed if the expression compares
121 // unequal to 0. The condition must be a scalar type.
122 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
123
124 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("ifend");
125 llvm::BasicBlock *ThenBlock = new llvm::BasicBlock("ifthen");
126 llvm::BasicBlock *ElseBlock = ContBlock;
127
128 if (S.getElse())
129 ElseBlock = new llvm::BasicBlock("ifelse");
130
131 // Insert the conditional branch.
132 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
133
134 // Emit the 'then' code.
135 EmitBlock(ThenBlock);
136 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000137 llvm::BasicBlock *BB = Builder.GetInsertBlock();
138 if (isDummyBlock(BB)) {
139 BB->eraseFromParent();
140 Builder.SetInsertPoint(ThenBlock);
141 }
142 else
143 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000144
145 // Emit the 'else' code if present.
146 if (const Stmt *Else = S.getElse()) {
147 EmitBlock(ElseBlock);
148 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000149 llvm::BasicBlock *BB = Builder.GetInsertBlock();
150 if (isDummyBlock(BB)) {
151 BB->eraseFromParent();
152 Builder.SetInsertPoint(ElseBlock);
153 }
154 else
155 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000156 }
157
158 // Emit the continuation block for code after the if.
159 EmitBlock(ContBlock);
160}
161
162void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 // Emit the header for the loop, insert it, which will create an uncond br to
164 // it.
165 llvm::BasicBlock *LoopHeader = new llvm::BasicBlock("whilecond");
166 EmitBlock(LoopHeader);
167
168 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
169 // of the controlling expression takes place before each execution of the loop
170 // body.
171 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
172
173 // TODO: while(1) is common, avoid extra exit blocks, etc. Be sure
174 // to correctly handle break/continue though.
175
176 // Create an exit block for when the condition fails, create a block for the
177 // body of the loop.
178 llvm::BasicBlock *ExitBlock = new llvm::BasicBlock("whileexit");
179 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("whilebody");
180
181 // As long as the condition is true, go to the loop body.
182 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000183
184 // Store the blocks to use for break and continue.
185 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000186
187 // Emit the loop body.
188 EmitBlock(LoopBody);
189 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000190
191 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000192
193 // Cycle to the condition.
194 Builder.CreateBr(LoopHeader);
195
196 // Emit the exit block.
197 EmitBlock(ExitBlock);
198}
199
200void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 // TODO: "do {} while (0)" is common in macros, avoid extra blocks. Be sure
202 // to correctly handle break/continue though.
203
204 // Emit the body for the loop, insert it, which will create an uncond br to
205 // it.
206 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("dobody");
207 llvm::BasicBlock *AfterDo = new llvm::BasicBlock("afterdo");
208 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000209
210 llvm::BasicBlock *DoCond = new llvm::BasicBlock("docond");
211
212 // Store the blocks to use for break and continue.
213 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000214
215 // Emit the body of the loop into the block.
216 EmitStmt(S.getBody());
217
Chris Lattnerda138702007-07-16 21:28:45 +0000218 BreakContinueStack.pop_back();
219
220 EmitBlock(DoCond);
221
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
223 // after each execution of the loop body."
224
225 // Evaluate the conditional in the while header.
226 // C99 6.8.5p2/p4: The first substatement is executed if the expression
227 // compares unequal to 0. The condition must be a scalar type.
228 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
229
230 // As long as the condition is true, iterate the loop.
231 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
232
233 // Emit the exit block.
234 EmitBlock(AfterDo);
235}
236
237void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
239 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000240 // TODO: We could keep track of whether the loop body contains any
241 // break/continue statements and not create unnecessary blocks (like
242 // "afterfor" for a condless loop) if it doesn't.
243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 // Evaluate the first part before the loop.
245 if (S.getInit())
246 EmitStmt(S.getInit());
247
248 // Start the loop with a block that tests the condition.
249 llvm::BasicBlock *CondBlock = new llvm::BasicBlock("forcond");
Chris Lattnerda138702007-07-16 21:28:45 +0000250 llvm::BasicBlock *AfterFor = new llvm::BasicBlock("afterfor");
251
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 EmitBlock(CondBlock);
253
254 // Evaluate the condition if present. If not, treat it as a non-zero-constant
255 // according to 6.8.5.3p2, aka, true.
256 if (S.getCond()) {
257 // C99 6.8.5p2/p4: The first substatement is executed if the expression
258 // compares unequal to 0. The condition must be a scalar type.
259 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
260
261 // As long as the condition is true, iterate the loop.
262 llvm::BasicBlock *ForBody = new llvm::BasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
264 EmitBlock(ForBody);
265 } else {
266 // Treat it as a non-zero constant. Don't even create a new block for the
267 // body, just fall into it.
268 }
269
Chris Lattnerda138702007-07-16 21:28:45 +0000270 // If the for loop doesn't have an increment we can just use the
271 // condition as the continue block.
272 llvm::BasicBlock *ContinueBlock;
273 if (S.getInc())
274 ContinueBlock = new llvm::BasicBlock("forinc");
275 else
276 ContinueBlock = CondBlock;
277
278 // Store the blocks to use for break and continue.
279 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
280
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 // If the condition is true, execute the body of the for stmt.
282 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000283
284 BreakContinueStack.pop_back();
285
286 if (S.getInc())
287 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000288
289 // If there is an increment, emit it next.
290 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000291 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000292
293 // Finally, branch back up to the condition for the next iteration.
294 Builder.CreateBr(CondBlock);
295
Chris Lattnerda138702007-07-16 21:28:45 +0000296 // Emit the fall-through block.
297 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000298}
299
300/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
301/// if the function returns void, or may be missing one if the function returns
302/// non-void. Fun stuff :).
303void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 // Emit the result value, even if unused, to evalute the side effects.
305 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000306
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 QualType FnRetTy = CurFuncDecl->getType().getCanonicalType();
308 FnRetTy = cast<FunctionType>(FnRetTy)->getResultType();
309
310 if (FnRetTy->isVoidType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000311 // If the function returns void, emit ret void.
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 Builder.CreateRetVoid();
313 } else if (RV == 0) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000314 // Handle "return;" in a function that returns a value.
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
316 if (RetTy == llvm::Type::VoidTy)
317 Builder.CreateRetVoid(); // struct return etc.
318 else
319 Builder.CreateRet(llvm::UndefValue::get(RetTy));
Chris Lattner4b0029d2007-08-26 07:14:44 +0000320 } else if (!hasAggregateLLVMType(RV->getType())) {
321 Builder.CreateRet(EmitScalarExpr(RV));
322 } else if (RV->getType()->isComplexType()) {
323 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000324 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000326 llvm::Value *SRetPtr = CurFn->arg_begin();
327 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 }
329
330 // Emit a block after the branch so that dead code after a return has some
331 // place to go.
332 EmitBlock(new llvm::BasicBlock());
333}
334
335void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000336 for (const ScopedDecl *Decl = S.getDecl(); Decl;
337 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000339}
Chris Lattnerda138702007-07-16 21:28:45 +0000340
341void CodeGenFunction::EmitBreakStmt() {
342 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
343
344 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
345 Builder.CreateBr(Block);
346 EmitBlock(new llvm::BasicBlock());
347}
348
349void CodeGenFunction::EmitContinueStmt() {
350 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
351
352 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
353 Builder.CreateBr(Block);
354 EmitBlock(new llvm::BasicBlock());
355}
Devang Patel51b09f22007-10-04 23:45:31 +0000356
357void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
358 StartBlock("sw.bb");
359 llvm::Value *V = EmitScalarExpr(S.getLHS());
360 SwitchInsn->addCase(cast<llvm::ConstantInt>(V), Builder.GetInsertBlock());
361 assert (!S.getRHS() && "Case statement range is not yet supported");
362 EmitStmt(S.getSubStmt());
363}
364
365void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
366 StartBlock("sw.default");
367 // Current insert block is the default destination.
368 SwitchInsn->setSuccessor(0, Builder.GetInsertBlock());
369 EmitStmt(S.getSubStmt());
370}
371
372void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
373 llvm::Value *CondV = EmitScalarExpr(S.getCond());
374
375 // Handle nested switch statements.
376 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
377
378 // Create basic block to hold stuff that comes after switch statement.
379 // Initially use it to hold DefaultStmt.
380 llvm::BasicBlock *NextBlock = new llvm::BasicBlock("after.sw", CurFn);
381 SwitchInsn = Builder.CreateSwitch(CondV, NextBlock);
382
383 // All break statements jump to NextBlock. If BreakContinueStack is non empty then
384 // reuse last ContinueBlock.
385 llvm::BasicBlock *ContinueBlock = NULL;
386 if (!BreakContinueStack.empty())
387 ContinueBlock = BreakContinueStack.back().ContinueBlock;
388 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
389
390 // Emit switch body.
391 EmitStmt(S.getBody());
392 BreakContinueStack.pop_back();
393
394 // Prune insert block if it is dummy.
395 llvm::BasicBlock *BB = Builder.GetInsertBlock();
396 if (isDummyBlock(BB))
397 BB->eraseFromParent();
398
399 // Place NextBlock as the new insert point.
400 Builder.SetInsertPoint(NextBlock);
401 SwitchInsn = SavedSwitchInsn;
402}