blob: 60e8bd6b7fd95a513e8b5f948dd76ebe62a68641 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "CodeGenFunction.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000019#include "llvm/ADT/StringExtras.h"
Anders Carlsson438ddd82008-12-12 05:52:00 +000020#include "llvm/InlineAsm.h"
21#include "llvm/Intrinsics.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23using namespace CodeGen;
24
25//===----------------------------------------------------------------------===//
26// Statement Emission
27//===----------------------------------------------------------------------===//
28
Daniel Dunbar6c81e562008-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
Chris Lattner4b009652007-07-25 00:24:17 +000036void CodeGenFunction::EmitStmt(const Stmt *S) {
37 assert(S && "Null statement?");
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +000038
Daniel Dunbar6c81e562008-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 Dunbar5aa22bc2008-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();
Chris Lattner4b009652007-07-25 00:24:17 +000050
Daniel Dunbar6c81e562008-11-12 08:21:33 +000051 // Generate a stoppoint if we are emitting debug info.
52 EmitStopPoint(S);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000053
Chris Lattner4b009652007-07-25 00:24:17 +000054 switch (S->getStmtClass()) {
55 default:
Chris Lattner35055b82007-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.
Chris Lattner4b009652007-07-25 00:24:17 +000058 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner35055b82007-08-26 22:58:05 +000059 if (!hasAggregateLLVMType(E->getType()))
60 EmitScalarExpr(E);
Chris Lattnerde0908b2008-04-04 16:54:41 +000061 else if (E->getType()->isAnyComplexType())
Chris Lattner35055b82007-08-26 22:58:05 +000062 EmitComplexExpr(E);
63 else
64 EmitAggExpr(E, 0, false);
Chris Lattner4b009652007-07-25 00:24:17 +000065 } else {
Daniel Dunbar9503b782008-08-16 00:56:44 +000066 ErrorUnsupported(S, "statement");
Chris Lattner4b009652007-07-25 00:24:17 +000067 }
68 break;
Daniel Dunbar879788d2008-08-04 16:51:22 +000069 case Stmt::IndirectGotoStmtClass:
70 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbar66e021e2008-10-02 18:02:06 +000079
Devang Patele58e0802007-10-04 23:45:31 +000080 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000081 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000082
83 case Stmt::ObjCAtTryStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000084 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
85 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000086 case Stmt::ObjCAtCatchStmtClass:
Anders Carlsson75d86732008-09-11 09:15:33 +000087 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
88 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000089 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000090 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar5e105892008-08-23 10:51:21 +000091 break;
92 case Stmt::ObjCAtThrowStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000093 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +000094 break;
95 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattnerdd978702008-11-15 21:26:17 +000096 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +000097 break;
Anders Carlsson82b0d0c2008-08-30 19:51:14 +000098 case Stmt::ObjCForCollectionStmtClass:
99 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +0000100 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000101 }
102}
103
Daniel Dunbar6c81e562008-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 Lattnerea6cdd72007-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 Lattnere24c4cf2007-08-31 22:49:20 +0000123RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
124 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner4b009652007-07-25 00:24:17 +0000125 // FIXME: handle vla's etc.
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000126 CGDebugInfo *DI = CGM.getDebugInfo();
127 if (DI) {
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000128 EnsureInsertPoint();
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000129 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000130 DI->EmitRegionStart(CurFn, Builder);
131 }
132
Anders Carlsson438ddd82008-12-12 05:52:00 +0000133 // Push a null stack save value.
134 StackSaveValues.push_back(0);
135
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000136 for (CompoundStmt::const_body_iterator I = S.body_begin(),
137 E = S.body_end()-GetLast; I != E; ++I)
Chris Lattner4b009652007-07-25 00:24:17 +0000138 EmitStmt(*I);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000139
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000140 if (DI) {
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000141 EnsureInsertPoint();
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000142 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000143 DI->EmitRegionEnd(CurFn, Builder);
144 }
145
Anders Carlsson438ddd82008-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 Lattnere24c4cf2007-08-31 22:49:20 +0000159
Anders Carlsson438ddd82008-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 Lattner09cee852008-07-26 20:23:23 +0000170 }
171
Anders Carlsson438ddd82008-12-12 05:52:00 +0000172 return RV;
Chris Lattner4b009652007-07-25 00:24:17 +0000173}
174
Daniel Dunbare2202612008-11-13 01:24:05 +0000175void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000176 // Fall out of the current block (if necessary).
177 EmitBranch(BB);
Daniel Dunbare2202612008-11-13 01:24:05 +0000178
179 if (IsFinished && BB->use_empty()) {
180 delete BB;
181 return;
182 }
183
Chris Lattner4b009652007-07-25 00:24:17 +0000184 CurFn->getBasicBlockList().push_back(BB);
185 Builder.SetInsertPoint(BB);
186}
187
Daniel Dunbar5276caa2008-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 Dunbar5276caa2008-11-11 09:41:28 +0000197 } else {
198 // Otherwise, create a fall-through branch.
199 Builder.CreateBr(Target);
200 }
Daniel Dunbarc55b7c52008-11-11 22:06:59 +0000201
202 Builder.ClearInsertionPoint();
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000203}
204
Chris Lattner09cee852008-07-26 20:23:23 +0000205void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000206 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Chris Lattner4b009652007-07-25 00:24:17 +0000207 EmitBlock(NextBB);
Chris Lattner09cee852008-07-26 20:23:23 +0000208}
209
210
211void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
212 EmitLabel(S);
Chris Lattner4b009652007-07-25 00:24:17 +0000213 EmitStmt(S.getSubStmt());
214}
215
216void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar66e021e2008-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
Anders Carlssonbdb0f922008-12-20 21:33:38 +0000223 for (int i = 0; i < StackSaveValues.size(); i++) {
224 if (StackSaveValues[i]) {
225 CGM.ErrorUnsupported(&S, "goto inside scope with VLA");
226 return;
227 }
Anders Carlsson842a36d2008-12-20 19:33:21 +0000228 }
229
Daniel Dunbar6c81e562008-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 Dunbar5276caa2008-11-11 09:41:28 +0000235 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Chris Lattner4b009652007-07-25 00:24:17 +0000236}
237
Daniel Dunbar879788d2008-08-04 16:51:22 +0000238void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbar66e021e2008-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 Dunbar879788d2008-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 Dunbar5aa22bc2008-11-11 23:11:34 +0000254 // Clear the insertion point to indicate we are in unreachable code.
255 Builder.ClearInsertionPoint();
Daniel Dunbar879788d2008-08-04 16:51:22 +0000256}
257
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000258void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +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.
Chris Lattner4b009652007-07-25 00:24:17 +0000261
Chris Lattner1875ba22008-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 Lattner3d6606b2008-11-12 08:04:58 +0000264 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattnerc72a6a32008-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 Lattner1875ba22008-11-12 07:46:33 +0000267 if (Cond == -1) // Condition false?
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000268 std::swap(Executed, Skipped);
Chris Lattner1875ba22008-11-12 07:46:33 +0000269
Chris Lattnerc72a6a32008-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 Lattner1875ba22008-11-12 07:46:33 +0000272 if (!ContainsLabel(Skipped)) {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000273 if (Executed)
274 EmitStmt(Executed);
275 return;
276 }
277 }
Chris Lattner1875ba22008-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 Dunbarc70a5df2008-11-13 00:47:57 +0000281 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
282 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
283 llvm::BasicBlock *ElseBlock = ContBlock;
Chris Lattner4b009652007-07-25 00:24:17 +0000284 if (S.getElse())
Daniel Dunbarc70a5df2008-11-13 00:47:57 +0000285 ElseBlock = createBasicBlock("if.else");
286 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000287
288 // Emit the 'then' code.
289 EmitBlock(ThenBlock);
290 EmitStmt(S.getThen());
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000291 EmitBranch(ContBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000292
293 // Emit the 'else' code if present.
294 if (const Stmt *Else = S.getElse()) {
295 EmitBlock(ElseBlock);
296 EmitStmt(Else);
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000297 EmitBranch(ContBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000298 }
299
300 // Emit the continuation block for code after the if.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000301 EmitBlock(ContBlock, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000302}
303
304void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
305 // Emit the header for the loop, insert it, which will create an uncond br to
306 // it.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000307 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Chris Lattner4b009652007-07-25 00:24:17 +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 Patel706f8442007-10-09 20:51:27 +0000314
315 // while(1) is common, avoid extra exit blocks. Be sure
Chris Lattner4b009652007-07-25 00:24:17 +0000316 // to correctly handle break/continue though.
Devang Patel706f8442007-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;
Chris Lattner4b009652007-07-25 00:24:17 +0000321
322 // Create an exit block for when the condition fails, create a block for the
323 // body of the loop.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000324 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000325 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Chris Lattner4b009652007-07-25 00:24:17 +0000326
327 // As long as the condition is true, go to the loop body.
Devang Patel706f8442007-10-09 20:51:27 +0000328 if (EmitBoolCondBranch)
329 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner3d6606b2008-11-12 08:04:58 +0000330
Chris Lattner4b009652007-07-25 00:24:17 +0000331 // Store the blocks to use for break and continue.
Anders Carlssonc2176192008-12-13 22:52:24 +0000332 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader,
333 ObjCEHStack.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000334
335 // Emit the loop body.
336 EmitBlock(LoopBody);
337 EmitStmt(S.getBody());
338
339 BreakContinueStack.pop_back();
340
341 // Cycle to the condition.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000342 EmitBranch(LoopHeader);
Chris Lattner4b009652007-07-25 00:24:17 +0000343
344 // Emit the exit block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000345 EmitBlock(ExitBlock, true);
Devang Patel706f8442007-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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000354}
355
356void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000357 // Emit the body for the loop, insert it, which will create an uncond br to
358 // it.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000359 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
360 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Chris Lattner4b009652007-07-25 00:24:17 +0000361 EmitBlock(LoopBody);
362
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000363 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattner4b009652007-07-25 00:24:17 +0000364
365 // Store the blocks to use for break and continue.
Anders Carlssonc2176192008-12-13 22:52:24 +0000366 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond,
367 ObjCEHStack.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000368
369 // Emit the body of the loop into the block.
370 EmitStmt(S.getBody());
371
372 BreakContinueStack.pop_back();
373
374 EmitBlock(DoCond);
375
376 // 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 Patel716d02c2007-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
Chris Lattner4b009652007-07-25 00:24:17 +0000391 // As long as the condition is true, iterate the loop.
Devang Patel716d02c2007-10-09 20:33:39 +0000392 if (EmitBoolCondBranch)
393 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Chris Lattner4b009652007-07-25 00:24:17 +0000394
395 // Emit the exit block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000396 EmitBlock(AfterDo, true);
Devang Patel716d02c2007-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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000404}
405
406void CodeGenFunction::EmitForStmt(const ForStmt &S) {
407 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
408 // which contains a continue/break?
Chris Lattner4b009652007-07-25 00:24:17 +0000409
410 // 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 Dunbar6e3a10c2008-11-13 01:38:36 +0000415 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
416 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattner4b009652007-07-25 00:24:17 +0000417
418 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()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000423 // As long as the condition is true, iterate the loop.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000424 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner3d6606b2008-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
Chris Lattner4b009652007-07-25 00:24:17 +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
436 // 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 Dunbar6e3a10c2008-11-13 01:38:36 +0000440 ContinueBlock = createBasicBlock("for.inc");
Chris Lattner4b009652007-07-25 00:24:17 +0000441 else
442 ContinueBlock = CondBlock;
443
444 // Store the blocks to use for break and continue.
Anders Carlssonc2176192008-12-13 22:52:24 +0000445 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock,
446 ObjCEHStack.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000447
448 // If the condition is true, execute the body of the for stmt.
449 EmitStmt(S.getBody());
450
451 BreakContinueStack.pop_back();
452
Chris Lattner4b009652007-07-25 00:24:17 +0000453 // If there is an increment, emit it next.
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000454 if (S.getInc()) {
455 EmitBlock(ContinueBlock);
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000456 EmitStmt(S.getInc());
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000457 }
Chris Lattner4b009652007-07-25 00:24:17 +0000458
459 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000460 EmitBranch(CondBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000461
462 // Emit the fall-through block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000463 EmitBlock(AfterFor, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000464}
465
Daniel Dunbare856ac22008-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 Dunbar5276caa2008-11-11 09:41:28 +0000474 EmitBranch(ReturnBlock);
Daniel Dunbare856ac22008-09-24 04:00:38 +0000475}
476
Chris Lattner4b009652007-07-25 00:24:17 +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) {
Anders Carlssonbdb0f922008-12-20 21:33:38 +0000481 for (int i = 0; i < StackSaveValues.size(); i++) {
482 if (StackSaveValues[i]) {
483 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
484 return;
485 }
Anders Carlsson842a36d2008-12-20 19:33:21 +0000486 }
487
Chris Lattner4b009652007-07-25 00:24:17 +0000488 // Emit the result value, even if unused, to evalute the side effects.
489 const Expr *RV = S.getRetValue();
Daniel Dunbar9fb751f2008-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 Friedman56977312008-05-22 01:22:33 +0000497 EmitAnyExpr(RV);
Chris Lattner4b009652007-07-25 00:24:17 +0000498 } else if (RV == 0) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000499 // Do nothing (return value is left uninitialized)
Chris Lattner74b93032007-08-26 07:14:44 +0000500 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000501 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattnerde0908b2008-04-04 16:54:41 +0000502 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000503 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000504 } else {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000505 EmitAggExpr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000506 }
Eli Friedman56977312008-05-22 01:22:33 +0000507
Daniel Dunbare9900eb2008-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 Dunbar72f96552008-11-11 02:29:29 +0000511 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbare9900eb2008-09-30 01:06:03 +0000512 EmitJumpThroughFinally(*i, ReturnPad);
513 EmitBlock(ReturnPad);
514 }
515 }
516
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000517 EmitBranch(ReturnBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000518}
519
520void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneka6b2b272008-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 Lattner4b009652007-07-25 00:24:17 +0000524}
525
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000526void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000527 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
528
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000529 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssonc2176192008-12-13 22:52:24 +0000530 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlsson842a36d2008-12-20 19:33:21 +0000531 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000532 return;
533 }
534
Anders Carlsson842a36d2008-12-20 19:33:21 +0000535 if (StackSaveValues.back()) {
536 CGM.ErrorUnsupported(&S, "break inside scope with VLA");
537 return;
538 }
539
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000540 // If this code is reachable then emit a stop point (if generating
541 // debug info). We have to do this ourselves because we are on the
542 // "simple" statement path.
543 if (HaveInsertPoint())
544 EmitStopPoint(&S);
Chris Lattner4b009652007-07-25 00:24:17 +0000545 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000546 EmitBranch(Block);
Chris Lattner4b009652007-07-25 00:24:17 +0000547}
548
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000549void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000550 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
551
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000552 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssonc2176192008-12-13 22:52:24 +0000553 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000554 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
555 return;
556 }
557
Anders Carlsson842a36d2008-12-20 19:33:21 +0000558 if (StackSaveValues.back()) {
559 CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
560 return;
561 }
562
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000563 // If this code is reachable then emit a stop point (if generating
564 // debug info). We have to do this ourselves because we are on the
565 // "simple" statement path.
566 if (HaveInsertPoint())
567 EmitStopPoint(&S);
Chris Lattner4b009652007-07-25 00:24:17 +0000568 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000569 EmitBranch(Block);
Chris Lattner4b009652007-07-25 00:24:17 +0000570}
Devang Patele58e0802007-10-04 23:45:31 +0000571
Devang Patel347ca322007-10-08 20:57:48 +0000572/// EmitCaseStmtRange - If case statement range is not too big then
573/// add multiple cases to switch instruction, one for each value within
574/// the range. If range is too big then emit "if" condition check.
575void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000576 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patel347ca322007-10-08 20:57:48 +0000577
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000578 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
579 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000580
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000581 // Emit the code for this case. We do this first to make sure it is
582 // properly chained from our predecessor before generating the
583 // switch machinery to enter this block.
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000584 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000585 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
586 EmitStmt(S.getSubStmt());
587
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000588 // If range is empty, do nothing.
589 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
590 return;
Devang Patel347ca322007-10-08 20:57:48 +0000591
592 llvm::APInt Range = RHS - LHS;
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000593 // FIXME: parameters such as this should not be hardcoded.
Devang Patel347ca322007-10-08 20:57:48 +0000594 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
595 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000596 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patelcf9dbf22007-10-05 20:54:07 +0000597 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
598 LHS++;
599 }
Devang Patel347ca322007-10-08 20:57:48 +0000600 return;
601 }
602
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000603 // The range is too big. Emit "if" condition into a new block,
604 // making sure to save and restore the current insertion point.
605 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patelcf9dbf22007-10-05 20:54:07 +0000606
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000607 // Push this test onto the chain of range checks (which terminates
608 // in the default basic block). The switch's default will be changed
609 // to the top of this chain after switch emission is complete.
610 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar72f96552008-11-11 02:29:29 +0000611 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patel347ca322007-10-08 20:57:48 +0000612
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000613 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
614 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000615
616 // Emit range check.
617 llvm::Value *Diff =
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000618 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
619 "tmp");
Devang Patel347ca322007-10-08 20:57:48 +0000620 llvm::Value *Cond =
621 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
622 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
623
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000624 // Restore the appropriate insertion point.
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000625 if (RestoreBB)
626 Builder.SetInsertPoint(RestoreBB);
627 else
628 Builder.ClearInsertionPoint();
Devang Patel347ca322007-10-08 20:57:48 +0000629}
630
631void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
632 if (S.getRHS()) {
633 EmitCaseStmtRange(S);
634 return;
635 }
636
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000637 EmitBlock(createBasicBlock("sw.bb"));
Devang Patel347ca322007-10-08 20:57:48 +0000638 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000639 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar72f96552008-11-11 02:29:29 +0000640 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patele58e0802007-10-04 23:45:31 +0000641 EmitStmt(S.getSubStmt());
642}
643
644void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000645 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar72f96552008-11-11 02:29:29 +0000646 assert(DefaultBlock->empty() &&
647 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000648 EmitBlock(DefaultBlock);
Devang Patele58e0802007-10-04 23:45:31 +0000649 EmitStmt(S.getSubStmt());
650}
651
652void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
653 llvm::Value *CondV = EmitScalarExpr(S.getCond());
654
655 // Handle nested switch statements.
656 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000657 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000658
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000659 // Create basic block to hold stuff that comes after switch
660 // statement. We also need to create a default block now so that
661 // explicit case ranges tests can have a place to jump to on
662 // failure.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000663 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
664 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000665 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
666 CaseRangeBlock = DefaultBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000667
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000668 // Clear the insertion point to indicate we are in unreachable code.
669 Builder.ClearInsertionPoint();
Eli Friedman51eaf1b2008-05-12 16:08:04 +0000670
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000671 // All break statements jump to NextBlock. If BreakContinueStack is non empty
672 // then reuse last ContinueBlock.
Devang Patele58e0802007-10-04 23:45:31 +0000673 llvm::BasicBlock *ContinueBlock = NULL;
674 if (!BreakContinueStack.empty())
675 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssonc2176192008-12-13 22:52:24 +0000676 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock,
677 ObjCEHStack.size()));
Devang Patele58e0802007-10-04 23:45:31 +0000678
679 // Emit switch body.
680 EmitStmt(S.getBody());
681 BreakContinueStack.pop_back();
682
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000683 // Update the default block in case explicit case range tests have
684 // been chained on top.
685 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000686
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000687 // If a default was never emitted then reroute any jumps to it and
688 // discard.
689 if (!DefaultBlock->getParent()) {
690 DefaultBlock->replaceAllUsesWith(NextBlock);
691 delete DefaultBlock;
692 }
Devang Patele58e0802007-10-04 23:45:31 +0000693
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000694 // Emit continuation.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000695 EmitBlock(NextBlock, true);
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000696
Devang Patele58e0802007-10-04 23:45:31 +0000697 SwitchInsn = SavedSwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000698 CaseRangeBlock = SavedCRBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000699}
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000700
Anders Carlssondf8f3042008-11-09 18:54:14 +0000701static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
702{
703 // FIXME: No need to create new std::string here, we could just make sure
704 // that we don't read past the end of the string data.
705 std::string str(S.getAsmString()->getStrData(),
706 S.getAsmString()->getByteLength());
707 const char *Start = str.c_str();
708
709 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
710 bool IsSimple = S.isSimple();
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000711 Failed = false;
712
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000713 static unsigned AsmCounter = 0;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000714 AsmCounter++;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000715 std::string Result;
Anders Carlsson52234522008-02-05 23:18:57 +0000716 if (IsSimple) {
717 while (*Start) {
718 switch (*Start) {
719 default:
720 Result += *Start;
721 break;
722 case '$':
723 Result += "$$";
724 break;
725 }
Anders Carlsson52234522008-02-05 23:18:57 +0000726 Start++;
727 }
728
729 return Result;
730 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000731
732 while (*Start) {
733 switch (*Start) {
734 default:
735 Result += *Start;
736 break;
737 case '$':
738 Result += "$$";
739 break;
740 case '%':
741 // Escaped character
742 Start++;
743 if (!*Start) {
744 // FIXME: This should be caught during Sema.
745 assert(0 && "Trailing '%' in asm string.");
746 }
747
748 char EscapedChar = *Start;
749 if (EscapedChar == '%') {
750 // Escaped percentage sign.
751 Result += '%';
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000752 } else if (EscapedChar == '=') {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000753 // Generate an unique ID.
754 Result += llvm::utostr(AsmCounter);
755 } else if (isdigit(EscapedChar)) {
756 // %n - Assembler operand n
757 char *End;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000758 unsigned long n = strtoul(Start, &End, 10);
759 if (Start == End) {
760 // FIXME: This should be caught during Sema.
761 assert(0 && "Missing operand!");
762 } else if (n >= NumOperands) {
763 // FIXME: This should be caught during Sema.
764 assert(0 && "Operand number out of range!");
765 }
766
767 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000768 Start = End - 1;
Anders Carlsson52234522008-02-05 23:18:57 +0000769 } else if (isalpha(EscapedChar)) {
770 char *End;
771
772 unsigned long n = strtoul(Start + 1, &End, 10);
773 if (Start == End) {
774 // FIXME: This should be caught during Sema.
775 assert(0 && "Missing operand!");
776 } else if (n >= NumOperands) {
777 // FIXME: This should be caught during Sema.
778 assert(0 && "Operand number out of range!");
779 }
780
781 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000782 Start = End - 1;
Anders Carlssondf8f3042008-11-09 18:54:14 +0000783 } else if (EscapedChar == '[') {
784 std::string SymbolicName;
785
786 Start++;
787
788 while (*Start && *Start != ']') {
789 SymbolicName += *Start;
790
791 Start++;
792 }
793
794 if (!Start) {
795 // FIXME: Should be caught by sema.
796 assert(0 && "Could not parse symbolic name");
797 }
798
799 assert(*Start == ']' && "Error parsing symbolic name");
800
801 int Index = -1;
802
803 // Check if this is an output operand.
804 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
805 if (S.getOutputName(i) == SymbolicName) {
806 Index = i;
807 break;
808 }
809 }
810
811 if (Index == -1) {
812 for (unsigned i = 0; i < S.getNumInputs(); i++) {
813 if (S.getInputName(i) == SymbolicName) {
814 Index = S.getNumOutputs() + i;
815 }
816 }
817 }
818
819 assert(Index != -1 && "Did not find right operand!");
820
821 Result += '$' + llvm::utostr(Index);
822
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000823 } else {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000824 Failed = true;
825 return "";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000826 }
827 }
828 Start++;
829 }
830
831 return Result;
832}
833
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000834static std::string SimplifyConstraint(const char* Constraint,
835 TargetInfo &Target) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000836 std::string Result;
837
838 while (*Constraint) {
839 switch (*Constraint) {
840 default:
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000841 Result += Target.convertConstraint(*Constraint);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000842 break;
843 // Ignore these
844 case '*':
845 case '?':
846 case '!':
847 break;
848 case 'g':
849 Result += "imr";
850 break;
851 }
852
853 Constraint++;
854 }
855
856 return Result;
857}
858
859void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000860 bool Failed;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000861 std::string AsmString =
Anders Carlssondf8f3042008-11-09 18:54:14 +0000862 ConvertAsmString(S, Failed);
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000863
864 if (Failed) {
865 ErrorUnsupported(&S, "asm string");
866 return;
867 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000868
869 std::string Constraints;
870
871 llvm::Value *ResultAddr = 0;
872 const llvm::Type *ResultType = llvm::Type::VoidTy;
873
874 std::vector<const llvm::Type*> ArgTypes;
875 std::vector<llvm::Value*> Args;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000876
877 // Keep track of inout constraints.
878 std::string InOutConstraints;
879 std::vector<llvm::Value*> InOutArgs;
880 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000881
882 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
883 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
884 S.getOutputConstraint(i)->getByteLength());
885
886 TargetInfo::ConstraintInfo Info;
887 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
888 Info);
Chris Lattner94c4b2d2008-10-12 00:31:50 +0000889 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000890
891 // Simplify the output constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000892 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000893
894 LValue Dest = EmitLValue(S.getOutputExpr(i));
895 const llvm::Type *DestValueType =
896 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
897
898 // If the first output operand is not a memory dest, we'll
899 // make it the return value.
900 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohman377ba9f2008-05-22 22:12:56 +0000901 DestValueType->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000902 ResultAddr = Dest.getAddress();
903 ResultType = DestValueType;
904 Constraints += "=" + OutputConstraint;
905 } else {
906 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlsson78725072008-02-05 16:57:38 +0000907 Args.push_back(Dest.getAddress());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000908 if (i != 0)
909 Constraints += ',';
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000910 Constraints += "=*";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000911 Constraints += OutputConstraint;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000912 }
913
914 if (Info & TargetInfo::CI_ReadWrite) {
915 // FIXME: This code should be shared with the code that handles inputs.
916 InOutConstraints += ',';
917
918 const Expr *InputExpr = S.getOutputExpr(i);
919 llvm::Value *Arg;
920 if ((Info & TargetInfo::CI_AllowsRegister) ||
921 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000922 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000923 Arg = EmitScalarExpr(InputExpr);
924 } else {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000925 ErrorUnsupported(&S,
926 "asm statement passing multiple-value types as inputs");
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000927 }
928 } else {
929 LValue Dest = EmitLValue(InputExpr);
930 Arg = Dest.getAddress();
931 InOutConstraints += '*';
932 }
933
934 InOutArgTypes.push_back(Arg->getType());
935 InOutArgs.push_back(Arg);
936 InOutConstraints += OutputConstraint;
937 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000938 }
939
940 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
941
942 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
943 const Expr *InputExpr = S.getInputExpr(i);
944
945 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
946 S.getInputConstraint(i)->getByteLength());
947
948 TargetInfo::ConstraintInfo Info;
949 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner94c4b2d2008-10-12 00:31:50 +0000950 NumConstraints, Info);
951 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000952
953 if (i != 0 || S.getNumOutputs() > 0)
954 Constraints += ',';
955
956 // Simplify the input constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000957 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000958
959 llvm::Value *Arg;
960
961 if ((Info & TargetInfo::CI_AllowsRegister) ||
962 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000963 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000964 Arg = EmitScalarExpr(InputExpr);
965 } else {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000966 ErrorUnsupported(&S,
967 "asm statement passing multiple-value types as inputs");
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000968 }
969 } else {
970 LValue Dest = EmitLValue(InputExpr);
971 Arg = Dest.getAddress();
972 Constraints += '*';
973 }
974
975 ArgTypes.push_back(Arg->getType());
976 Args.push_back(Arg);
977 Constraints += InputConstraint;
978 }
979
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000980 // Append the "input" part of inout constraints last.
981 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
982 ArgTypes.push_back(InOutArgTypes[i]);
983 Args.push_back(InOutArgs[i]);
984 }
985 Constraints += InOutConstraints;
986
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000987 // Clobbers
988 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
989 std::string Clobber(S.getClobber(i)->getStrData(),
990 S.getClobber(i)->getByteLength());
991
992 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
993
Anders Carlsson74385982008-02-06 00:11:32 +0000994 if (i != 0 || NumConstraints != 0)
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000995 Constraints += ',';
Anders Carlsson74385982008-02-06 00:11:32 +0000996
997 Constraints += "~{";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000998 Constraints += Clobber;
Anders Carlsson74385982008-02-06 00:11:32 +0000999 Constraints += '}';
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001000 }
1001
1002 // Add machine specific clobbers
1003 if (const char *C = Target.getClobbers()) {
1004 if (!Constraints.empty())
1005 Constraints += ',';
1006 Constraints += C;
1007 }
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001008
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001009 const llvm::FunctionType *FTy =
1010 llvm::FunctionType::get(ResultType, ArgTypes, false);
1011
1012 llvm::InlineAsm *IA =
1013 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1014 S.isVolatile() || S.getNumOutputs() == 0);
1015 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman2e630542008-06-13 23:01:12 +00001016 if (ResultAddr) // FIXME: volatility
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001017 Builder.CreateStore(Result, ResultAddr);
1018}