blob: afce63d41d8f08605b47cfd5d9d2f97ec1da66bf [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/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000020#include "llvm/InlineAsm.h"
21#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace CodeGen;
24
25//===----------------------------------------------------------------------===//
26// Statement Emission
27//===----------------------------------------------------------------------===//
28
Daniel Dunbar09124252008-11-12 08:21:33 +000029void CodeGenFunction::EmitStopPoint(const Stmt *S) {
30 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
31 DI->setLocation(S->getLocStart());
32 DI->EmitStopPoint(CurFn, Builder);
33 }
34}
35
Reid Spencer5f016e22007-07-11 17:01:13 +000036void CodeGenFunction::EmitStmt(const Stmt *S) {
37 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000038
Daniel Dunbar09124252008-11-12 08:21:33 +000039 // Check if we can handle this without bothering to generate an
40 // insert point or debug info.
41 if (EmitSimpleStmt(S))
42 return;
43
Daniel Dunbara448fb22008-11-11 23:11:34 +000044 // If we happen to be at an unreachable point just create a dummy
45 // basic block to hold the code. We could change parts of irgen to
46 // simply not generate this code, but this situation is rare and
47 // probably not worth the effort.
48 // FIXME: Verify previous performance/effort claim.
49 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000050
Daniel Dunbar09124252008-11-12 08:21:33 +000051 // Generate a stoppoint if we are emitting debug info.
52 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000053
Reid Spencer5f016e22007-07-11 17:01:13 +000054 switch (S->getStmtClass()) {
55 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000056 // Must be an expression in a stmt context. Emit the value (to get
57 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000058 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000059 if (!hasAggregateLLVMType(E->getType()))
60 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000061 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000062 EmitComplexExpr(E);
63 else
64 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000065 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000066 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000067 }
68 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000069 case Stmt::IndirectGotoStmtClass:
70 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000071
72 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
73 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
74 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
75 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
76
77 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
78 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000079
Devang Patel51b09f22007-10-04 23:45:31 +000080 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000081 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000082
83 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000084 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
85 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000086 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000087 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
88 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000089 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000090 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000091 break;
92 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000093 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000094 break;
95 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000096 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000097 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000098 case Stmt::ObjCForCollectionStmtClass:
99 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000100 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 }
102}
103
Daniel Dunbar09124252008-11-12 08:21:33 +0000104bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
105 switch (S->getStmtClass()) {
106 default: return false;
107 case Stmt::NullStmtClass: break;
108 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
109 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
110 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
111 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
112 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
113 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
114 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
115 }
116
117 return true;
118}
119
Chris Lattner33793202007-08-31 22:09:40 +0000120/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
121/// this captures the expression result of the last sub-statement and returns it
122/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000123RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
124 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000126 CGDebugInfo *DI = CGM.getDebugInfo();
127 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000128 EnsureInsertPoint();
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
Anders Carlsson17d28a32008-12-12 05:52:00 +0000133 // Push a null stack save value.
134 StackSaveValues.push_back(0);
135
Chris Lattner33793202007-08-31 22:09:40 +0000136 for (CompoundStmt::const_body_iterator I = S.body_begin(),
137 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000139
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000140 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000141 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000142 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000143 DI->EmitRegionEnd(CurFn, Builder);
144 }
145
Anders Carlsson17d28a32008-12-12 05:52:00 +0000146 RValue RV;
147 if (!GetLast)
148 RV = RValue::get(0);
149 else {
150 // We have to special case labels here. They are statements, but when put
151 // at the end of a statement expression, they yield the value of their
152 // subexpression. Handle this by walking through all labels we encounter,
153 // emitting them before we evaluate the subexpr.
154 const Stmt *LastStmt = S.body_back();
155 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
156 EmitLabel(*LS);
157 LastStmt = LS->getSubStmt();
158 }
Chris Lattner9b655512007-08-31 22:49:20 +0000159
Anders Carlsson17d28a32008-12-12 05:52:00 +0000160 EnsureInsertPoint();
161
162 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
163 }
164
165 if (llvm::Value *V = StackSaveValues.pop_back_val()) {
166 V = Builder.CreateLoad(V, "tmp");
167
168 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
169 Builder.CreateCall(F, V);
Chris Lattner91d723d2008-07-26 20:23:23 +0000170 }
171
Anders Carlsson17d28a32008-12-12 05:52:00 +0000172 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000173}
174
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000175void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000176 // Fall out of the current block (if necessary).
177 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000178
179 if (IsFinished && BB->use_empty()) {
180 delete BB;
181 return;
182 }
183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 CurFn->getBasicBlockList().push_back(BB);
185 Builder.SetInsertPoint(BB);
186}
187
Daniel Dunbard57a8712008-11-11 09:41:28 +0000188void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
189 // Emit a branch from the current block to the target one if this
190 // was a real block. If this was just a fall-through block after a
191 // terminator, don't emit it.
192 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
193
194 if (!CurBB || CurBB->getTerminator()) {
195 // If there is no insert point or the previous block is already
196 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000197 } else {
198 // Otherwise, create a fall-through branch.
199 Builder.CreateBr(Target);
200 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000201
202 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000203}
204
Chris Lattner91d723d2008-07-26 20:23:23 +0000205void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000208}
209
210
211void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
212 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 EmitStmt(S.getSubStmt());
214}
215
216void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000217 // FIXME: Implement goto out in @try or @catch blocks.
218 if (!ObjCEHStack.empty()) {
219 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
220 return;
221 }
222
Daniel Dunbar09124252008-11-12 08:21:33 +0000223 // If this code is reachable then emit a stop point (if generating
224 // debug info). We have to do this ourselves because we are on the
225 // "simple" statement path.
226 if (HaveInsertPoint())
227 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000228 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000229}
230
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000231void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000232 // FIXME: Implement indirect goto in @try or @catch blocks.
233 if (!ObjCEHStack.empty()) {
234 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
235 return;
236 }
237
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000238 // Emit initial switch which will be patched up later by
239 // EmitIndirectSwitches(). We need a default dest, so we use the
240 // current BB, but this is overwritten.
241 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
242 llvm::Type::Int32Ty,
243 "addr");
244 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
245 IndirectSwitches.push_back(I);
246
Daniel Dunbara448fb22008-11-11 23:11:34 +0000247 // Clear the insertion point to indicate we are in unreachable code.
248 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000249}
250
Chris Lattner62b72f62008-11-11 07:24:28 +0000251void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 // C99 6.8.4.1: The first substatement is executed if the expression compares
253 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000254
Chris Lattner9bc47e22008-11-12 07:46:33 +0000255 // If the condition constant folds and can be elided, try to avoid emitting
256 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000257 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000258 // Figure out which block (then or else) is executed.
259 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000260 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000261 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000262
Chris Lattner62b72f62008-11-11 07:24:28 +0000263 // If the skipped block has no labels in it, just emit the executed block.
264 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000265 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000266 if (Executed)
267 EmitStmt(Executed);
268 return;
269 }
270 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000271
272 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
273 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000274 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
275 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
276 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000278 ElseBlock = createBasicBlock("if.else");
279 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280
281 // Emit the 'then' code.
282 EmitBlock(ThenBlock);
283 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000284 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000285
286 // Emit the 'else' code if present.
287 if (const Stmt *Else = S.getElse()) {
288 EmitBlock(ElseBlock);
289 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000290 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 }
292
293 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000294 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000295}
296
297void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 // Emit the header for the loop, insert it, which will create an uncond br to
299 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000300 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 EmitBlock(LoopHeader);
302
303 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
304 // of the controlling expression takes place before each execution of the loop
305 // body.
306 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000307
308 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000310 bool EmitBoolCondBranch = true;
311 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
312 if (C->isOne())
313 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000314
315 // Create an exit block for when the condition fails, create a block for the
316 // body of the loop.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000317 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000318 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Reid Spencer5f016e22007-07-11 17:01:13 +0000319
320 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000321 if (EmitBoolCondBranch)
322 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000323
Chris Lattnerda138702007-07-16 21:28:45 +0000324 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000325 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader,
326 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000327
328 // Emit the loop body.
329 EmitBlock(LoopBody);
330 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000331
332 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000333
334 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000335 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000336
337 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000338 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000339
340 // If LoopHeader is a simple forwarding block then eliminate it.
341 if (!EmitBoolCondBranch
342 && &LoopHeader->front() == LoopHeader->getTerminator()) {
343 LoopHeader->replaceAllUsesWith(LoopBody);
344 LoopHeader->getTerminator()->eraseFromParent();
345 LoopHeader->eraseFromParent();
346 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000347}
348
349void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 // Emit the body for the loop, insert it, which will create an uncond br to
351 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000352 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
353 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000355
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000356 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000357
358 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000359 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond,
360 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000361
362 // Emit the body of the loop into the block.
363 EmitStmt(S.getBody());
364
Chris Lattnerda138702007-07-16 21:28:45 +0000365 BreakContinueStack.pop_back();
366
367 EmitBlock(DoCond);
368
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
370 // after each execution of the loop body."
371
372 // Evaluate the conditional in the while header.
373 // C99 6.8.5p2/p4: The first substatement is executed if the expression
374 // compares unequal to 0. The condition must be a scalar type.
375 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000376
377 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
378 // to correctly handle break/continue though.
379 bool EmitBoolCondBranch = true;
380 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
381 if (C->isZero())
382 EmitBoolCondBranch = false;
383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000385 if (EmitBoolCondBranch)
386 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000387
388 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000389 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000390
391 // If DoCond is a simple forwarding block then eliminate it.
392 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
393 DoCond->replaceAllUsesWith(AfterDo);
394 DoCond->getTerminator()->eraseFromParent();
395 DoCond->eraseFromParent();
396 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000397}
398
399void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
401 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000402
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 // Evaluate the first part before the loop.
404 if (S.getInit())
405 EmitStmt(S.getInit());
406
407 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000408 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
409 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 EmitBlock(CondBlock);
412
413 // Evaluate the condition if present. If not, treat it as a non-zero-constant
414 // according to 6.8.5.3p2, aka, true.
415 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000417 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000418
419 // C99 6.8.5p2/p4: The first substatement is executed if the expression
420 // compares unequal to 0. The condition must be a scalar type.
421 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 EmitBlock(ForBody);
424 } else {
425 // Treat it as a non-zero constant. Don't even create a new block for the
426 // body, just fall into it.
427 }
428
Chris Lattnerda138702007-07-16 21:28:45 +0000429 // If the for loop doesn't have an increment we can just use the
430 // condition as the continue block.
431 llvm::BasicBlock *ContinueBlock;
432 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000433 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000434 else
435 ContinueBlock = CondBlock;
436
437 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000438 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock,
439 ObjCEHStack.size()));
Chris Lattnerda138702007-07-16 21:28:45 +0000440
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 // If the condition is true, execute the body of the for stmt.
442 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000443
444 BreakContinueStack.pop_back();
445
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000447 if (S.getInc()) {
448 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000449 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000450 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000451
452 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000453 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454
Chris Lattnerda138702007-07-16 21:28:45 +0000455 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000456 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000457}
458
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000459void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
460 if (RV.isScalar()) {
461 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
462 } else if (RV.isAggregate()) {
463 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
464 } else {
465 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
466 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000467 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000468}
469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
471/// if the function returns void, or may be missing one if the function returns
472/// non-void. Fun stuff :).
473void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // Emit the result value, even if unused, to evalute the side effects.
475 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000476
477 // FIXME: Clean this up by using an LValue for ReturnTemp,
478 // EmitStoreThroughLValue, and EmitAnyExpr.
479 if (!ReturnValue) {
480 // Make sure not to return anything, but evaluate the expression
481 // for side effects.
482 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000483 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000485 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000486 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000487 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000488 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000489 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000491 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 }
Eli Friedman144ac612008-05-22 01:22:33 +0000493
Daniel Dunbar898d5082008-09-30 01:06:03 +0000494 if (!ObjCEHStack.empty()) {
495 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
496 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000497 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000498 EmitJumpThroughFinally(*i, ReturnPad);
499 EmitBlock(ReturnPad);
500 }
501 }
502
Daniel Dunbard57a8712008-11-11 09:41:28 +0000503 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000504}
505
506void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000507 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
508 I != E; ++I)
509 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000510}
Chris Lattnerda138702007-07-16 21:28:45 +0000511
Daniel Dunbar09124252008-11-12 08:21:33 +0000512void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000513 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
514
Daniel Dunbar09124252008-11-12 08:21:33 +0000515 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000516 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000517 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
518 return;
519 }
520
521 // If this code is reachable then emit a stop point (if generating
522 // debug info). We have to do this ourselves because we are on the
523 // "simple" statement path.
524 if (HaveInsertPoint())
525 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000526 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000527 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000528}
529
Daniel Dunbar09124252008-11-12 08:21:33 +0000530void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000531 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
532
Daniel Dunbar09124252008-11-12 08:21:33 +0000533 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000534 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000535 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
536 return;
537 }
538
539 // If this code is reachable then emit a stop point (if generating
540 // debug info). We have to do this ourselves because we are on the
541 // "simple" statement path.
542 if (HaveInsertPoint())
543 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000544 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000545 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000546}
Devang Patel51b09f22007-10-04 23:45:31 +0000547
Devang Patelc049e4f2007-10-08 20:57:48 +0000548/// EmitCaseStmtRange - If case statement range is not too big then
549/// add multiple cases to switch instruction, one for each value within
550/// the range. If range is too big then emit "if" condition check.
551void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000552 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000553
Anders Carlsson51fe9962008-11-22 21:04:56 +0000554 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
555 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000556
Daniel Dunbar16f23572008-07-25 01:11:38 +0000557 // Emit the code for this case. We do this first to make sure it is
558 // properly chained from our predecessor before generating the
559 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000560 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000561 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
562 EmitStmt(S.getSubStmt());
563
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000564 // If range is empty, do nothing.
565 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
566 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000567
568 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000569 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000570 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
571 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000572 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000573 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
574 LHS++;
575 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000576 return;
577 }
578
Daniel Dunbar16f23572008-07-25 01:11:38 +0000579 // The range is too big. Emit "if" condition into a new block,
580 // making sure to save and restore the current insertion point.
581 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000582
Daniel Dunbar16f23572008-07-25 01:11:38 +0000583 // Push this test onto the chain of range checks (which terminates
584 // in the default basic block). The switch's default will be changed
585 // to the top of this chain after switch emission is complete.
586 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000587 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000588
Daniel Dunbar16f23572008-07-25 01:11:38 +0000589 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
590 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000591
592 // Emit range check.
593 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000594 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
595 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000596 llvm::Value *Cond =
597 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
598 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
599
Daniel Dunbar16f23572008-07-25 01:11:38 +0000600 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000601 if (RestoreBB)
602 Builder.SetInsertPoint(RestoreBB);
603 else
604 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000605}
606
607void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
608 if (S.getRHS()) {
609 EmitCaseStmtRange(S);
610 return;
611 }
612
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000613 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000614 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000615 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000616 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000617 EmitStmt(S.getSubStmt());
618}
619
620void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000621 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000622 assert(DefaultBlock->empty() &&
623 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000624 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000625 EmitStmt(S.getSubStmt());
626}
627
628void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
629 llvm::Value *CondV = EmitScalarExpr(S.getCond());
630
631 // Handle nested switch statements.
632 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000633 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000634
Daniel Dunbar16f23572008-07-25 01:11:38 +0000635 // Create basic block to hold stuff that comes after switch
636 // statement. We also need to create a default block now so that
637 // explicit case ranges tests can have a place to jump to on
638 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000639 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
640 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000641 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
642 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000643
Daniel Dunbar09124252008-11-12 08:21:33 +0000644 // Clear the insertion point to indicate we are in unreachable code.
645 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000646
Devang Patele9b8c0a2007-10-30 20:59:40 +0000647 // All break statements jump to NextBlock. If BreakContinueStack is non empty
648 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000649 llvm::BasicBlock *ContinueBlock = NULL;
650 if (!BreakContinueStack.empty())
651 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone21269b2008-12-13 22:52:24 +0000652 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock,
653 ObjCEHStack.size()));
Devang Patel51b09f22007-10-04 23:45:31 +0000654
655 // Emit switch body.
656 EmitStmt(S.getBody());
657 BreakContinueStack.pop_back();
658
Daniel Dunbar16f23572008-07-25 01:11:38 +0000659 // Update the default block in case explicit case range tests have
660 // been chained on top.
661 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000662
Daniel Dunbar16f23572008-07-25 01:11:38 +0000663 // If a default was never emitted then reroute any jumps to it and
664 // discard.
665 if (!DefaultBlock->getParent()) {
666 DefaultBlock->replaceAllUsesWith(NextBlock);
667 delete DefaultBlock;
668 }
Devang Patel51b09f22007-10-04 23:45:31 +0000669
Daniel Dunbar16f23572008-07-25 01:11:38 +0000670 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000671 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000672
Devang Patel51b09f22007-10-04 23:45:31 +0000673 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000674 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000675}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000676
Anders Carlssonce179ab2008-11-09 18:54:14 +0000677static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
678{
679 // FIXME: No need to create new std::string here, we could just make sure
680 // that we don't read past the end of the string data.
681 std::string str(S.getAsmString()->getStrData(),
682 S.getAsmString()->getByteLength());
683 const char *Start = str.c_str();
684
685 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
686 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000687 Failed = false;
688
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000689 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000690 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000691 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000692 if (IsSimple) {
693 while (*Start) {
694 switch (*Start) {
695 default:
696 Result += *Start;
697 break;
698 case '$':
699 Result += "$$";
700 break;
701 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000702 Start++;
703 }
704
705 return Result;
706 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000707
708 while (*Start) {
709 switch (*Start) {
710 default:
711 Result += *Start;
712 break;
713 case '$':
714 Result += "$$";
715 break;
716 case '%':
717 // Escaped character
718 Start++;
719 if (!*Start) {
720 // FIXME: This should be caught during Sema.
721 assert(0 && "Trailing '%' in asm string.");
722 }
723
724 char EscapedChar = *Start;
725 if (EscapedChar == '%') {
726 // Escaped percentage sign.
727 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000728 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000729 // Generate an unique ID.
730 Result += llvm::utostr(AsmCounter);
731 } else if (isdigit(EscapedChar)) {
732 // %n - Assembler operand n
733 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000734 unsigned long n = strtoul(Start, &End, 10);
735 if (Start == End) {
736 // FIXME: This should be caught during Sema.
737 assert(0 && "Missing operand!");
738 } else if (n >= NumOperands) {
739 // FIXME: This should be caught during Sema.
740 assert(0 && "Operand number out of range!");
741 }
742
743 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000744 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000745 } else if (isalpha(EscapedChar)) {
746 char *End;
747
748 unsigned long n = strtoul(Start + 1, &End, 10);
749 if (Start == End) {
750 // FIXME: This should be caught during Sema.
751 assert(0 && "Missing operand!");
752 } else if (n >= NumOperands) {
753 // FIXME: This should be caught during Sema.
754 assert(0 && "Operand number out of range!");
755 }
756
757 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000758 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000759 } else if (EscapedChar == '[') {
760 std::string SymbolicName;
761
762 Start++;
763
764 while (*Start && *Start != ']') {
765 SymbolicName += *Start;
766
767 Start++;
768 }
769
770 if (!Start) {
771 // FIXME: Should be caught by sema.
772 assert(0 && "Could not parse symbolic name");
773 }
774
775 assert(*Start == ']' && "Error parsing symbolic name");
776
777 int Index = -1;
778
779 // Check if this is an output operand.
780 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
781 if (S.getOutputName(i) == SymbolicName) {
782 Index = i;
783 break;
784 }
785 }
786
787 if (Index == -1) {
788 for (unsigned i = 0; i < S.getNumInputs(); i++) {
789 if (S.getInputName(i) == SymbolicName) {
790 Index = S.getNumOutputs() + i;
791 }
792 }
793 }
794
795 assert(Index != -1 && "Did not find right operand!");
796
797 Result += '$' + llvm::utostr(Index);
798
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000799 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000800 Failed = true;
801 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000802 }
803 }
804 Start++;
805 }
806
807 return Result;
808}
809
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000810static std::string SimplifyConstraint(const char* Constraint,
811 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000812 std::string Result;
813
814 while (*Constraint) {
815 switch (*Constraint) {
816 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000817 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000818 break;
819 // Ignore these
820 case '*':
821 case '?':
822 case '!':
823 break;
824 case 'g':
825 Result += "imr";
826 break;
827 }
828
829 Constraint++;
830 }
831
832 return Result;
833}
834
835void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000836 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000837 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000838 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000839
840 if (Failed) {
841 ErrorUnsupported(&S, "asm string");
842 return;
843 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000844
845 std::string Constraints;
846
847 llvm::Value *ResultAddr = 0;
848 const llvm::Type *ResultType = llvm::Type::VoidTy;
849
850 std::vector<const llvm::Type*> ArgTypes;
851 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000852
853 // Keep track of inout constraints.
854 std::string InOutConstraints;
855 std::vector<llvm::Value*> InOutArgs;
856 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000857
858 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
859 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
860 S.getOutputConstraint(i)->getByteLength());
861
862 TargetInfo::ConstraintInfo Info;
863 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
864 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000865 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000866
867 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000868 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000869
870 LValue Dest = EmitLValue(S.getOutputExpr(i));
871 const llvm::Type *DestValueType =
872 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
873
874 // If the first output operand is not a memory dest, we'll
875 // make it the return value.
876 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000877 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000878 ResultAddr = Dest.getAddress();
879 ResultType = DestValueType;
880 Constraints += "=" + OutputConstraint;
881 } else {
882 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000883 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000884 if (i != 0)
885 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000886 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000887 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000888 }
889
890 if (Info & TargetInfo::CI_ReadWrite) {
891 // FIXME: This code should be shared with the code that handles inputs.
892 InOutConstraints += ',';
893
894 const Expr *InputExpr = S.getOutputExpr(i);
895 llvm::Value *Arg;
896 if ((Info & TargetInfo::CI_AllowsRegister) ||
897 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000898 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000899 Arg = EmitScalarExpr(InputExpr);
900 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000901 ErrorUnsupported(&S,
902 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000903 }
904 } else {
905 LValue Dest = EmitLValue(InputExpr);
906 Arg = Dest.getAddress();
907 InOutConstraints += '*';
908 }
909
910 InOutArgTypes.push_back(Arg->getType());
911 InOutArgs.push_back(Arg);
912 InOutConstraints += OutputConstraint;
913 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000914 }
915
916 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
917
918 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
919 const Expr *InputExpr = S.getInputExpr(i);
920
921 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
922 S.getInputConstraint(i)->getByteLength());
923
924 TargetInfo::ConstraintInfo Info;
925 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000926 NumConstraints, Info);
927 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000928
929 if (i != 0 || S.getNumOutputs() > 0)
930 Constraints += ',';
931
932 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000933 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000934
935 llvm::Value *Arg;
936
937 if ((Info & TargetInfo::CI_AllowsRegister) ||
938 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000939 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000940 Arg = EmitScalarExpr(InputExpr);
941 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000942 ErrorUnsupported(&S,
943 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000944 }
945 } else {
946 LValue Dest = EmitLValue(InputExpr);
947 Arg = Dest.getAddress();
948 Constraints += '*';
949 }
950
951 ArgTypes.push_back(Arg->getType());
952 Args.push_back(Arg);
953 Constraints += InputConstraint;
954 }
955
Anders Carlssonf39a4212008-02-05 20:01:53 +0000956 // Append the "input" part of inout constraints last.
957 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
958 ArgTypes.push_back(InOutArgTypes[i]);
959 Args.push_back(InOutArgs[i]);
960 }
961 Constraints += InOutConstraints;
962
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000963 // Clobbers
964 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
965 std::string Clobber(S.getClobber(i)->getStrData(),
966 S.getClobber(i)->getByteLength());
967
968 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
969
Anders Carlssonea041752008-02-06 00:11:32 +0000970 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000971 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000972
973 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000974 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000975 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000976 }
977
978 // Add machine specific clobbers
979 if (const char *C = Target.getClobbers()) {
980 if (!Constraints.empty())
981 Constraints += ',';
982 Constraints += C;
983 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000984
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000985 const llvm::FunctionType *FTy =
986 llvm::FunctionType::get(ResultType, ArgTypes, false);
987
988 llvm::InlineAsm *IA =
989 llvm::InlineAsm::get(FTy, AsmString, Constraints,
990 S.isVolatile() || S.getNumOutputs() == 0);
991 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000992 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000993 Builder.CreateStore(Result, ResultAddr);
994}