blob: 6d8f5da015c0534fe384267262914acb0df45d09 [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
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000223 if (StackSaveValues.back()) {
224 CGM.ErrorUnsupported(&S, "goto inside scope with VLA");
225 return;
226 }
227
Daniel Dunbar09124252008-11-12 08:21:33 +0000228 // If this code is reachable then emit a stop point (if generating
229 // debug info). We have to do this ourselves because we are on the
230 // "simple" statement path.
231 if (HaveInsertPoint())
232 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000233 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000234}
235
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000236void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000237 // FIXME: Implement indirect goto in @try or @catch blocks.
238 if (!ObjCEHStack.empty()) {
239 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
240 return;
241 }
242
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000243 // Emit initial switch which will be patched up later by
244 // EmitIndirectSwitches(). We need a default dest, so we use the
245 // current BB, but this is overwritten.
246 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
247 llvm::Type::Int32Ty,
248 "addr");
249 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
250 IndirectSwitches.push_back(I);
251
Daniel Dunbara448fb22008-11-11 23:11:34 +0000252 // Clear the insertion point to indicate we are in unreachable code.
253 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000254}
255
Chris Lattner62b72f62008-11-11 07:24:28 +0000256void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 // C99 6.8.4.1: The first substatement is executed if the expression compares
258 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000259
Chris Lattner9bc47e22008-11-12 07:46:33 +0000260 // If the condition constant folds and can be elided, try to avoid emitting
261 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000262 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000263 // Figure out which block (then or else) is executed.
264 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000265 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000266 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000267
Chris Lattner62b72f62008-11-11 07:24:28 +0000268 // If the skipped block has no labels in it, just emit the executed block.
269 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000270 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000271 if (Executed)
272 EmitStmt(Executed);
273 return;
274 }
275 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000276
277 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
278 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000279 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
280 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
281 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000283 ElseBlock = createBasicBlock("if.else");
284 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000285
286 // Emit the 'then' code.
287 EmitBlock(ThenBlock);
288 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000289 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000290
291 // Emit the 'else' code if present.
292 if (const Stmt *Else = S.getElse()) {
293 EmitBlock(ElseBlock);
294 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000295 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 }
297
298 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000299 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000300}
301
302void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // Emit the header for the loop, insert it, which will create an uncond br to
304 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000305 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 EmitBlock(LoopHeader);
307
308 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
309 // of the controlling expression takes place before each execution of the loop
310 // body.
311 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000312
313 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000315 bool EmitBoolCondBranch = true;
316 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
317 if (C->isOne())
318 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000319
320 // Create an exit block for when the condition fails, create a block for the
321 // body of the loop.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000322 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000323 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Reid Spencer5f016e22007-07-11 17:01:13 +0000324
325 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000326 if (EmitBoolCondBranch)
327 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000328
Chris Lattnerda138702007-07-16 21:28:45 +0000329 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000330 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader,
331 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000332
333 // Emit the loop body.
334 EmitBlock(LoopBody);
335 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000336
337 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
339 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000340 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000341
342 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000343 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000344
345 // If LoopHeader is a simple forwarding block then eliminate it.
346 if (!EmitBoolCondBranch
347 && &LoopHeader->front() == LoopHeader->getTerminator()) {
348 LoopHeader->replaceAllUsesWith(LoopBody);
349 LoopHeader->getTerminator()->eraseFromParent();
350 LoopHeader->eraseFromParent();
351 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
354void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 // Emit the body for the loop, insert it, which will create an uncond br to
356 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000357 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
358 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000360
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000361 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000362
363 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000364 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond,
365 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000366
367 // Emit the body of the loop into the block.
368 EmitStmt(S.getBody());
369
Chris Lattnerda138702007-07-16 21:28:45 +0000370 BreakContinueStack.pop_back();
371
372 EmitBlock(DoCond);
373
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
375 // after each execution of the loop body."
376
377 // Evaluate the conditional in the while header.
378 // C99 6.8.5p2/p4: The first substatement is executed if the expression
379 // compares unequal to 0. The condition must be a scalar type.
380 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000381
382 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
383 // to correctly handle break/continue though.
384 bool EmitBoolCondBranch = true;
385 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
386 if (C->isZero())
387 EmitBoolCondBranch = false;
388
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000390 if (EmitBoolCondBranch)
391 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000392
393 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000394 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000395
396 // If DoCond is a simple forwarding block then eliminate it.
397 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
398 DoCond->replaceAllUsesWith(AfterDo);
399 DoCond->getTerminator()->eraseFromParent();
400 DoCond->eraseFromParent();
401 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000402}
403
404void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
406 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // Evaluate the first part before the loop.
409 if (S.getInit())
410 EmitStmt(S.getInit());
411
412 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000413 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
414 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000415
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 EmitBlock(CondBlock);
417
418 // Evaluate the condition if present. If not, treat it as a non-zero-constant
419 // according to 6.8.5.3p2, aka, true.
420 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000422 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000423
424 // C99 6.8.5p2/p4: The first substatement is executed if the expression
425 // compares unequal to 0. The condition must be a scalar type.
426 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
427
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 EmitBlock(ForBody);
429 } else {
430 // Treat it as a non-zero constant. Don't even create a new block for the
431 // body, just fall into it.
432 }
433
Chris Lattnerda138702007-07-16 21:28:45 +0000434 // If the for loop doesn't have an increment we can just use the
435 // condition as the continue block.
436 llvm::BasicBlock *ContinueBlock;
437 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000438 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000439 else
440 ContinueBlock = CondBlock;
441
442 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000443 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock,
444 ObjCEHStack.size()));
Chris Lattnerda138702007-07-16 21:28:45 +0000445
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // If the condition is true, execute the body of the for stmt.
447 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000448
449 BreakContinueStack.pop_back();
450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000452 if (S.getInc()) {
453 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000454 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000455 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000456
457 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000458 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000459
Chris Lattnerda138702007-07-16 21:28:45 +0000460 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000461 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000462}
463
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000464void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
465 if (RV.isScalar()) {
466 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
467 } else if (RV.isAggregate()) {
468 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
469 } else {
470 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
471 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000472 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000473}
474
Reid Spencer5f016e22007-07-11 17:01:13 +0000475/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
476/// if the function returns void, or may be missing one if the function returns
477/// non-void. Fun stuff :).
478void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000479 if (StackSaveValues.back()) {
480 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
481 return;
482 }
483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 // Emit the result value, even if unused, to evalute the side effects.
485 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000486
487 // FIXME: Clean this up by using an LValue for ReturnTemp,
488 // EmitStoreThroughLValue, and EmitAnyExpr.
489 if (!ReturnValue) {
490 // Make sure not to return anything, but evaluate the expression
491 // for side effects.
492 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000493 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000495 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000496 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000497 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000498 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000499 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000501 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 }
Eli Friedman144ac612008-05-22 01:22:33 +0000503
Daniel Dunbar898d5082008-09-30 01:06:03 +0000504 if (!ObjCEHStack.empty()) {
505 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
506 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000507 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000508 EmitJumpThroughFinally(*i, ReturnPad);
509 EmitBlock(ReturnPad);
510 }
511 }
512
Daniel Dunbard57a8712008-11-11 09:41:28 +0000513 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000514}
515
516void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000517 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
518 I != E; ++I)
519 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000520}
Chris Lattnerda138702007-07-16 21:28:45 +0000521
Daniel Dunbar09124252008-11-12 08:21:33 +0000522void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000523 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
524
Daniel Dunbar09124252008-11-12 08:21:33 +0000525 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000526 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000527 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar09124252008-11-12 08:21:33 +0000528 return;
529 }
530
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000531 if (StackSaveValues.back()) {
532 CGM.ErrorUnsupported(&S, "break inside scope with VLA");
533 return;
534 }
535
Daniel Dunbar09124252008-11-12 08:21:33 +0000536 // If this code is reachable then emit a stop point (if generating
537 // debug info). We have to do this ourselves because we are on the
538 // "simple" statement path.
539 if (HaveInsertPoint())
540 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000541 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000542 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000543}
544
Daniel Dunbar09124252008-11-12 08:21:33 +0000545void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000546 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
547
Daniel Dunbar09124252008-11-12 08:21:33 +0000548 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000549 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000550 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
551 return;
552 }
553
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000554 if (StackSaveValues.back()) {
555 CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
556 return;
557 }
558
Daniel Dunbar09124252008-11-12 08:21:33 +0000559 // If this code is reachable then emit a stop point (if generating
560 // debug info). We have to do this ourselves because we are on the
561 // "simple" statement path.
562 if (HaveInsertPoint())
563 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000564 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000565 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000566}
Devang Patel51b09f22007-10-04 23:45:31 +0000567
Devang Patelc049e4f2007-10-08 20:57:48 +0000568/// EmitCaseStmtRange - If case statement range is not too big then
569/// add multiple cases to switch instruction, one for each value within
570/// the range. If range is too big then emit "if" condition check.
571void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000572 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000573
Anders Carlsson51fe9962008-11-22 21:04:56 +0000574 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
575 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000576
Daniel Dunbar16f23572008-07-25 01:11:38 +0000577 // Emit the code for this case. We do this first to make sure it is
578 // properly chained from our predecessor before generating the
579 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000580 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000581 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
582 EmitStmt(S.getSubStmt());
583
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000584 // If range is empty, do nothing.
585 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
586 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000587
588 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000589 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000590 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
591 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000592 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000593 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
594 LHS++;
595 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000596 return;
597 }
598
Daniel Dunbar16f23572008-07-25 01:11:38 +0000599 // The range is too big. Emit "if" condition into a new block,
600 // making sure to save and restore the current insertion point.
601 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000602
Daniel Dunbar16f23572008-07-25 01:11:38 +0000603 // Push this test onto the chain of range checks (which terminates
604 // in the default basic block). The switch's default will be changed
605 // to the top of this chain after switch emission is complete.
606 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000607 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000608
Daniel Dunbar16f23572008-07-25 01:11:38 +0000609 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
610 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000611
612 // Emit range check.
613 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000614 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
615 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000616 llvm::Value *Cond =
617 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
618 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
619
Daniel Dunbar16f23572008-07-25 01:11:38 +0000620 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000621 if (RestoreBB)
622 Builder.SetInsertPoint(RestoreBB);
623 else
624 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000625}
626
627void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
628 if (S.getRHS()) {
629 EmitCaseStmtRange(S);
630 return;
631 }
632
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000633 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000634 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000635 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000636 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000637 EmitStmt(S.getSubStmt());
638}
639
640void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000641 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000642 assert(DefaultBlock->empty() &&
643 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000644 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000645 EmitStmt(S.getSubStmt());
646}
647
648void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
649 llvm::Value *CondV = EmitScalarExpr(S.getCond());
650
651 // Handle nested switch statements.
652 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000653 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000654
Daniel Dunbar16f23572008-07-25 01:11:38 +0000655 // Create basic block to hold stuff that comes after switch
656 // statement. We also need to create a default block now so that
657 // explicit case ranges tests can have a place to jump to on
658 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000659 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
660 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000661 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
662 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000663
Daniel Dunbar09124252008-11-12 08:21:33 +0000664 // Clear the insertion point to indicate we are in unreachable code.
665 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000666
Devang Patele9b8c0a2007-10-30 20:59:40 +0000667 // All break statements jump to NextBlock. If BreakContinueStack is non empty
668 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000669 llvm::BasicBlock *ContinueBlock = NULL;
670 if (!BreakContinueStack.empty())
671 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone21269b2008-12-13 22:52:24 +0000672 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock,
673 ObjCEHStack.size()));
Devang Patel51b09f22007-10-04 23:45:31 +0000674
675 // Emit switch body.
676 EmitStmt(S.getBody());
677 BreakContinueStack.pop_back();
678
Daniel Dunbar16f23572008-07-25 01:11:38 +0000679 // Update the default block in case explicit case range tests have
680 // been chained on top.
681 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000682
Daniel Dunbar16f23572008-07-25 01:11:38 +0000683 // If a default was never emitted then reroute any jumps to it and
684 // discard.
685 if (!DefaultBlock->getParent()) {
686 DefaultBlock->replaceAllUsesWith(NextBlock);
687 delete DefaultBlock;
688 }
Devang Patel51b09f22007-10-04 23:45:31 +0000689
Daniel Dunbar16f23572008-07-25 01:11:38 +0000690 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000691 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000692
Devang Patel51b09f22007-10-04 23:45:31 +0000693 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000694 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000695}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000696
Anders Carlssonce179ab2008-11-09 18:54:14 +0000697static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
698{
699 // FIXME: No need to create new std::string here, we could just make sure
700 // that we don't read past the end of the string data.
701 std::string str(S.getAsmString()->getStrData(),
702 S.getAsmString()->getByteLength());
703 const char *Start = str.c_str();
704
705 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
706 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000707 Failed = false;
708
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000709 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000710 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000711 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000712 if (IsSimple) {
713 while (*Start) {
714 switch (*Start) {
715 default:
716 Result += *Start;
717 break;
718 case '$':
719 Result += "$$";
720 break;
721 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000722 Start++;
723 }
724
725 return Result;
726 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000727
728 while (*Start) {
729 switch (*Start) {
730 default:
731 Result += *Start;
732 break;
733 case '$':
734 Result += "$$";
735 break;
736 case '%':
737 // Escaped character
738 Start++;
739 if (!*Start) {
740 // FIXME: This should be caught during Sema.
741 assert(0 && "Trailing '%' in asm string.");
742 }
743
744 char EscapedChar = *Start;
745 if (EscapedChar == '%') {
746 // Escaped percentage sign.
747 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000748 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000749 // Generate an unique ID.
750 Result += llvm::utostr(AsmCounter);
751 } else if (isdigit(EscapedChar)) {
752 // %n - Assembler operand n
753 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000754 unsigned long n = strtoul(Start, &End, 10);
755 if (Start == End) {
756 // FIXME: This should be caught during Sema.
757 assert(0 && "Missing operand!");
758 } else if (n >= NumOperands) {
759 // FIXME: This should be caught during Sema.
760 assert(0 && "Operand number out of range!");
761 }
762
763 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000764 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000765 } else if (isalpha(EscapedChar)) {
766 char *End;
767
768 unsigned long n = strtoul(Start + 1, &End, 10);
769 if (Start == End) {
770 // FIXME: This should be caught during Sema.
771 assert(0 && "Missing operand!");
772 } else if (n >= NumOperands) {
773 // FIXME: This should be caught during Sema.
774 assert(0 && "Operand number out of range!");
775 }
776
777 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000778 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000779 } else if (EscapedChar == '[') {
780 std::string SymbolicName;
781
782 Start++;
783
784 while (*Start && *Start != ']') {
785 SymbolicName += *Start;
786
787 Start++;
788 }
789
790 if (!Start) {
791 // FIXME: Should be caught by sema.
792 assert(0 && "Could not parse symbolic name");
793 }
794
795 assert(*Start == ']' && "Error parsing symbolic name");
796
797 int Index = -1;
798
799 // Check if this is an output operand.
800 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
801 if (S.getOutputName(i) == SymbolicName) {
802 Index = i;
803 break;
804 }
805 }
806
807 if (Index == -1) {
808 for (unsigned i = 0; i < S.getNumInputs(); i++) {
809 if (S.getInputName(i) == SymbolicName) {
810 Index = S.getNumOutputs() + i;
811 }
812 }
813 }
814
815 assert(Index != -1 && "Did not find right operand!");
816
817 Result += '$' + llvm::utostr(Index);
818
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000819 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000820 Failed = true;
821 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000822 }
823 }
824 Start++;
825 }
826
827 return Result;
828}
829
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000830static std::string SimplifyConstraint(const char* Constraint,
831 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000832 std::string Result;
833
834 while (*Constraint) {
835 switch (*Constraint) {
836 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000837 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000838 break;
839 // Ignore these
840 case '*':
841 case '?':
842 case '!':
843 break;
844 case 'g':
845 Result += "imr";
846 break;
847 }
848
849 Constraint++;
850 }
851
852 return Result;
853}
854
855void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000856 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000857 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000858 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000859
860 if (Failed) {
861 ErrorUnsupported(&S, "asm string");
862 return;
863 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000864
865 std::string Constraints;
866
867 llvm::Value *ResultAddr = 0;
868 const llvm::Type *ResultType = llvm::Type::VoidTy;
869
870 std::vector<const llvm::Type*> ArgTypes;
871 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000872
873 // Keep track of inout constraints.
874 std::string InOutConstraints;
875 std::vector<llvm::Value*> InOutArgs;
876 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000877
878 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
879 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
880 S.getOutputConstraint(i)->getByteLength());
881
882 TargetInfo::ConstraintInfo Info;
883 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
884 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000885 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000886
887 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000888 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000889
890 LValue Dest = EmitLValue(S.getOutputExpr(i));
891 const llvm::Type *DestValueType =
892 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
893
894 // If the first output operand is not a memory dest, we'll
895 // make it the return value.
896 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000897 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000898 ResultAddr = Dest.getAddress();
899 ResultType = DestValueType;
900 Constraints += "=" + OutputConstraint;
901 } else {
902 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000903 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000904 if (i != 0)
905 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000906 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000907 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000908 }
909
910 if (Info & TargetInfo::CI_ReadWrite) {
911 // FIXME: This code should be shared with the code that handles inputs.
912 InOutConstraints += ',';
913
914 const Expr *InputExpr = S.getOutputExpr(i);
915 llvm::Value *Arg;
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 Carlssonf39a4212008-02-05 20:01:53 +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 Carlssonf39a4212008-02-05 20:01:53 +0000923 }
924 } else {
925 LValue Dest = EmitLValue(InputExpr);
926 Arg = Dest.getAddress();
927 InOutConstraints += '*';
928 }
929
930 InOutArgTypes.push_back(Arg->getType());
931 InOutArgs.push_back(Arg);
932 InOutConstraints += OutputConstraint;
933 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000934 }
935
936 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
937
938 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
939 const Expr *InputExpr = S.getInputExpr(i);
940
941 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
942 S.getInputConstraint(i)->getByteLength());
943
944 TargetInfo::ConstraintInfo Info;
945 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000946 NumConstraints, Info);
947 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000948
949 if (i != 0 || S.getNumOutputs() > 0)
950 Constraints += ',';
951
952 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000953 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000954
955 llvm::Value *Arg;
956
957 if ((Info & TargetInfo::CI_AllowsRegister) ||
958 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000959 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000960 Arg = EmitScalarExpr(InputExpr);
961 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000962 ErrorUnsupported(&S,
963 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000964 }
965 } else {
966 LValue Dest = EmitLValue(InputExpr);
967 Arg = Dest.getAddress();
968 Constraints += '*';
969 }
970
971 ArgTypes.push_back(Arg->getType());
972 Args.push_back(Arg);
973 Constraints += InputConstraint;
974 }
975
Anders Carlssonf39a4212008-02-05 20:01:53 +0000976 // Append the "input" part of inout constraints last.
977 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
978 ArgTypes.push_back(InOutArgTypes[i]);
979 Args.push_back(InOutArgs[i]);
980 }
981 Constraints += InOutConstraints;
982
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000983 // Clobbers
984 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
985 std::string Clobber(S.getClobber(i)->getStrData(),
986 S.getClobber(i)->getByteLength());
987
988 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
989
Anders Carlssonea041752008-02-06 00:11:32 +0000990 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000991 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000992
993 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000994 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000995 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000996 }
997
998 // Add machine specific clobbers
999 if (const char *C = Target.getClobbers()) {
1000 if (!Constraints.empty())
1001 Constraints += ',';
1002 Constraints += C;
1003 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001004
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001005 const llvm::FunctionType *FTy =
1006 llvm::FunctionType::get(ResultType, ArgTypes, false);
1007
1008 llvm::InlineAsm *IA =
1009 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1010 S.isVolatile() || S.getNumOutputs() == 0);
1011 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001012 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001013 Builder.CreateStore(Result, ResultAddr);
1014}