blob: 7986b4a11325295287518262c386a7756f240b38 [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;
Reid Spencer5f016e22007-07-11 17:01:13 +000090
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +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
103 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
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 if (FnRetTy->isVoidType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000364 // If the function returns void, emit ret void.
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 Builder.CreateRetVoid();
366 } else if (RV == 0) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000367 // Handle "return;" in a function that returns a value.
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
369 if (RetTy == llvm::Type::VoidTy)
370 Builder.CreateRetVoid(); // struct return etc.
371 else
372 Builder.CreateRet(llvm::UndefValue::get(RetTy));
Chris Lattner4b0029d2007-08-26 07:14:44 +0000373 } else if (!hasAggregateLLVMType(RV->getType())) {
374 Builder.CreateRet(EmitScalarExpr(RV));
Chris Lattner9b2dc282008-04-04 16:54:41 +0000375 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000376 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000377 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000379 llvm::Value *SRetPtr = CurFn->arg_begin();
380 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 }
382
383 // Emit a block after the branch so that dead code after a return has some
384 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000385 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000386}
387
388void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000389 for (const ScopedDecl *Decl = S.getDecl(); Decl;
390 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000392}
Chris Lattnerda138702007-07-16 21:28:45 +0000393
394void CodeGenFunction::EmitBreakStmt() {
395 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
396
397 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
398 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000399 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000400}
401
402void CodeGenFunction::EmitContinueStmt() {
403 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
404
405 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
406 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000407 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000408}
Devang Patel51b09f22007-10-04 23:45:31 +0000409
Devang Patelc049e4f2007-10-08 20:57:48 +0000410/// EmitCaseStmtRange - If case statement range is not too big then
411/// add multiple cases to switch instruction, one for each value within
412/// the range. If range is too big then emit "if" condition check.
413void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
414 assert (S.getRHS() && "Unexpected RHS value in CaseStmt");
415
416 const Expr *L = S.getLHS();
417 const Expr *R = S.getRHS();
418 llvm::ConstantInt *LV = cast<llvm::ConstantInt>(EmitScalarExpr(L));
419 llvm::ConstantInt *RV = cast<llvm::ConstantInt>(EmitScalarExpr(R));
420 llvm::APInt LHS = LV->getValue();
Devang Patel00ee4e42007-10-09 17:10:59 +0000421 const llvm::APInt &RHS = RV->getValue();
Devang Patelc049e4f2007-10-08 20:57:48 +0000422
423 llvm::APInt Range = RHS - LHS;
424 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
425 // Range is small enough to add multiple switch instruction cases.
426 StartBlock("sw.bb");
427 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
428 SwitchInsn->addCase(LV, CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000429 LHS++;
430 while (LHS != RHS) {
431 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
432 LHS++;
433 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000434 SwitchInsn->addCase(RV, CaseDest);
435 EmitStmt(S.getSubStmt());
436 return;
437 }
438
439 // The range is too big. Emit "if" condition.
440 llvm::BasicBlock *FalseDest = NULL;
Gabor Greif984d0b42008-04-06 20:42:52 +0000441 llvm::BasicBlock *CaseDest = llvm::BasicBlock::Create("sw.bb");
Devang Patel2d79d0f2007-10-05 20:54:07 +0000442
Devang Patelc049e4f2007-10-08 20:57:48 +0000443 // If we have already seen one case statement range for this switch
444 // instruction then piggy-back otherwise use default block as false
445 // destination.
446 if (CaseRangeBlock)
447 FalseDest = CaseRangeBlock;
448 else
449 FalseDest = SwitchInsn->getDefaultDest();
450
451 // Start new block to hold case statement range check instructions.
452 StartBlock("case.range");
453 CaseRangeBlock = Builder.GetInsertBlock();
454
455 // Emit range check.
456 llvm::Value *Diff =
457 Builder.CreateSub(SwitchInsn->getCondition(), LV, "tmp");
458 llvm::Value *Cond =
459 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
460 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
461
462 // Now emit case statement body.
463 EmitBlock(CaseDest);
464 EmitStmt(S.getSubStmt());
465}
466
467void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
468 if (S.getRHS()) {
469 EmitCaseStmtRange(S);
470 return;
471 }
472
473 StartBlock("sw.bb");
474 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Chris Lattnerc69a5812007-11-30 17:44:57 +0000475 llvm::APSInt CaseVal(32);
476 S.getLHS()->isIntegerConstantExpr(CaseVal, getContext());
477 llvm::ConstantInt *LV = llvm::ConstantInt::get(CaseVal);
Devang Patelc049e4f2007-10-08 20:57:48 +0000478 SwitchInsn->addCase(LV, CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000479 EmitStmt(S.getSubStmt());
480}
481
482void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
483 StartBlock("sw.default");
484 // Current insert block is the default destination.
485 SwitchInsn->setSuccessor(0, Builder.GetInsertBlock());
486 EmitStmt(S.getSubStmt());
487}
488
489void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
490 llvm::Value *CondV = EmitScalarExpr(S.getCond());
491
492 // Handle nested switch statements.
493 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000494 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
495 CaseRangeBlock = NULL;
Devang Patel51b09f22007-10-04 23:45:31 +0000496
497 // Create basic block to hold stuff that comes after switch statement.
498 // Initially use it to hold DefaultStmt.
Gabor Greif984d0b42008-04-06 20:42:52 +0000499 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("after.sw");
Devang Patel51b09f22007-10-04 23:45:31 +0000500 SwitchInsn = Builder.CreateSwitch(CondV, NextBlock);
501
Eli Friedmand28a80d2008-05-12 16:08:04 +0000502 // Create basic block for body of switch
503 StartBlock("body.sw");
504
Devang Patele9b8c0a2007-10-30 20:59:40 +0000505 // All break statements jump to NextBlock. If BreakContinueStack is non empty
506 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000507 llvm::BasicBlock *ContinueBlock = NULL;
508 if (!BreakContinueStack.empty())
509 ContinueBlock = BreakContinueStack.back().ContinueBlock;
510 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
511
512 // Emit switch body.
513 EmitStmt(S.getBody());
514 BreakContinueStack.pop_back();
515
Devang Patelc049e4f2007-10-08 20:57:48 +0000516 // If one or more case statement range is seen then use CaseRangeBlock
517 // as the default block. False edge of CaseRangeBlock will lead to
518 // original default block.
519 if (CaseRangeBlock)
520 SwitchInsn->setSuccessor(0, CaseRangeBlock);
521
Devang Patel51b09f22007-10-04 23:45:31 +0000522 // Prune insert block if it is dummy.
523 llvm::BasicBlock *BB = Builder.GetInsertBlock();
524 if (isDummyBlock(BB))
525 BB->eraseFromParent();
Chris Lattner1438b492007-12-01 05:27:33 +0000526 else // Otherwise, branch to continuation.
527 Builder.CreateBr(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000528
529 // Place NextBlock as the new insert point.
Chris Lattner1438b492007-12-01 05:27:33 +0000530 CurFn->getBasicBlockList().push_back(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000531 Builder.SetInsertPoint(NextBlock);
532 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000533 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000534}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000535
536static inline std::string ConvertAsmString(const char *Start,
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000537 unsigned NumOperands,
538 bool IsSimple)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000539{
540 static unsigned AsmCounter = 0;
541
542 AsmCounter++;
543
544 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000545 if (IsSimple) {
546 while (*Start) {
547 switch (*Start) {
548 default:
549 Result += *Start;
550 break;
551 case '$':
552 Result += "$$";
553 break;
554 }
555
556 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 += '%';
582 }
583 else if (EscapedChar == '=') {
584 // Generate an unique ID.
585 Result += llvm::utostr(AsmCounter);
586 } else if (isdigit(EscapedChar)) {
587 // %n - Assembler operand n
588 char *End;
589
590 unsigned long n = strtoul(Start, &End, 10);
591 if (Start == End) {
592 // FIXME: This should be caught during Sema.
593 assert(0 && "Missing operand!");
594 } else if (n >= NumOperands) {
595 // FIXME: This should be caught during Sema.
596 assert(0 && "Operand number out of range!");
597 }
598
599 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000600 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000601 } else if (isalpha(EscapedChar)) {
602 char *End;
603
604 unsigned long n = strtoul(Start + 1, &End, 10);
605 if (Start == End) {
606 // FIXME: This should be caught during Sema.
607 assert(0 && "Missing operand!");
608 } else if (n >= NumOperands) {
609 // FIXME: This should be caught during Sema.
610 assert(0 && "Operand number out of range!");
611 }
612
613 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000614 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000615 } else {
616 assert(0 && "Unhandled asm escaped character!");
617 }
618 }
619 Start++;
620 }
621
622 return Result;
623}
624
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000625static std::string SimplifyConstraint(const char* Constraint,
626 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000627 std::string Result;
628
629 while (*Constraint) {
630 switch (*Constraint) {
631 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000632 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000633 break;
634 // Ignore these
635 case '*':
636 case '?':
637 case '!':
638 break;
639 case 'g':
640 Result += "imr";
641 break;
642 }
643
644 Constraint++;
645 }
646
647 return Result;
648}
649
650void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
651 std::string AsmString =
652 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
653 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000654 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000655
656 std::string Constraints;
657
658 llvm::Value *ResultAddr = 0;
659 const llvm::Type *ResultType = llvm::Type::VoidTy;
660
661 std::vector<const llvm::Type*> ArgTypes;
662 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000663
664 // Keep track of inout constraints.
665 std::string InOutConstraints;
666 std::vector<llvm::Value*> InOutArgs;
667 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000668
669 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
670 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
671 S.getOutputConstraint(i)->getByteLength());
672
673 TargetInfo::ConstraintInfo Info;
674 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
675 Info);
676 assert(result && "Failed to parse output constraint");
677
678 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000679 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000680
681 LValue Dest = EmitLValue(S.getOutputExpr(i));
682 const llvm::Type *DestValueType =
683 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
684
685 // If the first output operand is not a memory dest, we'll
686 // make it the return value.
687 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
688 DestValueType->isFirstClassType()) {
689 ResultAddr = Dest.getAddress();
690 ResultType = DestValueType;
691 Constraints += "=" + OutputConstraint;
692 } else {
693 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000694 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000695 if (i != 0)
696 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000697 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000698 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000699 }
700
701 if (Info & TargetInfo::CI_ReadWrite) {
702 // FIXME: This code should be shared with the code that handles inputs.
703 InOutConstraints += ',';
704
705 const Expr *InputExpr = S.getOutputExpr(i);
706 llvm::Value *Arg;
707 if ((Info & TargetInfo::CI_AllowsRegister) ||
708 !(Info & TargetInfo::CI_AllowsMemory)) {
709 if (ConvertType(InputExpr->getType())->isFirstClassType()) {
710 Arg = EmitScalarExpr(InputExpr);
711 } else {
712 assert(0 && "FIXME: Implement passing non first class types as inputs");
713 }
714 } else {
715 LValue Dest = EmitLValue(InputExpr);
716 Arg = Dest.getAddress();
717 InOutConstraints += '*';
718 }
719
720 InOutArgTypes.push_back(Arg->getType());
721 InOutArgs.push_back(Arg);
722 InOutConstraints += OutputConstraint;
723 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000724 }
725
726 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
727
728 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
729 const Expr *InputExpr = S.getInputExpr(i);
730
731 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
732 S.getInputConstraint(i)->getByteLength());
733
734 TargetInfo::ConstraintInfo Info;
735 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
736 NumConstraints,
737 Info);
738 assert(result && "Failed to parse input constraint");
739
740 if (i != 0 || S.getNumOutputs() > 0)
741 Constraints += ',';
742
743 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000744 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000745
746 llvm::Value *Arg;
747
748 if ((Info & TargetInfo::CI_AllowsRegister) ||
749 !(Info & TargetInfo::CI_AllowsMemory)) {
750 if (ConvertType(InputExpr->getType())->isFirstClassType()) {
751 Arg = EmitScalarExpr(InputExpr);
752 } else {
753 assert(0 && "FIXME: Implement passing non first class types as inputs");
754 }
755 } else {
756 LValue Dest = EmitLValue(InputExpr);
757 Arg = Dest.getAddress();
758 Constraints += '*';
759 }
760
761 ArgTypes.push_back(Arg->getType());
762 Args.push_back(Arg);
763 Constraints += InputConstraint;
764 }
765
Anders Carlssonf39a4212008-02-05 20:01:53 +0000766 // Append the "input" part of inout constraints last.
767 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
768 ArgTypes.push_back(InOutArgTypes[i]);
769 Args.push_back(InOutArgs[i]);
770 }
771 Constraints += InOutConstraints;
772
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000773 // Clobbers
774 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
775 std::string Clobber(S.getClobber(i)->getStrData(),
776 S.getClobber(i)->getByteLength());
777
778 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
779
Anders Carlssonea041752008-02-06 00:11:32 +0000780 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000781 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000782
783 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000784 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000785 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000786 }
787
788 // Add machine specific clobbers
789 if (const char *C = Target.getClobbers()) {
790 if (!Constraints.empty())
791 Constraints += ',';
792 Constraints += C;
793 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000794
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000795 const llvm::FunctionType *FTy =
796 llvm::FunctionType::get(ResultType, ArgTypes, false);
797
798 llvm::InlineAsm *IA =
799 llvm::InlineAsm::get(FTy, AsmString, Constraints,
800 S.isVolatile() || S.getNumOutputs() == 0);
801 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
802 if (ResultAddr)
803 Builder.CreateStore(Result, ResultAddr);
804}