blob: 0a67e57e343f75ea5d5e0874502307dc5bbd094c [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/InlineAsm.h"
20#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22using namespace CodeGen;
23
24//===----------------------------------------------------------------------===//
25// Statement Emission
26//===----------------------------------------------------------------------===//
27
Daniel Dunbar09124252008-11-12 08:21:33 +000028void CodeGenFunction::EmitStopPoint(const Stmt *S) {
29 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
30 DI->setLocation(S->getLocStart());
31 DI->EmitStopPoint(CurFn, Builder);
32 }
33}
34
Reid Spencer5f016e22007-07-11 17:01:13 +000035void CodeGenFunction::EmitStmt(const Stmt *S) {
36 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000037
Daniel Dunbar09124252008-11-12 08:21:33 +000038 // Check if we can handle this without bothering to generate an
39 // insert point or debug info.
40 if (EmitSimpleStmt(S))
41 return;
42
Daniel Dunbara448fb22008-11-11 23:11:34 +000043 // If we happen to be at an unreachable point just create a dummy
44 // basic block to hold the code. We could change parts of irgen to
45 // simply not generate this code, but this situation is rare and
46 // probably not worth the effort.
47 // FIXME: Verify previous performance/effort claim.
48 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Daniel Dunbar09124252008-11-12 08:21:33 +000050 // Generate a stoppoint if we are emitting debug info.
51 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000052
Reid Spencer5f016e22007-07-11 17:01:13 +000053 switch (S->getStmtClass()) {
54 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000055 // Must be an expression in a stmt context. Emit the value (to get
56 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000057 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000058 if (!hasAggregateLLVMType(E->getType()))
59 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000060 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000061 EmitComplexExpr(E);
62 else
63 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000064 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000065 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000066 }
67 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000068 case Stmt::IndirectGotoStmtClass:
69 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000070
71 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
72 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
73 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
74 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
75
76 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
77 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000078
Devang Patel51b09f22007-10-04 23:45:31 +000079 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000080 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000081
82 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000083 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
84 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000085 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000086 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
87 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000088 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000089 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000090 break;
91 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000092 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000093 break;
94 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000095 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000096 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000097 case Stmt::ObjCForCollectionStmtClass:
98 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 }
101}
102
Daniel Dunbar09124252008-11-12 08:21:33 +0000103bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
104 switch (S->getStmtClass()) {
105 default: return false;
106 case Stmt::NullStmtClass: break;
107 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
108 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
109 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
110 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
111 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
112 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
113 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
114 }
115
116 return true;
117}
118
Chris Lattner33793202007-08-31 22:09:40 +0000119/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
120/// this captures the expression result of the last sub-statement and returns it
121/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000122RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
123 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000125 CGDebugInfo *DI = CGM.getDebugInfo();
126 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000127 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000128 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000129 DI->EmitRegionStart(CurFn, Builder);
130 }
131
Chris Lattner33793202007-08-31 22:09:40 +0000132 for (CompoundStmt::const_body_iterator I = S.body_begin(),
133 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000135
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000136 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000137 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000138 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000139 DI->EmitRegionEnd(CurFn, Builder);
140 }
141
Chris Lattner33793202007-08-31 22:09:40 +0000142 if (!GetLast)
143 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000144
Chris Lattner91d723d2008-07-26 20:23:23 +0000145 // We have to special case labels here. They are statements, but when put at
146 // the end of a statement expression, they yield the value of their
147 // subexpression. Handle this by walking through all labels we encounter,
148 // emitting them before we evaluate the subexpr.
149 const Stmt *LastStmt = S.body_back();
150 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
151 EmitLabel(*LS);
152 LastStmt = LS->getSubStmt();
153 }
154
Daniel Dunbara448fb22008-11-11 23:11:34 +0000155 EnsureInsertPoint();
156
Chris Lattner91d723d2008-07-26 20:23:23 +0000157 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000158}
159
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000160void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000161 // Fall out of the current block (if necessary).
162 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000163
164 if (IsFinished && BB->use_empty()) {
165 delete BB;
166 return;
167 }
168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 CurFn->getBasicBlockList().push_back(BB);
170 Builder.SetInsertPoint(BB);
171}
172
Daniel Dunbard57a8712008-11-11 09:41:28 +0000173void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
174 // Emit a branch from the current block to the target one if this
175 // was a real block. If this was just a fall-through block after a
176 // terminator, don't emit it.
177 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
178
179 if (!CurBB || CurBB->getTerminator()) {
180 // If there is no insert point or the previous block is already
181 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000182 } else {
183 // Otherwise, create a fall-through branch.
184 Builder.CreateBr(Target);
185 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000186
187 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000188}
189
Chris Lattner91d723d2008-07-26 20:23:23 +0000190void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000193}
194
195
196void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
197 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 EmitStmt(S.getSubStmt());
199}
200
201void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000202 // FIXME: Implement goto out in @try or @catch blocks.
203 if (!ObjCEHStack.empty()) {
204 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
205 return;
206 }
207
Daniel Dunbar09124252008-11-12 08:21:33 +0000208 // If this code is reachable then emit a stop point (if generating
209 // debug info). We have to do this ourselves because we are on the
210 // "simple" statement path.
211 if (HaveInsertPoint())
212 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000213 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000214}
215
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000216void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000217 // FIXME: Implement indirect goto in @try or @catch blocks.
218 if (!ObjCEHStack.empty()) {
219 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
220 return;
221 }
222
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000223 // Emit initial switch which will be patched up later by
224 // EmitIndirectSwitches(). We need a default dest, so we use the
225 // current BB, but this is overwritten.
226 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
227 llvm::Type::Int32Ty,
228 "addr");
229 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
230 IndirectSwitches.push_back(I);
231
Daniel Dunbara448fb22008-11-11 23:11:34 +0000232 // Clear the insertion point to indicate we are in unreachable code.
233 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000234}
235
Chris Lattner62b72f62008-11-11 07:24:28 +0000236void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 // C99 6.8.4.1: The first substatement is executed if the expression compares
238 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000239
Chris Lattner9bc47e22008-11-12 07:46:33 +0000240 // If the condition constant folds and can be elided, try to avoid emitting
241 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000242 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000243 // Figure out which block (then or else) is executed.
244 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000245 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000246 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000247
Chris Lattner62b72f62008-11-11 07:24:28 +0000248 // If the skipped block has no labels in it, just emit the executed block.
249 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000250 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000251 if (Executed)
252 EmitStmt(Executed);
253 return;
254 }
255 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000256
257 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
258 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000259 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
260 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
261 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000262 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000263 ElseBlock = createBasicBlock("if.else");
264 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000265
266 // Emit the 'then' code.
267 EmitBlock(ThenBlock);
268 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000269 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000270
271 // Emit the 'else' code if present.
272 if (const Stmt *Else = S.getElse()) {
273 EmitBlock(ElseBlock);
274 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000275 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 }
277
278 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000279 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280}
281
282void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 // Emit the header for the loop, insert it, which will create an uncond br to
284 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000285 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 EmitBlock(LoopHeader);
287
288 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
289 // of the controlling expression takes place before each execution of the loop
290 // body.
291 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000292
293 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000295 bool EmitBoolCondBranch = true;
296 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
297 if (C->isOne())
298 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299
300 // Create an exit block for when the condition fails, create a block for the
301 // body of the loop.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000302 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000303 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Reid Spencer5f016e22007-07-11 17:01:13 +0000304
305 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000306 if (EmitBoolCondBranch)
307 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000308
Chris Lattnerda138702007-07-16 21:28:45 +0000309 // Store the blocks to use for break and continue.
310 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000311
312 // Emit the loop body.
313 EmitBlock(LoopBody);
314 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000315
316 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000317
318 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000319 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000320
321 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000322 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000323
324 // If LoopHeader is a simple forwarding block then eliminate it.
325 if (!EmitBoolCondBranch
326 && &LoopHeader->front() == LoopHeader->getTerminator()) {
327 LoopHeader->replaceAllUsesWith(LoopBody);
328 LoopHeader->getTerminator()->eraseFromParent();
329 LoopHeader->eraseFromParent();
330 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000331}
332
333void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 // Emit the body for the loop, insert it, which will create an uncond br to
335 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000336 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
337 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000339
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000340 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000341
342 // Store the blocks to use for break and continue.
343 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
345 // Emit the body of the loop into the block.
346 EmitStmt(S.getBody());
347
Chris Lattnerda138702007-07-16 21:28:45 +0000348 BreakContinueStack.pop_back();
349
350 EmitBlock(DoCond);
351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
353 // after each execution of the loop body."
354
355 // Evaluate the conditional in the while header.
356 // C99 6.8.5p2/p4: The first substatement is executed if the expression
357 // compares unequal to 0. The condition must be a scalar type.
358 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000359
360 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
361 // to correctly handle break/continue though.
362 bool EmitBoolCondBranch = true;
363 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
364 if (C->isZero())
365 EmitBoolCondBranch = false;
366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000368 if (EmitBoolCondBranch)
369 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370
371 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000372 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000373
374 // If DoCond is a simple forwarding block then eliminate it.
375 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
376 DoCond->replaceAllUsesWith(AfterDo);
377 DoCond->getTerminator()->eraseFromParent();
378 DoCond->eraseFromParent();
379 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000380}
381
382void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
384 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // Evaluate the first part before the loop.
387 if (S.getInit())
388 EmitStmt(S.getInit());
389
390 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000391 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
392 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000393
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 EmitBlock(CondBlock);
395
396 // Evaluate the condition if present. If not, treat it as a non-zero-constant
397 // according to 6.8.5.3p2, aka, true.
398 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000400 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000401
402 // C99 6.8.5p2/p4: The first substatement is executed if the expression
403 // compares unequal to 0. The condition must be a scalar type.
404 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
405
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 EmitBlock(ForBody);
407 } else {
408 // Treat it as a non-zero constant. Don't even create a new block for the
409 // body, just fall into it.
410 }
411
Chris Lattnerda138702007-07-16 21:28:45 +0000412 // If the for loop doesn't have an increment we can just use the
413 // condition as the continue block.
414 llvm::BasicBlock *ContinueBlock;
415 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000416 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000417 else
418 ContinueBlock = CondBlock;
419
420 // Store the blocks to use for break and continue.
421 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 // If the condition is true, execute the body of the for stmt.
424 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000425
426 BreakContinueStack.pop_back();
427
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000429 if (S.getInc()) {
430 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000431 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000432 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000433
434 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000435 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000436
Chris Lattnerda138702007-07-16 21:28:45 +0000437 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000438 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000439}
440
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000441void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
442 if (RV.isScalar()) {
443 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
444 } else if (RV.isAggregate()) {
445 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
446 } else {
447 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
448 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000449 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000450}
451
Reid Spencer5f016e22007-07-11 17:01:13 +0000452/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
453/// if the function returns void, or may be missing one if the function returns
454/// non-void. Fun stuff :).
455void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 // Emit the result value, even if unused, to evalute the side effects.
457 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000458
459 // FIXME: Clean this up by using an LValue for ReturnTemp,
460 // EmitStoreThroughLValue, and EmitAnyExpr.
461 if (!ReturnValue) {
462 // Make sure not to return anything, but evaluate the expression
463 // for side effects.
464 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000465 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000467 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000468 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000469 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000470 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000471 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000473 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 }
Eli Friedman144ac612008-05-22 01:22:33 +0000475
Daniel Dunbar898d5082008-09-30 01:06:03 +0000476 if (!ObjCEHStack.empty()) {
477 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
478 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000479 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000480 EmitJumpThroughFinally(*i, ReturnPad);
481 EmitBlock(ReturnPad);
482 }
483 }
484
Daniel Dunbard57a8712008-11-11 09:41:28 +0000485 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000486}
487
488void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000489 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
490 I != E; ++I)
491 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000492}
Chris Lattnerda138702007-07-16 21:28:45 +0000493
Daniel Dunbar09124252008-11-12 08:21:33 +0000494void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000495 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
496
Daniel Dunbar09124252008-11-12 08:21:33 +0000497 // FIXME: Implement break in @try or @catch blocks.
498 if (!ObjCEHStack.empty()) {
499 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
500 return;
501 }
502
503 // If this code is reachable then emit a stop point (if generating
504 // debug info). We have to do this ourselves because we are on the
505 // "simple" statement path.
506 if (HaveInsertPoint())
507 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000508 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000509 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000510}
511
Daniel Dunbar09124252008-11-12 08:21:33 +0000512void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000513 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
514
Daniel Dunbar09124252008-11-12 08:21:33 +0000515 // FIXME: Implement continue in @try or @catch blocks.
516 if (!ObjCEHStack.empty()) {
517 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
518 return;
519 }
520
521 // If this code is reachable then emit a stop point (if generating
522 // debug info). We have to do this ourselves because we are on the
523 // "simple" statement path.
524 if (HaveInsertPoint())
525 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000526 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000527 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000528}
Devang Patel51b09f22007-10-04 23:45:31 +0000529
Devang Patelc049e4f2007-10-08 20:57:48 +0000530/// EmitCaseStmtRange - If case statement range is not too big then
531/// add multiple cases to switch instruction, one for each value within
532/// the range. If range is too big then emit "if" condition check.
533void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000534 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000535
Anders Carlsson51fe9962008-11-22 21:04:56 +0000536 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
537 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000538
Daniel Dunbar16f23572008-07-25 01:11:38 +0000539 // Emit the code for this case. We do this first to make sure it is
540 // properly chained from our predecessor before generating the
541 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000542 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000543 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
544 EmitStmt(S.getSubStmt());
545
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000546 // If range is empty, do nothing.
547 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
548 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000549
550 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000551 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000552 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
553 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000554 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000555 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
556 LHS++;
557 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000558 return;
559 }
560
Daniel Dunbar16f23572008-07-25 01:11:38 +0000561 // The range is too big. Emit "if" condition into a new block,
562 // making sure to save and restore the current insertion point.
563 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000564
Daniel Dunbar16f23572008-07-25 01:11:38 +0000565 // Push this test onto the chain of range checks (which terminates
566 // in the default basic block). The switch's default will be changed
567 // to the top of this chain after switch emission is complete.
568 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000569 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000570
Daniel Dunbar16f23572008-07-25 01:11:38 +0000571 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
572 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000573
574 // Emit range check.
575 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000576 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
577 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000578 llvm::Value *Cond =
579 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
580 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
581
Daniel Dunbar16f23572008-07-25 01:11:38 +0000582 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000583 if (RestoreBB)
584 Builder.SetInsertPoint(RestoreBB);
585 else
586 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000587}
588
589void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
590 if (S.getRHS()) {
591 EmitCaseStmtRange(S);
592 return;
593 }
594
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000595 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000596 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000597 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000598 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000599 EmitStmt(S.getSubStmt());
600}
601
602void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000603 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000604 assert(DefaultBlock->empty() &&
605 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000606 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000607 EmitStmt(S.getSubStmt());
608}
609
610void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
611 llvm::Value *CondV = EmitScalarExpr(S.getCond());
612
613 // Handle nested switch statements.
614 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000615 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000616
Daniel Dunbar16f23572008-07-25 01:11:38 +0000617 // Create basic block to hold stuff that comes after switch
618 // statement. We also need to create a default block now so that
619 // explicit case ranges tests can have a place to jump to on
620 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000621 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
622 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000623 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
624 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000625
Daniel Dunbar09124252008-11-12 08:21:33 +0000626 // Clear the insertion point to indicate we are in unreachable code.
627 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000628
Devang Patele9b8c0a2007-10-30 20:59:40 +0000629 // All break statements jump to NextBlock. If BreakContinueStack is non empty
630 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000631 llvm::BasicBlock *ContinueBlock = NULL;
632 if (!BreakContinueStack.empty())
633 ContinueBlock = BreakContinueStack.back().ContinueBlock;
634 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
635
636 // Emit switch body.
637 EmitStmt(S.getBody());
638 BreakContinueStack.pop_back();
639
Daniel Dunbar16f23572008-07-25 01:11:38 +0000640 // Update the default block in case explicit case range tests have
641 // been chained on top.
642 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000643
Daniel Dunbar16f23572008-07-25 01:11:38 +0000644 // If a default was never emitted then reroute any jumps to it and
645 // discard.
646 if (!DefaultBlock->getParent()) {
647 DefaultBlock->replaceAllUsesWith(NextBlock);
648 delete DefaultBlock;
649 }
Devang Patel51b09f22007-10-04 23:45:31 +0000650
Daniel Dunbar16f23572008-07-25 01:11:38 +0000651 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000652 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000653
Devang Patel51b09f22007-10-04 23:45:31 +0000654 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000655 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000656}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000657
Anders Carlssonce179ab2008-11-09 18:54:14 +0000658static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
659{
660 // FIXME: No need to create new std::string here, we could just make sure
661 // that we don't read past the end of the string data.
662 std::string str(S.getAsmString()->getStrData(),
663 S.getAsmString()->getByteLength());
664 const char *Start = str.c_str();
665
666 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
667 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000668 Failed = false;
669
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000670 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000671 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000672 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000673 if (IsSimple) {
674 while (*Start) {
675 switch (*Start) {
676 default:
677 Result += *Start;
678 break;
679 case '$':
680 Result += "$$";
681 break;
682 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000683 Start++;
684 }
685
686 return Result;
687 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000688
689 while (*Start) {
690 switch (*Start) {
691 default:
692 Result += *Start;
693 break;
694 case '$':
695 Result += "$$";
696 break;
697 case '%':
698 // Escaped character
699 Start++;
700 if (!*Start) {
701 // FIXME: This should be caught during Sema.
702 assert(0 && "Trailing '%' in asm string.");
703 }
704
705 char EscapedChar = *Start;
706 if (EscapedChar == '%') {
707 // Escaped percentage sign.
708 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000709 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000710 // Generate an unique ID.
711 Result += llvm::utostr(AsmCounter);
712 } else if (isdigit(EscapedChar)) {
713 // %n - Assembler operand n
714 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000715 unsigned long n = strtoul(Start, &End, 10);
716 if (Start == End) {
717 // FIXME: This should be caught during Sema.
718 assert(0 && "Missing operand!");
719 } else if (n >= NumOperands) {
720 // FIXME: This should be caught during Sema.
721 assert(0 && "Operand number out of range!");
722 }
723
724 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000725 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000726 } else if (isalpha(EscapedChar)) {
727 char *End;
728
729 unsigned long n = strtoul(Start + 1, &End, 10);
730 if (Start == End) {
731 // FIXME: This should be caught during Sema.
732 assert(0 && "Missing operand!");
733 } else if (n >= NumOperands) {
734 // FIXME: This should be caught during Sema.
735 assert(0 && "Operand number out of range!");
736 }
737
738 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000739 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000740 } else if (EscapedChar == '[') {
741 std::string SymbolicName;
742
743 Start++;
744
745 while (*Start && *Start != ']') {
746 SymbolicName += *Start;
747
748 Start++;
749 }
750
751 if (!Start) {
752 // FIXME: Should be caught by sema.
753 assert(0 && "Could not parse symbolic name");
754 }
755
756 assert(*Start == ']' && "Error parsing symbolic name");
757
758 int Index = -1;
759
760 // Check if this is an output operand.
761 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
762 if (S.getOutputName(i) == SymbolicName) {
763 Index = i;
764 break;
765 }
766 }
767
768 if (Index == -1) {
769 for (unsigned i = 0; i < S.getNumInputs(); i++) {
770 if (S.getInputName(i) == SymbolicName) {
771 Index = S.getNumOutputs() + i;
772 }
773 }
774 }
775
776 assert(Index != -1 && "Did not find right operand!");
777
778 Result += '$' + llvm::utostr(Index);
779
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000780 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000781 Failed = true;
782 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000783 }
784 }
785 Start++;
786 }
787
788 return Result;
789}
790
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000791static std::string SimplifyConstraint(const char* Constraint,
792 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000793 std::string Result;
794
795 while (*Constraint) {
796 switch (*Constraint) {
797 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000798 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000799 break;
800 // Ignore these
801 case '*':
802 case '?':
803 case '!':
804 break;
805 case 'g':
806 Result += "imr";
807 break;
808 }
809
810 Constraint++;
811 }
812
813 return Result;
814}
815
816void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000817 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000818 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000819 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000820
821 if (Failed) {
822 ErrorUnsupported(&S, "asm string");
823 return;
824 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000825
826 std::string Constraints;
827
828 llvm::Value *ResultAddr = 0;
829 const llvm::Type *ResultType = llvm::Type::VoidTy;
830
831 std::vector<const llvm::Type*> ArgTypes;
832 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000833
834 // Keep track of inout constraints.
835 std::string InOutConstraints;
836 std::vector<llvm::Value*> InOutArgs;
837 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000838
839 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
840 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
841 S.getOutputConstraint(i)->getByteLength());
842
843 TargetInfo::ConstraintInfo Info;
844 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
845 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000846 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000847
848 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000849 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000850
851 LValue Dest = EmitLValue(S.getOutputExpr(i));
852 const llvm::Type *DestValueType =
853 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
854
855 // If the first output operand is not a memory dest, we'll
856 // make it the return value.
857 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000858 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000859 ResultAddr = Dest.getAddress();
860 ResultType = DestValueType;
861 Constraints += "=" + OutputConstraint;
862 } else {
863 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000864 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000865 if (i != 0)
866 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000867 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000868 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000869 }
870
871 if (Info & TargetInfo::CI_ReadWrite) {
872 // FIXME: This code should be shared with the code that handles inputs.
873 InOutConstraints += ',';
874
875 const Expr *InputExpr = S.getOutputExpr(i);
876 llvm::Value *Arg;
877 if ((Info & TargetInfo::CI_AllowsRegister) ||
878 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000879 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000880 Arg = EmitScalarExpr(InputExpr);
881 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000882 ErrorUnsupported(&S,
883 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000884 }
885 } else {
886 LValue Dest = EmitLValue(InputExpr);
887 Arg = Dest.getAddress();
888 InOutConstraints += '*';
889 }
890
891 InOutArgTypes.push_back(Arg->getType());
892 InOutArgs.push_back(Arg);
893 InOutConstraints += OutputConstraint;
894 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000895 }
896
897 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
898
899 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
900 const Expr *InputExpr = S.getInputExpr(i);
901
902 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
903 S.getInputConstraint(i)->getByteLength());
904
905 TargetInfo::ConstraintInfo Info;
906 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000907 NumConstraints, Info);
908 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000909
910 if (i != 0 || S.getNumOutputs() > 0)
911 Constraints += ',';
912
913 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000914 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000915
916 llvm::Value *Arg;
917
918 if ((Info & TargetInfo::CI_AllowsRegister) ||
919 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000920 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000921 Arg = EmitScalarExpr(InputExpr);
922 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000923 ErrorUnsupported(&S,
924 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000925 }
926 } else {
927 LValue Dest = EmitLValue(InputExpr);
928 Arg = Dest.getAddress();
929 Constraints += '*';
930 }
931
932 ArgTypes.push_back(Arg->getType());
933 Args.push_back(Arg);
934 Constraints += InputConstraint;
935 }
936
Anders Carlssonf39a4212008-02-05 20:01:53 +0000937 // Append the "input" part of inout constraints last.
938 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
939 ArgTypes.push_back(InOutArgTypes[i]);
940 Args.push_back(InOutArgs[i]);
941 }
942 Constraints += InOutConstraints;
943
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000944 // Clobbers
945 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
946 std::string Clobber(S.getClobber(i)->getStrData(),
947 S.getClobber(i)->getByteLength());
948
949 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
950
Anders Carlssonea041752008-02-06 00:11:32 +0000951 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000952 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000953
954 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000955 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000956 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000957 }
958
959 // Add machine specific clobbers
960 if (const char *C = Target.getClobbers()) {
961 if (!Constraints.empty())
962 Constraints += ',';
963 Constraints += C;
964 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000965
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000966 const llvm::FunctionType *FTy =
967 llvm::FunctionType::get(ResultType, ArgTypes, false);
968
969 llvm::InlineAsm *IA =
970 llvm::InlineAsm::get(FTy, AsmString, Constraints,
971 S.isVolatile() || S.getNumOutputs() == 0);
972 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000973 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000974 Builder.CreateStore(Result, ResultAddr);
975}