blob: e40508669abb05b22f05777018bcde73f18f2eba [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:
95 ErrorUnsupported(S, "@synchronized statement");
96 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
160void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000161 // Fall out of the current block (if necessary).
162 EmitBranch(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 CurFn->getBasicBlockList().push_back(BB);
164 Builder.SetInsertPoint(BB);
165}
166
Daniel Dunbard57a8712008-11-11 09:41:28 +0000167void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
168 // Emit a branch from the current block to the target one if this
169 // was a real block. If this was just a fall-through block after a
170 // terminator, don't emit it.
171 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
172
173 if (!CurBB || CurBB->getTerminator()) {
174 // If there is no insert point or the previous block is already
175 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000176 } else {
177 // Otherwise, create a fall-through branch.
178 Builder.CreateBr(Target);
179 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000180
181 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000182}
183
Chris Lattner91d723d2008-07-26 20:23:23 +0000184void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000187}
188
189
190void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
191 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 EmitStmt(S.getSubStmt());
193}
194
195void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000196 // FIXME: Implement goto out in @try or @catch blocks.
197 if (!ObjCEHStack.empty()) {
198 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
199 return;
200 }
201
Daniel Dunbar09124252008-11-12 08:21:33 +0000202 // If this code is reachable then emit a stop point (if generating
203 // debug info). We have to do this ourselves because we are on the
204 // "simple" statement path.
205 if (HaveInsertPoint())
206 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000207 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000208}
209
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000210void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000211 // FIXME: Implement indirect goto in @try or @catch blocks.
212 if (!ObjCEHStack.empty()) {
213 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
214 return;
215 }
216
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000217 // Emit initial switch which will be patched up later by
218 // EmitIndirectSwitches(). We need a default dest, so we use the
219 // current BB, but this is overwritten.
220 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
221 llvm::Type::Int32Ty,
222 "addr");
223 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
224 IndirectSwitches.push_back(I);
225
Daniel Dunbara448fb22008-11-11 23:11:34 +0000226 // Clear the insertion point to indicate we are in unreachable code.
227 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000228}
229
Chris Lattner62b72f62008-11-11 07:24:28 +0000230void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // C99 6.8.4.1: The first substatement is executed if the expression compares
232 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000233
Chris Lattner9bc47e22008-11-12 07:46:33 +0000234 // If the condition constant folds and can be elided, try to avoid emitting
235 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000236 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000237 // Figure out which block (then or else) is executed.
238 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000239 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000240 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000241
Chris Lattner62b72f62008-11-11 07:24:28 +0000242 // 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.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000244 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000245 if (Executed)
246 EmitStmt(Executed);
247 return;
248 }
249 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000250
251 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
252 // the conditional branch.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000253 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Chris Lattner9bc47e22008-11-12 07:46:33 +0000254 llvm::BasicBlock *ElseBlock = createBasicBlock("ifelse");
255 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000256
Chris Lattner9bc47e22008-11-12 07:46:33 +0000257 llvm::BasicBlock *ContBlock = ElseBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 if (S.getElse())
Chris Lattner9bc47e22008-11-12 07:46:33 +0000259 ContBlock = createBasicBlock("ifend");
Reid Spencer5f016e22007-07-11 17:01:13 +0000260
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 Lattner31a09842008-11-12 08:04:58 +0000303
Chris Lattnerda138702007-07-16 21:28:45 +0000304 // 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()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000398 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Chris Lattner31a09842008-11-12 08:04:58 +0000399
400 // C99 6.8.5p2/p4: The first substatement is executed if the expression
401 // compares unequal to 0. The condition must be a scalar type.
402 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
403
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 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
Reid Spencer5f016e22007-07-11 17:01:13 +0000450/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
451/// if the function returns void, or may be missing one if the function returns
452/// non-void. Fun stuff :).
453void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 // Emit the result value, even if unused, to evalute the side effects.
455 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000456
457 // FIXME: Clean this up by using an LValue for ReturnTemp,
458 // EmitStoreThroughLValue, and EmitAnyExpr.
459 if (!ReturnValue) {
460 // Make sure not to return anything, but evaluate the expression
461 // for side effects.
462 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000463 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000465 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000466 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000467 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000468 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000469 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000471 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 }
Eli Friedman144ac612008-05-22 01:22:33 +0000473
Daniel Dunbar898d5082008-09-30 01:06:03 +0000474 if (!ObjCEHStack.empty()) {
475 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
476 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000477 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000478 EmitJumpThroughFinally(*i, ReturnPad);
479 EmitBlock(ReturnPad);
480 }
481 }
482
Daniel Dunbard57a8712008-11-11 09:41:28 +0000483 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000484}
485
486void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000487 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
488 I != E; ++I)
489 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000490}
Chris Lattnerda138702007-07-16 21:28:45 +0000491
Daniel Dunbar09124252008-11-12 08:21:33 +0000492void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000493 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
494
Daniel Dunbar09124252008-11-12 08:21:33 +0000495 // FIXME: Implement break in @try or @catch blocks.
496 if (!ObjCEHStack.empty()) {
497 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
498 return;
499 }
500
501 // If this code is reachable then emit a stop point (if generating
502 // debug info). We have to do this ourselves because we are on the
503 // "simple" statement path.
504 if (HaveInsertPoint())
505 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000506 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000507 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000508}
509
Daniel Dunbar09124252008-11-12 08:21:33 +0000510void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000511 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
512
Daniel Dunbar09124252008-11-12 08:21:33 +0000513 // FIXME: Implement continue in @try or @catch blocks.
514 if (!ObjCEHStack.empty()) {
515 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
516 return;
517 }
518
519 // If this code is reachable then emit a stop point (if generating
520 // debug info). We have to do this ourselves because we are on the
521 // "simple" statement path.
522 if (HaveInsertPoint())
523 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000524 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000525 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000526}
Devang Patel51b09f22007-10-04 23:45:31 +0000527
Devang Patelc049e4f2007-10-08 20:57:48 +0000528/// EmitCaseStmtRange - If case statement range is not too big then
529/// add multiple cases to switch instruction, one for each value within
530/// the range. If range is too big then emit "if" condition check.
531void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000532 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000533
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000534 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
535 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
536
Daniel Dunbar16f23572008-07-25 01:11:38 +0000537 // Emit the code for this case. We do this first to make sure it is
538 // properly chained from our predecessor before generating the
539 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000540 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000541 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
542 EmitStmt(S.getSubStmt());
543
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000544 // If range is empty, do nothing.
545 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
546 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000547
548 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000549 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000550 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
551 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000552 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000553 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
554 LHS++;
555 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000556 return;
557 }
558
Daniel Dunbar16f23572008-07-25 01:11:38 +0000559 // The range is too big. Emit "if" condition into a new block,
560 // making sure to save and restore the current insertion point.
561 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000562
Daniel Dunbar16f23572008-07-25 01:11:38 +0000563 // Push this test onto the chain of range checks (which terminates
564 // in the default basic block). The switch's default will be changed
565 // to the top of this chain after switch emission is complete.
566 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000567 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000568
Daniel Dunbar16f23572008-07-25 01:11:38 +0000569 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
570 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000571
572 // Emit range check.
573 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000574 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
575 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000576 llvm::Value *Cond =
577 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
578 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
579
Daniel Dunbar16f23572008-07-25 01:11:38 +0000580 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000581 if (RestoreBB)
582 Builder.SetInsertPoint(RestoreBB);
583 else
584 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000585}
586
587void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
588 if (S.getRHS()) {
589 EmitCaseStmtRange(S);
590 return;
591 }
592
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000593 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000594 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000595 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000596 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000597 EmitStmt(S.getSubStmt());
598}
599
600void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000601 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000602 assert(DefaultBlock->empty() &&
603 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000604 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000605 EmitStmt(S.getSubStmt());
606}
607
608void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
609 llvm::Value *CondV = EmitScalarExpr(S.getCond());
610
611 // Handle nested switch statements.
612 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000613 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000614
Daniel Dunbar16f23572008-07-25 01:11:38 +0000615 // Create basic block to hold stuff that comes after switch
616 // statement. We also need to create a default block now so that
617 // explicit case ranges tests can have a place to jump to on
618 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000619 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
620 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000621 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
622 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000623
Daniel Dunbar09124252008-11-12 08:21:33 +0000624 // Clear the insertion point to indicate we are in unreachable code.
625 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000626
Devang Patele9b8c0a2007-10-30 20:59:40 +0000627 // All break statements jump to NextBlock. If BreakContinueStack is non empty
628 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000629 llvm::BasicBlock *ContinueBlock = NULL;
630 if (!BreakContinueStack.empty())
631 ContinueBlock = BreakContinueStack.back().ContinueBlock;
632 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
633
634 // Emit switch body.
635 EmitStmt(S.getBody());
636 BreakContinueStack.pop_back();
637
Daniel Dunbar16f23572008-07-25 01:11:38 +0000638 // Update the default block in case explicit case range tests have
639 // been chained on top.
640 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000641
Daniel Dunbar16f23572008-07-25 01:11:38 +0000642 // If a default was never emitted then reroute any jumps to it and
643 // discard.
644 if (!DefaultBlock->getParent()) {
645 DefaultBlock->replaceAllUsesWith(NextBlock);
646 delete DefaultBlock;
647 }
Devang Patel51b09f22007-10-04 23:45:31 +0000648
Daniel Dunbar16f23572008-07-25 01:11:38 +0000649 // Emit continuation.
650 EmitBlock(NextBlock);
651
Devang Patel51b09f22007-10-04 23:45:31 +0000652 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000653 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000654}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000655
Anders Carlssonce179ab2008-11-09 18:54:14 +0000656static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
657{
658 // FIXME: No need to create new std::string here, we could just make sure
659 // that we don't read past the end of the string data.
660 std::string str(S.getAsmString()->getStrData(),
661 S.getAsmString()->getByteLength());
662 const char *Start = str.c_str();
663
664 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
665 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000666 Failed = false;
667
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000668 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000669 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000670 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000671 if (IsSimple) {
672 while (*Start) {
673 switch (*Start) {
674 default:
675 Result += *Start;
676 break;
677 case '$':
678 Result += "$$";
679 break;
680 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000681 Start++;
682 }
683
684 return Result;
685 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000686
687 while (*Start) {
688 switch (*Start) {
689 default:
690 Result += *Start;
691 break;
692 case '$':
693 Result += "$$";
694 break;
695 case '%':
696 // Escaped character
697 Start++;
698 if (!*Start) {
699 // FIXME: This should be caught during Sema.
700 assert(0 && "Trailing '%' in asm string.");
701 }
702
703 char EscapedChar = *Start;
704 if (EscapedChar == '%') {
705 // Escaped percentage sign.
706 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000707 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000708 // Generate an unique ID.
709 Result += llvm::utostr(AsmCounter);
710 } else if (isdigit(EscapedChar)) {
711 // %n - Assembler operand n
712 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000713 unsigned long n = strtoul(Start, &End, 10);
714 if (Start == End) {
715 // FIXME: This should be caught during Sema.
716 assert(0 && "Missing operand!");
717 } else if (n >= NumOperands) {
718 // FIXME: This should be caught during Sema.
719 assert(0 && "Operand number out of range!");
720 }
721
722 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000723 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000724 } else if (isalpha(EscapedChar)) {
725 char *End;
726
727 unsigned long n = strtoul(Start + 1, &End, 10);
728 if (Start == End) {
729 // FIXME: This should be caught during Sema.
730 assert(0 && "Missing operand!");
731 } else if (n >= NumOperands) {
732 // FIXME: This should be caught during Sema.
733 assert(0 && "Operand number out of range!");
734 }
735
736 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000737 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000738 } else if (EscapedChar == '[') {
739 std::string SymbolicName;
740
741 Start++;
742
743 while (*Start && *Start != ']') {
744 SymbolicName += *Start;
745
746 Start++;
747 }
748
749 if (!Start) {
750 // FIXME: Should be caught by sema.
751 assert(0 && "Could not parse symbolic name");
752 }
753
754 assert(*Start == ']' && "Error parsing symbolic name");
755
756 int Index = -1;
757
758 // Check if this is an output operand.
759 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
760 if (S.getOutputName(i) == SymbolicName) {
761 Index = i;
762 break;
763 }
764 }
765
766 if (Index == -1) {
767 for (unsigned i = 0; i < S.getNumInputs(); i++) {
768 if (S.getInputName(i) == SymbolicName) {
769 Index = S.getNumOutputs() + i;
770 }
771 }
772 }
773
774 assert(Index != -1 && "Did not find right operand!");
775
776 Result += '$' + llvm::utostr(Index);
777
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000778 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000779 Failed = true;
780 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000781 }
782 }
783 Start++;
784 }
785
786 return Result;
787}
788
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000789static std::string SimplifyConstraint(const char* Constraint,
790 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000791 std::string Result;
792
793 while (*Constraint) {
794 switch (*Constraint) {
795 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000796 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000797 break;
798 // Ignore these
799 case '*':
800 case '?':
801 case '!':
802 break;
803 case 'g':
804 Result += "imr";
805 break;
806 }
807
808 Constraint++;
809 }
810
811 return Result;
812}
813
814void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000815 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000816 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000817 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000818
819 if (Failed) {
820 ErrorUnsupported(&S, "asm string");
821 return;
822 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000823
824 std::string Constraints;
825
826 llvm::Value *ResultAddr = 0;
827 const llvm::Type *ResultType = llvm::Type::VoidTy;
828
829 std::vector<const llvm::Type*> ArgTypes;
830 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000831
832 // Keep track of inout constraints.
833 std::string InOutConstraints;
834 std::vector<llvm::Value*> InOutArgs;
835 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000836
837 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
838 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
839 S.getOutputConstraint(i)->getByteLength());
840
841 TargetInfo::ConstraintInfo Info;
842 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
843 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000844 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000845
846 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000847 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000848
849 LValue Dest = EmitLValue(S.getOutputExpr(i));
850 const llvm::Type *DestValueType =
851 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
852
853 // If the first output operand is not a memory dest, we'll
854 // make it the return value.
855 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000856 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000857 ResultAddr = Dest.getAddress();
858 ResultType = DestValueType;
859 Constraints += "=" + OutputConstraint;
860 } else {
861 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000862 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000863 if (i != 0)
864 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000865 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000866 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000867 }
868
869 if (Info & TargetInfo::CI_ReadWrite) {
870 // FIXME: This code should be shared with the code that handles inputs.
871 InOutConstraints += ',';
872
873 const Expr *InputExpr = S.getOutputExpr(i);
874 llvm::Value *Arg;
875 if ((Info & TargetInfo::CI_AllowsRegister) ||
876 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000877 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000878 Arg = EmitScalarExpr(InputExpr);
879 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000880 ErrorUnsupported(&S,
881 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000882 }
883 } else {
884 LValue Dest = EmitLValue(InputExpr);
885 Arg = Dest.getAddress();
886 InOutConstraints += '*';
887 }
888
889 InOutArgTypes.push_back(Arg->getType());
890 InOutArgs.push_back(Arg);
891 InOutConstraints += OutputConstraint;
892 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000893 }
894
895 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
896
897 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
898 const Expr *InputExpr = S.getInputExpr(i);
899
900 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
901 S.getInputConstraint(i)->getByteLength());
902
903 TargetInfo::ConstraintInfo Info;
904 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000905 NumConstraints, Info);
906 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000907
908 if (i != 0 || S.getNumOutputs() > 0)
909 Constraints += ',';
910
911 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000912 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000913
914 llvm::Value *Arg;
915
916 if ((Info & TargetInfo::CI_AllowsRegister) ||
917 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000918 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000919 Arg = EmitScalarExpr(InputExpr);
920 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000921 ErrorUnsupported(&S,
922 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000923 }
924 } else {
925 LValue Dest = EmitLValue(InputExpr);
926 Arg = Dest.getAddress();
927 Constraints += '*';
928 }
929
930 ArgTypes.push_back(Arg->getType());
931 Args.push_back(Arg);
932 Constraints += InputConstraint;
933 }
934
Anders Carlssonf39a4212008-02-05 20:01:53 +0000935 // Append the "input" part of inout constraints last.
936 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
937 ArgTypes.push_back(InOutArgTypes[i]);
938 Args.push_back(InOutArgs[i]);
939 }
940 Constraints += InOutConstraints;
941
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000942 // Clobbers
943 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
944 std::string Clobber(S.getClobber(i)->getStrData(),
945 S.getClobber(i)->getByteLength());
946
947 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
948
Anders Carlssonea041752008-02-06 00:11:32 +0000949 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000950 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000951
952 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000953 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000954 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000955 }
956
957 // Add machine specific clobbers
958 if (const char *C = Target.getClobbers()) {
959 if (!Constraints.empty())
960 Constraints += ',';
961 Constraints += C;
962 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000963
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000964 const llvm::FunctionType *FTy =
965 llvm::FunctionType::get(ResultType, ArgTypes, false);
966
967 llvm::InlineAsm *IA =
968 llvm::InlineAsm::get(FTy, AsmString, Constraints,
969 S.isVolatile() || S.getNumOutputs() == 0);
970 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000971 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000972 Builder.CreateStore(Result, ResultAddr);
973}