blob: edccbe41bfd5f2b4e247ea1e6015bc7336cb8237 [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"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
26//===----------------------------------------------------------------------===//
27// Statement Emission
28//===----------------------------------------------------------------------===//
29
Daniel Dunbar09124252008-11-12 08:21:33 +000030void CodeGenFunction::EmitStopPoint(const Stmt *S) {
31 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
32 DI->setLocation(S->getLocStart());
33 DI->EmitStopPoint(CurFn, Builder);
34 }
35}
36
Reid Spencer5f016e22007-07-11 17:01:13 +000037void CodeGenFunction::EmitStmt(const Stmt *S) {
38 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000039
Daniel Dunbar09124252008-11-12 08:21:33 +000040 // Check if we can handle this without bothering to generate an
41 // insert point or debug info.
42 if (EmitSimpleStmt(S))
43 return;
44
Daniel Dunbara448fb22008-11-11 23:11:34 +000045 // If we happen to be at an unreachable point just create a dummy
46 // basic block to hold the code. We could change parts of irgen to
47 // simply not generate this code, but this situation is rare and
48 // probably not worth the effort.
49 // FIXME: Verify previous performance/effort claim.
50 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000051
Daniel Dunbar09124252008-11-12 08:21:33 +000052 // Generate a stoppoint if we are emitting debug info.
53 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000054
Reid Spencer5f016e22007-07-11 17:01:13 +000055 switch (S->getStmtClass()) {
56 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000057 // Must be an expression in a stmt context. Emit the value (to get
58 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000059 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000060 if (!hasAggregateLLVMType(E->getType()))
61 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000062 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000063 EmitComplexExpr(E);
64 else
65 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000066 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000067 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000068 }
69 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000070 case Stmt::IndirectGotoStmtClass:
71 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000072
73 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
74 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
75 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
76 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
77
78 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
79 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000080
Devang Patel51b09f22007-10-04 23:45:31 +000081 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000082 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000083
84 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000085 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
86 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000087 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000088 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
89 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000090 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000091 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000092 break;
93 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000094 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000095 break;
96 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000097 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000098 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000099 case Stmt::ObjCForCollectionStmtClass:
100 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 }
103}
104
Daniel Dunbar09124252008-11-12 08:21:33 +0000105bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
106 switch (S->getStmtClass()) {
107 default: return false;
108 case Stmt::NullStmtClass: break;
109 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
110 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
111 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
112 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
113 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
114 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
115 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
116 }
117
118 return true;
119}
120
Chris Lattner33793202007-08-31 22:09:40 +0000121/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
122/// this captures the expression result of the last sub-statement and returns it
123/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000124RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
125 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000127 CGDebugInfo *DI = CGM.getDebugInfo();
128 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000129 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000130 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000131 DI->EmitRegionStart(CurFn, Builder);
132 }
133
Anders Carlsson17d28a32008-12-12 05:52:00 +0000134 // Push a null stack save value.
135 StackSaveValues.push_back(0);
136
Chris Lattner33793202007-08-31 22:09:40 +0000137 for (CompoundStmt::const_body_iterator I = S.body_begin(),
138 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000140
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000141 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000142 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000143 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000144 DI->EmitRegionEnd(CurFn, Builder);
145 }
146
Anders Carlsson17d28a32008-12-12 05:52:00 +0000147 RValue RV;
148 if (!GetLast)
149 RV = RValue::get(0);
150 else {
151 // We have to special case labels here. They are statements, but when put
152 // at the end of a statement expression, they yield the value of their
153 // subexpression. Handle this by walking through all labels we encounter,
154 // emitting them before we evaluate the subexpr.
155 const Stmt *LastStmt = S.body_back();
156 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
157 EmitLabel(*LS);
158 LastStmt = LS->getSubStmt();
159 }
Chris Lattner9b655512007-08-31 22:49:20 +0000160
Anders Carlsson17d28a32008-12-12 05:52:00 +0000161 EnsureInsertPoint();
162
163 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
164 }
165
166 if (llvm::Value *V = StackSaveValues.pop_back_val()) {
167 V = Builder.CreateLoad(V, "tmp");
168
169 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
170 Builder.CreateCall(F, V);
Chris Lattner91d723d2008-07-26 20:23:23 +0000171 }
172
Anders Carlsson17d28a32008-12-12 05:52:00 +0000173 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000174}
175
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000176void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000177 // Fall out of the current block (if necessary).
178 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000179
180 if (IsFinished && BB->use_empty()) {
181 delete BB;
182 return;
183 }
184
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 CurFn->getBasicBlockList().push_back(BB);
186 Builder.SetInsertPoint(BB);
187}
188
Daniel Dunbard57a8712008-11-11 09:41:28 +0000189void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
190 // Emit a branch from the current block to the target one if this
191 // was a real block. If this was just a fall-through block after a
192 // terminator, don't emit it.
193 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
194
195 if (!CurBB || CurBB->getTerminator()) {
196 // If there is no insert point or the previous block is already
197 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000198 } else {
199 // Otherwise, create a fall-through branch.
200 Builder.CreateBr(Target);
201 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000202
203 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000204}
205
Chris Lattner91d723d2008-07-26 20:23:23 +0000206void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000209}
210
211
212void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
213 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 EmitStmt(S.getSubStmt());
215}
216
217void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000218 // FIXME: Implement goto out in @try or @catch blocks.
219 if (!ObjCEHStack.empty()) {
220 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
221 return;
222 }
223
Eli Friedman20c802b2008-12-20 23:18:29 +0000224 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000225 if (StackSaveValues[i]) {
226 CGM.ErrorUnsupported(&S, "goto inside scope with VLA");
227 return;
228 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000229 }
230
Daniel Dunbar09124252008-11-12 08:21:33 +0000231 // If this code is reachable then emit a stop point (if generating
232 // debug info). We have to do this ourselves because we are on the
233 // "simple" statement path.
234 if (HaveInsertPoint())
235 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000236 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000237}
238
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000239void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000240 // FIXME: Implement indirect goto in @try or @catch blocks.
241 if (!ObjCEHStack.empty()) {
242 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
243 return;
244 }
245
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000246 // Emit initial switch which will be patched up later by
247 // EmitIndirectSwitches(). We need a default dest, so we use the
248 // current BB, but this is overwritten.
249 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
250 llvm::Type::Int32Ty,
251 "addr");
252 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
253 IndirectSwitches.push_back(I);
254
Daniel Dunbara448fb22008-11-11 23:11:34 +0000255 // Clear the insertion point to indicate we are in unreachable code.
256 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000257}
258
Chris Lattner62b72f62008-11-11 07:24:28 +0000259void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 // C99 6.8.4.1: The first substatement is executed if the expression compares
261 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000262
Chris Lattner9bc47e22008-11-12 07:46:33 +0000263 // If the condition constant folds and can be elided, try to avoid emitting
264 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000265 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000266 // Figure out which block (then or else) is executed.
267 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000268 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000269 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000270
Chris Lattner62b72f62008-11-11 07:24:28 +0000271 // If the skipped block has no labels in it, just emit the executed block.
272 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000273 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000274 if (Executed)
275 EmitStmt(Executed);
276 return;
277 }
278 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000279
280 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
281 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000282 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
283 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
284 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000286 ElseBlock = createBasicBlock("if.else");
287 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000288
289 // Emit the 'then' code.
290 EmitBlock(ThenBlock);
291 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000292 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000293
294 // Emit the 'else' code if present.
295 if (const Stmt *Else = S.getElse()) {
296 EmitBlock(ElseBlock);
297 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000298 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 }
300
301 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000302 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000303}
304
305void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 // Emit the header for the loop, insert it, which will create an uncond br to
307 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000308 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 EmitBlock(LoopHeader);
310
311 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
312 // of the controlling expression takes place before each execution of the loop
313 // body.
314 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000315
316 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000318 bool EmitBoolCondBranch = true;
319 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
320 if (C->isOne())
321 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000322
323 // Create an exit block for when the condition fails, create a block for the
324 // body of the loop.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000325 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000326 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Reid Spencer5f016e22007-07-11 17:01:13 +0000327
328 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000329 if (EmitBoolCondBranch)
330 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000331
Chris Lattnerda138702007-07-16 21:28:45 +0000332 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000333 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader,
334 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000335
336 // Emit the loop body.
337 EmitBlock(LoopBody);
338 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000339
340 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000341
342 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000343 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
345 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000346 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000347
348 // If LoopHeader is a simple forwarding block then eliminate it.
349 if (!EmitBoolCondBranch
350 && &LoopHeader->front() == LoopHeader->getTerminator()) {
351 LoopHeader->replaceAllUsesWith(LoopBody);
352 LoopHeader->getTerminator()->eraseFromParent();
353 LoopHeader->eraseFromParent();
354 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000355}
356
357void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // Emit the body for the loop, insert it, which will create an uncond br to
359 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000360 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
361 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000363
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000364 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000365
366 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000367 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond,
368 ObjCEHStack.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000369
370 // Emit the body of the loop into the block.
371 EmitStmt(S.getBody());
372
Chris Lattnerda138702007-07-16 21:28:45 +0000373 BreakContinueStack.pop_back();
374
375 EmitBlock(DoCond);
376
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
378 // after each execution of the loop body."
379
380 // Evaluate the conditional in the while header.
381 // C99 6.8.5p2/p4: The first substatement is executed if the expression
382 // compares unequal to 0. The condition must be a scalar type.
383 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000384
385 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
386 // to correctly handle break/continue though.
387 bool EmitBoolCondBranch = true;
388 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
389 if (C->isZero())
390 EmitBoolCondBranch = false;
391
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000393 if (EmitBoolCondBranch)
394 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000395
396 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000397 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000398
399 // If DoCond is a simple forwarding block then eliminate it.
400 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
401 DoCond->replaceAllUsesWith(AfterDo);
402 DoCond->getTerminator()->eraseFromParent();
403 DoCond->eraseFromParent();
404 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000405}
406
407void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
409 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 // Evaluate the first part before the loop.
412 if (S.getInit())
413 EmitStmt(S.getInit());
414
415 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000416 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
417 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000418
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 EmitBlock(CondBlock);
420
421 // Evaluate the condition if present. If not, treat it as a non-zero-constant
422 // according to 6.8.5.3p2, aka, true.
423 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000425 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000426
427 // C99 6.8.5p2/p4: The first substatement is executed if the expression
428 // compares unequal to 0. The condition must be a scalar type.
429 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
430
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 EmitBlock(ForBody);
432 } else {
433 // Treat it as a non-zero constant. Don't even create a new block for the
434 // body, just fall into it.
435 }
436
Chris Lattnerda138702007-07-16 21:28:45 +0000437 // If the for loop doesn't have an increment we can just use the
438 // condition as the continue block.
439 llvm::BasicBlock *ContinueBlock;
440 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000441 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000442 else
443 ContinueBlock = CondBlock;
444
445 // Store the blocks to use for break and continue.
Anders Carlssone21269b2008-12-13 22:52:24 +0000446 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock,
447 ObjCEHStack.size()));
Chris Lattnerda138702007-07-16 21:28:45 +0000448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 // If the condition is true, execute the body of the for stmt.
450 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000451
452 BreakContinueStack.pop_back();
453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000455 if (S.getInc()) {
456 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000457 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000458 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000459
460 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000461 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000462
Chris Lattnerda138702007-07-16 21:28:45 +0000463 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000464 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000465}
466
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000467void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
468 if (RV.isScalar()) {
469 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
470 } else if (RV.isAggregate()) {
471 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
472 } else {
473 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
474 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000475 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000476}
477
Reid Spencer5f016e22007-07-11 17:01:13 +0000478/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
479/// if the function returns void, or may be missing one if the function returns
480/// non-void. Fun stuff :).
481void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Eli Friedman20c802b2008-12-20 23:18:29 +0000482 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000483 if (StackSaveValues[i]) {
484 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
485 return;
486 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000487 }
488
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 // Emit the result value, even if unused, to evalute the side effects.
490 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000491
492 // FIXME: Clean this up by using an LValue for ReturnTemp,
493 // EmitStoreThroughLValue, and EmitAnyExpr.
494 if (!ReturnValue) {
495 // Make sure not to return anything, but evaluate the expression
496 // for side effects.
497 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000498 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000500 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000501 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000502 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000503 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000504 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000506 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 }
Eli Friedman144ac612008-05-22 01:22:33 +0000508
Daniel Dunbar898d5082008-09-30 01:06:03 +0000509 if (!ObjCEHStack.empty()) {
510 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
511 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000512 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000513 EmitJumpThroughFinally(*i, ReturnPad);
514 EmitBlock(ReturnPad);
515 }
516 }
517
Daniel Dunbard57a8712008-11-11 09:41:28 +0000518 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000519}
520
521void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000522 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
523 I != E; ++I)
524 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000525}
Chris Lattnerda138702007-07-16 21:28:45 +0000526
Daniel Dunbar09124252008-11-12 08:21:33 +0000527void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000528 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
529
Daniel Dunbar09124252008-11-12 08:21:33 +0000530 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000531 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000532 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar09124252008-11-12 08:21:33 +0000533 return;
534 }
535
Eli Friedman20c802b2008-12-20 23:18:29 +0000536 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
537 if (StackSaveValues[i]) {
538 CGM.ErrorUnsupported(&S, "break inside scope with VLA");
539 return;
540 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000541 }
542
Daniel Dunbar09124252008-11-12 08:21:33 +0000543 // If this code is reachable then emit a stop point (if generating
544 // debug info). We have to do this ourselves because we are on the
545 // "simple" statement path.
546 if (HaveInsertPoint())
547 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000548 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000549 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000550}
551
Daniel Dunbar09124252008-11-12 08:21:33 +0000552void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000553 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
554
Daniel Dunbar09124252008-11-12 08:21:33 +0000555 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000556 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000557 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
558 return;
559 }
560
Eli Friedman20c802b2008-12-20 23:18:29 +0000561 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
562 if (StackSaveValues[i]) {
563 CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
564 return;
565 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000566 }
567
Daniel Dunbar09124252008-11-12 08:21:33 +0000568 // If this code is reachable then emit a stop point (if generating
569 // debug info). We have to do this ourselves because we are on the
570 // "simple" statement path.
571 if (HaveInsertPoint())
572 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000573 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000574 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000575}
Devang Patel51b09f22007-10-04 23:45:31 +0000576
Devang Patelc049e4f2007-10-08 20:57:48 +0000577/// EmitCaseStmtRange - If case statement range is not too big then
578/// add multiple cases to switch instruction, one for each value within
579/// the range. If range is too big then emit "if" condition check.
580void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000581 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000582
Anders Carlsson51fe9962008-11-22 21:04:56 +0000583 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
584 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000585
Daniel Dunbar16f23572008-07-25 01:11:38 +0000586 // Emit the code for this case. We do this first to make sure it is
587 // properly chained from our predecessor before generating the
588 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000589 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000590 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
591 EmitStmt(S.getSubStmt());
592
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000593 // If range is empty, do nothing.
594 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
595 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000596
597 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000598 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000599 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
600 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000601 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000602 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
603 LHS++;
604 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000605 return;
606 }
607
Daniel Dunbar16f23572008-07-25 01:11:38 +0000608 // The range is too big. Emit "if" condition into a new block,
609 // making sure to save and restore the current insertion point.
610 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000611
Daniel Dunbar16f23572008-07-25 01:11:38 +0000612 // Push this test onto the chain of range checks (which terminates
613 // in the default basic block). The switch's default will be changed
614 // to the top of this chain after switch emission is complete.
615 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000616 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000617
Daniel Dunbar16f23572008-07-25 01:11:38 +0000618 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
619 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000620
621 // Emit range check.
622 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000623 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
624 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000625 llvm::Value *Cond =
626 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
627 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
628
Daniel Dunbar16f23572008-07-25 01:11:38 +0000629 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000630 if (RestoreBB)
631 Builder.SetInsertPoint(RestoreBB);
632 else
633 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000634}
635
636void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
637 if (S.getRHS()) {
638 EmitCaseStmtRange(S);
639 return;
640 }
641
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000642 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000643 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000644 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000645 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000646 EmitStmt(S.getSubStmt());
647}
648
649void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000650 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000651 assert(DefaultBlock->empty() &&
652 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000653 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000654 EmitStmt(S.getSubStmt());
655}
656
657void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
658 llvm::Value *CondV = EmitScalarExpr(S.getCond());
659
660 // Handle nested switch statements.
661 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000662 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000663
Daniel Dunbar16f23572008-07-25 01:11:38 +0000664 // Create basic block to hold stuff that comes after switch
665 // statement. We also need to create a default block now so that
666 // explicit case ranges tests can have a place to jump to on
667 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000668 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
669 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000670 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
671 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000672
Daniel Dunbar09124252008-11-12 08:21:33 +0000673 // Clear the insertion point to indicate we are in unreachable code.
674 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000675
Devang Patele9b8c0a2007-10-30 20:59:40 +0000676 // All break statements jump to NextBlock. If BreakContinueStack is non empty
677 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000678 llvm::BasicBlock *ContinueBlock = NULL;
679 if (!BreakContinueStack.empty())
680 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone21269b2008-12-13 22:52:24 +0000681 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock,
682 ObjCEHStack.size()));
Devang Patel51b09f22007-10-04 23:45:31 +0000683
684 // Emit switch body.
685 EmitStmt(S.getBody());
686 BreakContinueStack.pop_back();
687
Daniel Dunbar16f23572008-07-25 01:11:38 +0000688 // Update the default block in case explicit case range tests have
689 // been chained on top.
690 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000691
Daniel Dunbar16f23572008-07-25 01:11:38 +0000692 // If a default was never emitted then reroute any jumps to it and
693 // discard.
694 if (!DefaultBlock->getParent()) {
695 DefaultBlock->replaceAllUsesWith(NextBlock);
696 delete DefaultBlock;
697 }
Devang Patel51b09f22007-10-04 23:45:31 +0000698
Daniel Dunbar16f23572008-07-25 01:11:38 +0000699 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000700 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000701
Devang Patel51b09f22007-10-04 23:45:31 +0000702 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000703 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000704}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000705
Anders Carlssonce179ab2008-11-09 18:54:14 +0000706static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
707{
708 // FIXME: No need to create new std::string here, we could just make sure
709 // that we don't read past the end of the string data.
710 std::string str(S.getAsmString()->getStrData(),
711 S.getAsmString()->getByteLength());
712 const char *Start = str.c_str();
713
714 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
715 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000716 Failed = false;
717
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000718 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000719 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000720 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000721 if (IsSimple) {
722 while (*Start) {
723 switch (*Start) {
724 default:
725 Result += *Start;
726 break;
727 case '$':
728 Result += "$$";
729 break;
730 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000731 Start++;
732 }
733
734 return Result;
735 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000736
737 while (*Start) {
738 switch (*Start) {
739 default:
740 Result += *Start;
741 break;
742 case '$':
743 Result += "$$";
744 break;
745 case '%':
746 // Escaped character
747 Start++;
748 if (!*Start) {
749 // FIXME: This should be caught during Sema.
750 assert(0 && "Trailing '%' in asm string.");
751 }
752
753 char EscapedChar = *Start;
754 if (EscapedChar == '%') {
755 // Escaped percentage sign.
756 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000757 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000758 // Generate an unique ID.
759 Result += llvm::utostr(AsmCounter);
760 } else if (isdigit(EscapedChar)) {
761 // %n - Assembler operand n
762 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000763 unsigned long n = strtoul(Start, &End, 10);
764 if (Start == End) {
765 // FIXME: This should be caught during Sema.
766 assert(0 && "Missing operand!");
767 } else if (n >= NumOperands) {
768 // FIXME: This should be caught during Sema.
769 assert(0 && "Operand number out of range!");
770 }
771
772 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000773 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000774 } else if (isalpha(EscapedChar)) {
775 char *End;
776
777 unsigned long n = strtoul(Start + 1, &End, 10);
778 if (Start == End) {
779 // FIXME: This should be caught during Sema.
780 assert(0 && "Missing operand!");
781 } else if (n >= NumOperands) {
782 // FIXME: This should be caught during Sema.
783 assert(0 && "Operand number out of range!");
784 }
785
786 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000787 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000788 } else if (EscapedChar == '[') {
789 std::string SymbolicName;
790
791 Start++;
792
793 while (*Start && *Start != ']') {
794 SymbolicName += *Start;
795
796 Start++;
797 }
798
799 if (!Start) {
800 // FIXME: Should be caught by sema.
801 assert(0 && "Could not parse symbolic name");
802 }
803
804 assert(*Start == ']' && "Error parsing symbolic name");
805
806 int Index = -1;
807
808 // Check if this is an output operand.
809 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
810 if (S.getOutputName(i) == SymbolicName) {
811 Index = i;
812 break;
813 }
814 }
815
816 if (Index == -1) {
817 for (unsigned i = 0; i < S.getNumInputs(); i++) {
818 if (S.getInputName(i) == SymbolicName) {
819 Index = S.getNumOutputs() + i;
820 }
821 }
822 }
823
824 assert(Index != -1 && "Did not find right operand!");
825
826 Result += '$' + llvm::utostr(Index);
827
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000828 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000829 Failed = true;
830 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000831 }
832 }
833 Start++;
834 }
835
836 return Result;
837}
838
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000839static std::string SimplifyConstraint(const char* Constraint,
840 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000841 std::string Result;
842
843 while (*Constraint) {
844 switch (*Constraint) {
845 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000846 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000847 break;
848 // Ignore these
849 case '*':
850 case '?':
851 case '!':
852 break;
853 case 'g':
854 Result += "imr";
855 break;
856 }
857
858 Constraint++;
859 }
860
861 return Result;
862}
863
Anders Carlsson63471722009-01-11 19:32:54 +0000864llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
865 TargetInfo::ConstraintInfo Info,
866 const Expr *InputExpr,
867 std::string &ConstraintStr)
868{
869 llvm::Value *Arg;
870 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000871 !(Info & TargetInfo::CI_AllowsMemory)) {
872 const llvm::Type *Ty = ConvertType(InputExpr->getType());
873
874 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000875 Arg = EmitScalarExpr(InputExpr);
876 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000877 LValue Dest = EmitLValue(InputExpr);
878
879 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
880 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
881 Ty = llvm::IntegerType::get(Size);
882 Ty = llvm::PointerType::getUnqual(Ty);
883
884 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
885 } else {
886 Arg = Dest.getAddress();
887 ConstraintStr += '*';
888 }
Anders Carlsson63471722009-01-11 19:32:54 +0000889 }
890 } else {
891 LValue Dest = EmitLValue(InputExpr);
892 Arg = Dest.getAddress();
893 ConstraintStr += '*';
894 }
895
896 return Arg;
897}
898
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000899void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000900 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000901 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000902 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000903
904 if (Failed) {
905 ErrorUnsupported(&S, "asm string");
906 return;
907 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000908
909 std::string Constraints;
910
911 llvm::Value *ResultAddr = 0;
912 const llvm::Type *ResultType = llvm::Type::VoidTy;
913
914 std::vector<const llvm::Type*> ArgTypes;
915 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000916
917 // Keep track of inout constraints.
918 std::string InOutConstraints;
919 std::vector<llvm::Value*> InOutArgs;
920 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000921
922 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
923 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
924 S.getOutputConstraint(i)->getByteLength());
925
926 TargetInfo::ConstraintInfo Info;
927 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
928 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000929 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000930
931 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000932 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000933
934 LValue Dest = EmitLValue(S.getOutputExpr(i));
935 const llvm::Type *DestValueType =
936 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
937
938 // If the first output operand is not a memory dest, we'll
939 // make it the return value.
940 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000941 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000942 ResultAddr = Dest.getAddress();
943 ResultType = DestValueType;
944 Constraints += "=" + OutputConstraint;
945 } else {
946 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000947 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000948 if (i != 0)
949 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000950 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000951 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000952 }
953
954 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000955 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000956
Anders Carlssonf39a4212008-02-05 20:01:53 +0000957 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000958 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000959
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000960 if (Info & TargetInfo::CI_AllowsRegister)
961 InOutConstraints += llvm::utostr(i);
962 else
963 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000964
Anders Carlssonf39a4212008-02-05 20:01:53 +0000965 InOutArgTypes.push_back(Arg->getType());
966 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000967 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000968 }
969
970 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
971
972 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
973 const Expr *InputExpr = S.getInputExpr(i);
974
975 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
976 S.getInputConstraint(i)->getByteLength());
977
978 TargetInfo::ConstraintInfo Info;
979 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000980 NumConstraints, Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000981 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000982
983 if (i != 0 || S.getNumOutputs() > 0)
984 Constraints += ',';
985
986 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000987 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000988
Anders Carlsson63471722009-01-11 19:32:54 +0000989 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000990
991 ArgTypes.push_back(Arg->getType());
992 Args.push_back(Arg);
993 Constraints += InputConstraint;
994 }
995
Anders Carlssonf39a4212008-02-05 20:01:53 +0000996 // Append the "input" part of inout constraints last.
997 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
998 ArgTypes.push_back(InOutArgTypes[i]);
999 Args.push_back(InOutArgs[i]);
1000 }
1001 Constraints += InOutConstraints;
1002
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001003 // Clobbers
1004 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1005 std::string Clobber(S.getClobber(i)->getStrData(),
1006 S.getClobber(i)->getByteLength());
1007
1008 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1009
Anders Carlssonea041752008-02-06 00:11:32 +00001010 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001011 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +00001012
1013 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001014 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001015 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001016 }
1017
1018 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001019 std::string MachineClobbers = Target.getClobbers();
1020 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001021 if (!Constraints.empty())
1022 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001023 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001024 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001025
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001026 const llvm::FunctionType *FTy =
1027 llvm::FunctionType::get(ResultType, ArgTypes, false);
1028
1029 llvm::InlineAsm *IA =
1030 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1031 S.isVolatile() || S.getNumOutputs() == 0);
1032 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001033 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001034 Builder.CreateStore(Result, ResultAddr);
1035}