blob: 91b726335c2b4ceb86e4ae0da8901ba5e25dedbd [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 Carlsson74331892009-02-09 20:23:40 +0000137 bool OldDidCallStackSave = DidCallStackSave;
138
Anders Carlsson17d28a32008-12-12 05:52:00 +0000139 // Push a null stack save value.
140 StackSaveValues.push_back(0);
141
Chris Lattner33793202007-08-31 22:09:40 +0000142 for (CompoundStmt::const_body_iterator I = S.body_begin(),
143 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000145
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000146 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000147 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000148 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000149 DI->EmitRegionEnd(CurFn, Builder);
150 }
151
Anders Carlsson17d28a32008-12-12 05:52:00 +0000152 RValue RV;
153 if (!GetLast)
154 RV = RValue::get(0);
155 else {
156 // We have to special case labels here. They are statements, but when put
157 // at the end of a statement expression, they yield the value of their
158 // subexpression. Handle this by walking through all labels we encounter,
159 // emitting them before we evaluate the subexpr.
160 const Stmt *LastStmt = S.body_back();
161 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
162 EmitLabel(*LS);
163 LastStmt = LS->getSubStmt();
164 }
Chris Lattner9b655512007-08-31 22:49:20 +0000165
Anders Carlsson17d28a32008-12-12 05:52:00 +0000166 EnsureInsertPoint();
167
168 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
169 }
170
171 if (llvm::Value *V = StackSaveValues.pop_back_val()) {
Mike Stump36a2ada2009-02-07 12:52:26 +0000172 StackDepth = V;
Anders Carlsson17d28a32008-12-12 05:52:00 +0000173 V = Builder.CreateLoad(V, "tmp");
174
175 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
176 Builder.CreateCall(F, V);
Chris Lattner91d723d2008-07-26 20:23:23 +0000177 }
178
Anders Carlsson74331892009-02-09 20:23:40 +0000179 DidCallStackSave = OldDidCallStackSave;
180
Anders Carlssonc71c8452009-02-07 23:50:39 +0000181 EmitCleanupBlocks(CleanupStackDepth);
182
Anders Carlsson17d28a32008-12-12 05:52:00 +0000183 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000184}
185
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000186void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000187 // Fall out of the current block (if necessary).
188 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000189
190 if (IsFinished && BB->use_empty()) {
191 delete BB;
192 return;
193 }
194
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000195 // If necessary, associate the block with the cleanup stack size.
196 if (!CleanupEntries.empty()) {
197 BlockScopes[BB] = CleanupEntries.size() - 1;
198 CleanupEntries.back().Blocks.push_back(BB);
199 }
200
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 CurFn->getBasicBlockList().push_back(BB);
202 Builder.SetInsertPoint(BB);
203}
204
Mike Stumpec9771d2009-02-08 09:22:19 +0000205bool CodeGenFunction::EmitStackUpdate(llvm::Value *V) {
Mike Stump225b16d2009-02-08 22:00:53 +0000206 // If we're already at the depth we want...
207 if (StackDepth == V)
208 return false;
209
Mike Stump36a2ada2009-02-07 12:52:26 +0000210 // V can be 0 here, if it is, be sure to start searching from the
211 // top of the function, as we want the next save after that point.
212 for (unsigned int i = 0; i < StackSaveValues.size(); ++i)
213 if (StackSaveValues[i] == V) {
214 // The actual depth is actually in the next used slot, if any.
215 while (++i < StackSaveValues.size()
216 && (V = StackSaveValues[i]) == 0) ;
217 // If there were no other depth changes, we don't need any
218 // adjustments.
219 if (V) {
220 V = Builder.CreateLoad(V, "tmp");
221 // and restore it.
222 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
223 Builder.CreateCall(F, V);
224 }
Mike Stumpec9771d2009-02-08 09:22:19 +0000225 } else return true;
226 return false;
227}
228
229bool CodeGenFunction::EmitStackUpdate(const void *S) {
230 if (StackDepthMap.find(S) == StackDepthMap.end()) {
231 // If we can't find it, just remember the depth now,
232 // so we can validate it later.
233 // FIXME: We need to save a place to insert the adjustment,
234 // if needed, here, sa that later in EmitLabel, we can
235 // backpatch the adjustment into that place, instead of
236 // saying unsupported.
237 StackDepthMap[S] = StackDepth;
238 return false;
239 }
240
241 // Find applicable stack depth, if any...
242 llvm::Value *V = StackDepthMap[S];
243 return EmitStackUpdate(V);
Mike Stump36a2ada2009-02-07 12:52:26 +0000244}
245
Daniel Dunbard57a8712008-11-11 09:41:28 +0000246void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
247 // Emit a branch from the current block to the target one if this
248 // was a real block. If this was just a fall-through block after a
249 // terminator, don't emit it.
250 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
251
252 if (!CurBB || CurBB->getTerminator()) {
253 // If there is no insert point or the previous block is already
254 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000255 } else {
256 // Otherwise, create a fall-through branch.
257 Builder.CreateBr(Target);
258 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000259
260 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000261}
262
Mike Stumpec9771d2009-02-08 09:22:19 +0000263bool CodeGenFunction::StackFixupAtLabel(const void *S) {
264 if (StackDepthMap.find(S) == StackDepthMap.end()) {
Mike Stump36a2ada2009-02-07 12:52:26 +0000265 // We need to remember the stack depth so that we can readjust the
266 // stack back to the right depth for this label if we want to
267 // transfer here from a different depth.
Mike Stumpec9771d2009-02-08 09:22:19 +0000268 StackDepthMap[S] = StackDepth;
Mike Stump36a2ada2009-02-07 12:52:26 +0000269 } else {
Mike Stumpec9771d2009-02-08 09:22:19 +0000270 if (StackDepthMap[S] != StackDepth) {
Mike Stump36a2ada2009-02-07 12:52:26 +0000271 // FIXME: Sema needs to ckeck for jumps that cross decls with
272 // initializations for C++, and all VLAs, not just the first in
273 // a block that does a stacksave.
274 // FIXME: We need to save a place to insert the adjustment
275 // when we do a EmitStackUpdate on a forward jump, and then
276 // backpatch the adjustment into that place.
Mike Stumpec9771d2009-02-08 09:22:19 +0000277 return true;
Mike Stump36a2ada2009-02-07 12:52:26 +0000278 }
279 }
Mike Stumpec9771d2009-02-08 09:22:19 +0000280 return false;
281}
282
283void CodeGenFunction::EmitLabel(const LabelStmt &S) {
284 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
285 if (StackFixupAtLabel(&S))
286 CGM.ErrorUnsupported(&S, "forward goto inside scope with VLA");
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000288}
289
290
291void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
292 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 EmitStmt(S.getSubStmt());
294}
295
296void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000297 // FIXME: Implement goto out in @try or @catch blocks.
298 if (!ObjCEHStack.empty()) {
299 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
300 return;
301 }
302
Daniel Dunbar09124252008-11-12 08:21:33 +0000303 // If this code is reachable then emit a stop point (if generating
304 // debug info). We have to do this ourselves because we are on the
305 // "simple" statement path.
306 if (HaveInsertPoint())
307 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000308
309 // We need to adjust the stack, if the destination was (will be) at
310 // a different depth.
Mike Stumpec9771d2009-02-08 09:22:19 +0000311 if (EmitStackUpdate(S.getLabel()))
312 // FIXME: Move to semq and assert here, codegen isn't the right
313 // time to be checking.
314 CGM.ErrorUnsupported(S.getLabel(),
315 "invalid goto to VLA scope that has finished");
Mike Stump36a2ada2009-02-07 12:52:26 +0000316
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000317 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000318}
319
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000320void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000321 // FIXME: Implement indirect goto in @try or @catch blocks.
322 if (!ObjCEHStack.empty()) {
323 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
324 return;
325 }
326
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000327 // Emit initial switch which will be patched up later by
328 // EmitIndirectSwitches(). We need a default dest, so we use the
329 // current BB, but this is overwritten.
330 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
331 llvm::Type::Int32Ty,
332 "addr");
333 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
334 IndirectSwitches.push_back(I);
335
Daniel Dunbara448fb22008-11-11 23:11:34 +0000336 // Clear the insertion point to indicate we are in unreachable code.
337 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000338}
339
Chris Lattner62b72f62008-11-11 07:24:28 +0000340void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 // C99 6.8.4.1: The first substatement is executed if the expression compares
342 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
Chris Lattner9bc47e22008-11-12 07:46:33 +0000344 // If the condition constant folds and can be elided, try to avoid emitting
345 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000346 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000347 // Figure out which block (then or else) is executed.
348 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000349 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000350 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000351
Chris Lattner62b72f62008-11-11 07:24:28 +0000352 // If the skipped block has no labels in it, just emit the executed block.
353 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000354 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000355 if (Executed)
356 EmitStmt(Executed);
357 return;
358 }
359 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000360
361 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
362 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000363 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
364 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
365 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000367 ElseBlock = createBasicBlock("if.else");
368 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000369
370 // Emit the 'then' code.
371 EmitBlock(ThenBlock);
372 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000373 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000374
375 // Emit the 'else' code if present.
376 if (const Stmt *Else = S.getElse()) {
377 EmitBlock(ElseBlock);
378 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000379 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 }
381
382 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000383 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000384}
385
386void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // Emit the header for the loop, insert it, which will create an uncond br to
388 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000389 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000391
392 // Create an exit block for when the condition fails, create a block for the
393 // body of the loop.
394 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
395 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
396
397 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000398 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000399
Mike Stump16b16202009-02-07 17:18:33 +0000400 // Evaluate the conditional in the while header. C99 6.8.5.1: The
401 // evaluation of the controlling expression takes place before each
402 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000404
405 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000407 bool EmitBoolCondBranch = true;
408 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
409 if (C->isOne())
410 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000413 if (EmitBoolCondBranch)
414 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000415
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 // Emit the loop body.
417 EmitBlock(LoopBody);
418 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000419
Anders Carlssone4b6d342009-02-10 05:52:02 +0000420 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000421
422 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000423 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000424
425 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000426 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000427
428 // If LoopHeader is a simple forwarding block then eliminate it.
429 if (!EmitBoolCondBranch
430 && &LoopHeader->front() == LoopHeader->getTerminator()) {
431 LoopHeader->replaceAllUsesWith(LoopBody);
432 LoopHeader->getTerminator()->eraseFromParent();
433 LoopHeader->eraseFromParent();
434 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000435}
436
437void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 // Emit the body for the loop, insert it, which will create an uncond br to
439 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000440 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
441 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000443
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000444 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000445
446 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000447 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000448
449 // Emit the body of the loop into the block.
450 EmitStmt(S.getBody());
451
Anders Carlssone4b6d342009-02-10 05:52:02 +0000452 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000453
454 EmitBlock(DoCond);
455
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
457 // after each execution of the loop body."
458
459 // Evaluate the conditional in the while header.
460 // C99 6.8.5p2/p4: The first substatement is executed if the expression
461 // compares unequal to 0. The condition must be a scalar type.
462 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000463
464 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
465 // to correctly handle break/continue though.
466 bool EmitBoolCondBranch = true;
467 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
468 if (C->isZero())
469 EmitBoolCondBranch = false;
470
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000472 if (EmitBoolCondBranch)
473 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000474
475 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000476 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000477
478 // If DoCond is a simple forwarding block then eliminate it.
479 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
480 DoCond->replaceAllUsesWith(AfterDo);
481 DoCond->getTerminator()->eraseFromParent();
482 DoCond->eraseFromParent();
483 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000484}
485
486void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
488 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000489
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 // Evaluate the first part before the loop.
491 if (S.getInit())
492 EmitStmt(S.getInit());
493
494 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000495 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
496 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000497
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 EmitBlock(CondBlock);
499
Mike Stump20926c62009-02-07 20:14:12 +0000500 // Evaluate the condition if present. If not, treat it as a
501 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000504 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000505
506 // C99 6.8.5p2/p4: The first substatement is executed if the expression
507 // compares unequal to 0. The condition must be a scalar type.
508 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 EmitBlock(ForBody);
511 } else {
512 // Treat it as a non-zero constant. Don't even create a new block for the
513 // body, just fall into it.
514 }
515
Chris Lattnerda138702007-07-16 21:28:45 +0000516 // If the for loop doesn't have an increment we can just use the
517 // condition as the continue block.
518 llvm::BasicBlock *ContinueBlock;
519 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000520 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000521 else
522 ContinueBlock = CondBlock;
523
524 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000525 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000526
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 // If the condition is true, execute the body of the for stmt.
528 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000529
Anders Carlssone4b6d342009-02-10 05:52:02 +0000530 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000531
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000533 if (S.getInc()) {
534 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000535 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000536 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000537
538 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000539 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000540
Chris Lattnerda138702007-07-16 21:28:45 +0000541 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000542 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000543}
544
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000545void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
546 if (RV.isScalar()) {
547 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
548 } else if (RV.isAggregate()) {
549 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
550 } else {
551 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
552 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000553 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000554}
555
Reid Spencer5f016e22007-07-11 17:01:13 +0000556/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
557/// if the function returns void, or may be missing one if the function returns
558/// non-void. Fun stuff :).
559void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Eli Friedman20c802b2008-12-20 23:18:29 +0000560 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000561 if (StackSaveValues[i]) {
562 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
563 return;
564 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000565 }
566
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 // Emit the result value, even if unused, to evalute the side effects.
568 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000569
570 // FIXME: Clean this up by using an LValue for ReturnTemp,
571 // EmitStoreThroughLValue, and EmitAnyExpr.
572 if (!ReturnValue) {
573 // Make sure not to return anything, but evaluate the expression
574 // for side effects.
575 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000576 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000578 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000579 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000580 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000581 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000582 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000584 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 }
Eli Friedman144ac612008-05-22 01:22:33 +0000586
Daniel Dunbar898d5082008-09-30 01:06:03 +0000587 if (!ObjCEHStack.empty()) {
588 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
589 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000590 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000591 EmitJumpThroughFinally(*i, ReturnPad);
592 EmitBlock(ReturnPad);
593 }
594 }
595
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000596 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000597}
598
599void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000600 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
601 I != E; ++I)
602 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000603}
Chris Lattnerda138702007-07-16 21:28:45 +0000604
Daniel Dunbar09124252008-11-12 08:21:33 +0000605void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000606 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
607
Daniel Dunbar09124252008-11-12 08:21:33 +0000608 // If this code is reachable then emit a stop point (if generating
609 // debug info). We have to do this ourselves because we are on the
610 // "simple" statement path.
611 if (HaveInsertPoint())
612 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000613
Chris Lattnerda138702007-07-16 21:28:45 +0000614 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000615 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000616}
617
Daniel Dunbar09124252008-11-12 08:21:33 +0000618void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000619 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
620
Daniel Dunbar09124252008-11-12 08:21:33 +0000621 // If this code is reachable then emit a stop point (if generating
622 // debug info). We have to do this ourselves because we are on the
623 // "simple" statement path.
624 if (HaveInsertPoint())
625 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000626
Chris Lattnerda138702007-07-16 21:28:45 +0000627 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000628 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000629}
Devang Patel51b09f22007-10-04 23:45:31 +0000630
Devang Patelc049e4f2007-10-08 20:57:48 +0000631/// EmitCaseStmtRange - If case statement range is not too big then
632/// add multiple cases to switch instruction, one for each value within
633/// the range. If range is too big then emit "if" condition check.
634void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000635 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000636
Anders Carlsson51fe9962008-11-22 21:04:56 +0000637 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
638 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000639
Daniel Dunbar16f23572008-07-25 01:11:38 +0000640 // Emit the code for this case. We do this first to make sure it is
641 // properly chained from our predecessor before generating the
642 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000643 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000644 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
645 EmitStmt(S.getSubStmt());
646
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000647 // If range is empty, do nothing.
648 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
649 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000650
651 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000652 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000653 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
654 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000655 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000656 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
657 LHS++;
658 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000659 return;
660 }
661
Daniel Dunbar16f23572008-07-25 01:11:38 +0000662 // The range is too big. Emit "if" condition into a new block,
663 // making sure to save and restore the current insertion point.
664 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000665
Daniel Dunbar16f23572008-07-25 01:11:38 +0000666 // Push this test onto the chain of range checks (which terminates
667 // in the default basic block). The switch's default will be changed
668 // to the top of this chain after switch emission is complete.
669 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000670 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000671
Daniel Dunbar16f23572008-07-25 01:11:38 +0000672 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
673 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000674
675 // Emit range check.
676 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000677 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
678 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000679 llvm::Value *Cond =
680 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
681 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
682
Daniel Dunbar16f23572008-07-25 01:11:38 +0000683 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000684 if (RestoreBB)
685 Builder.SetInsertPoint(RestoreBB);
686 else
687 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000688}
689
690void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
691 if (S.getRHS()) {
692 EmitCaseStmtRange(S);
693 return;
694 }
695
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000696 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000697 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000698 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000699 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000700 EmitStmt(S.getSubStmt());
701}
702
703void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000704 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000705 assert(DefaultBlock->empty() &&
706 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000707 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000708 EmitStmt(S.getSubStmt());
709}
710
711void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
712 llvm::Value *CondV = EmitScalarExpr(S.getCond());
713
714 // Handle nested switch statements.
715 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000716 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000717
Daniel Dunbar16f23572008-07-25 01:11:38 +0000718 // Create basic block to hold stuff that comes after switch
719 // statement. We also need to create a default block now so that
720 // explicit case ranges tests can have a place to jump to on
721 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000722 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
723 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000724 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
725 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000726
Daniel Dunbar09124252008-11-12 08:21:33 +0000727 // Clear the insertion point to indicate we are in unreachable code.
728 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000729
Devang Patele9b8c0a2007-10-30 20:59:40 +0000730 // All break statements jump to NextBlock. If BreakContinueStack is non empty
731 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000732 llvm::BasicBlock *ContinueBlock = 0;
733 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000734 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000735
Mike Stump3e9da662009-02-07 23:02:10 +0000736 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000737 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000738
739 // Emit switch body.
740 EmitStmt(S.getBody());
Anders Carlssone4b6d342009-02-10 05:52:02 +0000741
742 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000743
Daniel Dunbar16f23572008-07-25 01:11:38 +0000744 // Update the default block in case explicit case range tests have
745 // been chained on top.
746 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000747
Daniel Dunbar16f23572008-07-25 01:11:38 +0000748 // If a default was never emitted then reroute any jumps to it and
749 // discard.
750 if (!DefaultBlock->getParent()) {
751 DefaultBlock->replaceAllUsesWith(NextBlock);
752 delete DefaultBlock;
753 }
Devang Patel51b09f22007-10-04 23:45:31 +0000754
Daniel Dunbar16f23572008-07-25 01:11:38 +0000755 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000756 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000757
Devang Patel51b09f22007-10-04 23:45:31 +0000758 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000759 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000760}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000761
Anders Carlssonce179ab2008-11-09 18:54:14 +0000762static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
763{
764 // FIXME: No need to create new std::string here, we could just make sure
765 // that we don't read past the end of the string data.
766 std::string str(S.getAsmString()->getStrData(),
767 S.getAsmString()->getByteLength());
768 const char *Start = str.c_str();
769
770 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
771 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000772 Failed = false;
773
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000774 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000775 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000776 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000777 if (IsSimple) {
778 while (*Start) {
779 switch (*Start) {
780 default:
781 Result += *Start;
782 break;
783 case '$':
784 Result += "$$";
785 break;
786 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000787 Start++;
788 }
789
790 return Result;
791 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000792
793 while (*Start) {
794 switch (*Start) {
795 default:
796 Result += *Start;
797 break;
798 case '$':
799 Result += "$$";
800 break;
801 case '%':
802 // Escaped character
803 Start++;
804 if (!*Start) {
805 // FIXME: This should be caught during Sema.
806 assert(0 && "Trailing '%' in asm string.");
807 }
808
809 char EscapedChar = *Start;
810 if (EscapedChar == '%') {
811 // Escaped percentage sign.
812 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000813 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000814 // Generate an unique ID.
815 Result += llvm::utostr(AsmCounter);
816 } else if (isdigit(EscapedChar)) {
817 // %n - Assembler operand n
818 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000819 unsigned long n = strtoul(Start, &End, 10);
820 if (Start == End) {
821 // FIXME: This should be caught during Sema.
822 assert(0 && "Missing operand!");
823 } else if (n >= NumOperands) {
824 // FIXME: This should be caught during Sema.
825 assert(0 && "Operand number out of range!");
826 }
827
828 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000829 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000830 } else if (isalpha(EscapedChar)) {
831 char *End;
832
833 unsigned long n = strtoul(Start + 1, &End, 10);
834 if (Start == End) {
835 // FIXME: This should be caught during Sema.
836 assert(0 && "Missing operand!");
837 } else if (n >= NumOperands) {
838 // FIXME: This should be caught during Sema.
839 assert(0 && "Operand number out of range!");
840 }
841
842 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000843 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000844 } else if (EscapedChar == '[') {
845 std::string SymbolicName;
846
847 Start++;
848
849 while (*Start && *Start != ']') {
850 SymbolicName += *Start;
851
852 Start++;
853 }
854
855 if (!Start) {
856 // FIXME: Should be caught by sema.
857 assert(0 && "Could not parse symbolic name");
858 }
859
860 assert(*Start == ']' && "Error parsing symbolic name");
861
862 int Index = -1;
863
864 // Check if this is an output operand.
865 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
866 if (S.getOutputName(i) == SymbolicName) {
867 Index = i;
868 break;
869 }
870 }
871
872 if (Index == -1) {
873 for (unsigned i = 0; i < S.getNumInputs(); i++) {
874 if (S.getInputName(i) == SymbolicName) {
875 Index = S.getNumOutputs() + i;
876 }
877 }
878 }
879
880 assert(Index != -1 && "Did not find right operand!");
881
882 Result += '$' + llvm::utostr(Index);
883
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000884 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000885 Failed = true;
886 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000887 }
888 }
889 Start++;
890 }
891
892 return Result;
893}
894
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000895static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000896 TargetInfo &Target,
897 const std::string *OutputNamesBegin = 0,
898 const std::string *OutputNamesEnd = 0)
899{
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000900 std::string Result;
901
902 while (*Constraint) {
903 switch (*Constraint) {
904 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000905 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000906 break;
907 // Ignore these
908 case '*':
909 case '?':
910 case '!':
911 break;
912 case 'g':
913 Result += "imr";
914 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000915 case '[': {
916 assert(OutputNamesBegin && OutputNamesEnd &&
917 "Must pass output names to constraints with a symbolic name");
918 unsigned Index;
919 bool result = Target.resolveSymbolicName(Constraint,
920 OutputNamesBegin,
921 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000922 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000923 Result += llvm::utostr(Index);
924 break;
925 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000926 }
927
928 Constraint++;
929 }
930
931 return Result;
932}
933
Anders Carlsson63471722009-01-11 19:32:54 +0000934llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
935 TargetInfo::ConstraintInfo Info,
936 const Expr *InputExpr,
937 std::string &ConstraintStr)
938{
939 llvm::Value *Arg;
940 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000941 !(Info & TargetInfo::CI_AllowsMemory)) {
942 const llvm::Type *Ty = ConvertType(InputExpr->getType());
943
944 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000945 Arg = EmitScalarExpr(InputExpr);
946 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000947 LValue Dest = EmitLValue(InputExpr);
948
949 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
950 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
951 Ty = llvm::IntegerType::get(Size);
952 Ty = llvm::PointerType::getUnqual(Ty);
953
954 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
955 } else {
956 Arg = Dest.getAddress();
957 ConstraintStr += '*';
958 }
Anders Carlsson63471722009-01-11 19:32:54 +0000959 }
960 } else {
961 LValue Dest = EmitLValue(InputExpr);
962 Arg = Dest.getAddress();
963 ConstraintStr += '*';
964 }
965
966 return Arg;
967}
968
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000969void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000970 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000971 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000972 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000973
974 if (Failed) {
975 ErrorUnsupported(&S, "asm string");
976 return;
977 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000978
979 std::string Constraints;
980
981 llvm::Value *ResultAddr = 0;
982 const llvm::Type *ResultType = llvm::Type::VoidTy;
983
984 std::vector<const llvm::Type*> ArgTypes;
985 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000986
987 // Keep track of inout constraints.
988 std::string InOutConstraints;
989 std::vector<llvm::Value*> InOutArgs;
990 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000991
992 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
993
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000994 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
995 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
996 S.getOutputConstraint(i)->getByteLength());
997
998 TargetInfo::ConstraintInfo Info;
999 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
1000 Info);
Chris Lattner3304e552008-10-12 00:31:50 +00001001 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001002
Anders Carlsson03eb5432009-01-27 20:38:24 +00001003 OutputConstraintInfos.push_back(Info);
1004
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001005 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001006 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001007
1008 LValue Dest = EmitLValue(S.getOutputExpr(i));
1009 const llvm::Type *DestValueType =
1010 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
1011
1012 // If the first output operand is not a memory dest, we'll
1013 // make it the return value.
1014 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +00001015 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001016 ResultAddr = Dest.getAddress();
1017 ResultType = DestValueType;
1018 Constraints += "=" + OutputConstraint;
1019 } else {
1020 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001021 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001022 if (i != 0)
1023 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +00001024 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001025 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001026 }
1027
1028 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001029 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001030
Anders Carlssonf39a4212008-02-05 20:01:53 +00001031 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +00001032 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001033
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001034 if (Info & TargetInfo::CI_AllowsRegister)
1035 InOutConstraints += llvm::utostr(i);
1036 else
1037 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001038
Anders Carlssonf39a4212008-02-05 20:01:53 +00001039 InOutArgTypes.push_back(Arg->getType());
1040 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001041 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001042 }
1043
1044 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1045
1046 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1047 const Expr *InputExpr = S.getInputExpr(i);
1048
1049 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
1050 S.getInputConstraint(i)->getByteLength());
1051
1052 TargetInfo::ConstraintInfo Info;
1053 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +00001054 S.begin_output_names(),
1055 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +00001056 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +00001057 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +00001058 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001059
1060 if (i != 0 || S.getNumOutputs() > 0)
1061 Constraints += ',';
1062
1063 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001064 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1065 S.begin_output_names(),
1066 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001067
Anders Carlsson63471722009-01-11 19:32:54 +00001068 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001069
1070 ArgTypes.push_back(Arg->getType());
1071 Args.push_back(Arg);
1072 Constraints += InputConstraint;
1073 }
1074
Anders Carlssonf39a4212008-02-05 20:01:53 +00001075 // Append the "input" part of inout constraints last.
1076 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1077 ArgTypes.push_back(InOutArgTypes[i]);
1078 Args.push_back(InOutArgs[i]);
1079 }
1080 Constraints += InOutConstraints;
1081
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001082 // Clobbers
1083 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1084 std::string Clobber(S.getClobber(i)->getStrData(),
1085 S.getClobber(i)->getByteLength());
1086
1087 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1088
Anders Carlssonea041752008-02-06 00:11:32 +00001089 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001090 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +00001091
1092 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001093 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001094 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001095 }
1096
1097 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001098 std::string MachineClobbers = Target.getClobbers();
1099 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001100 if (!Constraints.empty())
1101 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001102 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001103 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001104
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001105 const llvm::FunctionType *FTy =
1106 llvm::FunctionType::get(ResultType, ArgTypes, false);
1107
1108 llvm::InlineAsm *IA =
1109 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1110 S.isVolatile() || S.getNumOutputs() == 0);
1111 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001112 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001113 Builder.CreateStore(Result, ResultAddr);
1114}