blob: 97a7a05768766689dfc3cf5ba8f842e7f500eff5 [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?");
30
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000031 // Generate stoppoints if we are emitting debug info.
32 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
33 // executable code. So do not generate a stoppoint for that.
34 CGDebugInfo *DI = CGM.getDebugInfo();
35 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
Daniel Dunbar66031a52008-10-17 16:15:48 +000036 DI->setLocation(S->getLocStart());
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000037 DI->EmitStopPoint(CurFn, Builder);
38 }
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040 switch (S->getStmtClass()) {
41 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000042 // Must be an expression in a stmt context. Emit the value (to get
43 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000044 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000045 if (!hasAggregateLLVMType(E->getType()))
46 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000047 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000048 EmitComplexExpr(E);
49 else
50 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000051 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000052 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000053 }
54 break;
55 case Stmt::NullStmtClass: break;
56 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
57 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
58 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000059 case Stmt::IndirectGotoStmtClass:
60 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000061
62 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
63 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
64 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
65 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
66
67 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
68 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000069
Daniel Dunbara4275d12008-10-02 18:02:06 +000070 case Stmt::BreakStmtClass:
71 // FIXME: Implement break in @try or @catch blocks.
72 if (!ObjCEHStack.empty()) {
73 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
74 return;
75 }
76 EmitBreakStmt();
77 break;
78
79 case Stmt::ContinueStmtClass:
80 // FIXME: Implement continue in @try or @catch blocks.
81 if (!ObjCEHStack.empty()) {
82 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
83 return;
84 }
85 EmitContinueStmt();
86 break;
87
Devang Patel51b09f22007-10-04 23:45:31 +000088 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
89 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
90 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000091 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000092
93 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000094 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
95 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000096 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000097 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
98 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000100 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101 break;
102 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000103 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000104 break;
105 case Stmt::ObjCAtSynchronizedStmtClass:
106 ErrorUnsupported(S, "@synchronized statement");
107 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000108 case Stmt::ObjCForCollectionStmtClass:
109 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000110 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
112}
113
Chris Lattner33793202007-08-31 22:09:40 +0000114/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
115/// this captures the expression result of the last sub-statement and returns it
116/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000117RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
118 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000120 CGDebugInfo *DI = CGM.getDebugInfo();
121 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000122 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000123 DI->EmitRegionStart(CurFn, Builder);
124 }
125
Chris Lattner33793202007-08-31 22:09:40 +0000126 for (CompoundStmt::const_body_iterator I = S.body_begin(),
127 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000129
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000130 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000131 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Chris Lattner33793202007-08-31 22:09:40 +0000135 if (!GetLast)
136 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000137
Chris Lattner91d723d2008-07-26 20:23:23 +0000138 // We have to special case labels here. They are statements, but when put at
139 // the end of a statement expression, they yield the value of their
140 // subexpression. Handle this by walking through all labels we encounter,
141 // emitting them before we evaluate the subexpr.
142 const Stmt *LastStmt = S.body_back();
143 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
144 EmitLabel(*LS);
145 LastStmt = LS->getSubStmt();
146 }
147
148 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000149}
150
151void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000152 // Fall out of the current block (if necessary).
153 EmitBranch(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 CurFn->getBasicBlockList().push_back(BB);
155 Builder.SetInsertPoint(BB);
156}
157
Daniel Dunbard57a8712008-11-11 09:41:28 +0000158void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
159 // Emit a branch from the current block to the target one if this
160 // was a real block. If this was just a fall-through block after a
161 // terminator, don't emit it.
162 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
163
164 if (!CurBB || CurBB->getTerminator()) {
165 // If there is no insert point or the previous block is already
166 // terminated, don't touch it.
167 } else if (isDummyBlock(CurBB)) {
168 // If the last block was an empty placeholder, remove it now.
169 // TODO: cache and reuse these.
170 CurBB->eraseFromParent();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000171 } else {
172 // Otherwise, create a fall-through branch.
173 Builder.CreateBr(Target);
174 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000175
176 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000177}
178
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000179void CodeGenFunction::EmitDummyBlock() {
180 EmitBlock(createBasicBlock());
181}
182
Chris Lattner91d723d2008-07-26 20:23:23 +0000183void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000186}
187
188
189void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
190 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 EmitStmt(S.getSubStmt());
192}
193
194void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000195 // FIXME: Implement goto out in @try or @catch blocks.
196 if (!ObjCEHStack.empty()) {
197 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
198 return;
199 }
200
Daniel Dunbard57a8712008-11-11 09:41:28 +0000201 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000202
203 // Emit a block after the branch so that dead code after a goto has some place
204 // to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000205 EmitDummyBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000206}
207
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000208void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000209 // FIXME: Implement indirect goto in @try or @catch blocks.
210 if (!ObjCEHStack.empty()) {
211 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
212 return;
213 }
214
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000215 // Emit initial switch which will be patched up later by
216 // EmitIndirectSwitches(). We need a default dest, so we use the
217 // current BB, but this is overwritten.
218 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
219 llvm::Type::Int32Ty,
220 "addr");
221 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
222 IndirectSwitches.push_back(I);
223
224 // Emit a block after the branch so that dead code after a goto has some place
225 // to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000226 EmitDummyBlock();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000227}
228
Chris Lattner62b72f62008-11-11 07:24:28 +0000229void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 // C99 6.8.4.1: The first substatement is executed if the expression compares
231 // unequal to 0. The condition must be a scalar type.
232 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
233
Chris Lattner62b72f62008-11-11 07:24:28 +0000234 // If we constant folded the condition to true or false, try to avoid emitting
235 // the dead arm at all.
236 if (llvm::ConstantInt *CondCst = dyn_cast<llvm::ConstantInt>(BoolCondVal)) {
237 // Figure out which block (then or else) is executed.
238 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
239 if (!CondCst->getZExtValue())
240 std::swap(Executed, Skipped);
241
242 // If the skipped block has no labels in it, just emit the executed block.
243 // This avoids emitting dead code and simplifies the CFG substantially.
244 if (Skipped == 0 || !ContainsLabel(Skipped)) {
245 if (Executed)
246 EmitStmt(Executed);
247 return;
248 }
249 }
250
Daniel Dunbar55e87422008-11-11 02:29:29 +0000251 llvm::BasicBlock *ContBlock = createBasicBlock("ifend");
252 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 llvm::BasicBlock *ElseBlock = ContBlock;
254
255 if (S.getElse())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000256 ElseBlock = createBasicBlock("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000257
258 // Insert the conditional branch.
259 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
260
261 // Emit the 'then' code.
262 EmitBlock(ThenBlock);
263 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000264 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000265
266 // Emit the 'else' code if present.
267 if (const Stmt *Else = S.getElse()) {
268 EmitBlock(ElseBlock);
269 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000270 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 }
272
273 // Emit the continuation block for code after the if.
274 EmitBlock(ContBlock);
275}
276
277void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 // Emit the header for the loop, insert it, which will create an uncond br to
279 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000280 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 EmitBlock(LoopHeader);
282
283 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
284 // of the controlling expression takes place before each execution of the loop
285 // body.
286 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000287
288 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000290 bool EmitBoolCondBranch = true;
291 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
292 if (C->isOne())
293 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000294
295 // Create an exit block for when the condition fails, create a block for the
296 // body of the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000297 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
298 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000299
300 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000301 if (EmitBoolCondBranch)
302 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000303
304 // Store the blocks to use for break and continue.
305 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000306
307 // Emit the loop body.
308 EmitBlock(LoopBody);
309 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000310
311 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000312
313 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000314 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000315
316 // Emit the exit block.
317 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000318
319 // If LoopHeader is a simple forwarding block then eliminate it.
320 if (!EmitBoolCondBranch
321 && &LoopHeader->front() == LoopHeader->getTerminator()) {
322 LoopHeader->replaceAllUsesWith(LoopBody);
323 LoopHeader->getTerminator()->eraseFromParent();
324 LoopHeader->eraseFromParent();
325 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000326}
327
328void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 // Emit the body for the loop, insert it, which will create an uncond br to
330 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000331 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
332 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000334
Daniel Dunbar55e87422008-11-11 02:29:29 +0000335 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000336
337 // Store the blocks to use for break and continue.
338 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000339
340 // Emit the body of the loop into the block.
341 EmitStmt(S.getBody());
342
Chris Lattnerda138702007-07-16 21:28:45 +0000343 BreakContinueStack.pop_back();
344
345 EmitBlock(DoCond);
346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
348 // after each execution of the loop body."
349
350 // Evaluate the conditional in the while header.
351 // C99 6.8.5p2/p4: The first substatement is executed if the expression
352 // compares unequal to 0. The condition must be a scalar type.
353 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000354
355 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
356 // to correctly handle break/continue though.
357 bool EmitBoolCondBranch = true;
358 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
359 if (C->isZero())
360 EmitBoolCondBranch = false;
361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000363 if (EmitBoolCondBranch)
364 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000365
366 // Emit the exit block.
367 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000368
369 // If DoCond is a simple forwarding block then eliminate it.
370 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
371 DoCond->replaceAllUsesWith(AfterDo);
372 DoCond->getTerminator()->eraseFromParent();
373 DoCond->eraseFromParent();
374 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000375}
376
377void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
379 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000380 // TODO: We could keep track of whether the loop body contains any
381 // break/continue statements and not create unnecessary blocks (like
382 // "afterfor" for a condless loop) if it doesn't.
383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 // Evaluate the first part before the loop.
385 if (S.getInit())
386 EmitStmt(S.getInit());
387
388 // Start the loop with a block that tests the condition.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000389 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
390 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000391
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 EmitBlock(CondBlock);
393
394 // Evaluate the condition if present. If not, treat it as a non-zero-constant
395 // according to 6.8.5.3p2, aka, true.
396 if (S.getCond()) {
397 // C99 6.8.5p2/p4: The first substatement is executed if the expression
398 // compares unequal to 0. The condition must be a scalar type.
399 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
400
401 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000402 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
404 EmitBlock(ForBody);
405 } else {
406 // Treat it as a non-zero constant. Don't even create a new block for the
407 // body, just fall into it.
408 }
409
Chris Lattnerda138702007-07-16 21:28:45 +0000410 // If the for loop doesn't have an increment we can just use the
411 // condition as the continue block.
412 llvm::BasicBlock *ContinueBlock;
413 if (S.getInc())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000414 ContinueBlock = createBasicBlock("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000415 else
416 ContinueBlock = CondBlock;
417
418 // Store the blocks to use for break and continue.
419 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
420
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 // If the condition is true, execute the body of the for stmt.
422 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000423
424 BreakContinueStack.pop_back();
425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000427 if (S.getInc()) {
428 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000429 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000430 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000431
432 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000433 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000434
Chris Lattnerda138702007-07-16 21:28:45 +0000435 // Emit the fall-through block.
436 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000437}
438
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000439void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
440 if (RV.isScalar()) {
441 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
442 } else if (RV.isAggregate()) {
443 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
444 } else {
445 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
446 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000447 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000448
449 // Emit a block after the branch so that dead code after a return has some
450 // place to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000451 EmitDummyBlock();
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000452}
453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
455/// if the function returns void, or may be missing one if the function returns
456/// non-void. Fun stuff :).
457void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 // Emit the result value, even if unused, to evalute the side effects.
459 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000460
461 // FIXME: Clean this up by using an LValue for ReturnTemp,
462 // EmitStoreThroughLValue, and EmitAnyExpr.
463 if (!ReturnValue) {
464 // Make sure not to return anything, but evaluate the expression
465 // for side effects.
466 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000467 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000469 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000470 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000471 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000472 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000473 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000475 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 }
Eli Friedman144ac612008-05-22 01:22:33 +0000477
Daniel Dunbar898d5082008-09-30 01:06:03 +0000478 if (!ObjCEHStack.empty()) {
479 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
480 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000481 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000482 EmitJumpThroughFinally(*i, ReturnPad);
483 EmitBlock(ReturnPad);
484 }
485 }
486
Daniel Dunbard57a8712008-11-11 09:41:28 +0000487 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000488
489 // Emit a block after the branch so that dead code after a return has some
490 // place to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000491 EmitDummyBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000492}
493
494void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000495 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
496 I != E; ++I)
497 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000498}
Chris Lattnerda138702007-07-16 21:28:45 +0000499
500void CodeGenFunction::EmitBreakStmt() {
501 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
502
503 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000504 EmitBranch(Block);
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000505 EmitDummyBlock();
Chris Lattnerda138702007-07-16 21:28:45 +0000506}
507
508void CodeGenFunction::EmitContinueStmt() {
509 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
510
511 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000512 EmitBranch(Block);
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000513 EmitDummyBlock();
Chris Lattnerda138702007-07-16 21:28:45 +0000514}
Devang Patel51b09f22007-10-04 23:45:31 +0000515
Devang Patelc049e4f2007-10-08 20:57:48 +0000516/// EmitCaseStmtRange - If case statement range is not too big then
517/// add multiple cases to switch instruction, one for each value within
518/// the range. If range is too big then emit "if" condition check.
519void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000520 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000521
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000522 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
523 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
524
Daniel Dunbar16f23572008-07-25 01:11:38 +0000525 // Emit the code for this case. We do this first to make sure it is
526 // properly chained from our predecessor before generating the
527 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000528 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000529 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
530 EmitStmt(S.getSubStmt());
531
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000532 // If range is empty, do nothing.
533 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
534 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000535
536 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000537 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000538 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
539 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000540 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000541 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
542 LHS++;
543 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000544 return;
545 }
546
Daniel Dunbar16f23572008-07-25 01:11:38 +0000547 // The range is too big. Emit "if" condition into a new block,
548 // making sure to save and restore the current insertion point.
549 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000550
Daniel Dunbar16f23572008-07-25 01:11:38 +0000551 // Push this test onto the chain of range checks (which terminates
552 // in the default basic block). The switch's default will be changed
553 // to the top of this chain after switch emission is complete.
554 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000555 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000556
Daniel Dunbar16f23572008-07-25 01:11:38 +0000557 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
558 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000559
560 // Emit range check.
561 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000562 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
563 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000564 llvm::Value *Cond =
565 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
566 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
567
Daniel Dunbar16f23572008-07-25 01:11:38 +0000568 // Restore the appropriate insertion point.
569 Builder.SetInsertPoint(RestoreBB);
Devang Patelc049e4f2007-10-08 20:57:48 +0000570}
571
572void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
573 if (S.getRHS()) {
574 EmitCaseStmtRange(S);
575 return;
576 }
577
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000578 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000579 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000580 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000581 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000582 EmitStmt(S.getSubStmt());
583}
584
585void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000586 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000587 assert(DefaultBlock->empty() &&
588 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000589 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000590 EmitStmt(S.getSubStmt());
591}
592
593void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
594 llvm::Value *CondV = EmitScalarExpr(S.getCond());
595
596 // Handle nested switch statements.
597 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000598 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000599
Daniel Dunbar16f23572008-07-25 01:11:38 +0000600 // Create basic block to hold stuff that comes after switch
601 // statement. We also need to create a default block now so that
602 // explicit case ranges tests can have a place to jump to on
603 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000604 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
605 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000606 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
607 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000608
Eli Friedmand28a80d2008-05-12 16:08:04 +0000609 // Create basic block for body of switch
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000610 EmitBlock(createBasicBlock("sw.body"));
Eli Friedmand28a80d2008-05-12 16:08:04 +0000611
Devang Patele9b8c0a2007-10-30 20:59:40 +0000612 // All break statements jump to NextBlock. If BreakContinueStack is non empty
613 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000614 llvm::BasicBlock *ContinueBlock = NULL;
615 if (!BreakContinueStack.empty())
616 ContinueBlock = BreakContinueStack.back().ContinueBlock;
617 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
618
619 // Emit switch body.
620 EmitStmt(S.getBody());
621 BreakContinueStack.pop_back();
622
Daniel Dunbar16f23572008-07-25 01:11:38 +0000623 // Update the default block in case explicit case range tests have
624 // been chained on top.
625 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000626
Daniel Dunbar16f23572008-07-25 01:11:38 +0000627 // If a default was never emitted then reroute any jumps to it and
628 // discard.
629 if (!DefaultBlock->getParent()) {
630 DefaultBlock->replaceAllUsesWith(NextBlock);
631 delete DefaultBlock;
632 }
Devang Patel51b09f22007-10-04 23:45:31 +0000633
Daniel Dunbar16f23572008-07-25 01:11:38 +0000634 // Emit continuation.
635 EmitBlock(NextBlock);
636
Devang Patel51b09f22007-10-04 23:45:31 +0000637 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000638 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000639}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000640
Anders Carlssonce179ab2008-11-09 18:54:14 +0000641static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
642{
643 // FIXME: No need to create new std::string here, we could just make sure
644 // that we don't read past the end of the string data.
645 std::string str(S.getAsmString()->getStrData(),
646 S.getAsmString()->getByteLength());
647 const char *Start = str.c_str();
648
649 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
650 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000651 Failed = false;
652
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000653 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000654 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000655 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000656 if (IsSimple) {
657 while (*Start) {
658 switch (*Start) {
659 default:
660 Result += *Start;
661 break;
662 case '$':
663 Result += "$$";
664 break;
665 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000666 Start++;
667 }
668
669 return Result;
670 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000671
672 while (*Start) {
673 switch (*Start) {
674 default:
675 Result += *Start;
676 break;
677 case '$':
678 Result += "$$";
679 break;
680 case '%':
681 // Escaped character
682 Start++;
683 if (!*Start) {
684 // FIXME: This should be caught during Sema.
685 assert(0 && "Trailing '%' in asm string.");
686 }
687
688 char EscapedChar = *Start;
689 if (EscapedChar == '%') {
690 // Escaped percentage sign.
691 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000692 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000693 // Generate an unique ID.
694 Result += llvm::utostr(AsmCounter);
695 } else if (isdigit(EscapedChar)) {
696 // %n - Assembler operand n
697 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000698 unsigned long n = strtoul(Start, &End, 10);
699 if (Start == End) {
700 // FIXME: This should be caught during Sema.
701 assert(0 && "Missing operand!");
702 } else if (n >= NumOperands) {
703 // FIXME: This should be caught during Sema.
704 assert(0 && "Operand number out of range!");
705 }
706
707 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000708 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000709 } else if (isalpha(EscapedChar)) {
710 char *End;
711
712 unsigned long n = strtoul(Start + 1, &End, 10);
713 if (Start == End) {
714 // FIXME: This should be caught during Sema.
715 assert(0 && "Missing operand!");
716 } else if (n >= NumOperands) {
717 // FIXME: This should be caught during Sema.
718 assert(0 && "Operand number out of range!");
719 }
720
721 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000722 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000723 } else if (EscapedChar == '[') {
724 std::string SymbolicName;
725
726 Start++;
727
728 while (*Start && *Start != ']') {
729 SymbolicName += *Start;
730
731 Start++;
732 }
733
734 if (!Start) {
735 // FIXME: Should be caught by sema.
736 assert(0 && "Could not parse symbolic name");
737 }
738
739 assert(*Start == ']' && "Error parsing symbolic name");
740
741 int Index = -1;
742
743 // Check if this is an output operand.
744 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
745 if (S.getOutputName(i) == SymbolicName) {
746 Index = i;
747 break;
748 }
749 }
750
751 if (Index == -1) {
752 for (unsigned i = 0; i < S.getNumInputs(); i++) {
753 if (S.getInputName(i) == SymbolicName) {
754 Index = S.getNumOutputs() + i;
755 }
756 }
757 }
758
759 assert(Index != -1 && "Did not find right operand!");
760
761 Result += '$' + llvm::utostr(Index);
762
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000763 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000764 Failed = true;
765 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000766 }
767 }
768 Start++;
769 }
770
771 return Result;
772}
773
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000774static std::string SimplifyConstraint(const char* Constraint,
775 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000776 std::string Result;
777
778 while (*Constraint) {
779 switch (*Constraint) {
780 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000781 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000782 break;
783 // Ignore these
784 case '*':
785 case '?':
786 case '!':
787 break;
788 case 'g':
789 Result += "imr";
790 break;
791 }
792
793 Constraint++;
794 }
795
796 return Result;
797}
798
799void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000800 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000801 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000802 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000803
804 if (Failed) {
805 ErrorUnsupported(&S, "asm string");
806 return;
807 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000808
809 std::string Constraints;
810
811 llvm::Value *ResultAddr = 0;
812 const llvm::Type *ResultType = llvm::Type::VoidTy;
813
814 std::vector<const llvm::Type*> ArgTypes;
815 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000816
817 // Keep track of inout constraints.
818 std::string InOutConstraints;
819 std::vector<llvm::Value*> InOutArgs;
820 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000821
822 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
823 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
824 S.getOutputConstraint(i)->getByteLength());
825
826 TargetInfo::ConstraintInfo Info;
827 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
828 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000829 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000830
831 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000832 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000833
834 LValue Dest = EmitLValue(S.getOutputExpr(i));
835 const llvm::Type *DestValueType =
836 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
837
838 // If the first output operand is not a memory dest, we'll
839 // make it the return value.
840 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000841 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000842 ResultAddr = Dest.getAddress();
843 ResultType = DestValueType;
844 Constraints += "=" + OutputConstraint;
845 } else {
846 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000847 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000848 if (i != 0)
849 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000850 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000851 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000852 }
853
854 if (Info & TargetInfo::CI_ReadWrite) {
855 // FIXME: This code should be shared with the code that handles inputs.
856 InOutConstraints += ',';
857
858 const Expr *InputExpr = S.getOutputExpr(i);
859 llvm::Value *Arg;
860 if ((Info & TargetInfo::CI_AllowsRegister) ||
861 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000862 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000863 Arg = EmitScalarExpr(InputExpr);
864 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000865 ErrorUnsupported(&S,
866 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000867 }
868 } else {
869 LValue Dest = EmitLValue(InputExpr);
870 Arg = Dest.getAddress();
871 InOutConstraints += '*';
872 }
873
874 InOutArgTypes.push_back(Arg->getType());
875 InOutArgs.push_back(Arg);
876 InOutConstraints += OutputConstraint;
877 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000878 }
879
880 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
881
882 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
883 const Expr *InputExpr = S.getInputExpr(i);
884
885 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
886 S.getInputConstraint(i)->getByteLength());
887
888 TargetInfo::ConstraintInfo Info;
889 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000890 NumConstraints, Info);
891 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000892
893 if (i != 0 || S.getNumOutputs() > 0)
894 Constraints += ',';
895
896 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000897 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000898
899 llvm::Value *Arg;
900
901 if ((Info & TargetInfo::CI_AllowsRegister) ||
902 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000903 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000904 Arg = EmitScalarExpr(InputExpr);
905 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000906 ErrorUnsupported(&S,
907 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000908 }
909 } else {
910 LValue Dest = EmitLValue(InputExpr);
911 Arg = Dest.getAddress();
912 Constraints += '*';
913 }
914
915 ArgTypes.push_back(Arg->getType());
916 Args.push_back(Arg);
917 Constraints += InputConstraint;
918 }
919
Anders Carlssonf39a4212008-02-05 20:01:53 +0000920 // Append the "input" part of inout constraints last.
921 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
922 ArgTypes.push_back(InOutArgTypes[i]);
923 Args.push_back(InOutArgs[i]);
924 }
925 Constraints += InOutConstraints;
926
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000927 // Clobbers
928 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
929 std::string Clobber(S.getClobber(i)->getStrData(),
930 S.getClobber(i)->getByteLength());
931
932 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
933
Anders Carlssonea041752008-02-06 00:11:32 +0000934 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000935 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000936
937 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000938 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000939 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000940 }
941
942 // Add machine specific clobbers
943 if (const char *C = Target.getClobbers()) {
944 if (!Constraints.empty())
945 Constraints += ',';
946 Constraints += C;
947 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000948
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000949 const llvm::FunctionType *FTy =
950 llvm::FunctionType::get(ResultType, ArgTypes, false);
951
952 llvm::InlineAsm *IA =
953 llvm::InlineAsm::get(FTy, AsmString, Constraints,
954 S.isVolatile() || S.getNumOutputs() == 0);
955 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000956 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000957 Builder.CreateStore(Result, ResultAddr);
958}