blob: 19977ec380e52a26ae1db4ed45f8907c10bc9e82 [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"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000020#include "llvm/InlineAsm.h"
21#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
26//===----------------------------------------------------------------------===//
27// Statement Emission
28//===----------------------------------------------------------------------===//
29
Daniel Dunbar09124252008-11-12 08:21:33 +000030void CodeGenFunction::EmitStopPoint(const Stmt *S) {
31 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
32 DI->setLocation(S->getLocStart());
33 DI->EmitStopPoint(CurFn, Builder);
34 }
35}
36
Reid Spencer5f016e22007-07-11 17:01:13 +000037void CodeGenFunction::EmitStmt(const Stmt *S) {
38 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000039
Daniel Dunbar09124252008-11-12 08:21:33 +000040 // Check if we can handle this without bothering to generate an
41 // insert point or debug info.
42 if (EmitSimpleStmt(S))
43 return;
44
Daniel Dunbara448fb22008-11-11 23:11:34 +000045 // If we happen to be at an unreachable point just create a dummy
46 // basic block to hold the code. We could change parts of irgen to
47 // simply not generate this code, but this situation is rare and
48 // probably not worth the effort.
49 // FIXME: Verify previous performance/effort claim.
50 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000051
Daniel Dunbar09124252008-11-12 08:21:33 +000052 // Generate a stoppoint if we are emitting debug info.
53 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000054
Reid Spencer5f016e22007-07-11 17:01:13 +000055 switch (S->getStmtClass()) {
56 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000057 // Must be an expression in a stmt context. Emit the value (to get
58 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000059 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000060 if (!hasAggregateLLVMType(E->getType()))
61 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000062 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000063 EmitComplexExpr(E);
64 else
65 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000066 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000067 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000068 }
69 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000070 case Stmt::IndirectGotoStmtClass:
71 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000072
73 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
74 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
75 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
76 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
77
78 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
79 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000080
Devang Patel51b09f22007-10-04 23:45:31 +000081 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000082 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000083
84 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000085 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
86 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000087 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000088 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
89 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000090 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000091 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000092 break;
93 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000094 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000095 break;
96 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000097 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000098 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000099 case Stmt::ObjCForCollectionStmtClass:
100 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 }
103}
104
Daniel Dunbar09124252008-11-12 08:21:33 +0000105bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
106 switch (S->getStmtClass()) {
107 default: return false;
108 case Stmt::NullStmtClass: break;
109 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
110 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
111 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
112 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
113 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
114 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
115 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
116 }
117
118 return true;
119}
120
Chris Lattner33793202007-08-31 22:09:40 +0000121/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
122/// this captures the expression result of the last sub-statement and returns it
123/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000124RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
125 llvm::Value *AggLoc, bool isAggVol) {
Anders Carlssonc71c8452009-02-07 23:50:39 +0000126
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000127 CGDebugInfo *DI = CGM.getDebugInfo();
128 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000129 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000130 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000131 DI->EmitRegionStart(CurFn, Builder);
132 }
133
Anders Carlssonc71c8452009-02-07 23:50:39 +0000134 // Keep track of the current cleanup stack depth.
135 size_t CleanupStackDepth = CleanupEntries.size();
136
Anders Carlsson17d28a32008-12-12 05:52:00 +0000137 // Push a null stack save value.
138 StackSaveValues.push_back(0);
139
Chris Lattner33793202007-08-31 22:09:40 +0000140 for (CompoundStmt::const_body_iterator I = S.body_begin(),
141 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000143
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000144 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000145 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000146 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000147 DI->EmitRegionEnd(CurFn, Builder);
148 }
149
Anders Carlsson17d28a32008-12-12 05:52:00 +0000150 RValue RV;
151 if (!GetLast)
152 RV = RValue::get(0);
153 else {
154 // We have to special case labels here. They are statements, but when put
155 // at the end of a statement expression, they yield the value of their
156 // subexpression. Handle this by walking through all labels we encounter,
157 // emitting them before we evaluate the subexpr.
158 const Stmt *LastStmt = S.body_back();
159 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
160 EmitLabel(*LS);
161 LastStmt = LS->getSubStmt();
162 }
Chris Lattner9b655512007-08-31 22:49:20 +0000163
Anders Carlsson17d28a32008-12-12 05:52:00 +0000164 EnsureInsertPoint();
165
166 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
167 }
168
169 if (llvm::Value *V = StackSaveValues.pop_back_val()) {
Mike Stump36a2ada2009-02-07 12:52:26 +0000170 StackDepth = V;
Anders Carlsson17d28a32008-12-12 05:52:00 +0000171 V = Builder.CreateLoad(V, "tmp");
172
173 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
174 Builder.CreateCall(F, V);
Chris Lattner91d723d2008-07-26 20:23:23 +0000175 }
176
Anders Carlssonc71c8452009-02-07 23:50:39 +0000177 EmitCleanupBlocks(CleanupStackDepth);
178
Anders Carlsson17d28a32008-12-12 05:52:00 +0000179 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000180}
181
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000182void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000183 // Fall out of the current block (if necessary).
184 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000185
186 if (IsFinished && BB->use_empty()) {
187 delete BB;
188 return;
189 }
190
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000191 // If necessary, associate the block with the cleanup stack size.
192 if (!CleanupEntries.empty()) {
193 BlockScopes[BB] = CleanupEntries.size() - 1;
194 CleanupEntries.back().Blocks.push_back(BB);
195 }
196
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 CurFn->getBasicBlockList().push_back(BB);
198 Builder.SetInsertPoint(BB);
199}
200
Mike Stump36a2ada2009-02-07 12:52:26 +0000201void CodeGenFunction::EmitStackUpdate(const LabelStmt &S) {
202 if (StackDepthMap.find(&S) == StackDepthMap.end()) {
203 // If we can't find it, just remember the depth now,
204 // so we can validate it later.
205 // FIXME: We need to save a place to insert the adjustment,
206 // if needed, here, sa that later in EmitLabel, we can
207 // backpatch the adjustment into that place, instead of
208 // saying unsupported.
209 StackDepthMap[&S] = StackDepth;
210 return;
211 }
212
213 // Find applicable stack depth, if any...
214 llvm::Value *V = StackDepthMap[&S];
215 // V can be 0 here, if it is, be sure to start searching from the
216 // top of the function, as we want the next save after that point.
217 for (unsigned int i = 0; i < StackSaveValues.size(); ++i)
218 if (StackSaveValues[i] == V) {
219 // The actual depth is actually in the next used slot, if any.
220 while (++i < StackSaveValues.size()
221 && (V = StackSaveValues[i]) == 0) ;
222 // If there were no other depth changes, we don't need any
223 // adjustments.
224 if (V) {
225 V = Builder.CreateLoad(V, "tmp");
226 // and restore it.
227 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
228 Builder.CreateCall(F, V);
229 }
230 } else
231 // FIXME: Move to semq and assert here, codegen isn't the right
232 // time to be checking.
233 CGM.ErrorUnsupported(&S, "invalid goto to VLA scope that has finished");
234}
235
Daniel Dunbard57a8712008-11-11 09:41:28 +0000236void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
237 // Emit a branch from the current block to the target one if this
238 // was a real block. If this was just a fall-through block after a
239 // terminator, don't emit it.
240 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
241
242 if (!CurBB || CurBB->getTerminator()) {
243 // If there is no insert point or the previous block is already
244 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000245 } else {
246 // Otherwise, create a fall-through branch.
247 Builder.CreateBr(Target);
248 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000249
250 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000251}
252
Chris Lattner91d723d2008-07-26 20:23:23 +0000253void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000255 if (StackDepthMap.find(&S) == StackDepthMap.end()) {
256 // We need to remember the stack depth so that we can readjust the
257 // stack back to the right depth for this label if we want to
258 // transfer here from a different depth.
259 StackDepthMap[&S] = StackDepth;
260 } else {
261 if (StackDepthMap[&S] != StackDepth) {
262 // FIXME: Sema needs to ckeck for jumps that cross decls with
263 // initializations for C++, and all VLAs, not just the first in
264 // a block that does a stacksave.
265 // FIXME: We need to save a place to insert the adjustment
266 // when we do a EmitStackUpdate on a forward jump, and then
267 // backpatch the adjustment into that place.
268 CGM.ErrorUnsupported(&S, "forward goto inside scope with VLA");
269 }
270 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000272}
273
274
275void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
276 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 EmitStmt(S.getSubStmt());
278}
279
280void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000281 // FIXME: Implement goto out in @try or @catch blocks.
282 if (!ObjCEHStack.empty()) {
283 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
284 return;
285 }
286
Daniel Dunbar09124252008-11-12 08:21:33 +0000287 // If this code is reachable then emit a stop point (if generating
288 // debug info). We have to do this ourselves because we are on the
289 // "simple" statement path.
290 if (HaveInsertPoint())
291 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000292
293 // We need to adjust the stack, if the destination was (will be) at
294 // a different depth.
295 EmitStackUpdate(*S.getLabel());
296
Daniel Dunbard57a8712008-11-11 09:41:28 +0000297 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000298}
299
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000300void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000301 // FIXME: Implement indirect goto in @try or @catch blocks.
302 if (!ObjCEHStack.empty()) {
303 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
304 return;
305 }
306
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000307 // Emit initial switch which will be patched up later by
308 // EmitIndirectSwitches(). We need a default dest, so we use the
309 // current BB, but this is overwritten.
310 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
311 llvm::Type::Int32Ty,
312 "addr");
313 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
314 IndirectSwitches.push_back(I);
315
Daniel Dunbara448fb22008-11-11 23:11:34 +0000316 // Clear the insertion point to indicate we are in unreachable code.
317 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000318}
319
Chris Lattner62b72f62008-11-11 07:24:28 +0000320void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // C99 6.8.4.1: The first substatement is executed if the expression compares
322 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000323
Chris Lattner9bc47e22008-11-12 07:46:33 +0000324 // If the condition constant folds and can be elided, try to avoid emitting
325 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000326 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000327 // Figure out which block (then or else) is executed.
328 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000329 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000330 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000331
Chris Lattner62b72f62008-11-11 07:24:28 +0000332 // If the skipped block has no labels in it, just emit the executed block.
333 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000334 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000335 if (Executed)
336 EmitStmt(Executed);
337 return;
338 }
339 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000340
341 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
342 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000343 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
344 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
345 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000347 ElseBlock = createBasicBlock("if.else");
348 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000349
350 // Emit the 'then' code.
351 EmitBlock(ThenBlock);
352 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000353 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354
355 // Emit the 'else' code if present.
356 if (const Stmt *Else = S.getElse()) {
357 EmitBlock(ElseBlock);
358 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000359 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 }
361
362 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000363 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
366void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // Emit the header for the loop, insert it, which will create an uncond br to
368 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000369 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000371
372 // Create an exit block for when the condition fails, create a block for the
373 // body of the loop.
374 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
375 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
376
377 // Store the blocks to use for break and continue.
378 BreakContinuePush(ExitBlock, LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000379
Mike Stump16b16202009-02-07 17:18:33 +0000380 // Evaluate the conditional in the while header. C99 6.8.5.1: The
381 // evaluation of the controlling expression takes place before each
382 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000384
385 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000387 bool EmitBoolCondBranch = true;
388 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
389 if (C->isOne())
390 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000391
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000393 if (EmitBoolCondBranch)
394 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000395
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 // Emit the loop body.
397 EmitBlock(LoopBody);
398 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000399
Mike Stump36a2ada2009-02-07 12:52:26 +0000400 BreakContinuePop();
Reid Spencer5f016e22007-07-11 17:01:13 +0000401
402 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000403 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000404
405 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000406 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000407
408 // If LoopHeader is a simple forwarding block then eliminate it.
409 if (!EmitBoolCondBranch
410 && &LoopHeader->front() == LoopHeader->getTerminator()) {
411 LoopHeader->replaceAllUsesWith(LoopBody);
412 LoopHeader->getTerminator()->eraseFromParent();
413 LoopHeader->eraseFromParent();
414 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000415}
416
417void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 // Emit the body for the loop, insert it, which will create an uncond br to
419 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000420 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
421 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000423
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000424 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000425
426 // Store the blocks to use for break and continue.
Mike Stump36a2ada2009-02-07 12:52:26 +0000427 BreakContinuePush(AfterDo, DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000428
429 // Emit the body of the loop into the block.
430 EmitStmt(S.getBody());
431
Mike Stump36a2ada2009-02-07 12:52:26 +0000432 BreakContinuePop();
Chris Lattnerda138702007-07-16 21:28:45 +0000433
434 EmitBlock(DoCond);
435
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
437 // after each execution of the loop body."
438
439 // Evaluate the conditional in the while header.
440 // C99 6.8.5p2/p4: The first substatement is executed if the expression
441 // compares unequal to 0. The condition must be a scalar type.
442 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000443
444 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
445 // to correctly handle break/continue though.
446 bool EmitBoolCondBranch = true;
447 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
448 if (C->isZero())
449 EmitBoolCondBranch = false;
450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000452 if (EmitBoolCondBranch)
453 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454
455 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000456 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000457
458 // If DoCond is a simple forwarding block then eliminate it.
459 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
460 DoCond->replaceAllUsesWith(AfterDo);
461 DoCond->getTerminator()->eraseFromParent();
462 DoCond->eraseFromParent();
463 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000464}
465
466void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
468 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 // Evaluate the first part before the loop.
471 if (S.getInit())
472 EmitStmt(S.getInit());
473
474 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000475 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
476 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000477
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 EmitBlock(CondBlock);
479
Mike Stump3e9da662009-02-07 23:02:10 +0000480 llvm::Value *saveStackDepth = StackDepth;
481
Mike Stump20926c62009-02-07 20:14:12 +0000482 // Evaluate the condition if present. If not, treat it as a
483 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000486 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000487
488 // C99 6.8.5p2/p4: The first substatement is executed if the expression
489 // compares unequal to 0. The condition must be a scalar type.
490 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
491
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 EmitBlock(ForBody);
493 } else {
494 // Treat it as a non-zero constant. Don't even create a new block for the
495 // body, just fall into it.
496 }
497
Chris Lattnerda138702007-07-16 21:28:45 +0000498 // If the for loop doesn't have an increment we can just use the
499 // condition as the continue block.
500 llvm::BasicBlock *ContinueBlock;
501 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000502 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000503 else
504 ContinueBlock = CondBlock;
505
506 // Store the blocks to use for break and continue.
Mike Stump3e9da662009-02-07 23:02:10 +0000507 // Ensure any vlas created between there and here, are undone
508 BreakContinuePush(AfterFor, ContinueBlock,
509 saveStackDepth, saveStackDepth);
510
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 // If the condition is true, execute the body of the for stmt.
512 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000513
Mike Stump36a2ada2009-02-07 12:52:26 +0000514 BreakContinuePop();
Chris Lattnerda138702007-07-16 21:28:45 +0000515
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000517 if (S.getInc()) {
518 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000519 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000520 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000521
522 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000523 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000524
Chris Lattnerda138702007-07-16 21:28:45 +0000525 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000526 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000527}
528
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000529void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
530 if (RV.isScalar()) {
531 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
532 } else if (RV.isAggregate()) {
533 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
534 } else {
535 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
536 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000537 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000538}
539
Reid Spencer5f016e22007-07-11 17:01:13 +0000540/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
541/// if the function returns void, or may be missing one if the function returns
542/// non-void. Fun stuff :).
543void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Eli Friedman20c802b2008-12-20 23:18:29 +0000544 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000545 if (StackSaveValues[i]) {
546 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
547 return;
548 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000549 }
550
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 // Emit the result value, even if unused, to evalute the side effects.
552 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000553
554 // FIXME: Clean this up by using an LValue for ReturnTemp,
555 // EmitStoreThroughLValue, and EmitAnyExpr.
556 if (!ReturnValue) {
557 // Make sure not to return anything, but evaluate the expression
558 // for side effects.
559 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000560 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000562 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000563 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000564 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000565 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000566 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000568 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 }
Eli Friedman144ac612008-05-22 01:22:33 +0000570
Daniel Dunbar898d5082008-09-30 01:06:03 +0000571 if (!ObjCEHStack.empty()) {
572 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
573 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000574 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000575 EmitJumpThroughFinally(*i, ReturnPad);
576 EmitBlock(ReturnPad);
577 }
578 }
579
Daniel Dunbard57a8712008-11-11 09:41:28 +0000580 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000581}
582
583void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000584 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
585 I != E; ++I)
586 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000587}
Chris Lattnerda138702007-07-16 21:28:45 +0000588
Daniel Dunbar09124252008-11-12 08:21:33 +0000589void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000590 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
591
Daniel Dunbar09124252008-11-12 08:21:33 +0000592 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000593 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000594 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar09124252008-11-12 08:21:33 +0000595 return;
596 }
597
Eli Friedman20c802b2008-12-20 23:18:29 +0000598 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
599 if (StackSaveValues[i]) {
600 CGM.ErrorUnsupported(&S, "break inside scope with VLA");
601 return;
602 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000603 }
604
Daniel Dunbar09124252008-11-12 08:21:33 +0000605 // If this code is reachable then emit a stop point (if generating
606 // debug info). We have to do this ourselves because we are on the
607 // "simple" statement path.
608 if (HaveInsertPoint())
609 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000610 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000611 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000612}
613
Daniel Dunbar09124252008-11-12 08:21:33 +0000614void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000615 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
616
Daniel Dunbar09124252008-11-12 08:21:33 +0000617 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000618 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000619 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
620 return;
621 }
622
Eli Friedman20c802b2008-12-20 23:18:29 +0000623 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
624 if (StackSaveValues[i]) {
625 CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
626 return;
627 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000628 }
629
Daniel Dunbar09124252008-11-12 08:21:33 +0000630 // If this code is reachable then emit a stop point (if generating
631 // debug info). We have to do this ourselves because we are on the
632 // "simple" statement path.
633 if (HaveInsertPoint())
634 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000635 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000636 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000637}
Devang Patel51b09f22007-10-04 23:45:31 +0000638
Devang Patelc049e4f2007-10-08 20:57:48 +0000639/// EmitCaseStmtRange - If case statement range is not too big then
640/// add multiple cases to switch instruction, one for each value within
641/// the range. If range is too big then emit "if" condition check.
642void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000643 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000644
Anders Carlsson51fe9962008-11-22 21:04:56 +0000645 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
646 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000647
Daniel Dunbar16f23572008-07-25 01:11:38 +0000648 // Emit the code for this case. We do this first to make sure it is
649 // properly chained from our predecessor before generating the
650 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000651 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000652 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
653 EmitStmt(S.getSubStmt());
654
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000655 // If range is empty, do nothing.
656 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
657 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000658
659 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000660 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000661 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
662 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000663 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000664 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
665 LHS++;
666 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000667 return;
668 }
669
Daniel Dunbar16f23572008-07-25 01:11:38 +0000670 // The range is too big. Emit "if" condition into a new block,
671 // making sure to save and restore the current insertion point.
672 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000673
Daniel Dunbar16f23572008-07-25 01:11:38 +0000674 // Push this test onto the chain of range checks (which terminates
675 // in the default basic block). The switch's default will be changed
676 // to the top of this chain after switch emission is complete.
677 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000678 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000679
Daniel Dunbar16f23572008-07-25 01:11:38 +0000680 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
681 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000682
683 // Emit range check.
684 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000685 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
686 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000687 llvm::Value *Cond =
688 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
689 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
690
Daniel Dunbar16f23572008-07-25 01:11:38 +0000691 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000692 if (RestoreBB)
693 Builder.SetInsertPoint(RestoreBB);
694 else
695 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000696}
697
698void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
699 if (S.getRHS()) {
700 EmitCaseStmtRange(S);
701 return;
702 }
703
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000704 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000705 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000706 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000707 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000708 EmitStmt(S.getSubStmt());
709}
710
711void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000712 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000713 assert(DefaultBlock->empty() &&
714 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000715 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000716 EmitStmt(S.getSubStmt());
717}
718
719void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
720 llvm::Value *CondV = EmitScalarExpr(S.getCond());
721
722 // Handle nested switch statements.
723 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000724 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000725
Mike Stump3e9da662009-02-07 23:02:10 +0000726 // Ensure any vlas created inside are destroyed on break.
727 llvm::Value *saveBreakStackDepth = StackDepth;
728
Daniel Dunbar16f23572008-07-25 01:11:38 +0000729 // Create basic block to hold stuff that comes after switch
730 // statement. We also need to create a default block now so that
731 // explicit case ranges tests can have a place to jump to on
732 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000733 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
734 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000735 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
736 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000737
Daniel Dunbar09124252008-11-12 08:21:33 +0000738 // Clear the insertion point to indicate we are in unreachable code.
739 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000740
Devang Patele9b8c0a2007-10-30 20:59:40 +0000741 // All break statements jump to NextBlock. If BreakContinueStack is non empty
742 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000743 llvm::BasicBlock *ContinueBlock = NULL;
Mike Stump3e9da662009-02-07 23:02:10 +0000744 llvm::Value *saveContinueStackDepth = NULL;
745 if (!BreakContinueStack.empty()) {
Devang Patel51b09f22007-10-04 23:45:31 +0000746 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Mike Stump3e9da662009-02-07 23:02:10 +0000747 saveContinueStackDepth = BreakContinueStack.back().SaveContinueStackDepth;
748 }
749 // Ensure any vlas created between there and here, are undone
750 BreakContinuePush(NextBlock, ContinueBlock,
751 saveBreakStackDepth, saveContinueStackDepth);
Devang Patel51b09f22007-10-04 23:45:31 +0000752
753 // Emit switch body.
754 EmitStmt(S.getBody());
Mike Stump36a2ada2009-02-07 12:52:26 +0000755 BreakContinuePop();
Devang Patel51b09f22007-10-04 23:45:31 +0000756
Daniel Dunbar16f23572008-07-25 01:11:38 +0000757 // Update the default block in case explicit case range tests have
758 // been chained on top.
759 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000760
Daniel Dunbar16f23572008-07-25 01:11:38 +0000761 // If a default was never emitted then reroute any jumps to it and
762 // discard.
763 if (!DefaultBlock->getParent()) {
764 DefaultBlock->replaceAllUsesWith(NextBlock);
765 delete DefaultBlock;
766 }
Devang Patel51b09f22007-10-04 23:45:31 +0000767
Daniel Dunbar16f23572008-07-25 01:11:38 +0000768 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000769 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000770
Devang Patel51b09f22007-10-04 23:45:31 +0000771 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000772 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000773}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000774
Anders Carlssonce179ab2008-11-09 18:54:14 +0000775static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
776{
777 // FIXME: No need to create new std::string here, we could just make sure
778 // that we don't read past the end of the string data.
779 std::string str(S.getAsmString()->getStrData(),
780 S.getAsmString()->getByteLength());
781 const char *Start = str.c_str();
782
783 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
784 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000785 Failed = false;
786
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000787 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000788 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000789 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000790 if (IsSimple) {
791 while (*Start) {
792 switch (*Start) {
793 default:
794 Result += *Start;
795 break;
796 case '$':
797 Result += "$$";
798 break;
799 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000800 Start++;
801 }
802
803 return Result;
804 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000805
806 while (*Start) {
807 switch (*Start) {
808 default:
809 Result += *Start;
810 break;
811 case '$':
812 Result += "$$";
813 break;
814 case '%':
815 // Escaped character
816 Start++;
817 if (!*Start) {
818 // FIXME: This should be caught during Sema.
819 assert(0 && "Trailing '%' in asm string.");
820 }
821
822 char EscapedChar = *Start;
823 if (EscapedChar == '%') {
824 // Escaped percentage sign.
825 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000826 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000827 // Generate an unique ID.
828 Result += llvm::utostr(AsmCounter);
829 } else if (isdigit(EscapedChar)) {
830 // %n - Assembler operand n
831 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000832 unsigned long n = strtoul(Start, &End, 10);
833 if (Start == End) {
834 // FIXME: This should be caught during Sema.
835 assert(0 && "Missing operand!");
836 } else if (n >= NumOperands) {
837 // FIXME: This should be caught during Sema.
838 assert(0 && "Operand number out of range!");
839 }
840
841 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000842 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000843 } else if (isalpha(EscapedChar)) {
844 char *End;
845
846 unsigned long n = strtoul(Start + 1, &End, 10);
847 if (Start == End) {
848 // FIXME: This should be caught during Sema.
849 assert(0 && "Missing operand!");
850 } else if (n >= NumOperands) {
851 // FIXME: This should be caught during Sema.
852 assert(0 && "Operand number out of range!");
853 }
854
855 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000856 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000857 } else if (EscapedChar == '[') {
858 std::string SymbolicName;
859
860 Start++;
861
862 while (*Start && *Start != ']') {
863 SymbolicName += *Start;
864
865 Start++;
866 }
867
868 if (!Start) {
869 // FIXME: Should be caught by sema.
870 assert(0 && "Could not parse symbolic name");
871 }
872
873 assert(*Start == ']' && "Error parsing symbolic name");
874
875 int Index = -1;
876
877 // Check if this is an output operand.
878 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
879 if (S.getOutputName(i) == SymbolicName) {
880 Index = i;
881 break;
882 }
883 }
884
885 if (Index == -1) {
886 for (unsigned i = 0; i < S.getNumInputs(); i++) {
887 if (S.getInputName(i) == SymbolicName) {
888 Index = S.getNumOutputs() + i;
889 }
890 }
891 }
892
893 assert(Index != -1 && "Did not find right operand!");
894
895 Result += '$' + llvm::utostr(Index);
896
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000897 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000898 Failed = true;
899 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000900 }
901 }
902 Start++;
903 }
904
905 return Result;
906}
907
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000908static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000909 TargetInfo &Target,
910 const std::string *OutputNamesBegin = 0,
911 const std::string *OutputNamesEnd = 0)
912{
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000913 std::string Result;
914
915 while (*Constraint) {
916 switch (*Constraint) {
917 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000918 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000919 break;
920 // Ignore these
921 case '*':
922 case '?':
923 case '!':
924 break;
925 case 'g':
926 Result += "imr";
927 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000928 case '[': {
929 assert(OutputNamesBegin && OutputNamesEnd &&
930 "Must pass output names to constraints with a symbolic name");
931 unsigned Index;
932 bool result = Target.resolveSymbolicName(Constraint,
933 OutputNamesBegin,
934 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000935 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000936 Result += llvm::utostr(Index);
937 break;
938 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000939 }
940
941 Constraint++;
942 }
943
944 return Result;
945}
946
Anders Carlsson63471722009-01-11 19:32:54 +0000947llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
948 TargetInfo::ConstraintInfo Info,
949 const Expr *InputExpr,
950 std::string &ConstraintStr)
951{
952 llvm::Value *Arg;
953 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000954 !(Info & TargetInfo::CI_AllowsMemory)) {
955 const llvm::Type *Ty = ConvertType(InputExpr->getType());
956
957 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000958 Arg = EmitScalarExpr(InputExpr);
959 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000960 LValue Dest = EmitLValue(InputExpr);
961
962 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
963 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
964 Ty = llvm::IntegerType::get(Size);
965 Ty = llvm::PointerType::getUnqual(Ty);
966
967 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
968 } else {
969 Arg = Dest.getAddress();
970 ConstraintStr += '*';
971 }
Anders Carlsson63471722009-01-11 19:32:54 +0000972 }
973 } else {
974 LValue Dest = EmitLValue(InputExpr);
975 Arg = Dest.getAddress();
976 ConstraintStr += '*';
977 }
978
979 return Arg;
980}
981
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000982void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000983 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000984 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000985 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000986
987 if (Failed) {
988 ErrorUnsupported(&S, "asm string");
989 return;
990 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000991
992 std::string Constraints;
993
994 llvm::Value *ResultAddr = 0;
995 const llvm::Type *ResultType = llvm::Type::VoidTy;
996
997 std::vector<const llvm::Type*> ArgTypes;
998 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000999
1000 // Keep track of inout constraints.
1001 std::string InOutConstraints;
1002 std::vector<llvm::Value*> InOutArgs;
1003 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +00001004
1005 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1006
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001007 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1008 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
1009 S.getOutputConstraint(i)->getByteLength());
1010
1011 TargetInfo::ConstraintInfo Info;
1012 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
1013 Info);
Chris Lattner3304e552008-10-12 00:31:50 +00001014 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001015
Anders Carlsson03eb5432009-01-27 20:38:24 +00001016 OutputConstraintInfos.push_back(Info);
1017
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001018 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001019 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001020
1021 LValue Dest = EmitLValue(S.getOutputExpr(i));
1022 const llvm::Type *DestValueType =
1023 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
1024
1025 // If the first output operand is not a memory dest, we'll
1026 // make it the return value.
1027 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +00001028 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001029 ResultAddr = Dest.getAddress();
1030 ResultType = DestValueType;
1031 Constraints += "=" + OutputConstraint;
1032 } else {
1033 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001034 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001035 if (i != 0)
1036 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +00001037 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001038 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001039 }
1040
1041 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001042 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001043
Anders Carlssonf39a4212008-02-05 20:01:53 +00001044 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +00001045 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001046
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001047 if (Info & TargetInfo::CI_AllowsRegister)
1048 InOutConstraints += llvm::utostr(i);
1049 else
1050 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001051
Anders Carlssonf39a4212008-02-05 20:01:53 +00001052 InOutArgTypes.push_back(Arg->getType());
1053 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001054 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001055 }
1056
1057 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1058
1059 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1060 const Expr *InputExpr = S.getInputExpr(i);
1061
1062 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
1063 S.getInputConstraint(i)->getByteLength());
1064
1065 TargetInfo::ConstraintInfo Info;
1066 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +00001067 S.begin_output_names(),
1068 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +00001069 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +00001070 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +00001071 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001072
1073 if (i != 0 || S.getNumOutputs() > 0)
1074 Constraints += ',';
1075
1076 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001077 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1078 S.begin_output_names(),
1079 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001080
Anders Carlsson63471722009-01-11 19:32:54 +00001081 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001082
1083 ArgTypes.push_back(Arg->getType());
1084 Args.push_back(Arg);
1085 Constraints += InputConstraint;
1086 }
1087
Anders Carlssonf39a4212008-02-05 20:01:53 +00001088 // Append the "input" part of inout constraints last.
1089 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1090 ArgTypes.push_back(InOutArgTypes[i]);
1091 Args.push_back(InOutArgs[i]);
1092 }
1093 Constraints += InOutConstraints;
1094
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001095 // Clobbers
1096 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1097 std::string Clobber(S.getClobber(i)->getStrData(),
1098 S.getClobber(i)->getByteLength());
1099
1100 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1101
Anders Carlssonea041752008-02-06 00:11:32 +00001102 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001103 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +00001104
1105 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001106 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001107 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001108 }
1109
1110 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001111 std::string MachineClobbers = Target.getClobbers();
1112 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001113 if (!Constraints.empty())
1114 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001115 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001116 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001117
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001118 const llvm::FunctionType *FTy =
1119 llvm::FunctionType::get(ResultType, ArgTypes, false);
1120
1121 llvm::InlineAsm *IA =
1122 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1123 S.isVolatile() || S.getNumOutputs() == 0);
1124 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001125 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001126 Builder.CreateStore(Result, ResultAddr);
1127}