blob: 1d28708c46decac9895a4d155d3b93b3dea7c308 [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) {
Anders Carlssone896d982009-02-13 08:11:52 +000031 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar09124252008-11-12 08:21:33 +000032 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) {
Anders Carlssonc71c8452009-02-07 23:50:39 +0000126
Anders Carlssone896d982009-02-13 08:11:52 +0000127 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000128 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 Carlssonc71c8452009-02-07 23:50:39 +0000134 // Keep track of the current cleanup stack depth.
135 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlsson74331892009-02-09 20:23:40 +0000136 bool OldDidCallStackSave = DidCallStackSave;
137
Chris Lattner33793202007-08-31 22:09:40 +0000138 for (CompoundStmt::const_body_iterator I = S.body_begin(),
139 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000141
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000142 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000143 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000144 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000145 DI->EmitRegionEnd(CurFn, Builder);
146 }
147
Anders Carlsson17d28a32008-12-12 05:52:00 +0000148 RValue RV;
149 if (!GetLast)
150 RV = RValue::get(0);
151 else {
152 // We have to special case labels here. They are statements, but when put
153 // at the end of a statement expression, they yield the value of their
154 // subexpression. Handle this by walking through all labels we encounter,
155 // emitting them before we evaluate the subexpr.
156 const Stmt *LastStmt = S.body_back();
157 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
158 EmitLabel(*LS);
159 LastStmt = LS->getSubStmt();
160 }
Chris Lattner9b655512007-08-31 22:49:20 +0000161
Anders Carlsson17d28a32008-12-12 05:52:00 +0000162 EnsureInsertPoint();
163
164 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
165 }
166
Anders Carlsson74331892009-02-09 20:23:40 +0000167 DidCallStackSave = OldDidCallStackSave;
168
Anders Carlssonc71c8452009-02-07 23:50:39 +0000169 EmitCleanupBlocks(CleanupStackDepth);
170
Anders Carlsson17d28a32008-12-12 05:52:00 +0000171 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000172}
173
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000174void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000175 // Fall out of the current block (if necessary).
176 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000177
178 if (IsFinished && BB->use_empty()) {
179 delete BB;
180 return;
181 }
182
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000183 // If necessary, associate the block with the cleanup stack size.
184 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000185 // Check if the basic block has already been inserted.
186 BlockScopeMap::iterator I = BlockScopes.find(BB);
187 if (I != BlockScopes.end()) {
188 assert(I->second == CleanupEntries.size() - 1);
189 } else {
190 BlockScopes[BB] = CleanupEntries.size() - 1;
191 CleanupEntries.back().Blocks.push_back(BB);
192 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000193 }
194
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 CurFn->getBasicBlockList().push_back(BB);
196 Builder.SetInsertPoint(BB);
197}
198
Daniel Dunbard57a8712008-11-11 09:41:28 +0000199void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
200 // Emit a branch from the current block to the target one if this
201 // was a real block. If this was just a fall-through block after a
202 // terminator, don't emit it.
203 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
204
205 if (!CurBB || CurBB->getTerminator()) {
206 // If there is no insert point or the previous block is already
207 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000208 } else {
209 // Otherwise, create a fall-through branch.
210 Builder.CreateBr(Target);
211 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000212
213 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000214}
215
Mike Stumpec9771d2009-02-08 09:22:19 +0000216void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000217 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000218}
219
220
221void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
222 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 EmitStmt(S.getSubStmt());
224}
225
226void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000227 // If this code is reachable then emit a stop point (if generating
228 // debug info). We have to do this ourselves because we are on the
229 // "simple" statement path.
230 if (HaveInsertPoint())
231 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000232
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000233 EmitBranchThroughCleanup(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) {
237 // Emit initial switch which will be patched up later by
238 // EmitIndirectSwitches(). We need a default dest, so we use the
239 // current BB, but this is overwritten.
240 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
241 llvm::Type::Int32Ty,
242 "addr");
243 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
244 IndirectSwitches.push_back(I);
245
Daniel Dunbara448fb22008-11-11 23:11:34 +0000246 // Clear the insertion point to indicate we are in unreachable code.
247 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000248}
249
Chris Lattner62b72f62008-11-11 07:24:28 +0000250void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 // C99 6.8.4.1: The first substatement is executed if the expression compares
252 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000253
Chris Lattner9bc47e22008-11-12 07:46:33 +0000254 // If the condition constant folds and can be elided, try to avoid emitting
255 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000256 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000257 // Figure out which block (then or else) is executed.
258 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000259 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000260 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000261
Chris Lattner62b72f62008-11-11 07:24:28 +0000262 // If the skipped block has no labels in it, just emit the executed block.
263 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000264 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000265 if (Executed)
266 EmitStmt(Executed);
267 return;
268 }
269 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000270
271 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
272 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000273 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
274 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
275 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000277 ElseBlock = createBasicBlock("if.else");
278 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279
280 // Emit the 'then' code.
281 EmitBlock(ThenBlock);
282 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000283 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000284
285 // Emit the 'else' code if present.
286 if (const Stmt *Else = S.getElse()) {
287 EmitBlock(ElseBlock);
288 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000289 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 }
291
292 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000293 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000294}
295
296void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // Emit the header for the loop, insert it, which will create an uncond br to
298 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000299 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000301
302 // Create an exit block for when the condition fails, create a block for the
303 // body of the loop.
304 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
305 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
306
307 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000308 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000309
Mike Stump16b16202009-02-07 17:18:33 +0000310 // Evaluate the conditional in the while header. C99 6.8.5.1: The
311 // evaluation of the controlling expression takes place before each
312 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000314
315 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000317 bool EmitBoolCondBranch = true;
318 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
319 if (C->isOne())
320 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000321
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000323 if (EmitBoolCondBranch)
324 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000325
Reid Spencer5f016e22007-07-11 17:01:13 +0000326 // Emit the loop body.
327 EmitBlock(LoopBody);
328 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000329
Anders Carlssone4b6d342009-02-10 05:52:02 +0000330 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000331
332 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000333 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000334
335 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000336 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000337
338 // If LoopHeader is a simple forwarding block then eliminate it.
339 if (!EmitBoolCondBranch
340 && &LoopHeader->front() == LoopHeader->getTerminator()) {
341 LoopHeader->replaceAllUsesWith(LoopBody);
342 LoopHeader->getTerminator()->eraseFromParent();
343 LoopHeader->eraseFromParent();
344 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000345}
346
347void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // Emit the body for the loop, insert it, which will create an uncond br to
349 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000350 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
351 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000353
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000354 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000355
356 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000357 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000358
359 // Emit the body of the loop into the block.
360 EmitStmt(S.getBody());
361
Anders Carlssone4b6d342009-02-10 05:52:02 +0000362 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000363
364 EmitBlock(DoCond);
365
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
367 // after each execution of the loop body."
368
369 // Evaluate the conditional in the while header.
370 // C99 6.8.5p2/p4: The first substatement is executed if the expression
371 // compares unequal to 0. The condition must be a scalar type.
372 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000373
374 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
375 // to correctly handle break/continue though.
376 bool EmitBoolCondBranch = true;
377 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
378 if (C->isZero())
379 EmitBoolCondBranch = false;
380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000382 if (EmitBoolCondBranch)
383 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000384
385 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000386 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000387
388 // If DoCond is a simple forwarding block then eliminate it.
389 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
390 DoCond->replaceAllUsesWith(AfterDo);
391 DoCond->getTerminator()->eraseFromParent();
392 DoCond->eraseFromParent();
393 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000394}
395
396void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
398 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // Evaluate the first part before the loop.
401 if (S.getInit())
402 EmitStmt(S.getInit());
403
404 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000405 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
406 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 EmitBlock(CondBlock);
409
Mike Stump20926c62009-02-07 20:14:12 +0000410 // Evaluate the condition if present. If not, treat it as a
411 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000414 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000415
416 // C99 6.8.5p2/p4: The first substatement is executed if the expression
417 // compares unequal to 0. The condition must be a scalar type.
418 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 EmitBlock(ForBody);
421 } else {
422 // Treat it as a non-zero constant. Don't even create a new block for the
423 // body, just fall into it.
424 }
425
Chris Lattnerda138702007-07-16 21:28:45 +0000426 // If the for loop doesn't have an increment we can just use the
427 // condition as the continue block.
428 llvm::BasicBlock *ContinueBlock;
429 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000430 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000431 else
432 ContinueBlock = CondBlock;
433
434 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000435 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000436
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 // If the condition is true, execute the body of the for stmt.
438 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000439
Anders Carlssone4b6d342009-02-10 05:52:02 +0000440 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000441
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000443 if (S.getInc()) {
444 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000445 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000446 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000447
448 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000449 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000450
Chris Lattnerda138702007-07-16 21:28:45 +0000451 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000452 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000453}
454
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000455void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
456 if (RV.isScalar()) {
457 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
458 } else if (RV.isAggregate()) {
459 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
460 } else {
461 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
462 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000463 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000464}
465
Reid Spencer5f016e22007-07-11 17:01:13 +0000466/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
467/// if the function returns void, or may be missing one if the function returns
468/// non-void. Fun stuff :).
469void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 // Emit the result value, even if unused, to evalute the side effects.
471 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000472
473 // FIXME: Clean this up by using an LValue for ReturnTemp,
474 // EmitStoreThroughLValue, and EmitAnyExpr.
475 if (!ReturnValue) {
476 // Make sure not to return anything, but evaluate the expression
477 // for side effects.
478 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000479 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000481 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000482 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000483 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000484 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000485 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000487 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 }
Eli Friedman144ac612008-05-22 01:22:33 +0000489
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000490 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000491}
492
493void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000494 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
495 I != E; ++I)
496 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000497}
Chris Lattnerda138702007-07-16 21:28:45 +0000498
Daniel Dunbar09124252008-11-12 08:21:33 +0000499void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000500 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
501
Daniel Dunbar09124252008-11-12 08:21:33 +0000502 // If this code is reachable then emit a stop point (if generating
503 // debug info). We have to do this ourselves because we are on the
504 // "simple" statement path.
505 if (HaveInsertPoint())
506 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000507
Chris Lattnerda138702007-07-16 21:28:45 +0000508 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000509 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000510}
511
Daniel Dunbar09124252008-11-12 08:21:33 +0000512void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000513 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
514
Daniel Dunbar09124252008-11-12 08:21:33 +0000515 // If this code is reachable then emit a stop point (if generating
516 // debug info). We have to do this ourselves because we are on the
517 // "simple" statement path.
518 if (HaveInsertPoint())
519 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000520
Chris Lattnerda138702007-07-16 21:28:45 +0000521 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000522 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000523}
Devang Patel51b09f22007-10-04 23:45:31 +0000524
Devang Patelc049e4f2007-10-08 20:57:48 +0000525/// EmitCaseStmtRange - If case statement range is not too big then
526/// add multiple cases to switch instruction, one for each value within
527/// the range. If range is too big then emit "if" condition check.
528void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000529 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000530
Anders Carlsson51fe9962008-11-22 21:04:56 +0000531 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
532 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000533
Daniel Dunbar16f23572008-07-25 01:11:38 +0000534 // Emit the code for this case. We do this first to make sure it is
535 // properly chained from our predecessor before generating the
536 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000537 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000538 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
539 EmitStmt(S.getSubStmt());
540
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000541 // If range is empty, do nothing.
542 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
543 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000544
545 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000546 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000547 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
548 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000549 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000550 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
551 LHS++;
552 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000553 return;
554 }
555
Daniel Dunbar16f23572008-07-25 01:11:38 +0000556 // The range is too big. Emit "if" condition into a new block,
557 // making sure to save and restore the current insertion point.
558 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000559
Daniel Dunbar16f23572008-07-25 01:11:38 +0000560 // Push this test onto the chain of range checks (which terminates
561 // in the default basic block). The switch's default will be changed
562 // to the top of this chain after switch emission is complete.
563 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000564 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000565
Daniel Dunbar16f23572008-07-25 01:11:38 +0000566 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
567 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000568
569 // Emit range check.
570 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000571 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
572 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000573 llvm::Value *Cond =
574 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
575 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
576
Daniel Dunbar16f23572008-07-25 01:11:38 +0000577 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000578 if (RestoreBB)
579 Builder.SetInsertPoint(RestoreBB);
580 else
581 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000582}
583
584void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
585 if (S.getRHS()) {
586 EmitCaseStmtRange(S);
587 return;
588 }
589
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000590 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000591 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000592 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000593 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000594 EmitStmt(S.getSubStmt());
595}
596
597void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000598 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000599 assert(DefaultBlock->empty() &&
600 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000601 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000602 EmitStmt(S.getSubStmt());
603}
604
605void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
606 llvm::Value *CondV = EmitScalarExpr(S.getCond());
607
608 // Handle nested switch statements.
609 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000610 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000611
Daniel Dunbar16f23572008-07-25 01:11:38 +0000612 // Create basic block to hold stuff that comes after switch
613 // statement. We also need to create a default block now so that
614 // explicit case ranges tests can have a place to jump to on
615 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000616 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
617 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000618 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
619 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000620
Daniel Dunbar09124252008-11-12 08:21:33 +0000621 // Clear the insertion point to indicate we are in unreachable code.
622 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000623
Devang Patele9b8c0a2007-10-30 20:59:40 +0000624 // All break statements jump to NextBlock. If BreakContinueStack is non empty
625 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000626 llvm::BasicBlock *ContinueBlock = 0;
627 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000628 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000629
Mike Stump3e9da662009-02-07 23:02:10 +0000630 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000631 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000632
633 // Emit switch body.
634 EmitStmt(S.getBody());
Anders Carlssone4b6d342009-02-10 05:52:02 +0000635
636 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000637
Daniel Dunbar16f23572008-07-25 01:11:38 +0000638 // Update the default block in case explicit case range tests have
639 // been chained on top.
640 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000641
Daniel Dunbar16f23572008-07-25 01:11:38 +0000642 // If a default was never emitted then reroute any jumps to it and
643 // discard.
644 if (!DefaultBlock->getParent()) {
645 DefaultBlock->replaceAllUsesWith(NextBlock);
646 delete DefaultBlock;
647 }
Devang Patel51b09f22007-10-04 23:45:31 +0000648
Daniel Dunbar16f23572008-07-25 01:11:38 +0000649 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000650 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000651
Devang Patel51b09f22007-10-04 23:45:31 +0000652 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000653 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000654}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000655
Anders Carlssonce179ab2008-11-09 18:54:14 +0000656static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
657{
658 // FIXME: No need to create new std::string here, we could just make sure
659 // that we don't read past the end of the string data.
660 std::string str(S.getAsmString()->getStrData(),
661 S.getAsmString()->getByteLength());
662 const char *Start = str.c_str();
663
664 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
665 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000666 Failed = false;
667
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000668 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000669 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000670 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000671 if (IsSimple) {
672 while (*Start) {
673 switch (*Start) {
674 default:
675 Result += *Start;
676 break;
677 case '$':
678 Result += "$$";
679 break;
680 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000681 Start++;
682 }
683
684 return Result;
685 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000686
687 while (*Start) {
688 switch (*Start) {
689 default:
690 Result += *Start;
691 break;
692 case '$':
693 Result += "$$";
694 break;
695 case '%':
696 // Escaped character
697 Start++;
698 if (!*Start) {
699 // FIXME: This should be caught during Sema.
700 assert(0 && "Trailing '%' in asm string.");
701 }
702
703 char EscapedChar = *Start;
704 if (EscapedChar == '%') {
705 // Escaped percentage sign.
706 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000707 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000708 // Generate an unique ID.
709 Result += llvm::utostr(AsmCounter);
710 } else if (isdigit(EscapedChar)) {
711 // %n - Assembler operand n
712 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000713 unsigned long n = strtoul(Start, &End, 10);
714 if (Start == End) {
715 // FIXME: This should be caught during Sema.
716 assert(0 && "Missing operand!");
717 } else if (n >= NumOperands) {
718 // FIXME: This should be caught during Sema.
719 assert(0 && "Operand number out of range!");
720 }
721
722 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000723 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000724 } else if (isalpha(EscapedChar)) {
725 char *End;
726
727 unsigned long n = strtoul(Start + 1, &End, 10);
728 if (Start == End) {
729 // FIXME: This should be caught during Sema.
730 assert(0 && "Missing operand!");
731 } else if (n >= NumOperands) {
732 // FIXME: This should be caught during Sema.
733 assert(0 && "Operand number out of range!");
734 }
735
736 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000737 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000738 } else if (EscapedChar == '[') {
739 std::string SymbolicName;
740
741 Start++;
742
743 while (*Start && *Start != ']') {
744 SymbolicName += *Start;
745
746 Start++;
747 }
748
749 if (!Start) {
750 // FIXME: Should be caught by sema.
751 assert(0 && "Could not parse symbolic name");
752 }
753
754 assert(*Start == ']' && "Error parsing symbolic name");
755
756 int Index = -1;
757
758 // Check if this is an output operand.
759 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
760 if (S.getOutputName(i) == SymbolicName) {
761 Index = i;
762 break;
763 }
764 }
765
766 if (Index == -1) {
767 for (unsigned i = 0; i < S.getNumInputs(); i++) {
768 if (S.getInputName(i) == SymbolicName) {
769 Index = S.getNumOutputs() + i;
770 }
771 }
772 }
773
774 assert(Index != -1 && "Did not find right operand!");
775
776 Result += '$' + llvm::utostr(Index);
777
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000778 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000779 Failed = true;
780 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000781 }
782 }
783 Start++;
784 }
785
786 return Result;
787}
788
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000789static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000790 TargetInfo &Target,
791 const std::string *OutputNamesBegin = 0,
792 const std::string *OutputNamesEnd = 0)
793{
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000794 std::string Result;
795
796 while (*Constraint) {
797 switch (*Constraint) {
798 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000799 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000800 break;
801 // Ignore these
802 case '*':
803 case '?':
804 case '!':
805 break;
806 case 'g':
807 Result += "imr";
808 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000809 case '[': {
810 assert(OutputNamesBegin && OutputNamesEnd &&
811 "Must pass output names to constraints with a symbolic name");
812 unsigned Index;
813 bool result = Target.resolveSymbolicName(Constraint,
814 OutputNamesBegin,
815 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000816 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000817 Result += llvm::utostr(Index);
818 break;
819 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000820 }
821
822 Constraint++;
823 }
824
825 return Result;
826}
827
Anders Carlsson63471722009-01-11 19:32:54 +0000828llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
829 TargetInfo::ConstraintInfo Info,
830 const Expr *InputExpr,
831 std::string &ConstraintStr)
832{
833 llvm::Value *Arg;
834 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000835 !(Info & TargetInfo::CI_AllowsMemory)) {
836 const llvm::Type *Ty = ConvertType(InputExpr->getType());
837
838 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000839 Arg = EmitScalarExpr(InputExpr);
840 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000841 LValue Dest = EmitLValue(InputExpr);
842
843 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
844 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
845 Ty = llvm::IntegerType::get(Size);
846 Ty = llvm::PointerType::getUnqual(Ty);
847
848 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
849 } else {
850 Arg = Dest.getAddress();
851 ConstraintStr += '*';
852 }
Anders Carlsson63471722009-01-11 19:32:54 +0000853 }
854 } else {
855 LValue Dest = EmitLValue(InputExpr);
856 Arg = Dest.getAddress();
857 ConstraintStr += '*';
858 }
859
860 return Arg;
861}
862
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000863void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000864 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000865 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000866 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000867
868 if (Failed) {
869 ErrorUnsupported(&S, "asm string");
870 return;
871 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000872
873 std::string Constraints;
874
875 llvm::Value *ResultAddr = 0;
876 const llvm::Type *ResultType = llvm::Type::VoidTy;
877
878 std::vector<const llvm::Type*> ArgTypes;
879 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000880
881 // Keep track of inout constraints.
882 std::string InOutConstraints;
883 std::vector<llvm::Value*> InOutArgs;
884 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000885
886 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
887
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000888 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
889 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
890 S.getOutputConstraint(i)->getByteLength());
891
892 TargetInfo::ConstraintInfo Info;
893 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
894 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000895 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000896
Anders Carlsson03eb5432009-01-27 20:38:24 +0000897 OutputConstraintInfos.push_back(Info);
898
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000899 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000900 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000901
902 LValue Dest = EmitLValue(S.getOutputExpr(i));
903 const llvm::Type *DestValueType =
904 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
905
906 // If the first output operand is not a memory dest, we'll
907 // make it the return value.
908 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000909 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000910 ResultAddr = Dest.getAddress();
911 ResultType = DestValueType;
912 Constraints += "=" + OutputConstraint;
913 } else {
914 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000915 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000916 if (i != 0)
917 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000918 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000919 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000920 }
921
922 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000923 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000924
Anders Carlssonf39a4212008-02-05 20:01:53 +0000925 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000926 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000927
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000928 if (Info & TargetInfo::CI_AllowsRegister)
929 InOutConstraints += llvm::utostr(i);
930 else
931 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000932
Anders Carlssonf39a4212008-02-05 20:01:53 +0000933 InOutArgTypes.push_back(Arg->getType());
934 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000935 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000936 }
937
938 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
939
940 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
941 const Expr *InputExpr = S.getInputExpr(i);
942
943 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
944 S.getInputConstraint(i)->getByteLength());
945
946 TargetInfo::ConstraintInfo Info;
947 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +0000948 S.begin_output_names(),
949 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +0000950 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +0000951 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +0000952 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000953
954 if (i != 0 || S.getNumOutputs() > 0)
955 Constraints += ',';
956
957 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000958 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
959 S.begin_output_names(),
960 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000961
Anders Carlsson63471722009-01-11 19:32:54 +0000962 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000963
964 ArgTypes.push_back(Arg->getType());
965 Args.push_back(Arg);
966 Constraints += InputConstraint;
967 }
968
Anders Carlssonf39a4212008-02-05 20:01:53 +0000969 // Append the "input" part of inout constraints last.
970 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
971 ArgTypes.push_back(InOutArgTypes[i]);
972 Args.push_back(InOutArgs[i]);
973 }
974 Constraints += InOutConstraints;
975
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000976 // Clobbers
977 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
978 std::string Clobber(S.getClobber(i)->getStrData(),
979 S.getClobber(i)->getByteLength());
980
981 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
982
Anders Carlssonea041752008-02-06 00:11:32 +0000983 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000984 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000985
986 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000987 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000988 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000989 }
990
991 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +0000992 std::string MachineClobbers = Target.getClobbers();
993 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000994 if (!Constraints.empty())
995 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +0000996 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000997 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000998
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000999 const llvm::FunctionType *FTy =
1000 llvm::FunctionType::get(ResultType, ArgTypes, false);
1001
1002 llvm::InlineAsm *IA =
1003 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1004 S.isVolatile() || S.getNumOutputs() == 0);
1005 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001006 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001007 Builder.CreateStore(Result, ResultAddr);
1008}