blob: 1aa62e7e0368fa56f0bff4ba7127e2ffd709abe5 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "CodeGenFunction.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner614edd32009-03-05 08:04:57 +000018#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000020#include "llvm/ADT/StringExtras.h"
Anders Carlsson438ddd82008-12-12 05:52:00 +000021#include "llvm/InlineAsm.h"
22#include "llvm/Intrinsics.h"
Anders Carlssonfc12cfe2009-01-12 02:22:13 +000023#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
Daniel Dunbar6c81e562008-11-12 08:21:33 +000031void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlsson73007792009-02-13 08:11:52 +000032 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6c81e562008-11-12 08:21:33 +000033 DI->setLocation(S->getLocStart());
34 DI->EmitStopPoint(CurFn, Builder);
35 }
36}
37
Chris Lattner4b009652007-07-25 00:24:17 +000038void CodeGenFunction::EmitStmt(const Stmt *S) {
39 assert(S && "Null statement?");
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +000040
Daniel Dunbar6c81e562008-11-12 08:21:33 +000041 // Check if we can handle this without bothering to generate an
42 // insert point or debug info.
43 if (EmitSimpleStmt(S))
44 return;
45
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +000046 // If we happen to be at an unreachable point just create a dummy
47 // basic block to hold the code. We could change parts of irgen to
48 // simply not generate this code, but this situation is rare and
49 // probably not worth the effort.
50 // FIXME: Verify previous performance/effort claim.
51 EnsureInsertPoint();
Chris Lattner4b009652007-07-25 00:24:17 +000052
Daniel Dunbar6c81e562008-11-12 08:21:33 +000053 // Generate a stoppoint if we are emitting debug info.
54 EmitStopPoint(S);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000055
Chris Lattner4b009652007-07-25 00:24:17 +000056 switch (S->getStmtClass()) {
57 default:
Chris Lattner35055b82007-08-26 22:58:05 +000058 // Must be an expression in a stmt context. Emit the value (to get
59 // side-effects) and ignore the result.
Chris Lattner4b009652007-07-25 00:24:17 +000060 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner35055b82007-08-26 22:58:05 +000061 if (!hasAggregateLLVMType(E->getType()))
62 EmitScalarExpr(E);
Chris Lattnerde0908b2008-04-04 16:54:41 +000063 else if (E->getType()->isAnyComplexType())
Chris Lattner35055b82007-08-26 22:58:05 +000064 EmitComplexExpr(E);
65 else
66 EmitAggExpr(E, 0, false);
Chris Lattner4b009652007-07-25 00:24:17 +000067 } else {
Daniel Dunbar9503b782008-08-16 00:56:44 +000068 ErrorUnsupported(S, "statement");
Chris Lattner4b009652007-07-25 00:24:17 +000069 }
70 break;
Daniel Dunbar879788d2008-08-04 16:51:22 +000071 case Stmt::IndirectGotoStmtClass:
72 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Chris Lattner4b009652007-07-25 00:24:17 +000073
74 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
75 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
76 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
77 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
78
79 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
80 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar66e021e2008-10-02 18:02:06 +000081
Devang Patele58e0802007-10-04 23:45:31 +000082 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000083 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000084
85 case Stmt::ObjCAtTryStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000086 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
87 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000088 case Stmt::ObjCAtCatchStmtClass:
Anders Carlsson75d86732008-09-11 09:15:33 +000089 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
90 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000091 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000092 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar5e105892008-08-23 10:51:21 +000093 break;
94 case Stmt::ObjCAtThrowStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000095 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +000096 break;
97 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattnerdd978702008-11-15 21:26:17 +000098 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +000099 break;
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000100 case Stmt::ObjCForCollectionStmtClass:
101 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +0000102 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000103 }
104}
105
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000106bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
107 switch (S->getStmtClass()) {
108 default: return false;
109 case Stmt::NullStmtClass: break;
110 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
111 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
112 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
113 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
114 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
115 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
116 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
117 }
118
119 return true;
120}
121
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000122/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
123/// this captures the expression result of the last sub-statement and returns it
124/// (for use by the statement expression extension).
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000125RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
126 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner614edd32009-03-05 08:04:57 +0000127 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
128 "LLVM IR generation of compound statement ('{}')");
129
Anders Carlsson73007792009-02-13 08:11:52 +0000130 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000131 if (DI) {
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000132 EnsureInsertPoint();
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000133 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000134 DI->EmitRegionStart(CurFn, Builder);
135 }
136
Anders Carlsson883fa552009-02-07 23:50:39 +0000137 // Keep track of the current cleanup stack depth.
138 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlssond5c42342009-02-09 20:23:40 +0000139 bool OldDidCallStackSave = DidCallStackSave;
Anders Carlsson03650a52009-02-22 18:44:21 +0000140 DidCallStackSave = false;
Anders Carlssond5c42342009-02-09 20:23:40 +0000141
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000142 for (CompoundStmt::const_body_iterator I = S.body_begin(),
143 E = S.body_end()-GetLast; I != E; ++I)
Chris Lattner4b009652007-07-25 00:24:17 +0000144 EmitStmt(*I);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000145
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000146 if (DI) {
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000147 EnsureInsertPoint();
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000148 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000149 DI->EmitRegionEnd(CurFn, Builder);
150 }
151
Anders Carlsson438ddd82008-12-12 05:52:00 +0000152 RValue RV;
153 if (!GetLast)
154 RV = RValue::get(0);
155 else {
156 // We have to special case labels here. They are statements, but when put
157 // at the end of a statement expression, they yield the value of their
158 // subexpression. Handle this by walking through all labels we encounter,
159 // emitting them before we evaluate the subexpr.
160 const Stmt *LastStmt = S.body_back();
161 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
162 EmitLabel(*LS);
163 LastStmt = LS->getSubStmt();
164 }
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000165
Anders Carlsson438ddd82008-12-12 05:52:00 +0000166 EnsureInsertPoint();
167
168 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
169 }
170
Anders Carlssond5c42342009-02-09 20:23:40 +0000171 DidCallStackSave = OldDidCallStackSave;
172
Anders Carlsson883fa552009-02-07 23:50:39 +0000173 EmitCleanupBlocks(CleanupStackDepth);
174
Anders Carlsson438ddd82008-12-12 05:52:00 +0000175 return RV;
Chris Lattner4b009652007-07-25 00:24:17 +0000176}
177
Daniel Dunbare2202612008-11-13 01:24:05 +0000178void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000179 // Fall out of the current block (if necessary).
180 EmitBranch(BB);
Daniel Dunbare2202612008-11-13 01:24:05 +0000181
182 if (IsFinished && BB->use_empty()) {
183 delete BB;
184 return;
185 }
186
Anders Carlssone7de3522009-02-08 00:16:35 +0000187 // If necessary, associate the block with the cleanup stack size.
188 if (!CleanupEntries.empty()) {
Anders Carlsson7a56d8c2009-02-10 22:50:24 +0000189 // Check if the basic block has already been inserted.
190 BlockScopeMap::iterator I = BlockScopes.find(BB);
191 if (I != BlockScopes.end()) {
192 assert(I->second == CleanupEntries.size() - 1);
193 } else {
194 BlockScopes[BB] = CleanupEntries.size() - 1;
195 CleanupEntries.back().Blocks.push_back(BB);
196 }
Anders Carlssone7de3522009-02-08 00:16:35 +0000197 }
198
Chris Lattner4b009652007-07-25 00:24:17 +0000199 CurFn->getBasicBlockList().push_back(BB);
200 Builder.SetInsertPoint(BB);
201}
202
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000203void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
204 // Emit a branch from the current block to the target one if this
205 // was a real block. If this was just a fall-through block after a
206 // terminator, don't emit it.
207 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
208
209 if (!CurBB || CurBB->getTerminator()) {
210 // If there is no insert point or the previous block is already
211 // terminated, don't touch it.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000212 } else {
213 // Otherwise, create a fall-through branch.
214 Builder.CreateBr(Target);
215 }
Daniel Dunbarc55b7c52008-11-11 22:06:59 +0000216
217 Builder.ClearInsertionPoint();
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000218}
219
Mike Stump7e39f182009-02-08 09:22:19 +0000220void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonc2d37152009-02-10 06:07:49 +0000221 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner09cee852008-07-26 20:23:23 +0000222}
223
224
225void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
226 EmitLabel(S);
Chris Lattner4b009652007-07-25 00:24:17 +0000227 EmitStmt(S.getSubStmt());
228}
229
230void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar6c81e562008-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);
Mike Stump88ad9112009-02-07 12:52:26 +0000236
Anders Carlssonde6fd8c2009-02-09 20:31:03 +0000237 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Chris Lattner4b009652007-07-25 00:24:17 +0000238}
239
Daniel Dunbar879788d2008-08-04 16:51:22 +0000240void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
241 // Emit initial switch which will be patched up later by
242 // EmitIndirectSwitches(). We need a default dest, so we use the
243 // current BB, but this is overwritten.
244 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
245 llvm::Type::Int32Ty,
246 "addr");
247 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
248 IndirectSwitches.push_back(I);
249
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000250 // Clear the insertion point to indicate we are in unreachable code.
251 Builder.ClearInsertionPoint();
Daniel Dunbar879788d2008-08-04 16:51:22 +0000252}
253
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000254void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000255 // C99 6.8.4.1: The first substatement is executed if the expression compares
256 // unequal to 0. The condition must be a scalar type.
Chris Lattner4b009652007-07-25 00:24:17 +0000257
Chris Lattner1875ba22008-11-12 07:46:33 +0000258 // If the condition constant folds and can be elided, try to avoid emitting
259 // the condition and the dead arm of the if/else.
Chris Lattner3d6606b2008-11-12 08:04:58 +0000260 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000261 // Figure out which block (then or else) is executed.
262 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner1875ba22008-11-12 07:46:33 +0000263 if (Cond == -1) // Condition false?
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000264 std::swap(Executed, Skipped);
Chris Lattner1875ba22008-11-12 07:46:33 +0000265
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000266 // If the skipped block has no labels in it, just emit the executed block.
267 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner1875ba22008-11-12 07:46:33 +0000268 if (!ContainsLabel(Skipped)) {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000269 if (Executed)
270 EmitStmt(Executed);
271 return;
272 }
273 }
Chris Lattner1875ba22008-11-12 07:46:33 +0000274
275 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
276 // the conditional branch.
Daniel Dunbarc70a5df2008-11-13 00:47:57 +0000277 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
278 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
279 llvm::BasicBlock *ElseBlock = ContBlock;
Chris Lattner4b009652007-07-25 00:24:17 +0000280 if (S.getElse())
Daniel Dunbarc70a5df2008-11-13 00:47:57 +0000281 ElseBlock = createBasicBlock("if.else");
282 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000283
284 // Emit the 'then' code.
285 EmitBlock(ThenBlock);
286 EmitStmt(S.getThen());
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000287 EmitBranch(ContBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000288
289 // Emit the 'else' code if present.
290 if (const Stmt *Else = S.getElse()) {
291 EmitBlock(ElseBlock);
292 EmitStmt(Else);
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000293 EmitBranch(ContBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000294 }
295
296 // Emit the continuation block for code after the if.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000297 EmitBlock(ContBlock, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000298}
299
300void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
301 // Emit the header for the loop, insert it, which will create an uncond br to
302 // it.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000303 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Chris Lattner4b009652007-07-25 00:24:17 +0000304 EmitBlock(LoopHeader);
Mike Stumpcfdf4c22009-02-07 18:08:12 +0000305
306 // Create an exit block for when the condition fails, create a block for the
307 // body of the loop.
308 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
309 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
310
311 // Store the blocks to use for break and continue.
Anders Carlsson7c314902009-02-10 05:52:02 +0000312 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Chris Lattner4b009652007-07-25 00:24:17 +0000313
Mike Stump80225e12009-02-07 17:18:33 +0000314 // Evaluate the conditional in the while header. C99 6.8.5.1: The
315 // evaluation of the controlling expression takes place before each
316 // execution of the loop body.
Chris Lattner4b009652007-07-25 00:24:17 +0000317 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel706f8442007-10-09 20:51:27 +0000318
319 // while(1) is common, avoid extra exit blocks. Be sure
Chris Lattner4b009652007-07-25 00:24:17 +0000320 // to correctly handle break/continue though.
Devang Patel706f8442007-10-09 20:51:27 +0000321 bool EmitBoolCondBranch = true;
322 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
323 if (C->isOne())
324 EmitBoolCondBranch = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000325
Chris Lattner4b009652007-07-25 00:24:17 +0000326 // As long as the condition is true, go to the loop body.
Devang Patel706f8442007-10-09 20:51:27 +0000327 if (EmitBoolCondBranch)
328 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner3d6606b2008-11-12 08:04:58 +0000329
Chris Lattner4b009652007-07-25 00:24:17 +0000330 // Emit the loop body.
331 EmitBlock(LoopBody);
332 EmitStmt(S.getBody());
333
Anders Carlsson7c314902009-02-10 05:52:02 +0000334 BreakContinueStack.pop_back();
Chris Lattner4b009652007-07-25 00:24:17 +0000335
336 // Cycle to the condition.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000337 EmitBranch(LoopHeader);
Chris Lattner4b009652007-07-25 00:24:17 +0000338
339 // Emit the exit block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000340 EmitBlock(ExitBlock, true);
Devang Patel706f8442007-10-09 20:51:27 +0000341
342 // If LoopHeader is a simple forwarding block then eliminate it.
343 if (!EmitBoolCondBranch
344 && &LoopHeader->front() == LoopHeader->getTerminator()) {
345 LoopHeader->replaceAllUsesWith(LoopBody);
346 LoopHeader->getTerminator()->eraseFromParent();
347 LoopHeader->eraseFromParent();
348 }
Chris Lattner4b009652007-07-25 00:24:17 +0000349}
350
351void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000352 // Emit the body for the loop, insert it, which will create an uncond br to
353 // it.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000354 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
355 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Chris Lattner4b009652007-07-25 00:24:17 +0000356 EmitBlock(LoopBody);
357
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000358 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattner4b009652007-07-25 00:24:17 +0000359
360 // Store the blocks to use for break and continue.
Anders Carlsson7c314902009-02-10 05:52:02 +0000361 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Chris Lattner4b009652007-07-25 00:24:17 +0000362
363 // Emit the body of the loop into the block.
364 EmitStmt(S.getBody());
365
Anders Carlsson7c314902009-02-10 05:52:02 +0000366 BreakContinueStack.pop_back();
Chris Lattner4b009652007-07-25 00:24:17 +0000367
368 EmitBlock(DoCond);
369
370 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
371 // after each execution of the loop body."
372
373 // Evaluate the conditional in the while header.
374 // C99 6.8.5p2/p4: The first substatement is executed if the expression
375 // compares unequal to 0. The condition must be a scalar type.
376 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel716d02c2007-10-09 20:33:39 +0000377
378 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
379 // to correctly handle break/continue though.
380 bool EmitBoolCondBranch = true;
381 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
382 if (C->isZero())
383 EmitBoolCondBranch = false;
384
Chris Lattner4b009652007-07-25 00:24:17 +0000385 // As long as the condition is true, iterate the loop.
Devang Patel716d02c2007-10-09 20:33:39 +0000386 if (EmitBoolCondBranch)
387 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Chris Lattner4b009652007-07-25 00:24:17 +0000388
389 // Emit the exit block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000390 EmitBlock(AfterDo, true);
Devang Patel716d02c2007-10-09 20:33:39 +0000391
392 // If DoCond is a simple forwarding block then eliminate it.
393 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
394 DoCond->replaceAllUsesWith(AfterDo);
395 DoCond->getTerminator()->eraseFromParent();
396 DoCond->eraseFromParent();
397 }
Chris Lattner4b009652007-07-25 00:24:17 +0000398}
399
400void CodeGenFunction::EmitForStmt(const ForStmt &S) {
401 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
402 // which contains a continue/break?
Chris Lattner4b009652007-07-25 00:24:17 +0000403
404 // Evaluate the first part before the loop.
405 if (S.getInit())
406 EmitStmt(S.getInit());
407
408 // Start the loop with a block that tests the condition.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000409 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
410 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattner4b009652007-07-25 00:24:17 +0000411
412 EmitBlock(CondBlock);
413
Mike Stump024c71f2009-02-07 20:14:12 +0000414 // Evaluate the condition if present. If not, treat it as a
415 // non-zero-constant according to 6.8.5.3p2, aka, true.
Chris Lattner4b009652007-07-25 00:24:17 +0000416 if (S.getCond()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000417 // As long as the condition is true, iterate the loop.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000418 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000419
420 // C99 6.8.5p2/p4: The first substatement is executed if the expression
421 // compares unequal to 0. The condition must be a scalar type.
422 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
423
Chris Lattner4b009652007-07-25 00:24:17 +0000424 EmitBlock(ForBody);
425 } else {
426 // Treat it as a non-zero constant. Don't even create a new block for the
427 // body, just fall into it.
428 }
429
430 // If the for loop doesn't have an increment we can just use the
431 // condition as the continue block.
432 llvm::BasicBlock *ContinueBlock;
433 if (S.getInc())
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000434 ContinueBlock = createBasicBlock("for.inc");
Chris Lattner4b009652007-07-25 00:24:17 +0000435 else
436 ContinueBlock = CondBlock;
437
438 // Store the blocks to use for break and continue.
Anders Carlsson7c314902009-02-10 05:52:02 +0000439 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stumpa1ac4772009-02-07 23:02:10 +0000440
Chris Lattner4b009652007-07-25 00:24:17 +0000441 // If the condition is true, execute the body of the for stmt.
442 EmitStmt(S.getBody());
443
Anders Carlsson7c314902009-02-10 05:52:02 +0000444 BreakContinueStack.pop_back();
Chris Lattner4b009652007-07-25 00:24:17 +0000445
Chris Lattner4b009652007-07-25 00:24:17 +0000446 // If there is an increment, emit it next.
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000447 if (S.getInc()) {
448 EmitBlock(ContinueBlock);
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000449 EmitStmt(S.getInc());
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000450 }
Chris Lattner4b009652007-07-25 00:24:17 +0000451
452 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000453 EmitBranch(CondBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000454
455 // Emit the fall-through block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000456 EmitBlock(AfterFor, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000457}
458
Daniel Dunbare856ac22008-09-24 04:00:38 +0000459void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
460 if (RV.isScalar()) {
461 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
462 } else if (RV.isAggregate()) {
463 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
464 } else {
465 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
466 }
Anders Carlssonde6fd8c2009-02-09 20:31:03 +0000467 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbare856ac22008-09-24 04:00:38 +0000468}
469
Chris Lattner4b009652007-07-25 00:24:17 +0000470/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
471/// if the function returns void, or may be missing one if the function returns
472/// non-void. Fun stuff :).
473void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000474 // Emit the result value, even if unused, to evalute the side effects.
475 const Expr *RV = S.getRetValue();
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000476
477 // FIXME: Clean this up by using an LValue for ReturnTemp,
478 // EmitStoreThroughLValue, and EmitAnyExpr.
479 if (!ReturnValue) {
480 // Make sure not to return anything, but evaluate the expression
481 // for side effects.
482 if (RV)
Eli Friedman56977312008-05-22 01:22:33 +0000483 EmitAnyExpr(RV);
Chris Lattner4b009652007-07-25 00:24:17 +0000484 } else if (RV == 0) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000485 // Do nothing (return value is left uninitialized)
Chris Lattner74b93032007-08-26 07:14:44 +0000486 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000487 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattnerde0908b2008-04-04 16:54:41 +0000488 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000489 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000490 } else {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000491 EmitAggExpr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000492 }
Eli Friedman56977312008-05-22 01:22:33 +0000493
Anders Carlssonde6fd8c2009-02-09 20:31:03 +0000494 EmitBranchThroughCleanup(ReturnBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000495}
496
497void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneka6b2b272008-10-06 18:42:27 +0000498 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
499 I != E; ++I)
500 EmitDecl(**I);
Chris Lattner4b009652007-07-25 00:24:17 +0000501}
502
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000503void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000504 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
505
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000506 // If this code is reachable then emit a stop point (if generating
507 // debug info). We have to do this ourselves because we are on the
508 // "simple" statement path.
509 if (HaveInsertPoint())
510 EmitStopPoint(&S);
Mike Stump7e39f182009-02-08 09:22:19 +0000511
Chris Lattner4b009652007-07-25 00:24:17 +0000512 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlssonde6fd8c2009-02-09 20:31:03 +0000513 EmitBranchThroughCleanup(Block);
Chris Lattner4b009652007-07-25 00:24:17 +0000514}
515
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000516void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000517 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
518
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000519 // If this code is reachable then emit a stop point (if generating
520 // debug info). We have to do this ourselves because we are on the
521 // "simple" statement path.
522 if (HaveInsertPoint())
523 EmitStopPoint(&S);
Mike Stump7e39f182009-02-08 09:22:19 +0000524
Chris Lattner4b009652007-07-25 00:24:17 +0000525 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlssonde6fd8c2009-02-09 20:31:03 +0000526 EmitBranchThroughCleanup(Block);
Chris Lattner4b009652007-07-25 00:24:17 +0000527}
Devang Patele58e0802007-10-04 23:45:31 +0000528
Devang Patel347ca322007-10-08 20:57:48 +0000529/// EmitCaseStmtRange - If case statement range is not too big then
530/// add multiple cases to switch instruction, one for each value within
531/// the range. If range is too big then emit "if" condition check.
532void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000533 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patel347ca322007-10-08 20:57:48 +0000534
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000535 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
536 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000537
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000538 // Emit the code for this case. We do this first to make sure it is
539 // properly chained from our predecessor before generating the
540 // switch machinery to enter this block.
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000541 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000542 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
543 EmitStmt(S.getSubStmt());
544
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000545 // If range is empty, do nothing.
546 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
547 return;
Devang Patel347ca322007-10-08 20:57:48 +0000548
549 llvm::APInt Range = RHS - LHS;
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000550 // FIXME: parameters such as this should not be hardcoded.
Devang Patel347ca322007-10-08 20:57:48 +0000551 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
552 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000553 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patelcf9dbf22007-10-05 20:54:07 +0000554 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
555 LHS++;
556 }
Devang Patel347ca322007-10-08 20:57:48 +0000557 return;
558 }
559
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000560 // The range is too big. Emit "if" condition into a new block,
561 // making sure to save and restore the current insertion point.
562 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patelcf9dbf22007-10-05 20:54:07 +0000563
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000564 // Push this test onto the chain of range checks (which terminates
565 // in the default basic block). The switch's default will be changed
566 // to the top of this chain after switch emission is complete.
567 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar72f96552008-11-11 02:29:29 +0000568 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patel347ca322007-10-08 20:57:48 +0000569
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000570 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
571 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000572
573 // Emit range check.
574 llvm::Value *Diff =
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000575 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
576 "tmp");
Devang Patel347ca322007-10-08 20:57:48 +0000577 llvm::Value *Cond =
578 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
579 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
580
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000581 // Restore the appropriate insertion point.
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000582 if (RestoreBB)
583 Builder.SetInsertPoint(RestoreBB);
584 else
585 Builder.ClearInsertionPoint();
Devang Patel347ca322007-10-08 20:57:48 +0000586}
587
588void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
589 if (S.getRHS()) {
590 EmitCaseStmtRange(S);
591 return;
592 }
593
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000594 EmitBlock(createBasicBlock("sw.bb"));
Devang Patel347ca322007-10-08 20:57:48 +0000595 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000596 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar72f96552008-11-11 02:29:29 +0000597 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Chris Lattner5137a302009-03-04 04:46:18 +0000598
599 // Recursively emitting the statement is acceptable, but is not wonderful for
600 // code where we have many case statements nested together, i.e.:
601 // case 1:
602 // case 2:
603 // case 3: etc.
604 // Handling this recursively will create a new block for each case statement
605 // that falls through to the next case which is IR intensive. It also causes
606 // deep recursion which can run into stack depth limitations. Handle
607 // sequential non-range case statements specially.
608 const CaseStmt *CurCase = &S;
609 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
610
611 // Otherwise, iteratively add consequtive cases to this switch stmt.
612 while (NextCase && NextCase->getRHS() == 0) {
613 CurCase = NextCase;
614 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
615 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
616
617 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
618 }
619
620 // Normal default recursion for non-cases.
621 EmitStmt(CurCase->getSubStmt());
Devang Patele58e0802007-10-04 23:45:31 +0000622}
623
624void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000625 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar72f96552008-11-11 02:29:29 +0000626 assert(DefaultBlock->empty() &&
627 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000628 EmitBlock(DefaultBlock);
Devang Patele58e0802007-10-04 23:45:31 +0000629 EmitStmt(S.getSubStmt());
630}
631
632void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
633 llvm::Value *CondV = EmitScalarExpr(S.getCond());
634
635 // Handle nested switch statements.
636 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000637 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000638
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000639 // Create basic block to hold stuff that comes after switch
640 // statement. We also need to create a default block now so that
641 // explicit case ranges tests can have a place to jump to on
642 // failure.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000643 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
644 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000645 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
646 CaseRangeBlock = DefaultBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000647
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000648 // Clear the insertion point to indicate we are in unreachable code.
649 Builder.ClearInsertionPoint();
Eli Friedman51eaf1b2008-05-12 16:08:04 +0000650
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000651 // All break statements jump to NextBlock. If BreakContinueStack is non empty
652 // then reuse last ContinueBlock.
Anders Carlsson7c314902009-02-10 05:52:02 +0000653 llvm::BasicBlock *ContinueBlock = 0;
654 if (!BreakContinueStack.empty())
Devang Patele58e0802007-10-04 23:45:31 +0000655 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlsson7c314902009-02-10 05:52:02 +0000656
Mike Stumpa1ac4772009-02-07 23:02:10 +0000657 // Ensure any vlas created between there and here, are undone
Anders Carlsson7c314902009-02-10 05:52:02 +0000658 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patele58e0802007-10-04 23:45:31 +0000659
660 // Emit switch body.
661 EmitStmt(S.getBody());
Anders Carlsson7c314902009-02-10 05:52:02 +0000662
663 BreakContinueStack.pop_back();
Devang Patele58e0802007-10-04 23:45:31 +0000664
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000665 // Update the default block in case explicit case range tests have
666 // been chained on top.
667 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000668
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000669 // If a default was never emitted then reroute any jumps to it and
670 // discard.
671 if (!DefaultBlock->getParent()) {
672 DefaultBlock->replaceAllUsesWith(NextBlock);
673 delete DefaultBlock;
674 }
Devang Patele58e0802007-10-04 23:45:31 +0000675
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000676 // Emit continuation.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000677 EmitBlock(NextBlock, true);
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000678
Devang Patele58e0802007-10-04 23:45:31 +0000679 SwitchInsn = SavedSwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000680 CaseRangeBlock = SavedCRBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000681}
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000682
Chris Lattner504fba22009-03-10 04:38:46 +0000683/// ConvertAsmString - Convert the GNU-style asm string to the LLVM-style asm
684/// string.
685static std::string ConvertAsmString(const AsmStmt& S, bool &Failed) {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000686 Failed = false;
Chris Lattner504fba22009-03-10 04:38:46 +0000687
688 const char *StrStart = S.getAsmString()->getStrData();
689 const char *StrEnd = StrStart + S.getAsmString()->getByteLength();
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000690
Chris Lattner504fba22009-03-10 04:38:46 +0000691 // "Simple" inline asms have no constraints or operands, just convert the asm
692 // string to escape $'s.
693 if (S.isSimple()) {
694 std::string Result;
695 for (; StrStart != StrEnd; ++StrStart) {
696 switch (*StrStart) {
Anders Carlsson52234522008-02-05 23:18:57 +0000697 case '$':
698 Result += "$$";
699 break;
Chris Lattner504fba22009-03-10 04:38:46 +0000700 default:
701 Result += *StrStart;
702 break;
Anders Carlsson52234522008-02-05 23:18:57 +0000703 }
Anders Carlsson52234522008-02-05 23:18:57 +0000704 }
Anders Carlsson52234522008-02-05 23:18:57 +0000705 return Result;
706 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000707
Chris Lattner504fba22009-03-10 04:38:46 +0000708 std::string Result;
Chris Lattner504fba22009-03-10 04:38:46 +0000709
710 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
711
Chris Lattner0e46afb2009-03-10 06:11:34 +0000712 while (1) {
713 // Done with the string?
714 if (StrStart == StrEnd)
715 return Result;
716
717 char CurChar = *StrStart++;
718 if (CurChar == '$') {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000719 Result += "$$";
Chris Lattner0e46afb2009-03-10 06:11:34 +0000720 continue;
721 } else if (CurChar != '%') {
722 Result += CurChar;
723 continue;
724 }
725
726 // Escaped "%" character in asm string.
727 // FIXME: This should be caught during Sema.
728 assert(StrStart != StrEnd && "Trailing '%' in asm string.");
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000729
Chris Lattner0e46afb2009-03-10 06:11:34 +0000730 char EscapedChar = *StrStart++;
731 if (EscapedChar == '%') { // %% -> %
732 // Escaped percentage sign.
733 Result += '%';
734 continue;
735 }
736
737 if (EscapedChar == '=') { // %= -> Generate an unique ID.
738 Result += "${:uid}";
739 continue;
740 }
741
Chris Lattnerd86eb962009-03-10 06:38:02 +0000742 // Handle %x4 and %x[foo] by capturing x as the modifier character.
743 char Modifier = '\0';
744 if (isalpha(EscapedChar)) {
745 Modifier = EscapedChar;
746 EscapedChar = *StrStart++;
747 }
748
Chris Lattner0e46afb2009-03-10 06:11:34 +0000749 if (isdigit(EscapedChar)) {
750 // %n - Assembler operand n
751 char *End;
752 unsigned long N = strtoul(StrStart-1, &End, 10);
753 assert(End != StrStart-1 && "We know that EscapedChar is a digit!");
Chris Lattnerd86eb962009-03-10 06:38:02 +0000754 StrStart = End;
Chris Lattner0e46afb2009-03-10 06:11:34 +0000755
756 // FIXME: This should be caught during Sema.
757 assert(N < NumOperands && "Operand number out of range!");
758
Chris Lattnerd86eb962009-03-10 06:38:02 +0000759 if (Modifier == '\0')
760 Result += '$' + llvm::utostr(N);
761 else
762 Result += "${" + llvm::utostr(N) + ':' + Modifier + '}';
Chris Lattner0e46afb2009-03-10 06:11:34 +0000763 continue;
764 }
765
766 // Handle %[foo], a symbolic operand reference.
767 if (EscapedChar == '[') {
768 const char *NameEnd = (const char*)memchr(StrStart, ']', StrEnd-StrStart);
769 // FIXME: Should be caught by sema.
Chris Lattner20ac04c2009-03-10 06:33:24 +0000770 // FIXME: Does sema catch multiple operands with the same name?
Chris Lattner0e46afb2009-03-10 06:11:34 +0000771 assert(NameEnd != 0 && "Could not parse symbolic name");
Chris Lattner0e46afb2009-03-10 06:11:34 +0000772 std::string SymbolicName(StrStart, NameEnd);
Chris Lattner0e46afb2009-03-10 06:11:34 +0000773 StrStart = NameEnd+1;
774
Chris Lattnerd86eb962009-03-10 06:38:02 +0000775 int N = S.getNamedOperand(SymbolicName);
776 assert(N != -1 && "FIXME: Catch in Sema.");
Chris Lattner20ac04c2009-03-10 06:33:24 +0000777
Chris Lattnerd86eb962009-03-10 06:38:02 +0000778 if (Modifier == '\0')
779 Result += '$' + llvm::utostr(N);
780 else
781 Result += "${" + llvm::utostr(N) + ':' + Modifier + '}';
Chris Lattner0e46afb2009-03-10 06:11:34 +0000782 continue;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000783 }
Chris Lattner0e46afb2009-03-10 06:11:34 +0000784
785 Failed = true;
786 return "";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000787 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000788}
789
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000790static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson9363d792009-01-18 02:06:20 +0000791 TargetInfo &Target,
792 const std::string *OutputNamesBegin = 0,
Chris Lattner8c23f972009-03-10 05:39:21 +0000793 const std::string *OutputNamesEnd = 0) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000794 std::string Result;
795
796 while (*Constraint) {
797 switch (*Constraint) {
798 default:
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000799 Result += Target.convertConstraint(*Constraint);
Anders Carlssonaf6a6c22008-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 Carlsson9363d792009-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 Lattner64e8d332009-01-21 07:35:26 +0000816 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson9363d792009-01-18 02:06:20 +0000817 Result += llvm::utostr(Index);
818 break;
819 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000820 }
821
822 Constraint++;
823 }
824
825 return Result;
826}
827
Anders Carlsson054f9962009-01-11 19:32:54 +0000828llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
829 TargetInfo::ConstraintInfo Info,
830 const Expr *InputExpr,
Chris Lattner8c23f972009-03-10 05:39:21 +0000831 std::string &ConstraintStr) {
Anders Carlsson054f9962009-01-11 19:32:54 +0000832 llvm::Value *Arg;
833 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonfc12cfe2009-01-12 02:22:13 +0000834 !(Info & TargetInfo::CI_AllowsMemory)) {
835 const llvm::Type *Ty = ConvertType(InputExpr->getType());
836
837 if (Ty->isSingleValueType()) {
Anders Carlsson054f9962009-01-11 19:32:54 +0000838 Arg = EmitScalarExpr(InputExpr);
839 } else {
Anders Carlssonfc12cfe2009-01-12 02:22:13 +0000840 LValue Dest = EmitLValue(InputExpr);
841
842 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
843 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
844 Ty = llvm::IntegerType::get(Size);
845 Ty = llvm::PointerType::getUnqual(Ty);
846
847 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
848 } else {
849 Arg = Dest.getAddress();
850 ConstraintStr += '*';
851 }
Anders Carlsson054f9962009-01-11 19:32:54 +0000852 }
853 } else {
854 LValue Dest = EmitLValue(InputExpr);
855 Arg = Dest.getAddress();
856 ConstraintStr += '*';
857 }
858
859 return Arg;
860}
861
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000862void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000863 bool Failed;
Chris Lattner504fba22009-03-10 04:38:46 +0000864 std::string AsmString = ConvertAsmString(S, Failed);
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000865
866 if (Failed) {
867 ErrorUnsupported(&S, "asm string");
868 return;
869 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000870
871 std::string Constraints;
872
873 llvm::Value *ResultAddr = 0;
874 const llvm::Type *ResultType = llvm::Type::VoidTy;
875
876 std::vector<const llvm::Type*> ArgTypes;
877 std::vector<llvm::Value*> Args;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000878
879 // Keep track of inout constraints.
880 std::string InOutConstraints;
881 std::vector<llvm::Value*> InOutArgs;
882 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssondd3a4fe2009-01-27 20:38:24 +0000883
884 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
885
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000886 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattnere8625112009-03-10 04:59:06 +0000887 std::string OutputConstraint(S.getOutputConstraint(i));
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000888
889 TargetInfo::ConstraintInfo Info;
890 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
891 Info);
Chris Lattner94c4b2d2008-10-12 00:31:50 +0000892 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000893
Anders Carlssondd3a4fe2009-01-27 20:38:24 +0000894 OutputConstraintInfos.push_back(Info);
895
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000896 // Simplify the output constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000897 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000898
899 LValue Dest = EmitLValue(S.getOutputExpr(i));
900 const llvm::Type *DestValueType =
901 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
902
903 // If the first output operand is not a memory dest, we'll
904 // make it the return value.
905 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohman377ba9f2008-05-22 22:12:56 +0000906 DestValueType->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000907 ResultAddr = Dest.getAddress();
908 ResultType = DestValueType;
909 Constraints += "=" + OutputConstraint;
910 } else {
911 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlsson78725072008-02-05 16:57:38 +0000912 Args.push_back(Dest.getAddress());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000913 if (i != 0)
914 Constraints += ',';
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000915 Constraints += "=*";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000916 Constraints += OutputConstraint;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000917 }
918
919 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000920 InOutConstraints += ',';
Anders Carlsson054f9962009-01-11 19:32:54 +0000921
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000922 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson054f9962009-01-11 19:32:54 +0000923 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000924
Anders Carlsson7ff60572009-01-11 21:23:27 +0000925 if (Info & TargetInfo::CI_AllowsRegister)
926 InOutConstraints += llvm::utostr(i);
927 else
928 InOutConstraints += OutputConstraint;
Anders Carlssonc180e8e2009-01-11 19:46:50 +0000929
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000930 InOutArgTypes.push_back(Arg->getType());
931 InOutArgs.push_back(Arg);
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000932 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000933 }
934
935 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
936
937 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
938 const Expr *InputExpr = S.getInputExpr(i);
939
Chris Lattnere8625112009-03-10 04:59:06 +0000940 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000941
942 TargetInfo::ConstraintInfo Info;
943 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson7b49cec2009-01-17 23:36:15 +0000944 S.begin_output_names(),
945 S.end_output_names(),
Anders Carlssondd3a4fe2009-01-27 20:38:24 +0000946 &OutputConstraintInfos[0],
Chris Lattner64e8d332009-01-21 07:35:26 +0000947 Info); result=result;
Anders Carlssonb5c85692009-01-18 01:56:57 +0000948 assert(result && "Failed to parse input constraint");
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000949
950 if (i != 0 || S.getNumOutputs() > 0)
951 Constraints += ',';
952
953 // Simplify the input constraint.
Anders Carlsson9363d792009-01-18 02:06:20 +0000954 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
955 S.begin_output_names(),
956 S.end_output_names());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000957
Anders Carlsson054f9962009-01-11 19:32:54 +0000958 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000959
960 ArgTypes.push_back(Arg->getType());
961 Args.push_back(Arg);
962 Constraints += InputConstraint;
963 }
964
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000965 // Append the "input" part of inout constraints last.
966 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
967 ArgTypes.push_back(InOutArgTypes[i]);
968 Args.push_back(InOutArgs[i]);
969 }
970 Constraints += InOutConstraints;
971
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000972 // Clobbers
973 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
974 std::string Clobber(S.getClobber(i)->getStrData(),
975 S.getClobber(i)->getByteLength());
976
977 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
978
Anders Carlsson74385982008-02-06 00:11:32 +0000979 if (i != 0 || NumConstraints != 0)
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000980 Constraints += ',';
Anders Carlsson74385982008-02-06 00:11:32 +0000981
982 Constraints += "~{";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000983 Constraints += Clobber;
Anders Carlsson74385982008-02-06 00:11:32 +0000984 Constraints += '}';
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000985 }
986
987 // Add machine specific clobbers
Eli Friedmand5e9d1e2008-12-21 01:15:32 +0000988 std::string MachineClobbers = Target.getClobbers();
989 if (!MachineClobbers.empty()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000990 if (!Constraints.empty())
991 Constraints += ',';
Eli Friedmand5e9d1e2008-12-21 01:15:32 +0000992 Constraints += MachineClobbers;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000993 }
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000994
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000995 const llvm::FunctionType *FTy =
996 llvm::FunctionType::get(ResultType, ArgTypes, false);
997
998 llvm::InlineAsm *IA =
999 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1000 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlsson8e379f22009-03-02 19:58:15 +00001001 llvm::CallInst *Result
1002 = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
1003 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1004
Eli Friedman2e630542008-06-13 23:01:12 +00001005 if (ResultAddr) // FIXME: volatility
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001006 Builder.CreateStore(Result, ResultAddr);
1007}