blob: fddc547fd345568e1215566e305f424f7ea9be43 [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"
Chris Lattner7d22bf02009-03-05 08:04:57 +000018#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000020#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000021#include "llvm/InlineAsm.h"
22#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000023#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
Daniel Dunbar09124252008-11-12 08:21:33 +000031void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000032 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar09124252008-11-12 08:21:33 +000033 DI->setLocation(S->getLocStart());
34 DI->EmitStopPoint(CurFn, Builder);
35 }
36}
37
Reid Spencer5f016e22007-07-11 17:01:13 +000038void CodeGenFunction::EmitStmt(const Stmt *S) {
39 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000040
Daniel Dunbar09124252008-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 Dunbara448fb22008-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();
Reid Spencer5f016e22007-07-11 17:01:13 +000052
Daniel Dunbar09124252008-11-12 08:21:33 +000053 // Generate a stoppoint if we are emitting debug info.
54 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000055
Reid Spencer5f016e22007-07-11 17:01:13 +000056 switch (S->getStmtClass()) {
57 default:
Chris Lattner1e4d21e2007-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.
Reid Spencer5f016e22007-07-11 17:01:13 +000060 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000061 if (!hasAggregateLLVMType(E->getType()))
62 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000063 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000064 EmitComplexExpr(E);
65 else
66 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000067 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000068 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000069 }
70 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000071 case Stmt::IndirectGotoStmtClass:
72 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbara4275d12008-10-02 18:02:06 +000081
Devang Patel51b09f22007-10-04 23:45:31 +000082 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000083 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000084
85 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000086 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
87 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000088 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000089 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
90 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000091 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000092 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000093 break;
94 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000095 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000096 break;
97 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000098 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000100 case Stmt::ObjCForCollectionStmtClass:
101 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000102 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 }
104}
105
Daniel Dunbar09124252008-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 Lattner33793202007-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 Lattner9b655512007-08-31 22:49:20 +0000125RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
126 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000127 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
128 "LLVM IR generation of compound statement ('{}')");
129
Anders Carlssone896d982009-02-13 08:11:52 +0000130 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000131 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000132 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000133 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000134 DI->EmitRegionStart(CurFn, Builder);
135 }
136
Anders Carlssonc71c8452009-02-07 23:50:39 +0000137 // Keep track of the current cleanup stack depth.
138 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlsson74331892009-02-09 20:23:40 +0000139 bool OldDidCallStackSave = DidCallStackSave;
Anders Carlsson66b41512009-02-22 18:44:21 +0000140 DidCallStackSave = false;
Anders Carlsson74331892009-02-09 20:23:40 +0000141
Chris Lattner33793202007-08-31 22:09:40 +0000142 for (CompoundStmt::const_body_iterator I = S.body_begin(),
143 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000145
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000146 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000147 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000148 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000149 DI->EmitRegionEnd(CurFn, Builder);
150 }
151
Anders Carlsson17d28a32008-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 Lattner9b655512007-08-31 22:49:20 +0000165
Anders Carlsson17d28a32008-12-12 05:52:00 +0000166 EnsureInsertPoint();
167
168 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
169 }
170
Anders Carlsson74331892009-02-09 20:23:40 +0000171 DidCallStackSave = OldDidCallStackSave;
172
Anders Carlssonc71c8452009-02-07 23:50:39 +0000173 EmitCleanupBlocks(CleanupStackDepth);
174
Anders Carlsson17d28a32008-12-12 05:52:00 +0000175 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000178void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000179 // Fall out of the current block (if necessary).
180 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000181
182 if (IsFinished && BB->use_empty()) {
183 delete BB;
184 return;
185 }
186
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000187 // If necessary, associate the block with the cleanup stack size.
188 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-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 Carlssonbd6fa3d2009-02-08 00:16:35 +0000197 }
198
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 CurFn->getBasicBlockList().push_back(BB);
200 Builder.SetInsertPoint(BB);
201}
202
Daniel Dunbard57a8712008-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 Dunbard57a8712008-11-11 09:41:28 +0000212 } else {
213 // Otherwise, create a fall-through branch.
214 Builder.CreateBr(Target);
215 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000216
217 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000218}
219
Mike Stumpec9771d2009-02-08 09:22:19 +0000220void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000221 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000222}
223
224
225void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
226 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 EmitStmt(S.getSubStmt());
228}
229
230void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000231 // If this code is reachable then emit a stop point (if generating
232 // debug info). We have to do this ourselves because we are on the
233 // "simple" statement path.
234 if (HaveInsertPoint())
235 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000236
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000237 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Daniel Dunbar0ffb1252008-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 Dunbara448fb22008-11-11 23:11:34 +0000250 // Clear the insertion point to indicate we are in unreachable code.
251 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000252}
253
Chris Lattner62b72f62008-11-11 07:24:28 +0000254void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000257
Chris Lattner9bc47e22008-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 Lattner31a09842008-11-12 08:04:58 +0000260 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-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 Lattner9bc47e22008-11-12 07:46:33 +0000263 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000264 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000265
Chris Lattner62b72f62008-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 Lattner9bc47e22008-11-12 07:46:33 +0000268 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000269 if (Executed)
270 EmitStmt(Executed);
271 return;
272 }
273 }
Chris Lattner9bc47e22008-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 Dunbar781d7ca2008-11-13 00:47:57 +0000277 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
278 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
279 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000281 ElseBlock = createBasicBlock("if.else");
282 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000283
284 // Emit the 'then' code.
285 EmitBlock(ThenBlock);
286 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000287 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000288
289 // Emit the 'else' code if present.
290 if (const Stmt *Else = S.getElse()) {
291 EmitBlock(ElseBlock);
292 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000293 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 }
295
296 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000297 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000298}
299
300void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 // Emit the header for the loop, insert it, which will create an uncond br to
302 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000303 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-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 Carlssone4b6d342009-02-10 05:52:02 +0000312 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000313
Mike Stump16b16202009-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000318
319 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000325
Reid Spencer5f016e22007-07-11 17:01:13 +0000326 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000327 if (EmitBoolCondBranch)
328 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000329
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 // Emit the loop body.
331 EmitBlock(LoopBody);
332 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000333
Anders Carlssone4b6d342009-02-10 05:52:02 +0000334 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000335
336 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000337 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
339 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000340 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-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 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000349}
350
351void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // Emit the body for the loop, insert it, which will create an uncond br to
353 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000354 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
355 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000357
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000358 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000359
360 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000361 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000362
363 // Emit the body of the loop into the block.
364 EmitStmt(S.getBody());
365
Anders Carlssone4b6d342009-02-10 05:52:02 +0000366 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000367
368 EmitBlock(DoCond);
369
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 // 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 Patel05f6e6b2007-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000386 if (EmitBoolCondBranch)
387 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388
389 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000390 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-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 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000398}
399
400void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
402 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000403
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 // 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 Dunbar9615ecb2008-11-13 01:38:36 +0000409 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
410 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 EmitBlock(CondBlock);
413
Mike Stump20926c62009-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000418 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-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
Reid Spencer5f016e22007-07-11 17:01:13 +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
Chris Lattnerda138702007-07-16 21:28:45 +0000430 // 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 Dunbar9615ecb2008-11-13 01:38:36 +0000434 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000435 else
436 ContinueBlock = CondBlock;
437
438 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000439 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000440
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 // If the condition is true, execute the body of the for stmt.
442 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000443
Anders Carlssone4b6d342009-02-10 05:52:02 +0000444 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000445
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000447 if (S.getInc()) {
448 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000449 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000450 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000451
452 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000453 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454
Chris Lattnerda138702007-07-16 21:28:45 +0000455 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000456 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000457}
458
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000459void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
460 if (RV.isScalar()) {
461 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
462 } else if (RV.isAggregate()) {
463 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
464 } else {
465 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
466 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000467 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000468}
469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
471/// if the function returns void, or may be missing one if the function returns
472/// non-void. Fun stuff :).
473void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // Emit the result value, even if unused, to evalute the side effects.
475 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000476
477 // FIXME: Clean this up by using an LValue for ReturnTemp,
478 // EmitStoreThroughLValue, and EmitAnyExpr.
479 if (!ReturnValue) {
480 // Make sure not to return anything, but evaluate the expression
481 // for side effects.
482 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000483 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000485 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000486 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000487 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000488 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000489 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000491 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 }
Eli Friedman144ac612008-05-22 01:22:33 +0000493
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000494 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000495}
496
497void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-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 Lattner6fa5f092007-07-12 15:43:07 +0000501}
Chris Lattnerda138702007-07-16 21:28:45 +0000502
Daniel Dunbar09124252008-11-12 08:21:33 +0000503void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000504 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
505
Daniel Dunbar09124252008-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 Stumpec9771d2009-02-08 09:22:19 +0000511
Chris Lattnerda138702007-07-16 21:28:45 +0000512 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000513 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000514}
515
Daniel Dunbar09124252008-11-12 08:21:33 +0000516void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000517 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
518
Daniel Dunbar09124252008-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 Stumpec9771d2009-02-08 09:22:19 +0000524
Chris Lattnerda138702007-07-16 21:28:45 +0000525 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000526 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000527}
Devang Patel51b09f22007-10-04 23:45:31 +0000528
Devang Patelc049e4f2007-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 Dunbar4efde8d2008-07-24 01:18:41 +0000533 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000534
Anders Carlsson51fe9962008-11-22 21:04:56 +0000535 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
536 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000537
Daniel Dunbar16f23572008-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 Dunbarf84dcda2008-11-11 04:12:31 +0000541 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000542 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
543 EmitStmt(S.getSubStmt());
544
Daniel Dunbar4efde8d2008-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 Patelc049e4f2007-10-08 20:57:48 +0000548
549 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000550 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-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 Dunbar4efde8d2008-07-24 01:18:41 +0000553 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000554 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
555 LHS++;
556 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000557 return;
558 }
559
Daniel Dunbar16f23572008-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 Patel2d79d0f2007-10-05 20:54:07 +0000563
Daniel Dunbar16f23572008-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 Dunbar55e87422008-11-11 02:29:29 +0000568 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000569
Daniel Dunbar16f23572008-07-25 01:11:38 +0000570 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
571 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000572
573 // Emit range check.
574 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000575 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
576 "tmp");
Devang Patelc049e4f2007-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 Dunbar16f23572008-07-25 01:11:38 +0000581 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000582 if (RestoreBB)
583 Builder.SetInsertPoint(RestoreBB);
584 else
585 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-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 Dunbarf84dcda2008-11-11 04:12:31 +0000594 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000595 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000596 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000597 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Chris Lattner5512f282009-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 Patel51b09f22007-10-04 23:45:31 +0000622}
623
624void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000625 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000626 assert(DefaultBlock->empty() &&
627 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000628 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-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 Patelc049e4f2007-10-08 20:57:48 +0000637 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000638
Daniel Dunbar16f23572008-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 Dunbar55e87422008-11-11 02:29:29 +0000643 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
644 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000645 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
646 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000647
Daniel Dunbar09124252008-11-12 08:21:33 +0000648 // Clear the insertion point to indicate we are in unreachable code.
649 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000650
Devang Patele9b8c0a2007-10-30 20:59:40 +0000651 // All break statements jump to NextBlock. If BreakContinueStack is non empty
652 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000653 llvm::BasicBlock *ContinueBlock = 0;
654 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000655 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000656
Mike Stump3e9da662009-02-07 23:02:10 +0000657 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000658 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000659
660 // Emit switch body.
661 EmitStmt(S.getBody());
Anders Carlssone4b6d342009-02-10 05:52:02 +0000662
663 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000664
Daniel Dunbar16f23572008-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 Patelc049e4f2007-10-08 20:57:48 +0000668
Daniel Dunbar16f23572008-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 Patel51b09f22007-10-04 23:45:31 +0000675
Daniel Dunbar16f23572008-07-25 01:11:38 +0000676 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000677 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000678
Devang Patel51b09f22007-10-04 23:45:31 +0000679 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000680 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000681}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000682
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000683static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000684 TargetInfo &Target,
685 const std::string *OutputNamesBegin = 0,
Chris Lattner63c8b142009-03-10 05:39:21 +0000686 const std::string *OutputNamesEnd = 0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000687 std::string Result;
688
689 while (*Constraint) {
690 switch (*Constraint) {
691 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000692 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000693 break;
694 // Ignore these
695 case '*':
696 case '?':
697 case '!':
698 break;
699 case 'g':
700 Result += "imr";
701 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000702 case '[': {
703 assert(OutputNamesBegin && OutputNamesEnd &&
704 "Must pass output names to constraints with a symbolic name");
705 unsigned Index;
706 bool result = Target.resolveSymbolicName(Constraint,
707 OutputNamesBegin,
708 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000709 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000710 Result += llvm::utostr(Index);
711 break;
712 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000713 }
714
715 Constraint++;
716 }
717
718 return Result;
719}
720
Anders Carlsson63471722009-01-11 19:32:54 +0000721llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
722 TargetInfo::ConstraintInfo Info,
723 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000724 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000725 llvm::Value *Arg;
726 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000727 !(Info & TargetInfo::CI_AllowsMemory)) {
728 const llvm::Type *Ty = ConvertType(InputExpr->getType());
729
730 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000731 Arg = EmitScalarExpr(InputExpr);
732 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000733 LValue Dest = EmitLValue(InputExpr);
734
735 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
736 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
737 Ty = llvm::IntegerType::get(Size);
738 Ty = llvm::PointerType::getUnqual(Ty);
739
740 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
741 } else {
742 Arg = Dest.getAddress();
743 ConstraintStr += '*';
744 }
Anders Carlsson63471722009-01-11 19:32:54 +0000745 }
746 } else {
747 LValue Dest = EmitLValue(InputExpr);
748 Arg = Dest.getAddress();
749 ConstraintStr += '*';
750 }
751
752 return Arg;
753}
754
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000755void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000756 // Analyze the asm string to decompose it into its pieces. We know that Sema
757 // has already done this, so it is guaranteed to be successful.
758 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000759 unsigned DiagOffs;
760 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Chris Lattner458cd9c2009-03-10 23:21:44 +0000761
762 // Assemble the pieces into the final asm string.
763 std::string AsmString;
764 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
765 if (Pieces[i].isString())
766 AsmString += Pieces[i].getString();
767 else if (Pieces[i].getModifier() == '\0')
768 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
769 else
770 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
771 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000772 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000773
774 std::string Constraints;
775
776 llvm::Value *ResultAddr = 0;
777 const llvm::Type *ResultType = llvm::Type::VoidTy;
778
779 std::vector<const llvm::Type*> ArgTypes;
780 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000781
782 // Keep track of inout constraints.
783 std::string InOutConstraints;
784 std::vector<llvm::Value*> InOutArgs;
785 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000786
787 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
788
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000789 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattnerb3277932009-03-10 04:59:06 +0000790 std::string OutputConstraint(S.getOutputConstraint(i));
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000791
792 TargetInfo::ConstraintInfo Info;
793 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
794 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000795 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000796
Anders Carlsson03eb5432009-01-27 20:38:24 +0000797 OutputConstraintInfos.push_back(Info);
798
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000799 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000800 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000801
802 LValue Dest = EmitLValue(S.getOutputExpr(i));
803 const llvm::Type *DestValueType =
804 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
805
806 // If the first output operand is not a memory dest, we'll
807 // make it the return value.
808 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000809 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000810 ResultAddr = Dest.getAddress();
811 ResultType = DestValueType;
812 Constraints += "=" + OutputConstraint;
813 } else {
814 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000815 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000816 if (i != 0)
817 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000818 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000819 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000820 }
821
822 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000823 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000824
Anders Carlssonf39a4212008-02-05 20:01:53 +0000825 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000826 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000827
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000828 if (Info & TargetInfo::CI_AllowsRegister)
829 InOutConstraints += llvm::utostr(i);
830 else
831 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000832
Anders Carlssonf39a4212008-02-05 20:01:53 +0000833 InOutArgTypes.push_back(Arg->getType());
834 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000835 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000836 }
837
838 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
839
840 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
841 const Expr *InputExpr = S.getInputExpr(i);
842
Chris Lattnerb3277932009-03-10 04:59:06 +0000843 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000844
845 TargetInfo::ConstraintInfo Info;
846 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +0000847 S.begin_output_names(),
848 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +0000849 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +0000850 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +0000851 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000852
853 if (i != 0 || S.getNumOutputs() > 0)
854 Constraints += ',';
855
856 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000857 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
858 S.begin_output_names(),
859 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000860
Anders Carlsson63471722009-01-11 19:32:54 +0000861 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000862
863 ArgTypes.push_back(Arg->getType());
864 Args.push_back(Arg);
865 Constraints += InputConstraint;
866 }
867
Anders Carlssonf39a4212008-02-05 20:01:53 +0000868 // Append the "input" part of inout constraints last.
869 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
870 ArgTypes.push_back(InOutArgTypes[i]);
871 Args.push_back(InOutArgs[i]);
872 }
873 Constraints += InOutConstraints;
874
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000875 // Clobbers
876 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
877 std::string Clobber(S.getClobber(i)->getStrData(),
878 S.getClobber(i)->getByteLength());
879
880 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
881
Anders Carlssonea041752008-02-06 00:11:32 +0000882 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000883 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000884
885 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000886 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000887 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000888 }
889
890 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +0000891 std::string MachineClobbers = Target.getClobbers();
892 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000893 if (!Constraints.empty())
894 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +0000895 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000896 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000897
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000898 const llvm::FunctionType *FTy =
899 llvm::FunctionType::get(ResultType, ArgTypes, false);
900
901 llvm::InlineAsm *IA =
902 llvm::InlineAsm::get(FTy, AsmString, Constraints,
903 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbc0822b2009-03-02 19:58:15 +0000904 llvm::CallInst *Result
905 = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
906 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
907
Eli Friedman1e692ac2008-06-13 23:01:12 +0000908 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000909 Builder.CreateStore(Result, ResultAddr);
910}