blob: 78d8563bfcdba5b3fd849bf20168dabce1a8be12 [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"
17#include "clang/AST/AST.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000022#include "llvm/InlineAsm.h"
23#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
31void CodeGenFunction::EmitStmt(const Stmt *S) {
32 assert(S && "Null statement?");
33
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000034 // Generate stoppoints if we are emitting debug info.
35 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
36 // executable code. So do not generate a stoppoint for that.
37 CGDebugInfo *DI = CGM.getDebugInfo();
38 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
39 if (S->getLocStart().isValid()) {
40 DI->setLocation(S->getLocStart());
41 }
42
43 DI->EmitStopPoint(CurFn, Builder);
44 }
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046 switch (S->getStmtClass()) {
47 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000048 // Must be an expression in a stmt context. Emit the value (to get
49 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000050 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000051 if (!hasAggregateLLVMType(E->getType()))
52 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000053 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000054 EmitComplexExpr(E);
55 else
56 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000057 } else {
Chris Lattnerdc4d2802007-12-02 01:49:16 +000058 WarnUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000059 }
60 break;
61 case Stmt::NullStmtClass: break;
62 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
63 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
64 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
65
66 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
67 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
68 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
69 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
70
71 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
72 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000073
74 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
75 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Devang Patel51b09f22007-10-04 23:45:31 +000076 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
77 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
78 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000079 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000080 }
81}
82
Chris Lattner33793202007-08-31 22:09:40 +000083/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
84/// this captures the expression result of the last sub-statement and returns it
85/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +000086RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
87 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +000088 // FIXME: handle vla's etc.
Chris Lattner33793202007-08-31 22:09:40 +000089 if (S.body_empty() || !isa<Expr>(S.body_back())) GetLast = false;
Chris Lattner345f7202008-07-26 20:15:14 +000090
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000091 CGDebugInfo *DI = CGM.getDebugInfo();
92 if (DI) {
Chris Lattner345f7202008-07-26 20:15:14 +000093 if (S.getLBracLoc().isValid())
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000094 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000095 DI->EmitRegionStart(CurFn, Builder);
96 }
97
Chris Lattner33793202007-08-31 22:09:40 +000098 for (CompoundStmt::const_body_iterator I = S.body_begin(),
99 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000101
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000102 if (DI) {
Chris Lattner345f7202008-07-26 20:15:14 +0000103 if (S.getRBracLoc().isValid())
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000104 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000105 DI->EmitRegionEnd(CurFn, Builder);
106 }
107
Chris Lattner33793202007-08-31 22:09:40 +0000108 if (!GetLast)
109 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000110
111 return EmitAnyExpr(cast<Expr>(S.body_back()), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000112}
113
114void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
115 // Emit a branch from this block to the next one if this was a real block. If
116 // this was just a fall-through block after a terminator, don't emit it.
117 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
118
119 if (LastBB->getTerminator()) {
120 // If the previous block is already terminated, don't touch it.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000121 } else if (LastBB->empty() && isDummyBlock(LastBB)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 // If the last block was an empty placeholder, remove it now.
123 // TODO: cache and reuse these.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000124 LastBB->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 } else {
126 // Otherwise, create a fall-through branch.
127 Builder.CreateBr(BB);
128 }
129 CurFn->getBasicBlockList().push_back(BB);
130 Builder.SetInsertPoint(BB);
131}
132
133void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
134 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
135
136 EmitBlock(NextBB);
137 EmitStmt(S.getSubStmt());
138}
139
140void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
141 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
142
143 // Emit a block after the branch so that dead code after a goto has some place
144 // to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000145 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Reid Spencer5f016e22007-07-11 17:01:13 +0000146}
147
148void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
149 // C99 6.8.4.1: The first substatement is executed if the expression compares
150 // unequal to 0. The condition must be a scalar type.
151 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
152
Gabor Greif984d0b42008-04-06 20:42:52 +0000153 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
154 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 llvm::BasicBlock *ElseBlock = ContBlock;
156
157 if (S.getElse())
Gabor Greif984d0b42008-04-06 20:42:52 +0000158 ElseBlock = llvm::BasicBlock::Create("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000159
160 // Insert the conditional branch.
161 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
162
163 // Emit the 'then' code.
164 EmitBlock(ThenBlock);
165 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000166 llvm::BasicBlock *BB = Builder.GetInsertBlock();
167 if (isDummyBlock(BB)) {
168 BB->eraseFromParent();
169 Builder.SetInsertPoint(ThenBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000170 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000171 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000172 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
174 // Emit the 'else' code if present.
175 if (const Stmt *Else = S.getElse()) {
176 EmitBlock(ElseBlock);
177 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000178 llvm::BasicBlock *BB = Builder.GetInsertBlock();
179 if (isDummyBlock(BB)) {
180 BB->eraseFromParent();
181 Builder.SetInsertPoint(ElseBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000182 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000183 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000184 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 }
186
187 // Emit the continuation block for code after the if.
188 EmitBlock(ContBlock);
189}
190
191void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 // Emit the header for the loop, insert it, which will create an uncond br to
193 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000194 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 EmitBlock(LoopHeader);
196
197 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
198 // of the controlling expression takes place before each execution of the loop
199 // body.
200 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000201
202 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000203 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000204 bool EmitBoolCondBranch = true;
205 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
206 if (C->isOne())
207 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000208
209 // Create an exit block for when the condition fails, create a block for the
210 // body of the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000211 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
212 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000213
214 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000215 if (EmitBoolCondBranch)
216 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000217
218 // Store the blocks to use for break and continue.
219 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000220
221 // Emit the loop body.
222 EmitBlock(LoopBody);
223 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000224
225 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000226
227 // Cycle to the condition.
228 Builder.CreateBr(LoopHeader);
229
230 // Emit the exit block.
231 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000232
233 // If LoopHeader is a simple forwarding block then eliminate it.
234 if (!EmitBoolCondBranch
235 && &LoopHeader->front() == LoopHeader->getTerminator()) {
236 LoopHeader->replaceAllUsesWith(LoopBody);
237 LoopHeader->getTerminator()->eraseFromParent();
238 LoopHeader->eraseFromParent();
239 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000240}
241
242void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 // Emit the body for the loop, insert it, which will create an uncond br to
244 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000245 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
246 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000247 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000248
Gabor Greif984d0b42008-04-06 20:42:52 +0000249 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000250
251 // Store the blocks to use for break and continue.
252 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000253
254 // Emit the body of the loop into the block.
255 EmitStmt(S.getBody());
256
Chris Lattnerda138702007-07-16 21:28:45 +0000257 BreakContinueStack.pop_back();
258
259 EmitBlock(DoCond);
260
Reid Spencer5f016e22007-07-11 17:01:13 +0000261 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
262 // after each execution of the loop body."
263
264 // Evaluate the conditional in the while header.
265 // C99 6.8.5p2/p4: The first substatement is executed if the expression
266 // compares unequal to 0. The condition must be a scalar type.
267 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000268
269 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
270 // to correctly handle break/continue though.
271 bool EmitBoolCondBranch = true;
272 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
273 if (C->isZero())
274 EmitBoolCondBranch = false;
275
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000277 if (EmitBoolCondBranch)
278 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279
280 // Emit the exit block.
281 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000282
283 // If DoCond is a simple forwarding block then eliminate it.
284 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
285 DoCond->replaceAllUsesWith(AfterDo);
286 DoCond->getTerminator()->eraseFromParent();
287 DoCond->eraseFromParent();
288 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000289}
290
291void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
293 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000294 // TODO: We could keep track of whether the loop body contains any
295 // break/continue statements and not create unnecessary blocks (like
296 // "afterfor" for a condless loop) if it doesn't.
297
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 // Evaluate the first part before the loop.
299 if (S.getInit())
300 EmitStmt(S.getInit());
301
302 // Start the loop with a block that tests the condition.
Gabor Greif984d0b42008-04-06 20:42:52 +0000303 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
304 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 EmitBlock(CondBlock);
307
308 // Evaluate the condition if present. If not, treat it as a non-zero-constant
309 // according to 6.8.5.3p2, aka, true.
310 if (S.getCond()) {
311 // C99 6.8.5p2/p4: The first substatement is executed if the expression
312 // compares unequal to 0. The condition must be a scalar type.
313 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
314
315 // As long as the condition is true, iterate the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000316 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
318 EmitBlock(ForBody);
319 } else {
320 // Treat it as a non-zero constant. Don't even create a new block for the
321 // body, just fall into it.
322 }
323
Chris Lattnerda138702007-07-16 21:28:45 +0000324 // If the for loop doesn't have an increment we can just use the
325 // condition as the continue block.
326 llvm::BasicBlock *ContinueBlock;
327 if (S.getInc())
Gabor Greif984d0b42008-04-06 20:42:52 +0000328 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000329 else
330 ContinueBlock = CondBlock;
331
332 // Store the blocks to use for break and continue.
333 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 // If the condition is true, execute the body of the for stmt.
336 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000337
338 BreakContinueStack.pop_back();
339
340 if (S.getInc())
341 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000342
343 // If there is an increment, emit it next.
344 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000345 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000346
347 // Finally, branch back up to the condition for the next iteration.
348 Builder.CreateBr(CondBlock);
349
Chris Lattnerda138702007-07-16 21:28:45 +0000350 // Emit the fall-through block.
351 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
354/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
355/// if the function returns void, or may be missing one if the function returns
356/// non-void. Fun stuff :).
357void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // Emit the result value, even if unused, to evalute the side effects.
359 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000360
Eli Friedman144ac612008-05-22 01:22:33 +0000361 llvm::Value* RetValue = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 if (FnRetTy->isVoidType()) {
Eli Friedman144ac612008-05-22 01:22:33 +0000363 // Make sure not to return anything
364 if (RV) {
365 // Evaluate the expression for side effects
366 EmitAnyExpr(RV);
367 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 } else if (RV == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
Eli Friedman144ac612008-05-22 01:22:33 +0000370 if (RetTy != llvm::Type::VoidTy) {
371 // Handle "return;" in a function that returns a value.
372 RetValue = llvm::UndefValue::get(RetTy);
373 }
Chris Lattner4b0029d2007-08-26 07:14:44 +0000374 } else if (!hasAggregateLLVMType(RV->getType())) {
Eli Friedman144ac612008-05-22 01:22:33 +0000375 RetValue = EmitScalarExpr(RV);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000376 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattner345f7202008-07-26 20:15:14 +0000377 EmitComplexExprIntoAddr(RV, CurFn->arg_begin(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 } else {
Chris Lattner345f7202008-07-26 20:15:14 +0000379 EmitAggExpr(RV, CurFn->arg_begin(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 }
Eli Friedman144ac612008-05-22 01:22:33 +0000381
382 if (RetValue) {
383 Builder.CreateRet(RetValue);
384 } else {
385 Builder.CreateRetVoid();
386 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000387
388 // Emit a block after the branch so that dead code after a return has some
389 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000390 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000391}
392
393void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000394 for (const ScopedDecl *Decl = S.getDecl(); Decl;
395 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000397}
Chris Lattnerda138702007-07-16 21:28:45 +0000398
399void CodeGenFunction::EmitBreakStmt() {
400 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
401
402 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
403 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000404 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000405}
406
407void CodeGenFunction::EmitContinueStmt() {
408 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
409
410 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
411 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000412 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000413}
Devang Patel51b09f22007-10-04 23:45:31 +0000414
Devang Patelc049e4f2007-10-08 20:57:48 +0000415/// EmitCaseStmtRange - If case statement range is not too big then
416/// add multiple cases to switch instruction, one for each value within
417/// the range. If range is too big then emit "if" condition check.
418void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000419 // XXX kill me with param - ddunbar
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000420 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000421
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000422 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
423 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
424
Daniel Dunbar16f23572008-07-25 01:11:38 +0000425 // Emit the code for this case. We do this first to make sure it is
426 // properly chained from our predecessor before generating the
427 // switch machinery to enter this block.
428 StartBlock("sw.bb");
429 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
430 EmitStmt(S.getSubStmt());
431
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000432 // If range is empty, do nothing.
433 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
434 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000435
436 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000437 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000438 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
439 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000440 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000441 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
442 LHS++;
443 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000444 return;
445 }
446
Daniel Dunbar16f23572008-07-25 01:11:38 +0000447 // The range is too big. Emit "if" condition into a new block,
448 // making sure to save and restore the current insertion point.
449 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000450
Daniel Dunbar16f23572008-07-25 01:11:38 +0000451 // Push this test onto the chain of range checks (which terminates
452 // in the default basic block). The switch's default will be changed
453 // to the top of this chain after switch emission is complete.
454 llvm::BasicBlock *FalseDest = CaseRangeBlock;
455 CaseRangeBlock = llvm::BasicBlock::Create("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000456
Daniel Dunbar16f23572008-07-25 01:11:38 +0000457 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
458 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000459
460 // Emit range check.
461 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000462 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
463 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000464 llvm::Value *Cond =
465 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
466 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
467
Daniel Dunbar16f23572008-07-25 01:11:38 +0000468 // Restore the appropriate insertion point.
469 Builder.SetInsertPoint(RestoreBB);
Devang Patelc049e4f2007-10-08 20:57:48 +0000470}
471
472void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
473 if (S.getRHS()) {
474 EmitCaseStmtRange(S);
475 return;
476 }
477
478 StartBlock("sw.bb");
479 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000480 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
481 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal),
482 CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000483 EmitStmt(S.getSubStmt());
484}
485
486void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000487 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
488 assert(DefaultBlock->empty() && "EmitDefaultStmt: Default block already defined?");
489 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000490 EmitStmt(S.getSubStmt());
491}
492
493void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
494 llvm::Value *CondV = EmitScalarExpr(S.getCond());
495
496 // Handle nested switch statements.
497 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000498 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000499
Daniel Dunbar16f23572008-07-25 01:11:38 +0000500 // Create basic block to hold stuff that comes after switch
501 // statement. We also need to create a default block now so that
502 // explicit case ranges tests can have a place to jump to on
503 // failure.
504 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("sw.epilog");
505 llvm::BasicBlock *DefaultBlock = llvm::BasicBlock::Create("sw.default");
506 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
507 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000508
Eli Friedmand28a80d2008-05-12 16:08:04 +0000509 // Create basic block for body of switch
Daniel Dunbar16f23572008-07-25 01:11:38 +0000510 StartBlock("sw.body");
Eli Friedmand28a80d2008-05-12 16:08:04 +0000511
Devang Patele9b8c0a2007-10-30 20:59:40 +0000512 // All break statements jump to NextBlock. If BreakContinueStack is non empty
513 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000514 llvm::BasicBlock *ContinueBlock = NULL;
515 if (!BreakContinueStack.empty())
516 ContinueBlock = BreakContinueStack.back().ContinueBlock;
517 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
518
519 // Emit switch body.
520 EmitStmt(S.getBody());
521 BreakContinueStack.pop_back();
522
Daniel Dunbar16f23572008-07-25 01:11:38 +0000523 // Update the default block in case explicit case range tests have
524 // been chained on top.
525 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000526
Daniel Dunbar16f23572008-07-25 01:11:38 +0000527 // If a default was never emitted then reroute any jumps to it and
528 // discard.
529 if (!DefaultBlock->getParent()) {
530 DefaultBlock->replaceAllUsesWith(NextBlock);
531 delete DefaultBlock;
532 }
Devang Patel51b09f22007-10-04 23:45:31 +0000533
Daniel Dunbar16f23572008-07-25 01:11:38 +0000534 // Emit continuation.
535 EmitBlock(NextBlock);
536
Devang Patel51b09f22007-10-04 23:45:31 +0000537 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000538 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000539}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000540
Chris Lattner345f7202008-07-26 20:15:14 +0000541static std::string ConvertAsmString(const char *Start, unsigned NumOperands,
542 bool IsSimple) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000543 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000544 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000545 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000546 if (IsSimple) {
547 while (*Start) {
548 switch (*Start) {
549 default:
550 Result += *Start;
551 break;
552 case '$':
553 Result += "$$";
554 break;
555 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000556 Start++;
557 }
558
559 return Result;
560 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000561
562 while (*Start) {
563 switch (*Start) {
564 default:
565 Result += *Start;
566 break;
567 case '$':
568 Result += "$$";
569 break;
570 case '%':
571 // Escaped character
572 Start++;
573 if (!*Start) {
574 // FIXME: This should be caught during Sema.
575 assert(0 && "Trailing '%' in asm string.");
576 }
577
578 char EscapedChar = *Start;
579 if (EscapedChar == '%') {
580 // Escaped percentage sign.
581 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000582 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000583 // Generate an unique ID.
584 Result += llvm::utostr(AsmCounter);
585 } else if (isdigit(EscapedChar)) {
586 // %n - Assembler operand n
587 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000588 unsigned long n = strtoul(Start, &End, 10);
589 if (Start == End) {
590 // FIXME: This should be caught during Sema.
591 assert(0 && "Missing operand!");
592 } else if (n >= NumOperands) {
593 // FIXME: This should be caught during Sema.
594 assert(0 && "Operand number out of range!");
595 }
596
597 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000598 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000599 } else if (isalpha(EscapedChar)) {
600 char *End;
601
602 unsigned long n = strtoul(Start + 1, &End, 10);
603 if (Start == End) {
604 // FIXME: This should be caught during Sema.
605 assert(0 && "Missing operand!");
606 } else if (n >= NumOperands) {
607 // FIXME: This should be caught during Sema.
608 assert(0 && "Operand number out of range!");
609 }
610
611 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000612 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000613 } else {
614 assert(0 && "Unhandled asm escaped character!");
615 }
616 }
617 Start++;
618 }
619
620 return Result;
621}
622
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000623static std::string SimplifyConstraint(const char* Constraint,
624 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000625 std::string Result;
626
627 while (*Constraint) {
628 switch (*Constraint) {
629 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000630 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000631 break;
632 // Ignore these
633 case '*':
634 case '?':
635 case '!':
636 break;
637 case 'g':
638 Result += "imr";
639 break;
640 }
641
642 Constraint++;
643 }
644
645 return Result;
646}
647
648void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
649 std::string AsmString =
650 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
651 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000652 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000653
654 std::string Constraints;
655
656 llvm::Value *ResultAddr = 0;
657 const llvm::Type *ResultType = llvm::Type::VoidTy;
658
659 std::vector<const llvm::Type*> ArgTypes;
660 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000661
662 // Keep track of inout constraints.
663 std::string InOutConstraints;
664 std::vector<llvm::Value*> InOutArgs;
665 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000666
667 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
668 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
669 S.getOutputConstraint(i)->getByteLength());
670
671 TargetInfo::ConstraintInfo Info;
672 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
673 Info);
674 assert(result && "Failed to parse output constraint");
675
676 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000677 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000678
679 LValue Dest = EmitLValue(S.getOutputExpr(i));
680 const llvm::Type *DestValueType =
681 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
682
683 // If the first output operand is not a memory dest, we'll
684 // make it the return value.
685 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000686 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000687 ResultAddr = Dest.getAddress();
688 ResultType = DestValueType;
689 Constraints += "=" + OutputConstraint;
690 } else {
691 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000692 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000693 if (i != 0)
694 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000695 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000696 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000697 }
698
699 if (Info & TargetInfo::CI_ReadWrite) {
700 // FIXME: This code should be shared with the code that handles inputs.
701 InOutConstraints += ',';
702
703 const Expr *InputExpr = S.getOutputExpr(i);
704 llvm::Value *Arg;
705 if ((Info & TargetInfo::CI_AllowsRegister) ||
706 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000707 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000708 Arg = EmitScalarExpr(InputExpr);
709 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000710 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000711 }
712 } else {
713 LValue Dest = EmitLValue(InputExpr);
714 Arg = Dest.getAddress();
715 InOutConstraints += '*';
716 }
717
718 InOutArgTypes.push_back(Arg->getType());
719 InOutArgs.push_back(Arg);
720 InOutConstraints += OutputConstraint;
721 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000722 }
723
724 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
725
726 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
727 const Expr *InputExpr = S.getInputExpr(i);
728
729 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
730 S.getInputConstraint(i)->getByteLength());
731
732 TargetInfo::ConstraintInfo Info;
733 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
734 NumConstraints,
735 Info);
736 assert(result && "Failed to parse input constraint");
737
738 if (i != 0 || S.getNumOutputs() > 0)
739 Constraints += ',';
740
741 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000742 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000743
744 llvm::Value *Arg;
745
746 if ((Info & TargetInfo::CI_AllowsRegister) ||
747 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000748 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000749 Arg = EmitScalarExpr(InputExpr);
750 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000751 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000752 }
753 } else {
754 LValue Dest = EmitLValue(InputExpr);
755 Arg = Dest.getAddress();
756 Constraints += '*';
757 }
758
759 ArgTypes.push_back(Arg->getType());
760 Args.push_back(Arg);
761 Constraints += InputConstraint;
762 }
763
Anders Carlssonf39a4212008-02-05 20:01:53 +0000764 // Append the "input" part of inout constraints last.
765 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
766 ArgTypes.push_back(InOutArgTypes[i]);
767 Args.push_back(InOutArgs[i]);
768 }
769 Constraints += InOutConstraints;
770
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000771 // Clobbers
772 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
773 std::string Clobber(S.getClobber(i)->getStrData(),
774 S.getClobber(i)->getByteLength());
775
776 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
777
Anders Carlssonea041752008-02-06 00:11:32 +0000778 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000779 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000780
781 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000782 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000783 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000784 }
785
786 // Add machine specific clobbers
787 if (const char *C = Target.getClobbers()) {
788 if (!Constraints.empty())
789 Constraints += ',';
790 Constraints += C;
791 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000792
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000793 const llvm::FunctionType *FTy =
794 llvm::FunctionType::get(ResultType, ArgTypes, false);
795
796 llvm::InlineAsm *IA =
797 llvm::InlineAsm::get(FTy, AsmString, Constraints,
798 S.isVolatile() || S.getNumOutputs() == 0);
799 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000800 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000801 Builder.CreateStore(Result, ResultAddr);
802}