blob: 62e465d7028f47956ee94d106697b4516e728eb0 [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 Dunbard286f052009-07-19 06:58:07 +000046 // Check if we are generating unreachable code.
47 if (!HaveInsertPoint()) {
48 // If so, and the statement doesn't contain a label, then we do not need to
49 // generate actual code. This is safe because (1) the current point is
50 // unreachable, so we don't need to execute the code, and (2) we've already
51 // handled the statements which update internal data structures (like the
52 // local variable map) which could be used by subsequent statements.
53 if (!ContainsLabel(S)) {
54 // Verify that any decl statements were handled as simple, they may be in
55 // scope of subsequent reachable statements.
56 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
57 return;
58 }
59
60 // Otherwise, make a new block to hold the code.
61 EnsureInsertPoint();
62 }
63
Daniel Dunbar09124252008-11-12 08:21:33 +000064 // Generate a stoppoint if we are emitting debug info.
65 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000066
Reid Spencer5f016e22007-07-11 17:01:13 +000067 switch (S->getStmtClass()) {
68 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000069 // Must be an expression in a stmt context. Emit the value (to get
70 // side-effects) and ignore the result.
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000071 if (!isa<Expr>(S))
Daniel Dunbar488e9932008-08-16 00:56:44 +000072 ErrorUnsupported(S, "statement");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000073
74 EmitAnyExpr(cast<Expr>(S), 0, false, true);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000076 // Expression emitters don't handle unreachable blocks yet, so look for one
77 // explicitly here. This handles the common case of a call to a noreturn
78 // function.
79 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
80 if (CurBB->empty() && CurBB->use_empty()) {
81 CurBB->eraseFromParent();
82 Builder.ClearInsertionPoint();
83 }
Reid Spencer5f016e22007-07-11 17:01:13 +000084 }
85 break;
Mike Stump1eb44332009-09-09 15:08:12 +000086 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000087 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000088
89 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
90 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
91 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
92 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +000093
Reid Spencer5f016e22007-07-11 17:01:13 +000094 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000095
Devang Patel51b09f22007-10-04 23:45:31 +000096 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000097 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000098
99 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000100 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000101 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000102 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000103 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
104 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000105 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000106 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000107 break;
108 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000109 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000110 break;
111 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000112 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000113 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000114 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000115 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000116 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000117
118 case Stmt::CXXTryStmtClass:
119 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
120 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 }
122}
123
Daniel Dunbar09124252008-11-12 08:21:33 +0000124bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
125 switch (S->getStmtClass()) {
126 default: return false;
127 case Stmt::NullStmtClass: break;
128 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000129 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000130 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
131 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
132 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
133 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
134 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
135 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
136 }
137
138 return true;
139}
140
Chris Lattner33793202007-08-31 22:09:40 +0000141/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
142/// this captures the expression result of the last sub-statement and returns it
143/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000144RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
145 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000146 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
147 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Anders Carlssone896d982009-02-13 08:11:52 +0000149 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000150 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000151#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
152 DI->setLocation(S.getLBracLoc());
153 DI->EmitRegionStart(CurFn, Builder);
154#else
Daniel Dunbar09124252008-11-12 08:21:33 +0000155 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000156 DI->setLocation(S.getLBracLoc());
Devang Patelbbd9fa42009-10-06 18:36:08 +0000157#endif
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000158 }
159
Anders Carlssonc71c8452009-02-07 23:50:39 +0000160 // Keep track of the current cleanup stack depth.
161 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlsson74331892009-02-09 20:23:40 +0000162 bool OldDidCallStackSave = DidCallStackSave;
Anders Carlsson66b41512009-02-22 18:44:21 +0000163 DidCallStackSave = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattner33793202007-08-31 22:09:40 +0000165 for (CompoundStmt::const_body_iterator I = S.body_begin(),
166 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000168
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000169 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000170#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
171 DI->setLocation(S.getLBracLoc());
172 DI->EmitRegionEnd(CurFn, Builder);
173#else
Daniel Dunbara448fb22008-11-11 23:11:34 +0000174 EnsureInsertPoint();
Devang Patelbbd9fa42009-10-06 18:36:08 +0000175 DI->setLocation(S.getLBracLoc());
176#endif
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000177 }
178
Anders Carlsson17d28a32008-12-12 05:52:00 +0000179 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000180 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000181 RV = RValue::get(0);
182 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000183 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000184 // at the end of a statement expression, they yield the value of their
185 // subexpression. Handle this by walking through all labels we encounter,
186 // emitting them before we evaluate the subexpr.
187 const Stmt *LastStmt = S.body_back();
188 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
189 EmitLabel(*LS);
190 LastStmt = LS->getSubStmt();
191 }
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Anders Carlsson17d28a32008-12-12 05:52:00 +0000193 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Anders Carlsson17d28a32008-12-12 05:52:00 +0000195 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
196 }
197
Anders Carlsson74331892009-02-09 20:23:40 +0000198 DidCallStackSave = OldDidCallStackSave;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Anders Carlssonc71c8452009-02-07 23:50:39 +0000200 EmitCleanupBlocks(CleanupStackDepth);
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Anders Carlsson17d28a32008-12-12 05:52:00 +0000202 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000203}
204
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000205void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
206 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000208 // If there is a cleanup stack, then we it isn't worth trying to
209 // simplify this block (we would need to remove it from the scope map
210 // and cleanup entry).
211 if (!CleanupEntries.empty())
212 return;
213
214 // Can only simplify direct branches.
215 if (!BI || !BI->isUnconditional())
216 return;
217
218 BB->replaceAllUsesWith(BI->getSuccessor(0));
219 BI->eraseFromParent();
220 BB->eraseFromParent();
221}
222
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000223void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000224 // Fall out of the current block (if necessary).
225 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000226
227 if (IsFinished && BB->use_empty()) {
228 delete BB;
229 return;
230 }
231
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000232 // If necessary, associate the block with the cleanup stack size.
233 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000234 // Check if the basic block has already been inserted.
235 BlockScopeMap::iterator I = BlockScopes.find(BB);
236 if (I != BlockScopes.end()) {
237 assert(I->second == CleanupEntries.size() - 1);
238 } else {
239 BlockScopes[BB] = CleanupEntries.size() - 1;
240 CleanupEntries.back().Blocks.push_back(BB);
241 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000242 }
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 CurFn->getBasicBlockList().push_back(BB);
245 Builder.SetInsertPoint(BB);
246}
247
Daniel Dunbard57a8712008-11-11 09:41:28 +0000248void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
249 // Emit a branch from the current block to the target one if this
250 // was a real block. If this was just a fall-through block after a
251 // terminator, don't emit it.
252 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
253
254 if (!CurBB || CurBB->getTerminator()) {
255 // If there is no insert point or the previous block is already
256 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000257 } else {
258 // Otherwise, create a fall-through branch.
259 Builder.CreateBr(Target);
260 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000261
262 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000263}
264
Mike Stumpec9771d2009-02-08 09:22:19 +0000265void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000266 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000267}
268
269
270void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
271 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 EmitStmt(S.getSubStmt());
273}
274
275void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000276 // If this code is reachable then emit a stop point (if generating
277 // debug info). We have to do this ourselves because we are on the
278 // "simple" statement path.
279 if (HaveInsertPoint())
280 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000281
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000282 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000283}
284
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000285void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
286 // Emit initial switch which will be patched up later by
287 // EmitIndirectSwitches(). We need a default dest, so we use the
288 // current BB, but this is overwritten.
289 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
Mike Stump1eb44332009-09-09 15:08:12 +0000290 llvm::Type::getInt32Ty(VMContext),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000291 "addr");
292 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
293 IndirectSwitches.push_back(I);
294
Daniel Dunbara448fb22008-11-11 23:11:34 +0000295 // Clear the insertion point to indicate we are in unreachable code.
296 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000297}
298
Chris Lattner62b72f62008-11-11 07:24:28 +0000299void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // C99 6.8.4.1: The first substatement is executed if the expression compares
301 // unequal to 0. The condition must be a scalar type.
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattner9bc47e22008-11-12 07:46:33 +0000303 // If the condition constant folds and can be elided, try to avoid emitting
304 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000305 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000306 // Figure out which block (then or else) is executed.
307 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000308 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000309 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattner62b72f62008-11-11 07:24:28 +0000311 // If the skipped block has no labels in it, just emit the executed block.
312 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000313 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000314 if (Executed)
315 EmitStmt(Executed);
316 return;
317 }
318 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000319
320 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
321 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000322 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
323 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
324 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000326 ElseBlock = createBasicBlock("if.else");
327 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 // Emit the 'then' code.
330 EmitBlock(ThenBlock);
331 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000332 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 // Emit the 'else' code if present.
335 if (const Stmt *Else = S.getElse()) {
336 EmitBlock(ElseBlock);
337 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000338 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 }
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000342 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000343}
344
345void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 // Emit the header for the loop, insert it, which will create an uncond br to
347 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000348 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000350
351 // Create an exit block for when the condition fails, create a block for the
352 // body of the loop.
353 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
354 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
355
356 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000357 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Mike Stump16b16202009-02-07 17:18:33 +0000359 // Evaluate the conditional in the while header. C99 6.8.5.1: The
360 // evaluation of the controlling expression takes place before each
361 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000363
364 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000366 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000367 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000368 if (C->isOne())
369 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000372 if (EmitBoolCondBranch)
373 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // Emit the loop body.
376 EmitBlock(LoopBody);
377 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000378
Mike Stump1eb44332009-09-09 15:08:12 +0000379 BreakContinueStack.pop_back();
380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000382 EmitBranch(LoopHeader);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000385 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000386
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000387 // The LoopHeader typically is just a branch if we skipped emitting
388 // a branch, try to erase it.
389 if (!EmitBoolCondBranch)
390 SimplifyForwardingBlocks(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000391}
392
393void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 // Emit the body for the loop, insert it, which will create an uncond br to
395 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000396 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
397 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000399
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000400 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattnerda138702007-07-16 21:28:45 +0000402 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000403 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 // Emit the body of the loop into the block.
406 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Anders Carlssone4b6d342009-02-10 05:52:02 +0000408 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattnerda138702007-07-16 21:28:45 +0000410 EmitBlock(DoCond);
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
413 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 // Evaluate the conditional in the while header.
416 // C99 6.8.5p2/p4: The first substatement is executed if the expression
417 // compares unequal to 0. The condition must be a scalar type.
418 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000419
420 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
421 // to correctly handle break/continue though.
422 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000423 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000424 if (C->isZero())
425 EmitBoolCondBranch = false;
426
Reid Spencer5f016e22007-07-11 17:01:13 +0000427 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000428 if (EmitBoolCondBranch)
429 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 // Emit the exit block.
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000432 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000433
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000434 // The DoCond block typically is just a branch if we skipped
435 // emitting a branch, try to erase it.
436 if (!EmitBoolCondBranch)
437 SimplifyForwardingBlocks(DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000438}
439
440void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
442 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 // Evaluate the first part before the loop.
445 if (S.getInit())
446 EmitStmt(S.getInit());
447
448 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000449 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
450 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000451
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 EmitBlock(CondBlock);
453
Mike Stump20926c62009-02-07 20:14:12 +0000454 // Evaluate the condition if present. If not, treat it as a
455 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000458 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Chris Lattner31a09842008-11-12 08:04:58 +0000460 // C99 6.8.5p2/p4: The first substatement is executed if the expression
461 // compares unequal to 0. The condition must be a scalar type.
462 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
Mike Stump1eb44332009-09-09 15:08:12 +0000463
464 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 } else {
466 // Treat it as a non-zero constant. Don't even create a new block for the
467 // body, just fall into it.
468 }
469
Mike Stump1eb44332009-09-09 15:08:12 +0000470 // If the for loop doesn't have an increment we can just use the
Chris Lattnerda138702007-07-16 21:28:45 +0000471 // condition as the continue block.
472 llvm::BasicBlock *ContinueBlock;
473 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000474 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000475 else
Mike Stump1eb44332009-09-09 15:08:12 +0000476 ContinueBlock = CondBlock;
477
Chris Lattnerda138702007-07-16 21:28:45 +0000478 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000479 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000480
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 // If the condition is true, execute the body of the for stmt.
Devang Patelbbd9fa42009-10-06 18:36:08 +0000482#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
483 CGDebugInfo *DI = getDebugInfo();
484 if (DI) {
485 DI->setLocation(S.getSourceRange().getBegin());
486 DI->EmitRegionStart(CurFn, Builder);
487 }
488#endif
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000490
Anders Carlssone4b6d342009-02-10 05:52:02 +0000491 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000494 if (S.getInc()) {
495 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000496 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000500 EmitBranch(CondBlock);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000501#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
502 if (DI) {
503 DI->setLocation(S.getSourceRange().getEnd());
504 DI->EmitRegionEnd(CurFn, Builder);
505 }
506#endif
Reid Spencer5f016e22007-07-11 17:01:13 +0000507
Chris Lattnerda138702007-07-16 21:28:45 +0000508 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000509 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000510}
511
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000512void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
513 if (RV.isScalar()) {
514 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
515 } else if (RV.isAggregate()) {
516 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
517 } else {
518 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
519 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000520 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000521}
522
Reid Spencer5f016e22007-07-11 17:01:13 +0000523/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
524/// if the function returns void, or may be missing one if the function returns
525/// non-void. Fun stuff :).
526void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 // Emit the result value, even if unused, to evalute the side effects.
528 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000530 // FIXME: Clean this up by using an LValue for ReturnTemp,
531 // EmitStoreThroughLValue, and EmitAnyExpr.
532 if (!ReturnValue) {
533 // Make sure not to return anything, but evaluate the expression
534 // for side effects.
535 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000536 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000538 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000539 } else if (FnRetTy->isReferenceType()) {
540 // If this function returns a reference, take the address of the expression
541 // rather than the value.
542 Builder.CreateStore(EmitLValue(RV).getAddress(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000543 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000544 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000545 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000546 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000548 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 }
Eli Friedman144ac612008-05-22 01:22:33 +0000550
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000551 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000552}
553
554void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000555 // As long as debug info is modeled with instructions, we have to ensure we
556 // have a place to insert here and write the stop point here.
557 if (getDebugInfo()) {
558 EnsureInsertPoint();
559 EmitStopPoint(&S);
560 }
561
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000562 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
563 I != E; ++I)
564 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000565}
Chris Lattnerda138702007-07-16 21:28:45 +0000566
Daniel Dunbar09124252008-11-12 08:21:33 +0000567void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000568 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
569
Daniel Dunbar09124252008-11-12 08:21:33 +0000570 // If this code is reachable then emit a stop point (if generating
571 // debug info). We have to do this ourselves because we are on the
572 // "simple" statement path.
573 if (HaveInsertPoint())
574 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000575
Chris Lattnerda138702007-07-16 21:28:45 +0000576 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000577 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000578}
579
Daniel Dunbar09124252008-11-12 08:21:33 +0000580void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000581 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
582
Daniel Dunbar09124252008-11-12 08:21:33 +0000583 // If this code is reachable then emit a stop point (if generating
584 // debug info). We have to do this ourselves because we are on the
585 // "simple" statement path.
586 if (HaveInsertPoint())
587 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000588
Chris Lattnerda138702007-07-16 21:28:45 +0000589 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000590 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000591}
Devang Patel51b09f22007-10-04 23:45:31 +0000592
Devang Patelc049e4f2007-10-08 20:57:48 +0000593/// EmitCaseStmtRange - If case statement range is not too big then
594/// add multiple cases to switch instruction, one for each value within
595/// the range. If range is too big then emit "if" condition check.
596void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000597 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000598
Anders Carlsson51fe9962008-11-22 21:04:56 +0000599 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
600 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000601
Daniel Dunbar16f23572008-07-25 01:11:38 +0000602 // Emit the code for this case. We do this first to make sure it is
603 // properly chained from our predecessor before generating the
604 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000605 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000606 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
607 EmitStmt(S.getSubStmt());
608
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000609 // If range is empty, do nothing.
610 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
611 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000612
613 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000614 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000615 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
616 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000617 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000618 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000619 LHS++;
620 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000621 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000622 }
623
Daniel Dunbar16f23572008-07-25 01:11:38 +0000624 // The range is too big. Emit "if" condition into a new block,
625 // making sure to save and restore the current insertion point.
626 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000627
Daniel Dunbar16f23572008-07-25 01:11:38 +0000628 // Push this test onto the chain of range checks (which terminates
629 // in the default basic block). The switch's default will be changed
630 // to the top of this chain after switch emission is complete.
631 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000632 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000633
Daniel Dunbar16f23572008-07-25 01:11:38 +0000634 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
635 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000636
637 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000638 llvm::Value *Diff =
639 Builder.CreateSub(SwitchInsn->getCondition(),
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000640 llvm::ConstantInt::get(VMContext, LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000641 llvm::Value *Cond =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000642 Builder.CreateICmpULE(Diff,
643 llvm::ConstantInt::get(VMContext, Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000644 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
645
Daniel Dunbar16f23572008-07-25 01:11:38 +0000646 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000647 if (RestoreBB)
648 Builder.SetInsertPoint(RestoreBB);
649 else
650 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000651}
652
653void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
654 if (S.getRHS()) {
655 EmitCaseStmtRange(S);
656 return;
657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000659 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000660 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000661 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000662 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Chris Lattner5512f282009-03-04 04:46:18 +0000664 // Recursively emitting the statement is acceptable, but is not wonderful for
665 // code where we have many case statements nested together, i.e.:
666 // case 1:
667 // case 2:
668 // case 3: etc.
669 // Handling this recursively will create a new block for each case statement
670 // that falls through to the next case which is IR intensive. It also causes
671 // deep recursion which can run into stack depth limitations. Handle
672 // sequential non-range case statements specially.
673 const CaseStmt *CurCase = &S;
674 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
675
676 // Otherwise, iteratively add consequtive cases to this switch stmt.
677 while (NextCase && NextCase->getRHS() == 0) {
678 CurCase = NextCase;
679 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000680 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000681
682 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
683 }
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner5512f282009-03-04 04:46:18 +0000685 // Normal default recursion for non-cases.
686 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000687}
688
689void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000690 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000691 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000692 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000693 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000694 EmitStmt(S.getSubStmt());
695}
696
697void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
698 llvm::Value *CondV = EmitScalarExpr(S.getCond());
699
700 // Handle nested switch statements.
701 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000702 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000703
Daniel Dunbar16f23572008-07-25 01:11:38 +0000704 // Create basic block to hold stuff that comes after switch
705 // statement. We also need to create a default block now so that
706 // explicit case ranges tests can have a place to jump to on
707 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000708 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
709 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000710 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
711 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000712
Daniel Dunbar09124252008-11-12 08:21:33 +0000713 // Clear the insertion point to indicate we are in unreachable code.
714 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000715
Devang Patele9b8c0a2007-10-30 20:59:40 +0000716 // All break statements jump to NextBlock. If BreakContinueStack is non empty
717 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000718 llvm::BasicBlock *ContinueBlock = 0;
719 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000720 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000721
Mike Stump3e9da662009-02-07 23:02:10 +0000722 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000723 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000724
725 // Emit switch body.
726 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Anders Carlssone4b6d342009-02-10 05:52:02 +0000728 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000729
Daniel Dunbar16f23572008-07-25 01:11:38 +0000730 // Update the default block in case explicit case range tests have
731 // been chained on top.
732 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Daniel Dunbar16f23572008-07-25 01:11:38 +0000734 // If a default was never emitted then reroute any jumps to it and
735 // discard.
736 if (!DefaultBlock->getParent()) {
737 DefaultBlock->replaceAllUsesWith(NextBlock);
738 delete DefaultBlock;
739 }
Devang Patel51b09f22007-10-04 23:45:31 +0000740
Daniel Dunbar16f23572008-07-25 01:11:38 +0000741 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000742 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000743
Devang Patel51b09f22007-10-04 23:45:31 +0000744 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000745 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000746}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000747
Chris Lattner2819fa82009-04-26 17:57:12 +0000748static std::string
749SimplifyConstraint(const char *Constraint, TargetInfo &Target,
750 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000751 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000753 while (*Constraint) {
754 switch (*Constraint) {
755 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000756 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000757 break;
758 // Ignore these
759 case '*':
760 case '?':
761 case '!':
762 break;
763 case 'g':
764 Result += "imr";
765 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000766 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000767 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000768 "Must pass output names to constraints with a symbolic name");
769 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +0000770 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000771 &(*OutCons)[0],
772 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000773 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000774 Result += llvm::utostr(Index);
775 break;
776 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000777 }
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000779 Constraint++;
780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000782 return Result;
783}
784
Anders Carlsson63471722009-01-11 19:32:54 +0000785llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
Daniel Dunbarb84e8a62009-05-04 06:56:16 +0000786 const TargetInfo::ConstraintInfo &Info,
Anders Carlsson63471722009-01-11 19:32:54 +0000787 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000788 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000789 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +0000790 if (Info.allowsRegister() || !Info.allowsMemory()) {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000791 const llvm::Type *Ty = ConvertType(InputExpr->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000793 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000794 Arg = EmitScalarExpr(InputExpr);
795 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000796 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000797 LValue Dest = EmitLValue(InputExpr);
798
799 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
800 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000801 Ty = llvm::IntegerType::get(VMContext, Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000802 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000804 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
805 } else {
806 Arg = Dest.getAddress();
807 ConstraintStr += '*';
808 }
Anders Carlsson63471722009-01-11 19:32:54 +0000809 }
810 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000811 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000812 LValue Dest = EmitLValue(InputExpr);
813 Arg = Dest.getAddress();
814 ConstraintStr += '*';
815 }
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Anders Carlsson63471722009-01-11 19:32:54 +0000817 return Arg;
818}
819
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000820void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000821 // Analyze the asm string to decompose it into its pieces. We know that Sema
822 // has already done this, so it is guaranteed to be successful.
823 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000824 unsigned DiagOffs;
825 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattner458cd9c2009-03-10 23:21:44 +0000827 // Assemble the pieces into the final asm string.
828 std::string AsmString;
829 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
830 if (Pieces[i].isString())
831 AsmString += Pieces[i].getString();
832 else if (Pieces[i].getModifier() == '\0')
833 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
834 else
835 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
836 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner481fef92009-05-03 07:05:00 +0000839 // Get all the output and input constraints together.
840 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
841 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
842
Mike Stump1eb44332009-09-09 15:08:12 +0000843 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000844 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
845 S.getOutputName(i));
846 bool result = Target.validateOutputConstraint(Info);
847 assert(result && "Failed to parse output constraint"); result=result;
848 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +0000849 }
850
Chris Lattner481fef92009-05-03 07:05:00 +0000851 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
852 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
853 S.getInputName(i));
Jay Foadbeaaccd2009-05-21 09:52:38 +0000854 bool result = Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner481fef92009-05-03 07:05:00 +0000855 S.getNumOutputs(),
856 Info); result=result;
857 assert(result && "Failed to parse input constraint");
858 InputConstraintInfos.push_back(Info);
859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000861 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattnerede9d902009-05-03 07:53:25 +0000863 std::vector<LValue> ResultRegDests;
864 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000865 std::vector<const llvm::Type *> ResultRegTypes;
866 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000867 std::vector<const llvm::Type*> ArgTypes;
868 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000869
870 // Keep track of inout constraints.
871 std::string InOutConstraints;
872 std::vector<llvm::Value*> InOutArgs;
873 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000874
Mike Stump1eb44332009-09-09 15:08:12 +0000875 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000876 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +0000877
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000878 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000879 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000880 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Chris Lattner810f6d52009-03-13 17:38:01 +0000882 const Expr *OutExpr = S.getOutputExpr(i);
883 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Chris Lattner810f6d52009-03-13 17:38:01 +0000885 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +0000886 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000887 Constraints += ',';
888
Chris Lattnera077b5c2009-05-03 08:21:20 +0000889 // If this is a register output, then make the inline asm return it
890 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +0000891 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000892 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +0000893 ResultRegQualTys.push_back(OutExpr->getType());
894 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000895 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
896 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chris Lattnera077b5c2009-05-03 08:21:20 +0000898 // If this output is tied to an input, and if the input is larger, then
899 // we need to set the actual result type of the inline asm node to be the
900 // same as the input type.
901 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +0000902 unsigned InputNo;
903 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
904 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
905 if (Input.hasTiedOperand() &&
Chris Lattner0bdaa5b2009-05-03 09:05:53 +0000906 Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +0000907 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +0000908 }
909 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Chris Lattnera077b5c2009-05-03 08:21:20 +0000911 QualType InputTy = S.getInputExpr(InputNo)->getType();
912 QualType OutputTy = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Chris Lattnera077b5c2009-05-03 08:21:20 +0000914 uint64_t InputSize = getContext().getTypeSize(InputTy);
915 if (getContext().getTypeSize(OutputTy) < InputSize) {
916 // Form the asm to return the value as a larger integer type.
Owen Anderson0032b272009-08-13 21:57:51 +0000917 ResultRegTypes.back() = llvm::IntegerType::get(VMContext, (unsigned)InputSize);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000918 }
919 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000920 } else {
921 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000922 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +0000923 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000924 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000925 }
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattner44def072009-04-26 07:16:29 +0000927 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000928 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000929
Anders Carlssonfca93612009-08-04 18:18:36 +0000930 const Expr *InputExpr = S.getOutputExpr(i);
931 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner44def072009-04-26 07:16:29 +0000933 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000934 InOutConstraints += llvm::utostr(i);
935 else
936 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000937
Anders Carlssonfca93612009-08-04 18:18:36 +0000938 InOutArgTypes.push_back(Arg->getType());
939 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000940 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000943 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000945 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
946 const Expr *InputExpr = S.getInputExpr(i);
947
Chris Lattner481fef92009-05-03 07:05:00 +0000948 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
949
Chris Lattnerede9d902009-05-03 07:53:25 +0000950 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000951 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000953 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000954 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000955 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000956 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000957
Anders Carlsson63471722009-01-11 19:32:54 +0000958 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner4df4ee02009-05-03 07:27:51 +0000960 // If this input argument is tied to a larger output result, extend the
961 // input to be the same size as the output. The LLVM backend wants to see
962 // the input and output of a matching constraint be the same size. Note
963 // that GCC does not define what the top bits are here. We use zext because
964 // that is usually cheaper, but LLVM IR should really get an anyext someday.
965 if (Info.hasTiedOperand()) {
966 unsigned Output = Info.getTiedOperand();
967 QualType OutputTy = S.getOutputExpr(Output)->getType();
968 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner4df4ee02009-05-03 07:27:51 +0000970 if (getContext().getTypeSize(OutputTy) >
971 getContext().getTypeSize(InputTy)) {
972 // Use ptrtoint as appropriate so that we can do our extension.
973 if (isa<llvm::PointerType>(Arg->getType()))
974 Arg = Builder.CreatePtrToInt(Arg,
Owen Anderson0032b272009-08-13 21:57:51 +0000975 llvm::IntegerType::get(VMContext, LLVMPointerWidth));
Chris Lattner4df4ee02009-05-03 07:27:51 +0000976 unsigned OutputSize = (unsigned)getContext().getTypeSize(OutputTy);
Owen Anderson0032b272009-08-13 21:57:51 +0000977 Arg = Builder.CreateZExt(Arg, llvm::IntegerType::get(VMContext, OutputSize));
Chris Lattner4df4ee02009-05-03 07:27:51 +0000978 }
979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
981
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000982 ArgTypes.push_back(Arg->getType());
983 Args.push_back(Arg);
984 Constraints += InputConstraint;
985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Anders Carlssonf39a4212008-02-05 20:01:53 +0000987 // Append the "input" part of inout constraints last.
988 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
989 ArgTypes.push_back(InOutArgTypes[i]);
990 Args.push_back(InOutArgs[i]);
991 }
992 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000994 // Clobbers
995 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
996 std::string Clobber(S.getClobber(i)->getStrData(),
997 S.getClobber(i)->getByteLength());
998
999 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Anders Carlssonea041752008-02-06 00:11:32 +00001001 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001002 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Anders Carlssonea041752008-02-06 00:11:32 +00001004 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001005 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001006 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001009 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001010 std::string MachineClobbers = Target.getClobbers();
1011 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001012 if (!Constraints.empty())
1013 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001014 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001015 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001016
1017 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001018 if (ResultRegTypes.empty())
Owen Anderson0032b272009-08-13 21:57:51 +00001019 ResultType = llvm::Type::getVoidTy(VMContext);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001020 else if (ResultRegTypes.size() == 1)
1021 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001022 else
Owen Anderson47a434f2009-08-05 23:18:46 +00001023 ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
1025 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001026 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
1028 llvm::InlineAsm *IA =
1029 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001030 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001031 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001032 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001033
1034
Chris Lattnera077b5c2009-05-03 08:21:20 +00001035 // Extract all of the register value results from the asm.
1036 std::vector<llvm::Value*> RegResults;
1037 if (ResultRegTypes.size() == 1) {
1038 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001039 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001040 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001041 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001042 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001043 }
1044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chris Lattnera077b5c2009-05-03 08:21:20 +00001046 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1047 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattnera077b5c2009-05-03 08:21:20 +00001049 // If the result type of the LLVM IR asm doesn't match the result type of
1050 // the expression, do the conversion.
1051 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1052 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1053 // Truncate the integer result to the right size, note that
1054 // ResultTruncRegTypes can be a pointer.
1055 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
Owen Anderson0032b272009-08-13 21:57:51 +00001056 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext, (unsigned)ResSize));
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chris Lattnera077b5c2009-05-03 08:21:20 +00001058 if (Tmp->getType() != TruncTy) {
1059 assert(isa<llvm::PointerType>(TruncTy));
1060 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1061 }
1062 }
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Chris Lattnera077b5c2009-05-03 08:21:20 +00001064 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1065 ResultRegQualTys[i]);
1066 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001067}