blob: fd01905698a930c26ea88ef935bd4a921fb0d2b9 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace CodeGen;
24
25//===----------------------------------------------------------------------===//
26// Statement Emission
27//===----------------------------------------------------------------------===//
28
Daniel Dunbar09124252008-11-12 08:21:33 +000029void CodeGenFunction::EmitStopPoint(const Stmt *S) {
30 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
31 DI->setLocation(S->getLocStart());
32 DI->EmitStopPoint(CurFn, Builder);
33 }
34}
35
Reid Spencer5f016e22007-07-11 17:01:13 +000036void CodeGenFunction::EmitStmt(const Stmt *S) {
37 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000038
Daniel Dunbar09124252008-11-12 08:21:33 +000039 // Check if we can handle this without bothering to generate an
40 // insert point or debug info.
41 if (EmitSimpleStmt(S))
42 return;
43
Daniel Dunbara448fb22008-11-11 23:11:34 +000044 // If we happen to be at an unreachable point just create a dummy
45 // basic block to hold the code. We could change parts of irgen to
46 // simply not generate this code, but this situation is rare and
47 // probably not worth the effort.
48 // FIXME: Verify previous performance/effort claim.
49 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000050
Daniel Dunbar09124252008-11-12 08:21:33 +000051 // Generate a stoppoint if we are emitting debug info.
52 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000053
Reid Spencer5f016e22007-07-11 17:01:13 +000054 switch (S->getStmtClass()) {
55 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000056 // Must be an expression in a stmt context. Emit the value (to get
57 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000058 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000059 if (!hasAggregateLLVMType(E->getType()))
60 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000061 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000062 EmitComplexExpr(E);
63 else
64 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000065 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000066 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000067 }
68 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000069 case Stmt::IndirectGotoStmtClass:
70 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000071
72 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
73 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
74 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
75 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
76
77 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
78 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000079
Devang Patel51b09f22007-10-04 23:45:31 +000080 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000081 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000082
83 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000084 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
85 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000086 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000087 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
88 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000089 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000090 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000091 break;
92 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000093 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000094 break;
95 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000096 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000097 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000098 case Stmt::ObjCForCollectionStmtClass:
99 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000100 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 }
102}
103
Daniel Dunbar09124252008-11-12 08:21:33 +0000104bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
105 switch (S->getStmtClass()) {
106 default: return false;
107 case Stmt::NullStmtClass: break;
108 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
109 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
110 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
111 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
112 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
113 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
114 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
115 }
116
117 return true;
118}
119
Chris Lattner33793202007-08-31 22:09:40 +0000120/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
121/// this captures the expression result of the last sub-statement and returns it
122/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000123RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
124 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000126 CGDebugInfo *DI = CGM.getDebugInfo();
127 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000128 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000129 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000130 DI->EmitRegionStart(CurFn, Builder);
131 }
132
Anders Carlsson17d28a32008-12-12 05:52:00 +0000133 // Push a null stack save value.
134 StackSaveValues.push_back(0);
135
Chris Lattner33793202007-08-31 22:09:40 +0000136 for (CompoundStmt::const_body_iterator I = S.body_begin(),
137 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000139
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000140 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000141 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000142 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000143 DI->EmitRegionEnd(CurFn, Builder);
144 }
145
Anders Carlsson17d28a32008-12-12 05:52:00 +0000146 RValue RV;
147 if (!GetLast)
148 RV = RValue::get(0);
149 else {
150 // We have to special case labels here. They are statements, but when put
151 // at the end of a statement expression, they yield the value of their
152 // subexpression. Handle this by walking through all labels we encounter,
153 // emitting them before we evaluate the subexpr.
154 const Stmt *LastStmt = S.body_back();
155 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
156 EmitLabel(*LS);
157 LastStmt = LS->getSubStmt();
158 }
Chris Lattner9b655512007-08-31 22:49:20 +0000159
Anders Carlsson17d28a32008-12-12 05:52:00 +0000160 EnsureInsertPoint();
161
162 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
163 }
164
165 if (llvm::Value *V = StackSaveValues.pop_back_val()) {
166 V = Builder.CreateLoad(V, "tmp");
167
168 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
169 Builder.CreateCall(F, V);
Chris Lattner91d723d2008-07-26 20:23:23 +0000170 }
171
Anders Carlsson17d28a32008-12-12 05:52:00 +0000172 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000173}
174
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000175void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000176 // Fall out of the current block (if necessary).
177 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000178
179 if (IsFinished && BB->use_empty()) {
180 delete BB;
181 return;
182 }
183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 CurFn->getBasicBlockList().push_back(BB);
185 Builder.SetInsertPoint(BB);
186}
187
Daniel Dunbard57a8712008-11-11 09:41:28 +0000188void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
189 // Emit a branch from the current block to the target one if this
190 // was a real block. If this was just a fall-through block after a
191 // terminator, don't emit it.
192 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
193
194 if (!CurBB || CurBB->getTerminator()) {
195 // If there is no insert point or the previous block is already
196 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000197 } else {
198 // Otherwise, create a fall-through branch.
199 Builder.CreateBr(Target);
200 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000201
202 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000203}
204
Chris Lattner91d723d2008-07-26 20:23:23 +0000205void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000208}
209
210
211void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
212 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 EmitStmt(S.getSubStmt());
214}
215
216void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000217 // FIXME: Implement goto out in @try or @catch blocks.
218 if (!ObjCEHStack.empty()) {
219 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
220 return;
221 }
222
Eli Friedman20c802b2008-12-20 23:18:29 +0000223 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000224 if (StackSaveValues[i]) {
225 CGM.ErrorUnsupported(&S, "goto inside scope with VLA");
226 return;
227 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000228 }
229
Daniel Dunbar09124252008-11-12 08:21:33 +0000230 // If this code is reachable then emit a stop point (if generating
231 // debug info). We have to do this ourselves because we are on the
232 // "simple" statement path.
233 if (HaveInsertPoint())
234 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000235 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000236}
237
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000238void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000239 // FIXME: Implement indirect goto in @try or @catch blocks.
240 if (!ObjCEHStack.empty()) {
241 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
242 return;
243 }
244
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000245 // Emit initial switch which will be patched up later by
246 // EmitIndirectSwitches(). We need a default dest, so we use the
247 // current BB, but this is overwritten.
248 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
249 llvm::Type::Int32Ty,
250 "addr");
251 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
252 IndirectSwitches.push_back(I);
253
Daniel Dunbara448fb22008-11-11 23:11:34 +0000254 // Clear the insertion point to indicate we are in unreachable code.
255 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000256}
257
Chris Lattner62b72f62008-11-11 07:24:28 +0000258void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 // C99 6.8.4.1: The first substatement is executed if the expression compares
260 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000261
Chris Lattner9bc47e22008-11-12 07:46:33 +0000262 // If the condition constant folds and can be elided, try to avoid emitting
263 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000264 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000265 // Figure out which block (then or else) is executed.
266 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000267 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000268 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000269
Chris Lattner62b72f62008-11-11 07:24:28 +0000270 // If the skipped block has no labels in it, just emit the executed block.
271 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000272 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000273 if (Executed)
274 EmitStmt(Executed);
275 return;
276 }
277 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000278
279 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
280 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000281 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
282 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
283 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000285 ElseBlock = createBasicBlock("if.else");
286 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000287
288 // Emit the 'then' code.
289 EmitBlock(ThenBlock);
290 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000291 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000292
293 // Emit the 'else' code if present.
294 if (const Stmt *Else = S.getElse()) {
295 EmitBlock(ElseBlock);
296 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000297 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 }
299
300 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000301 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000302}
303
304void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 // Emit the header for the loop, insert it, which will create an uncond br to
306 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000307 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 EmitBlock(LoopHeader);
309
310 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
311 // of the controlling expression takes place before each execution of the loop
312 // body.
313 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000314
315 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000317 bool EmitBoolCondBranch = true;
318 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
319 if (C->isOne())
320 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000321
322 // Create an exit block for when the condition fails, create a block for the
323 // body of the loop.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000324 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000325 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Reid Spencer5f016e22007-07-11 17:01:13 +0000326
327 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000328 if (EmitBoolCondBranch)
329 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000330
Chris Lattnerda138702007-07-16 21:28:45 +0000331 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000332 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader,
333 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000334
335 // Emit the loop body.
336 EmitBlock(LoopBody);
337 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000338
339 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000340
341 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000342 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
344 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000345 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000346
347 // If LoopHeader is a simple forwarding block then eliminate it.
348 if (!EmitBoolCondBranch
349 && &LoopHeader->front() == LoopHeader->getTerminator()) {
350 LoopHeader->replaceAllUsesWith(LoopBody);
351 LoopHeader->getTerminator()->eraseFromParent();
352 LoopHeader->eraseFromParent();
353 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
356void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // Emit the body for the loop, insert it, which will create an uncond br to
358 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000359 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
360 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000362
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000363 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000364
365 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000366 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond,
367 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000368
369 // Emit the body of the loop into the block.
370 EmitStmt(S.getBody());
371
Chris Lattnerda138702007-07-16 21:28:45 +0000372 BreakContinueStack.pop_back();
373
374 EmitBlock(DoCond);
375
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
377 // after each execution of the loop body."
378
379 // Evaluate the conditional in the while header.
380 // C99 6.8.5p2/p4: The first substatement is executed if the expression
381 // compares unequal to 0. The condition must be a scalar type.
382 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000383
384 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
385 // to correctly handle break/continue though.
386 bool EmitBoolCondBranch = true;
387 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
388 if (C->isZero())
389 EmitBoolCondBranch = false;
390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000392 if (EmitBoolCondBranch)
393 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000394
395 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000396 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000397
398 // If DoCond is a simple forwarding block then eliminate it.
399 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
400 DoCond->replaceAllUsesWith(AfterDo);
401 DoCond->getTerminator()->eraseFromParent();
402 DoCond->eraseFromParent();
403 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000404}
405
406void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
408 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000409
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 // Evaluate the first part before the loop.
411 if (S.getInit())
412 EmitStmt(S.getInit());
413
414 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000415 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
416 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000417
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 EmitBlock(CondBlock);
419
420 // Evaluate the condition if present. If not, treat it as a non-zero-constant
421 // according to 6.8.5.3p2, aka, true.
422 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000424 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000425
426 // C99 6.8.5p2/p4: The first substatement is executed if the expression
427 // compares unequal to 0. The condition must be a scalar type.
428 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
429
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 EmitBlock(ForBody);
431 } else {
432 // Treat it as a non-zero constant. Don't even create a new block for the
433 // body, just fall into it.
434 }
435
Chris Lattnerda138702007-07-16 21:28:45 +0000436 // If the for loop doesn't have an increment we can just use the
437 // condition as the continue block.
438 llvm::BasicBlock *ContinueBlock;
439 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000440 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000441 else
442 ContinueBlock = CondBlock;
443
444 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000445 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock,
446 ObjCEHStack.size()));
Chris Lattnerda138702007-07-16 21:28:45 +0000447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 // If the condition is true, execute the body of the for stmt.
449 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000450
451 BreakContinueStack.pop_back();
452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000454 if (S.getInc()) {
455 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000456 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000457 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000458
459 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000460 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461
Chris Lattnerda138702007-07-16 21:28:45 +0000462 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000463 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000464}
465
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000466void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
467 if (RV.isScalar()) {
468 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
469 } else if (RV.isAggregate()) {
470 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
471 } else {
472 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
473 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000474 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000475}
476
Reid Spencer5f016e22007-07-11 17:01:13 +0000477/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
478/// if the function returns void, or may be missing one if the function returns
479/// non-void. Fun stuff :).
480void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Eli Friedman20c802b2008-12-20 23:18:29 +0000481 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000482 if (StackSaveValues[i]) {
483 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
484 return;
485 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000486 }
487
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 // Emit the result value, even if unused, to evalute the side effects.
489 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000490
491 // FIXME: Clean this up by using an LValue for ReturnTemp,
492 // EmitStoreThroughLValue, and EmitAnyExpr.
493 if (!ReturnValue) {
494 // Make sure not to return anything, but evaluate the expression
495 // for side effects.
496 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000497 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000499 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000500 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000501 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000502 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000503 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000505 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 }
Eli Friedman144ac612008-05-22 01:22:33 +0000507
Daniel Dunbar898d5082008-09-30 01:06:03 +0000508 if (!ObjCEHStack.empty()) {
509 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
510 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000511 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000512 EmitJumpThroughFinally(*i, ReturnPad);
513 EmitBlock(ReturnPad);
514 }
515 }
516
Daniel Dunbard57a8712008-11-11 09:41:28 +0000517 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000518}
519
520void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000521 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
522 I != E; ++I)
523 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000524}
Chris Lattnerda138702007-07-16 21:28:45 +0000525
Daniel Dunbar09124252008-11-12 08:21:33 +0000526void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000527 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
528
Daniel Dunbar09124252008-11-12 08:21:33 +0000529 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000530 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000531 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar09124252008-11-12 08:21:33 +0000532 return;
533 }
534
Eli Friedman20c802b2008-12-20 23:18:29 +0000535 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
536 if (StackSaveValues[i]) {
537 CGM.ErrorUnsupported(&S, "break inside scope with VLA");
538 return;
539 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000540 }
541
Daniel Dunbar09124252008-11-12 08:21:33 +0000542 // If this code is reachable then emit a stop point (if generating
543 // debug info). We have to do this ourselves because we are on the
544 // "simple" statement path.
545 if (HaveInsertPoint())
546 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000547 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000548 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000549}
550
Daniel Dunbar09124252008-11-12 08:21:33 +0000551void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000552 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
553
Daniel Dunbar09124252008-11-12 08:21:33 +0000554 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000555 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000556 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
557 return;
558 }
559
Eli Friedman20c802b2008-12-20 23:18:29 +0000560 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
561 if (StackSaveValues[i]) {
562 CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
563 return;
564 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000565 }
566
Daniel Dunbar09124252008-11-12 08:21:33 +0000567 // If this code is reachable then emit a stop point (if generating
568 // debug info). We have to do this ourselves because we are on the
569 // "simple" statement path.
570 if (HaveInsertPoint())
571 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000572 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000573 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000574}
Devang Patel51b09f22007-10-04 23:45:31 +0000575
Devang Patelc049e4f2007-10-08 20:57:48 +0000576/// EmitCaseStmtRange - If case statement range is not too big then
577/// add multiple cases to switch instruction, one for each value within
578/// the range. If range is too big then emit "if" condition check.
579void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000580 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000581
Anders Carlsson51fe9962008-11-22 21:04:56 +0000582 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
583 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000584
Daniel Dunbar16f23572008-07-25 01:11:38 +0000585 // Emit the code for this case. We do this first to make sure it is
586 // properly chained from our predecessor before generating the
587 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000588 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000589 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
590 EmitStmt(S.getSubStmt());
591
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000592 // If range is empty, do nothing.
593 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
594 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000595
596 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000597 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000598 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
599 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000600 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000601 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
602 LHS++;
603 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000604 return;
605 }
606
Daniel Dunbar16f23572008-07-25 01:11:38 +0000607 // The range is too big. Emit "if" condition into a new block,
608 // making sure to save and restore the current insertion point.
609 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000610
Daniel Dunbar16f23572008-07-25 01:11:38 +0000611 // Push this test onto the chain of range checks (which terminates
612 // in the default basic block). The switch's default will be changed
613 // to the top of this chain after switch emission is complete.
614 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000615 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000616
Daniel Dunbar16f23572008-07-25 01:11:38 +0000617 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
618 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000619
620 // Emit range check.
621 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000622 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
623 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000624 llvm::Value *Cond =
625 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
626 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
627
Daniel Dunbar16f23572008-07-25 01:11:38 +0000628 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000629 if (RestoreBB)
630 Builder.SetInsertPoint(RestoreBB);
631 else
632 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000633}
634
635void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
636 if (S.getRHS()) {
637 EmitCaseStmtRange(S);
638 return;
639 }
640
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000641 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000642 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000643 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000644 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000645 EmitStmt(S.getSubStmt());
646}
647
648void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000649 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000650 assert(DefaultBlock->empty() &&
651 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000652 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000653 EmitStmt(S.getSubStmt());
654}
655
656void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
657 llvm::Value *CondV = EmitScalarExpr(S.getCond());
658
659 // Handle nested switch statements.
660 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000661 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000662
Daniel Dunbar16f23572008-07-25 01:11:38 +0000663 // Create basic block to hold stuff that comes after switch
664 // statement. We also need to create a default block now so that
665 // explicit case ranges tests can have a place to jump to on
666 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000667 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
668 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000669 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
670 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000671
Daniel Dunbar09124252008-11-12 08:21:33 +0000672 // Clear the insertion point to indicate we are in unreachable code.
673 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000674
Devang Patele9b8c0a2007-10-30 20:59:40 +0000675 // All break statements jump to NextBlock. If BreakContinueStack is non empty
676 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000677 llvm::BasicBlock *ContinueBlock = NULL;
678 if (!BreakContinueStack.empty())
679 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone21269b2008-12-13 22:52:24 +0000680 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock,
681 ObjCEHStack.size()));
Devang Patel51b09f22007-10-04 23:45:31 +0000682
683 // Emit switch body.
684 EmitStmt(S.getBody());
685 BreakContinueStack.pop_back();
686
Daniel Dunbar16f23572008-07-25 01:11:38 +0000687 // Update the default block in case explicit case range tests have
688 // been chained on top.
689 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000690
Daniel Dunbar16f23572008-07-25 01:11:38 +0000691 // If a default was never emitted then reroute any jumps to it and
692 // discard.
693 if (!DefaultBlock->getParent()) {
694 DefaultBlock->replaceAllUsesWith(NextBlock);
695 delete DefaultBlock;
696 }
Devang Patel51b09f22007-10-04 23:45:31 +0000697
Daniel Dunbar16f23572008-07-25 01:11:38 +0000698 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000699 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000700
Devang Patel51b09f22007-10-04 23:45:31 +0000701 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000702 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000703}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000704
Anders Carlssonce179ab2008-11-09 18:54:14 +0000705static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
706{
707 // FIXME: No need to create new std::string here, we could just make sure
708 // that we don't read past the end of the string data.
709 std::string str(S.getAsmString()->getStrData(),
710 S.getAsmString()->getByteLength());
711 const char *Start = str.c_str();
712
713 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
714 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000715 Failed = false;
716
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000717 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000718 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000719 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000720 if (IsSimple) {
721 while (*Start) {
722 switch (*Start) {
723 default:
724 Result += *Start;
725 break;
726 case '$':
727 Result += "$$";
728 break;
729 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000730 Start++;
731 }
732
733 return Result;
734 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000735
736 while (*Start) {
737 switch (*Start) {
738 default:
739 Result += *Start;
740 break;
741 case '$':
742 Result += "$$";
743 break;
744 case '%':
745 // Escaped character
746 Start++;
747 if (!*Start) {
748 // FIXME: This should be caught during Sema.
749 assert(0 && "Trailing '%' in asm string.");
750 }
751
752 char EscapedChar = *Start;
753 if (EscapedChar == '%') {
754 // Escaped percentage sign.
755 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000756 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000757 // Generate an unique ID.
758 Result += llvm::utostr(AsmCounter);
759 } else if (isdigit(EscapedChar)) {
760 // %n - Assembler operand n
761 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000762 unsigned long n = strtoul(Start, &End, 10);
763 if (Start == End) {
764 // FIXME: This should be caught during Sema.
765 assert(0 && "Missing operand!");
766 } else if (n >= NumOperands) {
767 // FIXME: This should be caught during Sema.
768 assert(0 && "Operand number out of range!");
769 }
770
771 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000772 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000773 } else if (isalpha(EscapedChar)) {
774 char *End;
775
776 unsigned long n = strtoul(Start + 1, &End, 10);
777 if (Start == End) {
778 // FIXME: This should be caught during Sema.
779 assert(0 && "Missing operand!");
780 } else if (n >= NumOperands) {
781 // FIXME: This should be caught during Sema.
782 assert(0 && "Operand number out of range!");
783 }
784
785 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000786 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000787 } else if (EscapedChar == '[') {
788 std::string SymbolicName;
789
790 Start++;
791
792 while (*Start && *Start != ']') {
793 SymbolicName += *Start;
794
795 Start++;
796 }
797
798 if (!Start) {
799 // FIXME: Should be caught by sema.
800 assert(0 && "Could not parse symbolic name");
801 }
802
803 assert(*Start == ']' && "Error parsing symbolic name");
804
805 int Index = -1;
806
807 // Check if this is an output operand.
808 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
809 if (S.getOutputName(i) == SymbolicName) {
810 Index = i;
811 break;
812 }
813 }
814
815 if (Index == -1) {
816 for (unsigned i = 0; i < S.getNumInputs(); i++) {
817 if (S.getInputName(i) == SymbolicName) {
818 Index = S.getNumOutputs() + i;
819 }
820 }
821 }
822
823 assert(Index != -1 && "Did not find right operand!");
824
825 Result += '$' + llvm::utostr(Index);
826
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000827 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000828 Failed = true;
829 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000830 }
831 }
832 Start++;
833 }
834
835 return Result;
836}
837
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000838static std::string SimplifyConstraint(const char* Constraint,
839 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000840 std::string Result;
841
842 while (*Constraint) {
843 switch (*Constraint) {
844 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000845 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000846 break;
847 // Ignore these
848 case '*':
849 case '?':
850 case '!':
851 break;
852 case 'g':
853 Result += "imr";
854 break;
855 }
856
857 Constraint++;
858 }
859
860 return Result;
861}
862
Anders Carlsson63471722009-01-11 19:32:54 +0000863llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
864 TargetInfo::ConstraintInfo Info,
865 const Expr *InputExpr,
866 std::string &ConstraintStr)
867{
868 llvm::Value *Arg;
869 if ((Info & TargetInfo::CI_AllowsRegister) ||
870 !(Info & TargetInfo::CI_AllowsMemory)) {
871 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
872 Arg = EmitScalarExpr(InputExpr);
873 } else {
874 ErrorUnsupported(&S,
875 "asm statement passing multiple-value types as inputs");
876 }
877 } else {
878 LValue Dest = EmitLValue(InputExpr);
879 Arg = Dest.getAddress();
880 ConstraintStr += '*';
881 }
882
883 return Arg;
884}
885
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000886void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000887 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000888 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000889 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000890
891 if (Failed) {
892 ErrorUnsupported(&S, "asm string");
893 return;
894 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000895
896 std::string Constraints;
897
898 llvm::Value *ResultAddr = 0;
899 const llvm::Type *ResultType = llvm::Type::VoidTy;
900
901 std::vector<const llvm::Type*> ArgTypes;
902 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000903
904 // Keep track of inout constraints.
905 std::string InOutConstraints;
906 std::vector<llvm::Value*> InOutArgs;
907 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000908
909 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
910 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
911 S.getOutputConstraint(i)->getByteLength());
912
913 TargetInfo::ConstraintInfo Info;
914 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
915 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000916 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000917
918 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000919 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000920
921 LValue Dest = EmitLValue(S.getOutputExpr(i));
922 const llvm::Type *DestValueType =
923 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
924
925 // If the first output operand is not a memory dest, we'll
926 // make it the return value.
927 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000928 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000929 ResultAddr = Dest.getAddress();
930 ResultType = DestValueType;
931 Constraints += "=" + OutputConstraint;
932 } else {
933 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000934 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000935 if (i != 0)
936 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000937 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000938 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000939 }
940
941 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000942 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000943
Anders Carlssonf39a4212008-02-05 20:01:53 +0000944 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000945 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000946
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000947 if (Info & TargetInfo::CI_AllowsRegister)
948 InOutConstraints += llvm::utostr(i);
949 else
950 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000951
Anders Carlssonf39a4212008-02-05 20:01:53 +0000952 InOutArgTypes.push_back(Arg->getType());
953 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000954 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000955 }
956
957 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
958
959 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
960 const Expr *InputExpr = S.getInputExpr(i);
961
962 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
963 S.getInputConstraint(i)->getByteLength());
964
965 TargetInfo::ConstraintInfo Info;
966 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000967 NumConstraints, Info);
968 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000969
970 if (i != 0 || S.getNumOutputs() > 0)
971 Constraints += ',';
972
973 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000974 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000975
Anders Carlsson63471722009-01-11 19:32:54 +0000976 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000977
978 ArgTypes.push_back(Arg->getType());
979 Args.push_back(Arg);
980 Constraints += InputConstraint;
981 }
982
Anders Carlssonf39a4212008-02-05 20:01:53 +0000983 // Append the "input" part of inout constraints last.
984 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
985 ArgTypes.push_back(InOutArgTypes[i]);
986 Args.push_back(InOutArgs[i]);
987 }
988 Constraints += InOutConstraints;
989
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000990 // Clobbers
991 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
992 std::string Clobber(S.getClobber(i)->getStrData(),
993 S.getClobber(i)->getByteLength());
994
995 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
996
Anders Carlssonea041752008-02-06 00:11:32 +0000997 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000998 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000999
1000 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001001 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001002 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001003 }
1004
1005 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001006 std::string MachineClobbers = Target.getClobbers();
1007 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001008 if (!Constraints.empty())
1009 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001010 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001011 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001012
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001013 const llvm::FunctionType *FTy =
1014 llvm::FunctionType::get(ResultType, ArgTypes, false);
1015
1016 llvm::InlineAsm *IA =
1017 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1018 S.isVolatile() || S.getNumOutputs() == 0);
1019 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001020 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001021 Builder.CreateStore(Result, ResultAddr);
1022}