blob: 88da20d4e829e5c5ef6492d44aabdefc06ebc252 [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
28void CodeGenFunction::EmitStmt(const Stmt *S) {
29 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000030
31 // If we happen to be at an unreachable point just create a dummy
32 // basic block to hold the code. We could change parts of irgen to
33 // simply not generate this code, but this situation is rare and
34 // probably not worth the effort.
35 // FIXME: Verify previous performance/effort claim.
36 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000037
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000038 // Generate stoppoints if we are emitting debug info.
39 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
40 // executable code. So do not generate a stoppoint for that.
41 CGDebugInfo *DI = CGM.getDebugInfo();
42 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
Daniel Dunbar66031a52008-10-17 16:15:48 +000043 DI->setLocation(S->getLocStart());
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000044 DI->EmitStopPoint(CurFn, Builder);
45 }
46
Reid Spencer5f016e22007-07-11 17:01:13 +000047 switch (S->getStmtClass()) {
48 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000049 // Must be an expression in a stmt context. Emit the value (to get
50 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000051 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000052 if (!hasAggregateLLVMType(E->getType()))
53 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000054 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000055 EmitComplexExpr(E);
56 else
57 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000058 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000059 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000060 }
61 break;
62 case Stmt::NullStmtClass: break;
63 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
64 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
65 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000066 case Stmt::IndirectGotoStmtClass:
67 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000068
69 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
70 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
71 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
72 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
73
74 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
75 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000076
Daniel Dunbara4275d12008-10-02 18:02:06 +000077 case Stmt::BreakStmtClass:
78 // FIXME: Implement break in @try or @catch blocks.
79 if (!ObjCEHStack.empty()) {
80 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
81 return;
82 }
83 EmitBreakStmt();
84 break;
85
86 case Stmt::ContinueStmtClass:
87 // FIXME: Implement continue in @try or @catch blocks.
88 if (!ObjCEHStack.empty()) {
89 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
90 return;
91 }
92 EmitContinueStmt();
93 break;
94
Devang Patel51b09f22007-10-04 23:45:31 +000095 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
96 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
97 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000098 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099
100 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000101 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
102 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000103 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000104 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
105 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000106 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000107 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000108 break;
109 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000110 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000111 break;
112 case Stmt::ObjCAtSynchronizedStmtClass:
113 ErrorUnsupported(S, "@synchronized statement");
114 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000115 case Stmt::ObjCForCollectionStmtClass:
116 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000117 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 }
119}
120
Chris Lattner33793202007-08-31 22:09:40 +0000121/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
122/// this captures the expression result of the last sub-statement and returns it
123/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000124RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
125 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000127 CGDebugInfo *DI = CGM.getDebugInfo();
128 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000129 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000130 DI->EmitRegionStart(CurFn, Builder);
131 }
132
Chris Lattner33793202007-08-31 22:09:40 +0000133 for (CompoundStmt::const_body_iterator I = S.body_begin(),
134 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000136
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000137 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000138 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000139 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000140 DI->EmitRegionEnd(CurFn, Builder);
141 }
142
Chris Lattner33793202007-08-31 22:09:40 +0000143 if (!GetLast)
144 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000145
Chris Lattner91d723d2008-07-26 20:23:23 +0000146 // We have to special case labels here. They are statements, but when put at
147 // the end of a statement expression, they yield the value of their
148 // subexpression. Handle this by walking through all labels we encounter,
149 // emitting them before we evaluate the subexpr.
150 const Stmt *LastStmt = S.body_back();
151 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
152 EmitLabel(*LS);
153 LastStmt = LS->getSubStmt();
154 }
155
Daniel Dunbara448fb22008-11-11 23:11:34 +0000156 EnsureInsertPoint();
157
Chris Lattner91d723d2008-07-26 20:23:23 +0000158 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000159}
160
161void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000162 // Fall out of the current block (if necessary).
163 EmitBranch(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 CurFn->getBasicBlockList().push_back(BB);
165 Builder.SetInsertPoint(BB);
166}
167
Daniel Dunbard57a8712008-11-11 09:41:28 +0000168void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
169 // Emit a branch from the current block to the target one if this
170 // was a real block. If this was just a fall-through block after a
171 // terminator, don't emit it.
172 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
173
174 if (!CurBB || CurBB->getTerminator()) {
175 // If there is no insert point or the previous block is already
176 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000177 } else {
178 // Otherwise, create a fall-through branch.
179 Builder.CreateBr(Target);
180 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000181
182 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000183}
184
Chris Lattner91d723d2008-07-26 20:23:23 +0000185void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000188}
189
190
191void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
192 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 EmitStmt(S.getSubStmt());
194}
195
196void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000197 // FIXME: Implement goto out in @try or @catch blocks.
198 if (!ObjCEHStack.empty()) {
199 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
200 return;
201 }
202
Daniel Dunbard57a8712008-11-11 09:41:28 +0000203 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000206void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000207 // FIXME: Implement indirect goto in @try or @catch blocks.
208 if (!ObjCEHStack.empty()) {
209 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
210 return;
211 }
212
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000213 // Emit initial switch which will be patched up later by
214 // EmitIndirectSwitches(). We need a default dest, so we use the
215 // current BB, but this is overwritten.
216 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
217 llvm::Type::Int32Ty,
218 "addr");
219 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
220 IndirectSwitches.push_back(I);
221
Daniel Dunbara448fb22008-11-11 23:11:34 +0000222 // Clear the insertion point to indicate we are in unreachable code.
223 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000224}
225
Chris Lattner62b72f62008-11-11 07:24:28 +0000226void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 // C99 6.8.4.1: The first substatement is executed if the expression compares
228 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000229
Chris Lattner9bc47e22008-11-12 07:46:33 +0000230 // If the condition constant folds and can be elided, try to avoid emitting
231 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000232 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000233 // Figure out which block (then or else) is executed.
234 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000235 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000236 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000237
Chris Lattner62b72f62008-11-11 07:24:28 +0000238 // If the skipped block has no labels in it, just emit the executed block.
239 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000240 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000241 if (Executed)
242 EmitStmt(Executed);
243 return;
244 }
245 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000246
247 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
248 // the conditional branch.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000249 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Chris Lattner9bc47e22008-11-12 07:46:33 +0000250 llvm::BasicBlock *ElseBlock = createBasicBlock("ifelse");
251 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000252
Chris Lattner9bc47e22008-11-12 07:46:33 +0000253 llvm::BasicBlock *ContBlock = ElseBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 if (S.getElse())
Chris Lattner9bc47e22008-11-12 07:46:33 +0000255 ContBlock = createBasicBlock("ifend");
Reid Spencer5f016e22007-07-11 17:01:13 +0000256
257 // Emit the 'then' code.
258 EmitBlock(ThenBlock);
259 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000260 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000261
262 // Emit the 'else' code if present.
263 if (const Stmt *Else = S.getElse()) {
264 EmitBlock(ElseBlock);
265 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000266 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 }
268
269 // Emit the continuation block for code after the if.
270 EmitBlock(ContBlock);
271}
272
273void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 // Emit the header for the loop, insert it, which will create an uncond br to
275 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000276 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 EmitBlock(LoopHeader);
278
279 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
280 // of the controlling expression takes place before each execution of the loop
281 // body.
282 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000283
284 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000286 bool EmitBoolCondBranch = true;
287 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
288 if (C->isOne())
289 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000290
291 // Create an exit block for when the condition fails, create a block for the
292 // body of the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000293 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
294 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000295
296 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000297 if (EmitBoolCondBranch)
298 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000299
Chris Lattnerda138702007-07-16 21:28:45 +0000300 // Store the blocks to use for break and continue.
301 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000302
303 // Emit the loop body.
304 EmitBlock(LoopBody);
305 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000306
307 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000308
309 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000310 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000311
312 // Emit the exit block.
313 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000314
315 // If LoopHeader is a simple forwarding block then eliminate it.
316 if (!EmitBoolCondBranch
317 && &LoopHeader->front() == LoopHeader->getTerminator()) {
318 LoopHeader->replaceAllUsesWith(LoopBody);
319 LoopHeader->getTerminator()->eraseFromParent();
320 LoopHeader->eraseFromParent();
321 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000322}
323
324void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 // Emit the body for the loop, insert it, which will create an uncond br to
326 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000327 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
328 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000330
Daniel Dunbar55e87422008-11-11 02:29:29 +0000331 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000332
333 // Store the blocks to use for break and continue.
334 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000335
336 // Emit the body of the loop into the block.
337 EmitStmt(S.getBody());
338
Chris Lattnerda138702007-07-16 21:28:45 +0000339 BreakContinueStack.pop_back();
340
341 EmitBlock(DoCond);
342
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
344 // after each execution of the loop body."
345
346 // Evaluate the conditional in the while header.
347 // C99 6.8.5p2/p4: The first substatement is executed if the expression
348 // compares unequal to 0. The condition must be a scalar type.
349 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000350
351 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
352 // to correctly handle break/continue though.
353 bool EmitBoolCondBranch = true;
354 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
355 if (C->isZero())
356 EmitBoolCondBranch = false;
357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000359 if (EmitBoolCondBranch)
360 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000361
362 // Emit the exit block.
363 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000364
365 // If DoCond is a simple forwarding block then eliminate it.
366 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
367 DoCond->replaceAllUsesWith(AfterDo);
368 DoCond->getTerminator()->eraseFromParent();
369 DoCond->eraseFromParent();
370 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000371}
372
373void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
375 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000376 // TODO: We could keep track of whether the loop body contains any
377 // break/continue statements and not create unnecessary blocks (like
378 // "afterfor" for a condless loop) if it doesn't.
379
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 // Evaluate the first part before the loop.
381 if (S.getInit())
382 EmitStmt(S.getInit());
383
384 // Start the loop with a block that tests the condition.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000385 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
386 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000387
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 EmitBlock(CondBlock);
389
390 // Evaluate the condition if present. If not, treat it as a non-zero-constant
391 // according to 6.8.5.3p2, aka, true.
392 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000394 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Chris Lattner31a09842008-11-12 08:04:58 +0000395
396 // C99 6.8.5p2/p4: The first substatement is executed if the expression
397 // compares unequal to 0. The condition must be a scalar type.
398 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 EmitBlock(ForBody);
401 } else {
402 // Treat it as a non-zero constant. Don't even create a new block for the
403 // body, just fall into it.
404 }
405
Chris Lattnerda138702007-07-16 21:28:45 +0000406 // If the for loop doesn't have an increment we can just use the
407 // condition as the continue block.
408 llvm::BasicBlock *ContinueBlock;
409 if (S.getInc())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000410 ContinueBlock = createBasicBlock("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000411 else
412 ContinueBlock = CondBlock;
413
414 // Store the blocks to use for break and continue.
415 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // If the condition is true, execute the body of the for stmt.
418 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000419
420 BreakContinueStack.pop_back();
421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000423 if (S.getInc()) {
424 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000425 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000426 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000427
428 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000429 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000430
Chris Lattnerda138702007-07-16 21:28:45 +0000431 // Emit the fall-through block.
432 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433}
434
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000435void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
436 if (RV.isScalar()) {
437 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
438 } else if (RV.isAggregate()) {
439 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
440 } else {
441 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
442 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000443 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000444}
445
Reid Spencer5f016e22007-07-11 17:01:13 +0000446/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
447/// if the function returns void, or may be missing one if the function returns
448/// non-void. Fun stuff :).
449void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 // Emit the result value, even if unused, to evalute the side effects.
451 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000452
453 // FIXME: Clean this up by using an LValue for ReturnTemp,
454 // EmitStoreThroughLValue, and EmitAnyExpr.
455 if (!ReturnValue) {
456 // Make sure not to return anything, but evaluate the expression
457 // for side effects.
458 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000459 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000461 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000462 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000463 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000464 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000465 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000467 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 }
Eli Friedman144ac612008-05-22 01:22:33 +0000469
Daniel Dunbar898d5082008-09-30 01:06:03 +0000470 if (!ObjCEHStack.empty()) {
471 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
472 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000473 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000474 EmitJumpThroughFinally(*i, ReturnPad);
475 EmitBlock(ReturnPad);
476 }
477 }
478
Daniel Dunbard57a8712008-11-11 09:41:28 +0000479 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480}
481
482void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000483 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
484 I != E; ++I)
485 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000486}
Chris Lattnerda138702007-07-16 21:28:45 +0000487
488void CodeGenFunction::EmitBreakStmt() {
489 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
490
491 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000492 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000493}
494
495void CodeGenFunction::EmitContinueStmt() {
496 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
497
498 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000499 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000500}
Devang Patel51b09f22007-10-04 23:45:31 +0000501
Devang Patelc049e4f2007-10-08 20:57:48 +0000502/// EmitCaseStmtRange - If case statement range is not too big then
503/// add multiple cases to switch instruction, one for each value within
504/// the range. If range is too big then emit "if" condition check.
505void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000506 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000507
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000508 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
509 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
510
Daniel Dunbar16f23572008-07-25 01:11:38 +0000511 // Emit the code for this case. We do this first to make sure it is
512 // properly chained from our predecessor before generating the
513 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000514 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000515 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
516 EmitStmt(S.getSubStmt());
517
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000518 // If range is empty, do nothing.
519 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
520 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000521
522 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000523 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000524 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
525 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000526 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000527 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
528 LHS++;
529 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000530 return;
531 }
532
Daniel Dunbar16f23572008-07-25 01:11:38 +0000533 // The range is too big. Emit "if" condition into a new block,
534 // making sure to save and restore the current insertion point.
535 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000536
Daniel Dunbar16f23572008-07-25 01:11:38 +0000537 // Push this test onto the chain of range checks (which terminates
538 // in the default basic block). The switch's default will be changed
539 // to the top of this chain after switch emission is complete.
540 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000541 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000542
Daniel Dunbar16f23572008-07-25 01:11:38 +0000543 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
544 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000545
546 // Emit range check.
547 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000548 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
549 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000550 llvm::Value *Cond =
551 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
552 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
553
Daniel Dunbar16f23572008-07-25 01:11:38 +0000554 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000555 if (RestoreBB)
556 Builder.SetInsertPoint(RestoreBB);
557 else
558 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000559}
560
561void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
562 if (S.getRHS()) {
563 EmitCaseStmtRange(S);
564 return;
565 }
566
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000567 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000568 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000569 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000570 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000571 EmitStmt(S.getSubStmt());
572}
573
574void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000575 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000576 assert(DefaultBlock->empty() &&
577 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000578 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000579 EmitStmt(S.getSubStmt());
580}
581
582void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
583 llvm::Value *CondV = EmitScalarExpr(S.getCond());
584
585 // Handle nested switch statements.
586 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000587 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000588
Daniel Dunbar16f23572008-07-25 01:11:38 +0000589 // Create basic block to hold stuff that comes after switch
590 // statement. We also need to create a default block now so that
591 // explicit case ranges tests can have a place to jump to on
592 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000593 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
594 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000595 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
596 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000597
Eli Friedmand28a80d2008-05-12 16:08:04 +0000598 // Create basic block for body of switch
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000599 EmitBlock(createBasicBlock("sw.body"));
Eli Friedmand28a80d2008-05-12 16:08:04 +0000600
Devang Patele9b8c0a2007-10-30 20:59:40 +0000601 // All break statements jump to NextBlock. If BreakContinueStack is non empty
602 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000603 llvm::BasicBlock *ContinueBlock = NULL;
604 if (!BreakContinueStack.empty())
605 ContinueBlock = BreakContinueStack.back().ContinueBlock;
606 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
607
608 // Emit switch body.
609 EmitStmt(S.getBody());
610 BreakContinueStack.pop_back();
611
Daniel Dunbar16f23572008-07-25 01:11:38 +0000612 // Update the default block in case explicit case range tests have
613 // been chained on top.
614 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000615
Daniel Dunbar16f23572008-07-25 01:11:38 +0000616 // If a default was never emitted then reroute any jumps to it and
617 // discard.
618 if (!DefaultBlock->getParent()) {
619 DefaultBlock->replaceAllUsesWith(NextBlock);
620 delete DefaultBlock;
621 }
Devang Patel51b09f22007-10-04 23:45:31 +0000622
Daniel Dunbar16f23572008-07-25 01:11:38 +0000623 // Emit continuation.
624 EmitBlock(NextBlock);
625
Devang Patel51b09f22007-10-04 23:45:31 +0000626 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000627 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000628}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000629
Anders Carlssonce179ab2008-11-09 18:54:14 +0000630static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
631{
632 // FIXME: No need to create new std::string here, we could just make sure
633 // that we don't read past the end of the string data.
634 std::string str(S.getAsmString()->getStrData(),
635 S.getAsmString()->getByteLength());
636 const char *Start = str.c_str();
637
638 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
639 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000640 Failed = false;
641
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000642 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000643 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000644 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000645 if (IsSimple) {
646 while (*Start) {
647 switch (*Start) {
648 default:
649 Result += *Start;
650 break;
651 case '$':
652 Result += "$$";
653 break;
654 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000655 Start++;
656 }
657
658 return Result;
659 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000660
661 while (*Start) {
662 switch (*Start) {
663 default:
664 Result += *Start;
665 break;
666 case '$':
667 Result += "$$";
668 break;
669 case '%':
670 // Escaped character
671 Start++;
672 if (!*Start) {
673 // FIXME: This should be caught during Sema.
674 assert(0 && "Trailing '%' in asm string.");
675 }
676
677 char EscapedChar = *Start;
678 if (EscapedChar == '%') {
679 // Escaped percentage sign.
680 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000681 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000682 // Generate an unique ID.
683 Result += llvm::utostr(AsmCounter);
684 } else if (isdigit(EscapedChar)) {
685 // %n - Assembler operand n
686 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000687 unsigned long n = strtoul(Start, &End, 10);
688 if (Start == End) {
689 // FIXME: This should be caught during Sema.
690 assert(0 && "Missing operand!");
691 } else if (n >= NumOperands) {
692 // FIXME: This should be caught during Sema.
693 assert(0 && "Operand number out of range!");
694 }
695
696 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000697 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000698 } else if (isalpha(EscapedChar)) {
699 char *End;
700
701 unsigned long n = strtoul(Start + 1, &End, 10);
702 if (Start == End) {
703 // FIXME: This should be caught during Sema.
704 assert(0 && "Missing operand!");
705 } else if (n >= NumOperands) {
706 // FIXME: This should be caught during Sema.
707 assert(0 && "Operand number out of range!");
708 }
709
710 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000711 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000712 } else if (EscapedChar == '[') {
713 std::string SymbolicName;
714
715 Start++;
716
717 while (*Start && *Start != ']') {
718 SymbolicName += *Start;
719
720 Start++;
721 }
722
723 if (!Start) {
724 // FIXME: Should be caught by sema.
725 assert(0 && "Could not parse symbolic name");
726 }
727
728 assert(*Start == ']' && "Error parsing symbolic name");
729
730 int Index = -1;
731
732 // Check if this is an output operand.
733 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
734 if (S.getOutputName(i) == SymbolicName) {
735 Index = i;
736 break;
737 }
738 }
739
740 if (Index == -1) {
741 for (unsigned i = 0; i < S.getNumInputs(); i++) {
742 if (S.getInputName(i) == SymbolicName) {
743 Index = S.getNumOutputs() + i;
744 }
745 }
746 }
747
748 assert(Index != -1 && "Did not find right operand!");
749
750 Result += '$' + llvm::utostr(Index);
751
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000752 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000753 Failed = true;
754 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000755 }
756 }
757 Start++;
758 }
759
760 return Result;
761}
762
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000763static std::string SimplifyConstraint(const char* Constraint,
764 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000765 std::string Result;
766
767 while (*Constraint) {
768 switch (*Constraint) {
769 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000770 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000771 break;
772 // Ignore these
773 case '*':
774 case '?':
775 case '!':
776 break;
777 case 'g':
778 Result += "imr";
779 break;
780 }
781
782 Constraint++;
783 }
784
785 return Result;
786}
787
788void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000789 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000790 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000791 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000792
793 if (Failed) {
794 ErrorUnsupported(&S, "asm string");
795 return;
796 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000797
798 std::string Constraints;
799
800 llvm::Value *ResultAddr = 0;
801 const llvm::Type *ResultType = llvm::Type::VoidTy;
802
803 std::vector<const llvm::Type*> ArgTypes;
804 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000805
806 // Keep track of inout constraints.
807 std::string InOutConstraints;
808 std::vector<llvm::Value*> InOutArgs;
809 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000810
811 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
812 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
813 S.getOutputConstraint(i)->getByteLength());
814
815 TargetInfo::ConstraintInfo Info;
816 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
817 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000818 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000819
820 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000821 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000822
823 LValue Dest = EmitLValue(S.getOutputExpr(i));
824 const llvm::Type *DestValueType =
825 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
826
827 // If the first output operand is not a memory dest, we'll
828 // make it the return value.
829 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000830 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000831 ResultAddr = Dest.getAddress();
832 ResultType = DestValueType;
833 Constraints += "=" + OutputConstraint;
834 } else {
835 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000836 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000837 if (i != 0)
838 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000839 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000840 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000841 }
842
843 if (Info & TargetInfo::CI_ReadWrite) {
844 // FIXME: This code should be shared with the code that handles inputs.
845 InOutConstraints += ',';
846
847 const Expr *InputExpr = S.getOutputExpr(i);
848 llvm::Value *Arg;
849 if ((Info & TargetInfo::CI_AllowsRegister) ||
850 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000851 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000852 Arg = EmitScalarExpr(InputExpr);
853 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000854 ErrorUnsupported(&S,
855 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000856 }
857 } else {
858 LValue Dest = EmitLValue(InputExpr);
859 Arg = Dest.getAddress();
860 InOutConstraints += '*';
861 }
862
863 InOutArgTypes.push_back(Arg->getType());
864 InOutArgs.push_back(Arg);
865 InOutConstraints += OutputConstraint;
866 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000867 }
868
869 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
870
871 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
872 const Expr *InputExpr = S.getInputExpr(i);
873
874 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
875 S.getInputConstraint(i)->getByteLength());
876
877 TargetInfo::ConstraintInfo Info;
878 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000879 NumConstraints, Info);
880 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000881
882 if (i != 0 || S.getNumOutputs() > 0)
883 Constraints += ',';
884
885 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000886 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000887
888 llvm::Value *Arg;
889
890 if ((Info & TargetInfo::CI_AllowsRegister) ||
891 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000892 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000893 Arg = EmitScalarExpr(InputExpr);
894 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000895 ErrorUnsupported(&S,
896 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000897 }
898 } else {
899 LValue Dest = EmitLValue(InputExpr);
900 Arg = Dest.getAddress();
901 Constraints += '*';
902 }
903
904 ArgTypes.push_back(Arg->getType());
905 Args.push_back(Arg);
906 Constraints += InputConstraint;
907 }
908
Anders Carlssonf39a4212008-02-05 20:01:53 +0000909 // Append the "input" part of inout constraints last.
910 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
911 ArgTypes.push_back(InOutArgTypes[i]);
912 Args.push_back(InOutArgs[i]);
913 }
914 Constraints += InOutConstraints;
915
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000916 // Clobbers
917 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
918 std::string Clobber(S.getClobber(i)->getStrData(),
919 S.getClobber(i)->getByteLength());
920
921 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
922
Anders Carlssonea041752008-02-06 00:11:32 +0000923 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000924 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000925
926 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000927 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000928 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000929 }
930
931 // Add machine specific clobbers
932 if (const char *C = Target.getClobbers()) {
933 if (!Constraints.empty())
934 Constraints += ',';
935 Constraints += C;
936 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000937
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000938 const llvm::FunctionType *FTy =
939 llvm::FunctionType::get(ResultType, ArgTypes, false);
940
941 llvm::InlineAsm *IA =
942 llvm::InlineAsm::get(FTy, AsmString, Constraints,
943 S.isVolatile() || S.getNumOutputs() == 0);
944 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000945 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000946 Builder.CreateStore(Result, ResultAddr);
947}