blob: 3f69cd0a02144a8afb3c6e50222b807a751911ed [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;
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000090
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000091 CGDebugInfo *DI = CGM.getDebugInfo();
92 if (DI) {
93 if (S.getLBracLoc().isValid()) {
94 DI->setLocation(S.getLBracLoc());
95 }
96 DI->EmitRegionStart(CurFn, Builder);
97 }
98
Chris Lattner33793202007-08-31 22:09:40 +000099 for (CompoundStmt::const_body_iterator I = S.body_begin(),
100 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000102
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000103 if (DI) {
104 if (S.getRBracLoc().isValid()) {
105 DI->setLocation(S.getRBracLoc());
106 }
107 DI->EmitRegionEnd(CurFn, Builder);
108 }
109
Chris Lattner33793202007-08-31 22:09:40 +0000110 if (!GetLast)
111 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000112
113 return EmitAnyExpr(cast<Expr>(S.body_back()), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000114}
115
116void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
117 // Emit a branch from this block to the next one if this was a real block. If
118 // this was just a fall-through block after a terminator, don't emit it.
119 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
120
121 if (LastBB->getTerminator()) {
122 // If the previous block is already terminated, don't touch it.
123 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
124 // If the last block was an empty placeholder, remove it now.
125 // TODO: cache and reuse these.
126 Builder.GetInsertBlock()->eraseFromParent();
127 } else {
128 // Otherwise, create a fall-through branch.
129 Builder.CreateBr(BB);
130 }
131 CurFn->getBasicBlockList().push_back(BB);
132 Builder.SetInsertPoint(BB);
133}
134
135void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
136 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
137
138 EmitBlock(NextBB);
139 EmitStmt(S.getSubStmt());
140}
141
142void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
143 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
144
145 // Emit a block after the branch so that dead code after a goto has some place
146 // to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000147 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Reid Spencer5f016e22007-07-11 17:01:13 +0000148}
149
150void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
151 // C99 6.8.4.1: The first substatement is executed if the expression compares
152 // unequal to 0. The condition must be a scalar type.
153 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
154
Gabor Greif984d0b42008-04-06 20:42:52 +0000155 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
156 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 llvm::BasicBlock *ElseBlock = ContBlock;
158
159 if (S.getElse())
Gabor Greif984d0b42008-04-06 20:42:52 +0000160 ElseBlock = llvm::BasicBlock::Create("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000161
162 // Insert the conditional branch.
163 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
164
165 // Emit the 'then' code.
166 EmitBlock(ThenBlock);
167 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000168 llvm::BasicBlock *BB = Builder.GetInsertBlock();
169 if (isDummyBlock(BB)) {
170 BB->eraseFromParent();
171 Builder.SetInsertPoint(ThenBlock);
172 }
173 else
174 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000175
176 // Emit the 'else' code if present.
177 if (const Stmt *Else = S.getElse()) {
178 EmitBlock(ElseBlock);
179 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000180 llvm::BasicBlock *BB = Builder.GetInsertBlock();
181 if (isDummyBlock(BB)) {
182 BB->eraseFromParent();
183 Builder.SetInsertPoint(ElseBlock);
184 }
185 else
186 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 }
188
189 // Emit the continuation block for code after the if.
190 EmitBlock(ContBlock);
191}
192
193void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 // Emit the header for the loop, insert it, which will create an uncond br to
195 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000196 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 EmitBlock(LoopHeader);
198
199 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
200 // of the controlling expression takes place before each execution of the loop
201 // body.
202 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000203
204 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000206 bool EmitBoolCondBranch = true;
207 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
208 if (C->isOne())
209 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000210
211 // Create an exit block for when the condition fails, create a block for the
212 // body of the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000213 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
214 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000215
216 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000217 if (EmitBoolCondBranch)
218 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000219
220 // Store the blocks to use for break and continue.
221 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000222
223 // Emit the loop body.
224 EmitBlock(LoopBody);
225 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000226
227 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000228
229 // Cycle to the condition.
230 Builder.CreateBr(LoopHeader);
231
232 // Emit the exit block.
233 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000234
235 // If LoopHeader is a simple forwarding block then eliminate it.
236 if (!EmitBoolCondBranch
237 && &LoopHeader->front() == LoopHeader->getTerminator()) {
238 LoopHeader->replaceAllUsesWith(LoopBody);
239 LoopHeader->getTerminator()->eraseFromParent();
240 LoopHeader->eraseFromParent();
241 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000242}
243
244void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 // Emit the body for the loop, insert it, which will create an uncond br to
246 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000247 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
248 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000250
Gabor Greif984d0b42008-04-06 20:42:52 +0000251 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000252
253 // Store the blocks to use for break and continue.
254 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000255
256 // Emit the body of the loop into the block.
257 EmitStmt(S.getBody());
258
Chris Lattnerda138702007-07-16 21:28:45 +0000259 BreakContinueStack.pop_back();
260
261 EmitBlock(DoCond);
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
264 // after each execution of the loop body."
265
266 // Evaluate the conditional in the while header.
267 // C99 6.8.5p2/p4: The first substatement is executed if the expression
268 // compares unequal to 0. The condition must be a scalar type.
269 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000270
271 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
272 // to correctly handle break/continue though.
273 bool EmitBoolCondBranch = true;
274 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
275 if (C->isZero())
276 EmitBoolCondBranch = false;
277
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000279 if (EmitBoolCondBranch)
280 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000281
282 // Emit the exit block.
283 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000284
285 // If DoCond is a simple forwarding block then eliminate it.
286 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
287 DoCond->replaceAllUsesWith(AfterDo);
288 DoCond->getTerminator()->eraseFromParent();
289 DoCond->eraseFromParent();
290 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000291}
292
293void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
295 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000296 // TODO: We could keep track of whether the loop body contains any
297 // break/continue statements and not create unnecessary blocks (like
298 // "afterfor" for a condless loop) if it doesn't.
299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // Evaluate the first part before the loop.
301 if (S.getInit())
302 EmitStmt(S.getInit());
303
304 // Start the loop with a block that tests the condition.
Gabor Greif984d0b42008-04-06 20:42:52 +0000305 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
306 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 EmitBlock(CondBlock);
309
310 // Evaluate the condition if present. If not, treat it as a non-zero-constant
311 // according to 6.8.5.3p2, aka, true.
312 if (S.getCond()) {
313 // C99 6.8.5p2/p4: The first substatement is executed if the expression
314 // compares unequal to 0. The condition must be a scalar type.
315 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
316
317 // As long as the condition is true, iterate the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000318 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
320 EmitBlock(ForBody);
321 } else {
322 // Treat it as a non-zero constant. Don't even create a new block for the
323 // body, just fall into it.
324 }
325
Chris Lattnerda138702007-07-16 21:28:45 +0000326 // If the for loop doesn't have an increment we can just use the
327 // condition as the continue block.
328 llvm::BasicBlock *ContinueBlock;
329 if (S.getInc())
Gabor Greif984d0b42008-04-06 20:42:52 +0000330 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000331 else
332 ContinueBlock = CondBlock;
333
334 // Store the blocks to use for break and continue.
335 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 // If the condition is true, execute the body of the for stmt.
338 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000339
340 BreakContinueStack.pop_back();
341
342 if (S.getInc())
343 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
345 // If there is an increment, emit it next.
346 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000347 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000348
349 // Finally, branch back up to the condition for the next iteration.
350 Builder.CreateBr(CondBlock);
351
Chris Lattnerda138702007-07-16 21:28:45 +0000352 // Emit the fall-through block.
353 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
356/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
357/// if the function returns void, or may be missing one if the function returns
358/// non-void. Fun stuff :).
359void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Emit the result value, even if unused, to evalute the side effects.
361 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000362
Eli Friedman144ac612008-05-22 01:22:33 +0000363 llvm::Value* RetValue = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 if (FnRetTy->isVoidType()) {
Eli Friedman144ac612008-05-22 01:22:33 +0000365 // Make sure not to return anything
366 if (RV) {
367 // Evaluate the expression for side effects
368 EmitAnyExpr(RV);
369 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 } else if (RV == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
Eli Friedman144ac612008-05-22 01:22:33 +0000372 if (RetTy != llvm::Type::VoidTy) {
373 // Handle "return;" in a function that returns a value.
374 RetValue = llvm::UndefValue::get(RetTy);
375 }
Chris Lattner4b0029d2007-08-26 07:14:44 +0000376 } else if (!hasAggregateLLVMType(RV->getType())) {
Eli Friedman144ac612008-05-22 01:22:33 +0000377 RetValue = EmitScalarExpr(RV);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000378 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000379 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000380 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000382 llvm::Value *SRetPtr = CurFn->arg_begin();
383 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 }
Eli Friedman144ac612008-05-22 01:22:33 +0000385
386 if (RetValue) {
387 Builder.CreateRet(RetValue);
388 } else {
389 Builder.CreateRetVoid();
390 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000391
392 // Emit a block after the branch so that dead code after a return has some
393 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000394 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000395}
396
397void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000398 for (const ScopedDecl *Decl = S.getDecl(); Decl;
399 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000401}
Chris Lattnerda138702007-07-16 21:28:45 +0000402
403void CodeGenFunction::EmitBreakStmt() {
404 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
405
406 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
407 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000408 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000409}
410
411void CodeGenFunction::EmitContinueStmt() {
412 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
413
414 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
415 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000416 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000417}
Devang Patel51b09f22007-10-04 23:45:31 +0000418
Devang Patelc049e4f2007-10-08 20:57:48 +0000419/// EmitCaseStmtRange - If case statement range is not too big then
420/// add multiple cases to switch instruction, one for each value within
421/// the range. If range is too big then emit "if" condition check.
422void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000423 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000424
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000425 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
426 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
427
428 // If range is empty, do nothing.
429 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
430 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000431
432 llvm::APInt Range = RHS - LHS;
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000433 // FIXME: parameters such as this should not be hardcoded
Devang Patelc049e4f2007-10-08 20:57:48 +0000434 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
435 // Range is small enough to add multiple switch instruction cases.
436 StartBlock("sw.bb");
437 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000438 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000439 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
440 LHS++;
441 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000442 EmitStmt(S.getSubStmt());
443 return;
444 }
445
446 // The range is too big. Emit "if" condition.
447 llvm::BasicBlock *FalseDest = NULL;
Gabor Greif984d0b42008-04-06 20:42:52 +0000448 llvm::BasicBlock *CaseDest = llvm::BasicBlock::Create("sw.bb");
Devang Patel2d79d0f2007-10-05 20:54:07 +0000449
Devang Patelc049e4f2007-10-08 20:57:48 +0000450 // If we have already seen one case statement range for this switch
451 // instruction then piggy-back otherwise use default block as false
452 // destination.
453 if (CaseRangeBlock)
454 FalseDest = CaseRangeBlock;
455 else
456 FalseDest = SwitchInsn->getDefaultDest();
457
458 // Start new block to hold case statement range check instructions.
459 StartBlock("case.range");
460 CaseRangeBlock = Builder.GetInsertBlock();
461
462 // Emit range check.
463 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000464 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
465 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000466 llvm::Value *Cond =
467 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
468 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
469
470 // Now emit case statement body.
471 EmitBlock(CaseDest);
472 EmitStmt(S.getSubStmt());
473}
474
475void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
476 if (S.getRHS()) {
477 EmitCaseStmtRange(S);
478 return;
479 }
480
481 StartBlock("sw.bb");
482 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000483 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
484 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal),
485 CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000486 EmitStmt(S.getSubStmt());
487}
488
489void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
490 StartBlock("sw.default");
491 // Current insert block is the default destination.
492 SwitchInsn->setSuccessor(0, Builder.GetInsertBlock());
493 EmitStmt(S.getSubStmt());
494}
495
496void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
497 llvm::Value *CondV = EmitScalarExpr(S.getCond());
498
499 // Handle nested switch statements.
500 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000501 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
502 CaseRangeBlock = NULL;
Devang Patel51b09f22007-10-04 23:45:31 +0000503
504 // Create basic block to hold stuff that comes after switch statement.
505 // Initially use it to hold DefaultStmt.
Gabor Greif984d0b42008-04-06 20:42:52 +0000506 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("after.sw");
Devang Patel51b09f22007-10-04 23:45:31 +0000507 SwitchInsn = Builder.CreateSwitch(CondV, NextBlock);
508
Eli Friedmand28a80d2008-05-12 16:08:04 +0000509 // Create basic block for body of switch
510 StartBlock("body.sw");
511
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
Devang Patelc049e4f2007-10-08 20:57:48 +0000523 // If one or more case statement range is seen then use CaseRangeBlock
524 // as the default block. False edge of CaseRangeBlock will lead to
525 // original default block.
526 if (CaseRangeBlock)
527 SwitchInsn->setSuccessor(0, CaseRangeBlock);
528
Devang Patel51b09f22007-10-04 23:45:31 +0000529 // Prune insert block if it is dummy.
530 llvm::BasicBlock *BB = Builder.GetInsertBlock();
531 if (isDummyBlock(BB))
532 BB->eraseFromParent();
Chris Lattner1438b492007-12-01 05:27:33 +0000533 else // Otherwise, branch to continuation.
534 Builder.CreateBr(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000535
536 // Place NextBlock as the new insert point.
Chris Lattner1438b492007-12-01 05:27:33 +0000537 CurFn->getBasicBlockList().push_back(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000538 Builder.SetInsertPoint(NextBlock);
539 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000540 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000541}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000542
543static inline std::string ConvertAsmString(const char *Start,
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000544 unsigned NumOperands,
545 bool IsSimple)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000546{
547 static unsigned AsmCounter = 0;
548
549 AsmCounter++;
550
551 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000552 if (IsSimple) {
553 while (*Start) {
554 switch (*Start) {
555 default:
556 Result += *Start;
557 break;
558 case '$':
559 Result += "$$";
560 break;
561 }
562
563 Start++;
564 }
565
566 return Result;
567 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000568
569 while (*Start) {
570 switch (*Start) {
571 default:
572 Result += *Start;
573 break;
574 case '$':
575 Result += "$$";
576 break;
577 case '%':
578 // Escaped character
579 Start++;
580 if (!*Start) {
581 // FIXME: This should be caught during Sema.
582 assert(0 && "Trailing '%' in asm string.");
583 }
584
585 char EscapedChar = *Start;
586 if (EscapedChar == '%') {
587 // Escaped percentage sign.
588 Result += '%';
589 }
590 else if (EscapedChar == '=') {
591 // Generate an unique ID.
592 Result += llvm::utostr(AsmCounter);
593 } else if (isdigit(EscapedChar)) {
594 // %n - Assembler operand n
595 char *End;
596
597 unsigned long n = strtoul(Start, &End, 10);
598 if (Start == End) {
599 // FIXME: This should be caught during Sema.
600 assert(0 && "Missing operand!");
601 } else if (n >= NumOperands) {
602 // FIXME: This should be caught during Sema.
603 assert(0 && "Operand number out of range!");
604 }
605
606 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000607 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000608 } else if (isalpha(EscapedChar)) {
609 char *End;
610
611 unsigned long n = strtoul(Start + 1, &End, 10);
612 if (Start == End) {
613 // FIXME: This should be caught during Sema.
614 assert(0 && "Missing operand!");
615 } else if (n >= NumOperands) {
616 // FIXME: This should be caught during Sema.
617 assert(0 && "Operand number out of range!");
618 }
619
620 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000621 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000622 } else {
623 assert(0 && "Unhandled asm escaped character!");
624 }
625 }
626 Start++;
627 }
628
629 return Result;
630}
631
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000632static std::string SimplifyConstraint(const char* Constraint,
633 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000634 std::string Result;
635
636 while (*Constraint) {
637 switch (*Constraint) {
638 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000639 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000640 break;
641 // Ignore these
642 case '*':
643 case '?':
644 case '!':
645 break;
646 case 'g':
647 Result += "imr";
648 break;
649 }
650
651 Constraint++;
652 }
653
654 return Result;
655}
656
657void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
658 std::string AsmString =
659 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
660 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000661 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000662
663 std::string Constraints;
664
665 llvm::Value *ResultAddr = 0;
666 const llvm::Type *ResultType = llvm::Type::VoidTy;
667
668 std::vector<const llvm::Type*> ArgTypes;
669 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000670
671 // Keep track of inout constraints.
672 std::string InOutConstraints;
673 std::vector<llvm::Value*> InOutArgs;
674 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000675
676 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
677 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
678 S.getOutputConstraint(i)->getByteLength());
679
680 TargetInfo::ConstraintInfo Info;
681 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
682 Info);
683 assert(result && "Failed to parse output constraint");
684
685 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000686 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000687
688 LValue Dest = EmitLValue(S.getOutputExpr(i));
689 const llvm::Type *DestValueType =
690 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
691
692 // If the first output operand is not a memory dest, we'll
693 // make it the return value.
694 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000695 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000696 ResultAddr = Dest.getAddress();
697 ResultType = DestValueType;
698 Constraints += "=" + OutputConstraint;
699 } else {
700 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000701 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000702 if (i != 0)
703 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000704 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000705 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000706 }
707
708 if (Info & TargetInfo::CI_ReadWrite) {
709 // FIXME: This code should be shared with the code that handles inputs.
710 InOutConstraints += ',';
711
712 const Expr *InputExpr = S.getOutputExpr(i);
713 llvm::Value *Arg;
714 if ((Info & TargetInfo::CI_AllowsRegister) ||
715 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000716 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000717 Arg = EmitScalarExpr(InputExpr);
718 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000719 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000720 }
721 } else {
722 LValue Dest = EmitLValue(InputExpr);
723 Arg = Dest.getAddress();
724 InOutConstraints += '*';
725 }
726
727 InOutArgTypes.push_back(Arg->getType());
728 InOutArgs.push_back(Arg);
729 InOutConstraints += OutputConstraint;
730 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000731 }
732
733 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
734
735 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
736 const Expr *InputExpr = S.getInputExpr(i);
737
738 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
739 S.getInputConstraint(i)->getByteLength());
740
741 TargetInfo::ConstraintInfo Info;
742 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
743 NumConstraints,
744 Info);
745 assert(result && "Failed to parse input constraint");
746
747 if (i != 0 || S.getNumOutputs() > 0)
748 Constraints += ',';
749
750 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000751 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000752
753 llvm::Value *Arg;
754
755 if ((Info & TargetInfo::CI_AllowsRegister) ||
756 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000757 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000758 Arg = EmitScalarExpr(InputExpr);
759 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000760 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000761 }
762 } else {
763 LValue Dest = EmitLValue(InputExpr);
764 Arg = Dest.getAddress();
765 Constraints += '*';
766 }
767
768 ArgTypes.push_back(Arg->getType());
769 Args.push_back(Arg);
770 Constraints += InputConstraint;
771 }
772
Anders Carlssonf39a4212008-02-05 20:01:53 +0000773 // Append the "input" part of inout constraints last.
774 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
775 ArgTypes.push_back(InOutArgTypes[i]);
776 Args.push_back(InOutArgs[i]);
777 }
778 Constraints += InOutConstraints;
779
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000780 // Clobbers
781 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
782 std::string Clobber(S.getClobber(i)->getStrData(),
783 S.getClobber(i)->getByteLength());
784
785 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
786
Anders Carlssonea041752008-02-06 00:11:32 +0000787 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000788 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000789
790 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000791 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000792 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000793 }
794
795 // Add machine specific clobbers
796 if (const char *C = Target.getClobbers()) {
797 if (!Constraints.empty())
798 Constraints += ',';
799 Constraints += C;
800 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000801
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000802 const llvm::FunctionType *FTy =
803 llvm::FunctionType::get(ResultType, ArgTypes, false);
804
805 llvm::InlineAsm *IA =
806 llvm::InlineAsm::get(FTy, AsmString, Constraints,
807 S.isVolatile() || S.getNumOutputs() == 0);
808 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000809 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000810 Builder.CreateStore(Result, ResultAddr);
811}