blob: 818c568255094e418dc9d863ffea72bd9f8674ec [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"
Peter Collingbourne4b93d662011-02-19 23:03:58 +000017#include "TargetInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattner7d22bf02009-03-05 08:04:57 +000019#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000020#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000021#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000022#include "llvm/InlineAsm.h"
23#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000024#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26using namespace CodeGen;
27
28//===----------------------------------------------------------------------===//
29// Statement Emission
30//===----------------------------------------------------------------------===//
31
Daniel Dunbar09124252008-11-12 08:21:33 +000032void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000033 if (CGDebugInfo *DI = getDebugInfo()) {
Devang Patel60e4fd92010-05-12 00:39:34 +000034 if (isa<DeclStmt>(S))
35 DI->setLocation(S->getLocEnd());
36 else
37 DI->setLocation(S->getLocStart());
Devang Patel5a6fbcf2010-07-22 22:29:16 +000038 DI->UpdateLineDirectiveRegion(Builder);
Devang Patel4d939e62010-07-20 22:20:10 +000039 DI->EmitStopPoint(Builder);
Daniel Dunbar09124252008-11-12 08:21:33 +000040 }
41}
42
Reid Spencer5f016e22007-07-11 17:01:13 +000043void CodeGenFunction::EmitStmt(const Stmt *S) {
44 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000045
Daniel Dunbar09124252008-11-12 08:21:33 +000046 // Check if we can handle this without bothering to generate an
47 // insert point or debug info.
48 if (EmitSimpleStmt(S))
49 return;
50
Daniel Dunbard286f052009-07-19 06:58:07 +000051 // Check if we are generating unreachable code.
52 if (!HaveInsertPoint()) {
53 // If so, and the statement doesn't contain a label, then we do not need to
54 // generate actual code. This is safe because (1) the current point is
55 // unreachable, so we don't need to execute the code, and (2) we've already
56 // handled the statements which update internal data structures (like the
57 // local variable map) which could be used by subsequent statements.
58 if (!ContainsLabel(S)) {
59 // Verify that any decl statements were handled as simple, they may be in
60 // scope of subsequent reachable statements.
61 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
62 return;
63 }
64
65 // Otherwise, make a new block to hold the code.
66 EnsureInsertPoint();
67 }
68
Daniel Dunbar09124252008-11-12 08:21:33 +000069 // Generate a stoppoint if we are emitting debug info.
70 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000071
Reid Spencer5f016e22007-07-11 17:01:13 +000072 switch (S->getStmtClass()) {
John McCall2a416372010-12-05 02:00:02 +000073 case Stmt::NoStmtClass:
74 case Stmt::CXXCatchStmtClass:
John McCall2a416372010-12-05 02:00:02 +000075 llvm_unreachable("invalid statement class to emit generically");
76 case Stmt::NullStmtClass:
77 case Stmt::CompoundStmtClass:
78 case Stmt::DeclStmtClass:
79 case Stmt::LabelStmtClass:
80 case Stmt::GotoStmtClass:
81 case Stmt::BreakStmtClass:
82 case Stmt::ContinueStmtClass:
83 case Stmt::DefaultStmtClass:
84 case Stmt::CaseStmtClass:
85 llvm_unreachable("should have emitted these statements as simple");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000086
John McCall2a416372010-12-05 02:00:02 +000087#define STMT(Type, Base)
88#define ABSTRACT_STMT(Op)
89#define EXPR(Type, Base) \
90 case Stmt::Type##Class:
91#include "clang/AST/StmtNodes.inc"
John McCallcd5b22e2011-01-12 03:41:02 +000092 {
93 // Remember the block we came in on.
94 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
95 assert(incoming && "expression emission must have an insertion point");
96
John McCall2a416372010-12-05 02:00:02 +000097 EmitIgnoredExpr(cast<Expr>(S));
Mike Stump1eb44332009-09-09 15:08:12 +000098
John McCallcd5b22e2011-01-12 03:41:02 +000099 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
100 assert(outgoing && "expression emission cleared block!");
101
102 // The expression emitters assume (reasonably!) that the insertion
103 // point is always set. To maintain that, the call-emission code
104 // for noreturn functions has to enter a new block with no
105 // predecessors. We want to kill that block and mark the current
106 // insertion point unreachable in the common case of a call like
107 // "exit();". Since expression emission doesn't otherwise create
108 // blocks with no predecessors, we can just test for that.
109 // However, we must be careful not to do this to our incoming
110 // block, because *statement* emission does sometimes create
111 // reachable blocks which will have no predecessors until later in
112 // the function. This occurs with, e.g., labels that are not
113 // reachable by fallthrough.
114 if (incoming != outgoing && outgoing->use_empty()) {
115 outgoing->eraseFromParent();
116 Builder.ClearInsertionPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 }
118 break;
John McCallcd5b22e2011-01-12 03:41:02 +0000119 }
John McCall2a416372010-12-05 02:00:02 +0000120
Mike Stump1eb44332009-09-09 15:08:12 +0000121 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000122 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000123
124 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
125 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
126 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
127 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +0000130
Devang Patel51b09f22007-10-04 23:45:31 +0000131 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000132 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000133
134 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000135 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000136 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000137 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000138 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
139 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000140 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000141 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000142 break;
143 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000144 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000145 break;
146 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000147 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000148 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000149 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000150 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000151 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000152
153 case Stmt::CXXTryStmtClass:
154 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
155 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000156 }
157}
158
Daniel Dunbar09124252008-11-12 08:21:33 +0000159bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
160 switch (S->getStmtClass()) {
161 default: return false;
162 case Stmt::NullStmtClass: break;
163 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000164 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000165 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
166 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
167 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
168 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
169 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
170 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
171 }
172
173 return true;
174}
175
Chris Lattner33793202007-08-31 22:09:40 +0000176/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
177/// this captures the expression result of the last sub-statement and returns it
178/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000179RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
John McCall558d2ab2010-09-15 10:14:12 +0000180 AggValueSlot AggSlot) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000181 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
182 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Anders Carlssone896d982009-02-13 08:11:52 +0000184 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000185 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000186 DI->setLocation(S.getLBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000187 DI->EmitRegionStart(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000188 }
189
Anders Carlssonc71c8452009-02-07 23:50:39 +0000190 // Keep track of the current cleanup stack depth.
John McCallf1549f62010-07-06 01:34:17 +0000191 RunCleanupsScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner33793202007-08-31 22:09:40 +0000193 for (CompoundStmt::const_body_iterator I = S.body_begin(),
194 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000196
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000197 if (DI) {
Devang Patelcd9199e2010-04-13 00:08:43 +0000198 DI->setLocation(S.getRBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000199 DI->EmitRegionEnd(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000200 }
201
Anders Carlsson17d28a32008-12-12 05:52:00 +0000202 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000203 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000204 RV = RValue::get(0);
205 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000206 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000207 // at the end of a statement expression, they yield the value of their
208 // subexpression. Handle this by walking through all labels we encounter,
209 // emitting them before we evaluate the subexpr.
210 const Stmt *LastStmt = S.body_back();
211 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000212 EmitLabel(LS->getDecl());
Anders Carlsson17d28a32008-12-12 05:52:00 +0000213 LastStmt = LS->getSubStmt();
214 }
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Anders Carlsson17d28a32008-12-12 05:52:00 +0000216 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000217
John McCall558d2ab2010-09-15 10:14:12 +0000218 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
Anders Carlsson17d28a32008-12-12 05:52:00 +0000219 }
220
Anders Carlsson17d28a32008-12-12 05:52:00 +0000221 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000222}
223
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000224void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
225 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000227 // If there is a cleanup stack, then we it isn't worth trying to
228 // simplify this block (we would need to remove it from the scope map
229 // and cleanup entry).
John McCallf1549f62010-07-06 01:34:17 +0000230 if (!EHStack.empty())
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000231 return;
232
233 // Can only simplify direct branches.
234 if (!BI || !BI->isUnconditional())
235 return;
236
237 BB->replaceAllUsesWith(BI->getSuccessor(0));
238 BI->eraseFromParent();
239 BB->eraseFromParent();
240}
241
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000242void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000243 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
244
Daniel Dunbard57a8712008-11-11 09:41:28 +0000245 // Fall out of the current block (if necessary).
246 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000247
248 if (IsFinished && BB->use_empty()) {
249 delete BB;
250 return;
251 }
252
John McCall839cbaa2010-04-21 10:29:06 +0000253 // Place the block after the current block, if possible, or else at
254 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000255 if (CurBB && CurBB->getParent())
256 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
John McCall839cbaa2010-04-21 10:29:06 +0000257 else
258 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 Builder.SetInsertPoint(BB);
260}
261
Daniel Dunbard57a8712008-11-11 09:41:28 +0000262void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
263 // Emit a branch from the current block to the target one if this
264 // was a real block. If this was just a fall-through block after a
265 // terminator, don't emit it.
266 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
267
268 if (!CurBB || CurBB->getTerminator()) {
269 // If there is no insert point or the previous block is already
270 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000271 } else {
272 // Otherwise, create a fall-through branch.
273 Builder.CreateBr(Target);
274 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000275
276 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000277}
278
John McCallf1549f62010-07-06 01:34:17 +0000279CodeGenFunction::JumpDest
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000280CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
281 JumpDest &Dest = LabelMap[D];
John McCallff8e1152010-07-23 21:56:41 +0000282 if (Dest.isValid()) return Dest;
John McCallf1549f62010-07-06 01:34:17 +0000283
284 // Create, but don't insert, the new block.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000285 Dest = JumpDest(createBasicBlock(D->getName()),
John McCallff8e1152010-07-23 21:56:41 +0000286 EHScopeStack::stable_iterator::invalid(),
287 NextCleanupDestIndex++);
John McCallf1549f62010-07-06 01:34:17 +0000288 return Dest;
289}
290
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000291void CodeGenFunction::EmitLabel(const LabelDecl *D) {
292 JumpDest &Dest = LabelMap[D];
John McCallf1549f62010-07-06 01:34:17 +0000293
John McCallff8e1152010-07-23 21:56:41 +0000294 // If we didn't need a forward reference to this label, just go
John McCallf1549f62010-07-06 01:34:17 +0000295 // ahead and create a destination at the current scope.
John McCallff8e1152010-07-23 21:56:41 +0000296 if (!Dest.isValid()) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000297 Dest = getJumpDestInCurrentScope(D->getName());
John McCallf1549f62010-07-06 01:34:17 +0000298
299 // Otherwise, we need to give this label a target depth and remove
300 // it from the branch-fixups list.
301 } else {
John McCallff8e1152010-07-23 21:56:41 +0000302 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
303 Dest = JumpDest(Dest.getBlock(),
304 EHStack.stable_begin(),
305 Dest.getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000306
John McCallff8e1152010-07-23 21:56:41 +0000307 ResolveBranchFixups(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000308 }
309
John McCallff8e1152010-07-23 21:56:41 +0000310 EmitBlock(Dest.getBlock());
Chris Lattner91d723d2008-07-26 20:23:23 +0000311}
312
313
314void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000315 EmitLabel(S.getDecl());
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 EmitStmt(S.getSubStmt());
317}
318
319void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000320 // If this code is reachable then emit a stop point (if generating
321 // debug info). We have to do this ourselves because we are on the
322 // "simple" statement path.
323 if (HaveInsertPoint())
324 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000325
John McCallf1549f62010-07-06 01:34:17 +0000326 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000327}
328
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000329
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000330void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000331 if (const LabelDecl *Target = S.getConstantTarget()) {
John McCall95c225d2010-10-28 08:53:48 +0000332 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
333 return;
334 }
335
Chris Lattner49c952f2009-11-06 18:10:47 +0000336 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000337 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
John McCalld16c2cf2011-02-08 08:22:06 +0000338 Int8PtrTy, "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000339 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
340
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000341
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000342 // Get the basic block for the indirect goto.
343 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
344
345 // The first instruction in the block has to be the PHI for the switch dest,
346 // add an entry for this branch.
347 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
348
349 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000350}
351
Chris Lattner62b72f62008-11-11 07:24:28 +0000352void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 // C99 6.8.4.1: The first substatement is executed if the expression compares
354 // unequal to 0. The condition must be a scalar type.
John McCallf1549f62010-07-06 01:34:17 +0000355 RunCleanupsScope ConditionScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000356
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000357 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000358 EmitAutoVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Chris Lattner9bc47e22008-11-12 07:46:33 +0000360 // If the condition constant folds and can be elided, try to avoid emitting
361 // the condition and the dead arm of the if/else.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000362 bool CondConstant;
363 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000364 // Figure out which block (then or else) is executed.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000365 const Stmt *Executed = S.getThen();
366 const Stmt *Skipped = S.getElse();
367 if (!CondConstant) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000368 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattner62b72f62008-11-11 07:24:28 +0000370 // If the skipped block has no labels in it, just emit the executed block.
371 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000372 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000373 if (Executed) {
John McCallf1549f62010-07-06 01:34:17 +0000374 RunCleanupsScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000375 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000376 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000377 return;
378 }
379 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000380
381 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
382 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000383 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
384 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
385 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000387 ElseBlock = createBasicBlock("if.else");
388 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000391 EmitBlock(ThenBlock);
392 {
John McCallf1549f62010-07-06 01:34:17 +0000393 RunCleanupsScope ThenScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000394 EmitStmt(S.getThen());
395 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000396 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // Emit the 'else' code if present.
399 if (const Stmt *Else = S.getElse()) {
400 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000401 {
John McCallf1549f62010-07-06 01:34:17 +0000402 RunCleanupsScope ElseScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000403 EmitStmt(Else);
404 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000405 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000409 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000410}
411
412void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000413 // Emit the header for the loop, which will also become
414 // the continue target.
415 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
John McCallff8e1152010-07-23 21:56:41 +0000416 EmitBlock(LoopHeader.getBlock());
Mike Stump72cac2c2009-02-07 18:08:12 +0000417
John McCallf1549f62010-07-06 01:34:17 +0000418 // Create an exit block for when the condition fails, which will
419 // also become the break target.
420 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
Mike Stump72cac2c2009-02-07 18:08:12 +0000421
422 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000423 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregor5656e142009-11-24 21:15:44 +0000425 // C++ [stmt.while]p2:
426 // When the condition of a while statement is a declaration, the
427 // scope of the variable that is declared extends from its point
428 // of declaration (3.3.2) to the end of the while statement.
429 // [...]
430 // The object created in a condition is destroyed and created
431 // with each iteration of the loop.
John McCallf1549f62010-07-06 01:34:17 +0000432 RunCleanupsScope ConditionScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000433
John McCallf1549f62010-07-06 01:34:17 +0000434 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000435 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregor5656e142009-11-24 21:15:44 +0000436
Mike Stump16b16202009-02-07 17:18:33 +0000437 // Evaluate the conditional in the while header. C99 6.8.5.1: The
438 // evaluation of the controlling expression takes place before each
439 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000441
Devang Patel2c30d8f2007-10-09 20:51:27 +0000442 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000444 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000445 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000446 if (C->isOne())
447 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 // As long as the condition is true, go to the loop body.
John McCallf1549f62010-07-06 01:34:17 +0000450 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
451 if (EmitBoolCondBranch) {
John McCallff8e1152010-07-23 21:56:41 +0000452 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
John McCallf1549f62010-07-06 01:34:17 +0000453 if (ConditionScope.requiresCleanups())
454 ExitBlock = createBasicBlock("while.exit");
455
456 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
457
John McCallff8e1152010-07-23 21:56:41 +0000458 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000459 EmitBlock(ExitBlock);
460 EmitBranchThroughCleanup(LoopExit);
461 }
462 }
Douglas Gregor5656e142009-11-24 21:15:44 +0000463
John McCallf1549f62010-07-06 01:34:17 +0000464 // Emit the loop body. We have to emit this in a cleanup scope
465 // because it might be a singleton DeclStmt.
Douglas Gregor5656e142009-11-24 21:15:44 +0000466 {
John McCallf1549f62010-07-06 01:34:17 +0000467 RunCleanupsScope BodyScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000468 EmitBlock(LoopBody);
469 EmitStmt(S.getBody());
470 }
Chris Lattnerda138702007-07-16 21:28:45 +0000471
Mike Stump1eb44332009-09-09 15:08:12 +0000472 BreakContinueStack.pop_back();
473
John McCallf1549f62010-07-06 01:34:17 +0000474 // Immediately force cleanup.
475 ConditionScope.ForceCleanup();
Douglas Gregor5656e142009-11-24 21:15:44 +0000476
John McCallf1549f62010-07-06 01:34:17 +0000477 // Branch to the loop header again.
John McCallff8e1152010-07-23 21:56:41 +0000478 EmitBranch(LoopHeader.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000481 EmitBlock(LoopExit.getBlock(), true);
Douglas Gregor5656e142009-11-24 21:15:44 +0000482
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000483 // The LoopHeader typically is just a branch if we skipped emitting
484 // a branch, try to erase it.
John McCallf1549f62010-07-06 01:34:17 +0000485 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000486 SimplifyForwardingBlocks(LoopHeader.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000487}
488
489void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000490 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
491 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Chris Lattnerda138702007-07-16 21:28:45 +0000493 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000494 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000495
John McCallf1549f62010-07-06 01:34:17 +0000496 // Emit the body of the loop.
497 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
498 EmitBlock(LoopBody);
499 {
500 RunCleanupsScope BodyScope(*this);
501 EmitStmt(S.getBody());
502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Anders Carlssone4b6d342009-02-10 05:52:02 +0000504 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000505
John McCallff8e1152010-07-23 21:56:41 +0000506 EmitBlock(LoopCond.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
509 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 // Evaluate the conditional in the while header.
512 // C99 6.8.5p2/p4: The first substatement is executed if the expression
513 // compares unequal to 0. The condition must be a scalar type.
514 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000515
516 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
517 // to correctly handle break/continue though.
518 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000519 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000520 if (C->isZero())
521 EmitBoolCondBranch = false;
522
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000524 if (EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000525 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000528 EmitBlock(LoopExit.getBlock());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000529
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000530 // The DoCond block typically is just a branch if we skipped
531 // emitting a branch, try to erase it.
532 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000533 SimplifyForwardingBlocks(LoopCond.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000534}
535
536void CodeGenFunction::EmitForStmt(const ForStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000537 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
538
539 RunCleanupsScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000540
Devang Patel0554e0e2010-08-25 00:28:56 +0000541 CGDebugInfo *DI = getDebugInfo();
542 if (DI) {
543 DI->setLocation(S.getSourceRange().getBegin());
544 DI->EmitRegionStart(Builder);
545 }
546
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 // Evaluate the first part before the loop.
548 if (S.getInit())
549 EmitStmt(S.getInit());
550
551 // Start the loop with a block that tests the condition.
John McCallf1549f62010-07-06 01:34:17 +0000552 // If there's an increment, the continue scope will be overwritten
553 // later.
554 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
John McCallff8e1152010-07-23 21:56:41 +0000555 llvm::BasicBlock *CondBlock = Continue.getBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 EmitBlock(CondBlock);
557
Douglas Gregord9752062009-11-25 01:51:31 +0000558 // Create a cleanup scope for the condition variable cleanups.
John McCallf1549f62010-07-06 01:34:17 +0000559 RunCleanupsScope ConditionScope(*this);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000560
Douglas Gregord9752062009-11-25 01:51:31 +0000561 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000563 // If the for statement has a condition scope, emit the local variable
564 // declaration.
John McCallff8e1152010-07-23 21:56:41 +0000565 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Douglas Gregord9752062009-11-25 01:51:31 +0000566 if (S.getConditionVariable()) {
John McCallb6bbcc92010-10-15 04:57:14 +0000567 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000568 }
John McCallf1549f62010-07-06 01:34:17 +0000569
570 // If there are any cleanups between here and the loop-exit scope,
571 // create a block to stage a loop exit along.
572 if (ForScope.requiresCleanups())
573 ExitBlock = createBasicBlock("for.cond.cleanup");
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000576 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner31a09842008-11-12 08:04:58 +0000578 // C99 6.8.5p2/p4: The first substatement is executed if the expression
579 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000580 BoolCondVal = EvaluateExprAsBool(S.getCond());
John McCallf1549f62010-07-06 01:34:17 +0000581 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
582
John McCallff8e1152010-07-23 21:56:41 +0000583 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000584 EmitBlock(ExitBlock);
585 EmitBranchThroughCleanup(LoopExit);
586 }
Mike Stump1eb44332009-09-09 15:08:12 +0000587
588 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 } else {
590 // Treat it as a non-zero constant. Don't even create a new block for the
591 // body, just fall into it.
592 }
593
Mike Stump1eb44332009-09-09 15:08:12 +0000594 // If the for loop doesn't have an increment we can just use the
John McCallf1549f62010-07-06 01:34:17 +0000595 // condition as the continue block. Otherwise we'll need to create
596 // a block for it (in the current scope, i.e. in the scope of the
597 // condition), and that we will become our continue block.
Chris Lattnerda138702007-07-16 21:28:45 +0000598 if (S.getInc())
John McCallf1549f62010-07-06 01:34:17 +0000599 Continue = getJumpDestInCurrentScope("for.inc");
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattnerda138702007-07-16 21:28:45 +0000601 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000602 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Mike Stump3e9da662009-02-07 23:02:10 +0000603
Douglas Gregord9752062009-11-25 01:51:31 +0000604 {
605 // Create a separate cleanup scope for the body, in case it is not
606 // a compound statement.
John McCallf1549f62010-07-06 01:34:17 +0000607 RunCleanupsScope BodyScope(*this);
Douglas Gregord9752062009-11-25 01:51:31 +0000608 EmitStmt(S.getBody());
609 }
Chris Lattnerda138702007-07-16 21:28:45 +0000610
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000612 if (S.getInc()) {
John McCallff8e1152010-07-23 21:56:41 +0000613 EmitBlock(Continue.getBlock());
Chris Lattner883f6a72007-08-11 00:04:45 +0000614 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000615 }
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Douglas Gregor45d3fe12010-05-21 18:36:48 +0000617 BreakContinueStack.pop_back();
Douglas Gregord9752062009-11-25 01:51:31 +0000618
John McCallf1549f62010-07-06 01:34:17 +0000619 ConditionScope.ForceCleanup();
620 EmitBranch(CondBlock);
621
622 ForScope.ForceCleanup();
623
Devang Patelbbd9fa42009-10-06 18:36:08 +0000624 if (DI) {
625 DI->setLocation(S.getSourceRange().getEnd());
Devang Patel4d939e62010-07-20 22:20:10 +0000626 DI->EmitRegionEnd(Builder);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000627 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000628
Chris Lattnerda138702007-07-16 21:28:45 +0000629 // Emit the fall-through block.
John McCallff8e1152010-07-23 21:56:41 +0000630 EmitBlock(LoopExit.getBlock(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000631}
632
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000633void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
634 if (RV.isScalar()) {
635 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
636 } else if (RV.isAggregate()) {
637 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
638 } else {
639 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
640 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000641 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000642}
643
Reid Spencer5f016e22007-07-11 17:01:13 +0000644/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
645/// if the function returns void, or may be missing one if the function returns
646/// non-void. Fun stuff :).
647void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 // Emit the result value, even if unused, to evalute the side effects.
649 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000651 // FIXME: Clean this up by using an LValue for ReturnTemp,
652 // EmitStoreThroughLValue, and EmitAnyExpr.
Douglas Gregord86c4772010-05-15 06:46:45 +0000653 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
654 !Target.useGlobalsForAutomaticVariables()) {
655 // Apply the named return value optimization for this return statement,
656 // which means doing nothing: the appropriate result has already been
657 // constructed into the NRVO variable.
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000658
659 // If there is an NRVO flag for this variable, set it to 1 into indicate
660 // that the cleanup code should not destroy the variable.
John McCalld16c2cf2011-02-08 08:22:06 +0000661 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
662 Builder.CreateStore(Builder.getTrue(), NRVOFlag);
Douglas Gregord86c4772010-05-15 06:46:45 +0000663 } else if (!ReturnValue) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000664 // Make sure not to return anything, but evaluate the expression
665 // for side effects.
666 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000667 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000669 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000670 } else if (FnRetTy->isReferenceType()) {
671 // If this function returns a reference, take the address of the expression
672 // rather than the value.
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000673 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
Douglas Gregor33fd1fc2010-03-24 23:14:04 +0000674 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000675 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000676 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000677 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000678 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 } else {
John McCall558d2ab2010-09-15 10:14:12 +0000680 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, false, true));
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 }
Eli Friedman144ac612008-05-22 01:22:33 +0000682
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000683 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000684}
685
686void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000687 // As long as debug info is modeled with instructions, we have to ensure we
688 // have a place to insert here and write the stop point here.
689 if (getDebugInfo()) {
690 EnsureInsertPoint();
691 EmitStopPoint(&S);
692 }
693
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000694 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
695 I != E; ++I)
696 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000697}
Chris Lattnerda138702007-07-16 21:28:45 +0000698
Daniel Dunbar09124252008-11-12 08:21:33 +0000699void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000700 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
701
Daniel Dunbar09124252008-11-12 08:21:33 +0000702 // If this code is reachable then emit a stop point (if generating
703 // debug info). We have to do this ourselves because we are on the
704 // "simple" statement path.
705 if (HaveInsertPoint())
706 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000707
John McCallf1549f62010-07-06 01:34:17 +0000708 JumpDest Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000709 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000710}
711
Daniel Dunbar09124252008-11-12 08:21:33 +0000712void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000713 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
714
Daniel Dunbar09124252008-11-12 08:21:33 +0000715 // If this code is reachable then emit a stop point (if generating
716 // debug info). We have to do this ourselves because we are on the
717 // "simple" statement path.
718 if (HaveInsertPoint())
719 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000720
John McCallf1549f62010-07-06 01:34:17 +0000721 JumpDest Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000722 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000723}
Devang Patel51b09f22007-10-04 23:45:31 +0000724
Devang Patelc049e4f2007-10-08 20:57:48 +0000725/// EmitCaseStmtRange - If case statement range is not too big then
726/// add multiple cases to switch instruction, one for each value within
727/// the range. If range is too big then emit "if" condition check.
728void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000729 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000730
Anders Carlsson51fe9962008-11-22 21:04:56 +0000731 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
732 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000733
Daniel Dunbar16f23572008-07-25 01:11:38 +0000734 // Emit the code for this case. We do this first to make sure it is
735 // properly chained from our predecessor before generating the
736 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000737 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000738 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
739 EmitStmt(S.getSubStmt());
740
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000741 // If range is empty, do nothing.
742 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
743 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000744
745 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000746 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000747 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
748 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000749 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
John McCalld16c2cf2011-02-08 08:22:06 +0000750 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), LHS),
751 CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000752 LHS++;
753 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000754 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000755 }
756
Daniel Dunbar16f23572008-07-25 01:11:38 +0000757 // The range is too big. Emit "if" condition into a new block,
758 // making sure to save and restore the current insertion point.
759 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000760
Daniel Dunbar16f23572008-07-25 01:11:38 +0000761 // Push this test onto the chain of range checks (which terminates
762 // in the default basic block). The switch's default will be changed
763 // to the top of this chain after switch emission is complete.
764 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000765 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000766
Daniel Dunbar16f23572008-07-25 01:11:38 +0000767 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
768 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000769
770 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000771 llvm::Value *Diff =
772 Builder.CreateSub(SwitchInsn->getCondition(),
John McCalld16c2cf2011-02-08 08:22:06 +0000773 llvm::ConstantInt::get(getLLVMContext(), LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000774 llvm::Value *Cond =
John McCalld16c2cf2011-02-08 08:22:06 +0000775 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(getLLVMContext(), Range),
776 "inbounds");
Devang Patelc049e4f2007-10-08 20:57:48 +0000777 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
778
Daniel Dunbar16f23572008-07-25 01:11:38 +0000779 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000780 if (RestoreBB)
781 Builder.SetInsertPoint(RestoreBB);
782 else
783 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000784}
785
786void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
787 if (S.getRHS()) {
788 EmitCaseStmtRange(S);
789 return;
790 }
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000792 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000793 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000794 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
John McCalld16c2cf2011-02-08 08:22:06 +0000795 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), CaseVal),
796 CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattner5512f282009-03-04 04:46:18 +0000798 // Recursively emitting the statement is acceptable, but is not wonderful for
799 // code where we have many case statements nested together, i.e.:
800 // case 1:
801 // case 2:
802 // case 3: etc.
803 // Handling this recursively will create a new block for each case statement
804 // that falls through to the next case which is IR intensive. It also causes
805 // deep recursion which can run into stack depth limitations. Handle
806 // sequential non-range case statements specially.
807 const CaseStmt *CurCase = &S;
808 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
809
810 // Otherwise, iteratively add consequtive cases to this switch stmt.
811 while (NextCase && NextCase->getRHS() == 0) {
812 CurCase = NextCase;
813 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
John McCalld16c2cf2011-02-08 08:22:06 +0000814 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), CaseVal),
815 CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000816
817 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Chris Lattner5512f282009-03-04 04:46:18 +0000820 // Normal default recursion for non-cases.
821 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000822}
823
824void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000825 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000826 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000827 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000828 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000829 EmitStmt(S.getSubStmt());
830}
831
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000832/// CollectStatementsForCase - Given the body of a 'switch' statement and a
833/// constant value that is being switched on, see if we can dead code eliminate
834/// the body of the switch to a simple series of statements to emit. Basically,
835/// on a switch (5) we want to find these statements:
836/// case 5:
837/// printf(...); <--
838/// ++i; <--
839/// break;
840///
841/// and add them to the ResultStmts vector. If it is unsafe to do this
842/// transformation (for example, one of the elided statements contains a label
843/// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
844/// should include statements after it (e.g. the printf() line is a substmt of
845/// the case) then return CSFC_FallThrough. If we handled it and found a break
846/// statement, then return CSFC_Success.
847///
848/// If Case is non-null, then we are looking for the specified case, checking
849/// that nothing we jump over contains labels. If Case is null, then we found
850/// the case and are looking for the break.
851///
852/// If the recursive walk actually finds our Case, then we set FoundCase to
853/// true.
854///
855enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
856static CSFC_Result CollectStatementsForCase(const Stmt *S,
857 const SwitchCase *Case,
858 bool &FoundCase,
859 llvm::SmallVectorImpl<const Stmt*> &ResultStmts) {
860 // If this is the switchcase (case 4: or default) that we're looking for, then
861 // we're in business. Just add the substatement.
862 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
863 if (S == Case) {
864 FoundCase = true;
865 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
866 ResultStmts);
867 }
868
869 // Otherwise, this is some other case or default statement, just ignore it.
870 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
871 ResultStmts);
872 }
873
874 // Okay, this is some other statement that we don't handle explicitly, like a
875 // for statement or increment etc. If we are skipping over this statement,
876 // just verify it doesn't have labels, which would make it invalid to elide.
877 if (Case) {
878 if (CodeGenFunction::ContainsLabel(S, true))
879 return CSFC_Failure;
880 return CSFC_Success;
881 }
882
883 // Otherwise, we want to include this statement. Everything is cool with that
884 // so long as it doesn't contain a break out of the switch we're in.
885 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
886
887 // Otherwise, everything is great. Include the statement and tell the caller
888 // that we fall through and include the next statement as well.
889 ResultStmts.push_back(S);
890 return CSFC_FallThrough;
891}
892
893/// FindCaseStatementsForValue - Find the case statement being jumped to and
894/// then invoke CollectStatementsForCase to find the list of statements to emit
895/// for a switch on constant. See the comment above CollectStatementsForCase
896/// for more details.
897static bool FindCaseStatementsForValue(const SwitchStmt &S,
898 const llvm::APInt &ConstantCondValue,
899 llvm::SmallVectorImpl<const Stmt*> &ResultStmts,
900 ASTContext &C) {
901 // First step, find the switch case that is being branched to. We can do this
902 // efficiently by scanning the SwitchCase list.
903 const SwitchCase *Case = S.getSwitchCaseList();
904 const DefaultStmt *DefaultCase = 0;
905
906 for (; Case; Case = Case->getNextSwitchCase()) {
907 // It's either a default or case. Just remember the default statement in
908 // case we're not jumping to any numbered cases.
909 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
910 DefaultCase = DS;
911 continue;
912 }
913
914 // Check to see if this case is the one we're looking for.
915 const CaseStmt *CS = cast<CaseStmt>(Case);
916 // Don't handle case ranges yet.
917 if (CS->getRHS()) return false;
918
919 // If we found our case, remember it as 'case'.
920 if (CS->getLHS()->EvaluateAsInt(C) == ConstantCondValue)
921 break;
922 }
923
924 // If we didn't find a matching case, we use a default if it exists, or we
925 // elide the whole switch body!
926 if (Case == 0) {
927 // It is safe to elide the body of the switch if it doesn't contain labels
928 // etc. If it is safe, return successfully with an empty ResultStmts list.
929 if (DefaultCase == 0)
930 return !CodeGenFunction::ContainsLabel(&S);
931 Case = DefaultCase;
932 }
933
934 // Ok, we know which case is being jumped to, try to collect all the
935 // statements that follow it. This can fail for a variety of reasons. Also,
936 // check to see that the recursive walk actually found our case statement.
937 // Insane cases like this can fail to find it in the recursive walk since we
938 // don't handle every stmt kind:
939 // switch (4) {
940 // while (1) {
941 // case 4: ...
942 bool FoundCase = false;
943 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
944 ResultStmts) != CSFC_Failure &&
945 FoundCase;
946}
947
Devang Patel51b09f22007-10-04 23:45:31 +0000948void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000949 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
950
951 RunCleanupsScope ConditionScope(*this);
Douglas Gregord3d53012009-11-24 17:07:59 +0000952
953 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000954 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord3d53012009-11-24 17:07:59 +0000955
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000956 // See if we can constant fold the condition of the switch and therefore only
957 // emit the live case statement (if any) of the switch.
958 llvm::APInt ConstantCondValue;
959 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
960 llvm::SmallVector<const Stmt*, 4> CaseStmts;
961 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
962 getContext())) {
963 RunCleanupsScope ExecutedScope(*this);
964
965 // Okay, we can dead code eliminate everything except this case. Emit the
966 // specified series of statements and we're good.
967 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
968 EmitStmt(CaseStmts[i]);
969 return;
970 }
971 }
972
Devang Patel51b09f22007-10-04 23:45:31 +0000973 llvm::Value *CondV = EmitScalarExpr(S.getCond());
974
975 // Handle nested switch statements.
976 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000977 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000978
Daniel Dunbar16f23572008-07-25 01:11:38 +0000979 // Create basic block to hold stuff that comes after switch
980 // statement. We also need to create a default block now so that
981 // explicit case ranges tests can have a place to jump to on
982 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000983 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000984 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
985 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000986
Daniel Dunbar09124252008-11-12 08:21:33 +0000987 // Clear the insertion point to indicate we are in unreachable code.
988 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000989
Devang Patele9b8c0a2007-10-30 20:59:40 +0000990 // All break statements jump to NextBlock. If BreakContinueStack is non empty
991 // then reuse last ContinueBlock.
John McCallf1549f62010-07-06 01:34:17 +0000992 JumpDest OuterContinue;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000993 if (!BreakContinueStack.empty())
John McCallf1549f62010-07-06 01:34:17 +0000994 OuterContinue = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000995
John McCallf1549f62010-07-06 01:34:17 +0000996 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
Devang Patel51b09f22007-10-04 23:45:31 +0000997
998 // Emit switch body.
999 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Anders Carlssone4b6d342009-02-10 05:52:02 +00001001 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +00001002
Daniel Dunbar16f23572008-07-25 01:11:38 +00001003 // Update the default block in case explicit case range tests have
1004 // been chained on top.
1005 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +00001006
John McCallf1549f62010-07-06 01:34:17 +00001007 // If a default was never emitted:
Daniel Dunbar16f23572008-07-25 01:11:38 +00001008 if (!DefaultBlock->getParent()) {
John McCallf1549f62010-07-06 01:34:17 +00001009 // If we have cleanups, emit the default block so that there's a
1010 // place to jump through the cleanups from.
1011 if (ConditionScope.requiresCleanups()) {
1012 EmitBlock(DefaultBlock);
1013
1014 // Otherwise, just forward the default block to the switch end.
1015 } else {
John McCallff8e1152010-07-23 21:56:41 +00001016 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001017 delete DefaultBlock;
1018 }
Daniel Dunbar16f23572008-07-25 01:11:38 +00001019 }
Devang Patel51b09f22007-10-04 23:45:31 +00001020
John McCallff8e1152010-07-23 21:56:41 +00001021 ConditionScope.ForceCleanup();
1022
Daniel Dunbar16f23572008-07-25 01:11:38 +00001023 // Emit continuation.
John McCallff8e1152010-07-23 21:56:41 +00001024 EmitBlock(SwitchExit.getBlock(), true);
Daniel Dunbar16f23572008-07-25 01:11:38 +00001025
Devang Patel51b09f22007-10-04 23:45:31 +00001026 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +00001027 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001028}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001029
Chris Lattner2819fa82009-04-26 17:57:12 +00001030static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +00001031SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001032 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001033 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001035 while (*Constraint) {
1036 switch (*Constraint) {
1037 default:
John Thompson2f474ea2010-09-18 01:15:13 +00001038 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001039 break;
1040 // Ignore these
1041 case '*':
1042 case '?':
1043 case '!':
John Thompsonef44e112010-08-10 19:20:14 +00001044 case '=': // Will see this and the following in mult-alt constraints.
1045 case '+':
1046 break;
John Thompson2f474ea2010-09-18 01:15:13 +00001047 case ',':
1048 Result += "|";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001049 break;
1050 case 'g':
1051 Result += "imr";
1052 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001053 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +00001054 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001055 "Must pass output names to constraints with a symbolic name");
1056 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +00001057 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +00001058 &(*OutCons)[0],
1059 OutCons->size(), Index);
Chris Lattnercbf40f92011-01-05 18:41:53 +00001060 assert(result && "Could not resolve symbolic name"); (void)result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001061 Result += llvm::utostr(Index);
1062 break;
1063 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001066 Constraint++;
1067 }
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001069 return Result;
1070}
1071
Rafael Espindola03117d12011-01-01 21:12:33 +00001072/// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1073/// as using a particular register add that as a constraint that will be used
1074/// in this asm stmt.
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001075static std::string
Rafael Espindola03117d12011-01-01 21:12:33 +00001076AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1077 const TargetInfo &Target, CodeGenModule &CGM,
1078 const AsmStmt &Stmt) {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001079 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1080 if (!AsmDeclRef)
1081 return Constraint;
1082 const ValueDecl &Value = *AsmDeclRef->getDecl();
1083 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1084 if (!Variable)
1085 return Constraint;
1086 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1087 if (!Attr)
1088 return Constraint;
1089 llvm::StringRef Register = Attr->getLabel();
Rafael Espindolabaf86952011-01-01 21:47:03 +00001090 assert(Target.isValidGCCRegisterName(Register));
Rafael Espindola33a53442011-01-02 03:59:13 +00001091 // FIXME: We should check which registers are compatible with "r" or "x".
1092 if (Constraint != "r" && Constraint != "x") {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001093 CGM.ErrorUnsupported(&Stmt, "__asm__");
1094 return Constraint;
1095 }
1096 return "{" + Register.str() + "}";
1097}
1098
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001099llvm::Value*
1100CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
1101 const TargetInfo::ConstraintInfo &Info,
1102 LValue InputValue, QualType InputType,
1103 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +00001104 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00001105 if (Info.allowsRegister() || !Info.allowsMemory()) {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001106 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
1107 Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
Anders Carlsson63471722009-01-11 19:32:54 +00001108 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001109 const llvm::Type *Ty = ConvertType(InputType);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001110 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
1111 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
John McCalld16c2cf2011-02-08 08:22:06 +00001112 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001113 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001115 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1116 Ty));
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001117 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001118 Arg = InputValue.getAddress();
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001119 ConstraintStr += '*';
1120 }
Anders Carlsson63471722009-01-11 19:32:54 +00001121 }
1122 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001123 Arg = InputValue.getAddress();
Anders Carlsson63471722009-01-11 19:32:54 +00001124 ConstraintStr += '*';
1125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Anders Carlsson63471722009-01-11 19:32:54 +00001127 return Arg;
1128}
1129
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001130llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
1131 const TargetInfo::ConstraintInfo &Info,
1132 const Expr *InputExpr,
1133 std::string &ConstraintStr) {
1134 if (Info.allowsRegister() || !Info.allowsMemory())
1135 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
1136 return EmitScalarExpr(InputExpr);
1137
1138 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1139 LValue Dest = EmitLValue(InputExpr);
1140 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
1141}
1142
Chris Lattner47fc7e92010-11-17 05:58:54 +00001143/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
Chris Lattner5d936532010-11-17 08:25:26 +00001144/// asm call instruction. The !srcloc MDNode contains a list of constant
1145/// integers which are the source locations of the start of each line in the
1146/// asm.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001147static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1148 CodeGenFunction &CGF) {
Chris Lattner5d936532010-11-17 08:25:26 +00001149 llvm::SmallVector<llvm::Value *, 8> Locs;
1150 // Add the location of the first line to the MDNode.
1151 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1152 Str->getLocStart().getRawEncoding()));
1153 llvm::StringRef StrVal = Str->getString();
1154 if (!StrVal.empty()) {
1155 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1156 const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1157
1158 // Add the location of the start of each subsequent line of the asm to the
1159 // MDNode.
1160 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1161 if (StrVal[i] != '\n') continue;
1162 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1163 CGF.Target);
1164 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1165 LineLoc.getRawEncoding()));
1166 }
1167 }
1168
1169 return llvm::MDNode::get(CGF.getLLVMContext(), Locs.data(), Locs.size());
Chris Lattner47fc7e92010-11-17 05:58:54 +00001170}
1171
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001172void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +00001173 // Analyze the asm string to decompose it into its pieces. We know that Sema
1174 // has already done this, so it is guaranteed to be successful.
1175 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001176 unsigned DiagOffs;
1177 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Chris Lattner458cd9c2009-03-10 23:21:44 +00001179 // Assemble the pieces into the final asm string.
1180 std::string AsmString;
1181 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1182 if (Pieces[i].isString())
1183 AsmString += Pieces[i].getString();
1184 else if (Pieces[i].getModifier() == '\0')
1185 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1186 else
1187 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1188 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +00001189 }
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Chris Lattner481fef92009-05-03 07:05:00 +00001191 // Get all the output and input constraints together.
1192 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1193 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1194
Mike Stump1eb44332009-09-09 15:08:12 +00001195 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001196 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1197 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001198 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1199 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +00001200 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001201 }
1202
Chris Lattner481fef92009-05-03 07:05:00 +00001203 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1204 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1205 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001206 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1207 S.getNumOutputs(), Info);
1208 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +00001209 InputConstraintInfos.push_back(Info);
1210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001212 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Chris Lattnerede9d902009-05-03 07:53:25 +00001214 std::vector<LValue> ResultRegDests;
1215 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001216 std::vector<const llvm::Type *> ResultRegTypes;
1217 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001218 std::vector<const llvm::Type*> ArgTypes;
1219 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001220
1221 // Keep track of inout constraints.
1222 std::string InOutConstraints;
1223 std::vector<llvm::Value*> InOutArgs;
1224 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +00001225
Mike Stump1eb44332009-09-09 15:08:12 +00001226 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001227 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +00001228
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001229 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001230 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001231 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chris Lattner810f6d52009-03-13 17:38:01 +00001233 const Expr *OutExpr = S.getOutputExpr(i);
1234 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Rafael Espindola03117d12011-01-01 21:12:33 +00001236 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, Target,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001237 CGM, S);
1238
Chris Lattner810f6d52009-03-13 17:38:01 +00001239 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +00001240 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +00001241 Constraints += ',';
1242
Chris Lattnera077b5c2009-05-03 08:21:20 +00001243 // If this is a register output, then make the inline asm return it
1244 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +00001245 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001246 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +00001247 ResultRegQualTys.push_back(OutExpr->getType());
1248 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001249 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1250 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Chris Lattnera077b5c2009-05-03 08:21:20 +00001252 // If this output is tied to an input, and if the input is larger, then
1253 // we need to set the actual result type of the inline asm node to be the
1254 // same as the input type.
1255 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +00001256 unsigned InputNo;
1257 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1258 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001259 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001260 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001261 }
1262 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Chris Lattnera077b5c2009-05-03 08:21:20 +00001264 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001265 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Chris Lattnera077b5c2009-05-03 08:21:20 +00001267 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001268 if (getContext().getTypeSize(OutputType) < InputSize) {
1269 // Form the asm to return the value as a larger integer or fp type.
1270 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001271 }
1272 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001273 if (const llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001274 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1275 ResultRegTypes.back()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001276 ResultRegTypes.back() = AdjTy;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001277 } else {
1278 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001279 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001280 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001281 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001282 }
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Chris Lattner44def072009-04-26 07:16:29 +00001284 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001285 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001286
Anders Carlssonfca93612009-08-04 18:18:36 +00001287 const Expr *InputExpr = S.getOutputExpr(i);
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001288 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1289 InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Chris Lattner44def072009-04-26 07:16:29 +00001291 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001292 InOutConstraints += llvm::utostr(i);
1293 else
1294 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001295
Anders Carlssonfca93612009-08-04 18:18:36 +00001296 InOutArgTypes.push_back(Arg->getType());
1297 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001298 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001299 }
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001301 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001303 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1304 const Expr *InputExpr = S.getInputExpr(i);
1305
Chris Lattner481fef92009-05-03 07:05:00 +00001306 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1307
Chris Lattnerede9d902009-05-03 07:53:25 +00001308 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001309 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001311 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001312 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001313 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001314 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001315
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001316 InputConstraint =
Rafael Espindola03117d12011-01-01 21:12:33 +00001317 AddVariableConstraints(InputConstraint,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001318 *InputExpr->IgnoreParenNoopCasts(getContext()),
1319 Target, CGM, S);
1320
Anders Carlsson63471722009-01-11 19:32:54 +00001321 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Chris Lattner4df4ee02009-05-03 07:27:51 +00001323 // If this input argument is tied to a larger output result, extend the
1324 // input to be the same size as the output. The LLVM backend wants to see
1325 // the input and output of a matching constraint be the same size. Note
1326 // that GCC does not define what the top bits are here. We use zext because
1327 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1328 if (Info.hasTiedOperand()) {
1329 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001330 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001331 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Chris Lattneraab64d02010-04-23 17:27:29 +00001333 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001334 getContext().getTypeSize(InputTy)) {
1335 // Use ptrtoint as appropriate so that we can do our extension.
1336 if (isa<llvm::PointerType>(Arg->getType()))
Chris Lattner77b89b82010-06-27 07:15:29 +00001337 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001338 const llvm::Type *OutputTy = ConvertType(OutputType);
1339 if (isa<llvm::IntegerType>(OutputTy))
1340 Arg = Builder.CreateZExt(Arg, OutputTy);
1341 else
1342 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001343 }
1344 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001345 if (const llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001346 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1347 Arg->getType()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001348 Arg = Builder.CreateBitCast(Arg, AdjTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001350 ArgTypes.push_back(Arg->getType());
1351 Args.push_back(Arg);
1352 Constraints += InputConstraint;
1353 }
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Anders Carlssonf39a4212008-02-05 20:01:53 +00001355 // Append the "input" part of inout constraints last.
1356 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1357 ArgTypes.push_back(InOutArgTypes[i]);
1358 Args.push_back(InOutArgs[i]);
1359 }
1360 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001362 // Clobbers
1363 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001364 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001365
Anders Carlsson83c021c2010-01-30 19:12:25 +00001366 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Anders Carlssonea041752008-02-06 00:11:32 +00001368 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001369 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Anders Carlssonea041752008-02-06 00:11:32 +00001371 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001372 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001373 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001374 }
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001376 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001377 std::string MachineClobbers = Target.getClobbers();
1378 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001379 if (!Constraints.empty())
1380 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001381 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001382 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001383
1384 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001385 if (ResultRegTypes.empty())
John McCalld16c2cf2011-02-08 08:22:06 +00001386 ResultType = llvm::Type::getVoidTy(getLLVMContext());
Chris Lattnera077b5c2009-05-03 08:21:20 +00001387 else if (ResultRegTypes.size() == 1)
1388 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001389 else
John McCalld16c2cf2011-02-08 08:22:06 +00001390 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
1392 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001393 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001394
1395 llvm::InlineAsm *IA =
1396 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001397 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001398 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001399 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001401 // Slap the source location of the inline asm into a !srcloc metadata on the
1402 // call.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001403 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Chris Lattnera077b5c2009-05-03 08:21:20 +00001405 // Extract all of the register value results from the asm.
1406 std::vector<llvm::Value*> RegResults;
1407 if (ResultRegTypes.size() == 1) {
1408 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001409 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001410 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001411 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001412 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001413 }
1414 }
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Chris Lattnera077b5c2009-05-03 08:21:20 +00001416 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1417 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Chris Lattnera077b5c2009-05-03 08:21:20 +00001419 // If the result type of the LLVM IR asm doesn't match the result type of
1420 // the expression, do the conversion.
1421 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1422 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001423
1424 // Truncate the integer result to the right size, note that TruncTy can be
1425 // a pointer.
1426 if (TruncTy->isFloatingPointTy())
1427 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001428 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001429 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
John McCalld16c2cf2011-02-08 08:22:06 +00001430 Tmp = Builder.CreateTrunc(Tmp,
1431 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001432 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001433 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1434 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
John McCalld16c2cf2011-02-08 08:22:06 +00001435 Tmp = Builder.CreatePtrToInt(Tmp,
1436 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
Dan Gohman2dca88f2010-04-24 04:55:02 +00001437 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1438 } else if (TruncTy->isIntegerTy()) {
1439 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001440 } else if (TruncTy->isVectorTy()) {
1441 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001442 }
1443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Chris Lattnera077b5c2009-05-03 08:21:20 +00001445 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1446 ResultRegQualTys[i]);
1447 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001448}