blob: a46a41262709ed4b4cd00c71da625d572fdee9b8 [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()) {
Devang Patel60e4fd92010-05-12 00:39:34 +000033 if (isa<DeclStmt>(S))
34 DI->setLocation(S->getLocEnd());
35 else
36 DI->setLocation(S->getLocStart());
Devang Patel5a6fbcf2010-07-22 22:29:16 +000037 DI->UpdateLineDirectiveRegion(Builder);
Devang Patel4d939e62010-07-20 22:20:10 +000038 DI->EmitStopPoint(Builder);
Daniel Dunbar09124252008-11-12 08:21:33 +000039 }
40}
41
Reid Spencer5f016e22007-07-11 17:01:13 +000042void CodeGenFunction::EmitStmt(const Stmt *S) {
43 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000044
Daniel Dunbar09124252008-11-12 08:21:33 +000045 // Check if we can handle this without bothering to generate an
46 // insert point or debug info.
47 if (EmitSimpleStmt(S))
48 return;
49
Daniel Dunbard286f052009-07-19 06:58:07 +000050 // Check if we are generating unreachable code.
51 if (!HaveInsertPoint()) {
52 // If so, and the statement doesn't contain a label, then we do not need to
53 // generate actual code. This is safe because (1) the current point is
54 // unreachable, so we don't need to execute the code, and (2) we've already
55 // handled the statements which update internal data structures (like the
56 // local variable map) which could be used by subsequent statements.
57 if (!ContainsLabel(S)) {
58 // Verify that any decl statements were handled as simple, they may be in
59 // scope of subsequent reachable statements.
60 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
61 return;
62 }
63
64 // Otherwise, make a new block to hold the code.
65 EnsureInsertPoint();
66 }
67
Daniel Dunbar09124252008-11-12 08:21:33 +000068 // Generate a stoppoint if we are emitting debug info.
69 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000070
Reid Spencer5f016e22007-07-11 17:01:13 +000071 switch (S->getStmtClass()) {
John McCall2a416372010-12-05 02:00:02 +000072 case Stmt::NoStmtClass:
73 case Stmt::CXXCatchStmtClass:
74 case Stmt::SwitchCaseClass:
75 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"
92 EmitIgnoredExpr(cast<Expr>(S));
Mike Stump1eb44332009-09-09 15:08:12 +000093
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000094 // Expression emitters don't handle unreachable blocks yet, so look for one
95 // explicitly here. This handles the common case of a call to a noreturn
96 // function.
97 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
John McCallf1549f62010-07-06 01:34:17 +000098 if (CurBB->empty() && CurBB->use_empty()) {
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000099 CurBB->eraseFromParent();
100 Builder.ClearInsertionPoint();
101 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 }
103 break;
John McCall2a416372010-12-05 02:00:02 +0000104
Mike Stump1eb44332009-09-09 15:08:12 +0000105 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000106 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000107
108 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
109 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
110 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
111 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +0000114
Devang Patel51b09f22007-10-04 23:45:31 +0000115 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000116 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000117
118 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000119 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000120 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000121 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000122 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
123 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000124 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000125 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000126 break;
127 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000128 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000129 break;
130 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000131 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000132 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000133 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000134 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000135 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000136
137 case Stmt::CXXTryStmtClass:
138 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
139 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 }
141}
142
Daniel Dunbar09124252008-11-12 08:21:33 +0000143bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
144 switch (S->getStmtClass()) {
145 default: return false;
146 case Stmt::NullStmtClass: break;
147 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000148 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000149 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
150 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
151 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
152 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
153 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
154 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
155 }
156
157 return true;
158}
159
Chris Lattner33793202007-08-31 22:09:40 +0000160/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
161/// this captures the expression result of the last sub-statement and returns it
162/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000163RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
John McCall558d2ab2010-09-15 10:14:12 +0000164 AggValueSlot AggSlot) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000165 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
166 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Anders Carlssone896d982009-02-13 08:11:52 +0000168 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000169 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000170 DI->setLocation(S.getLBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000171 DI->EmitRegionStart(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000172 }
173
Anders Carlssonc71c8452009-02-07 23:50:39 +0000174 // Keep track of the current cleanup stack depth.
John McCallf1549f62010-07-06 01:34:17 +0000175 RunCleanupsScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Chris Lattner33793202007-08-31 22:09:40 +0000177 for (CompoundStmt::const_body_iterator I = S.body_begin(),
178 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000180
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000181 if (DI) {
Devang Patelcd9199e2010-04-13 00:08:43 +0000182 DI->setLocation(S.getRBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000183 DI->EmitRegionEnd(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000184 }
185
Anders Carlsson17d28a32008-12-12 05:52:00 +0000186 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000187 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000188 RV = RValue::get(0);
189 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000190 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000191 // at the end of a statement expression, they yield the value of their
192 // subexpression. Handle this by walking through all labels we encounter,
193 // emitting them before we evaluate the subexpr.
194 const Stmt *LastStmt = S.body_back();
195 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
196 EmitLabel(*LS);
197 LastStmt = LS->getSubStmt();
198 }
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Anders Carlsson17d28a32008-12-12 05:52:00 +0000200 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000201
John McCall558d2ab2010-09-15 10:14:12 +0000202 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
Anders Carlsson17d28a32008-12-12 05:52:00 +0000203 }
204
Anders Carlsson17d28a32008-12-12 05:52:00 +0000205 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000206}
207
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000208void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
209 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000211 // If there is a cleanup stack, then we it isn't worth trying to
212 // simplify this block (we would need to remove it from the scope map
213 // and cleanup entry).
John McCallf1549f62010-07-06 01:34:17 +0000214 if (!EHStack.empty())
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000215 return;
216
217 // Can only simplify direct branches.
218 if (!BI || !BI->isUnconditional())
219 return;
220
221 BB->replaceAllUsesWith(BI->getSuccessor(0));
222 BI->eraseFromParent();
223 BB->eraseFromParent();
224}
225
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000226void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000227 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
228
Daniel Dunbard57a8712008-11-11 09:41:28 +0000229 // Fall out of the current block (if necessary).
230 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000231
232 if (IsFinished && BB->use_empty()) {
233 delete BB;
234 return;
235 }
236
John McCall839cbaa2010-04-21 10:29:06 +0000237 // Place the block after the current block, if possible, or else at
238 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000239 if (CurBB && CurBB->getParent())
240 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
John McCall839cbaa2010-04-21 10:29:06 +0000241 else
242 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 Builder.SetInsertPoint(BB);
244}
245
Daniel Dunbard57a8712008-11-11 09:41:28 +0000246void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
247 // Emit a branch from the current block to the target one if this
248 // was a real block. If this was just a fall-through block after a
249 // terminator, don't emit it.
250 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
251
252 if (!CurBB || CurBB->getTerminator()) {
253 // If there is no insert point or the previous block is already
254 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000255 } else {
256 // Otherwise, create a fall-through branch.
257 Builder.CreateBr(Target);
258 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000259
260 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000261}
262
John McCallf1549f62010-07-06 01:34:17 +0000263CodeGenFunction::JumpDest
264CodeGenFunction::getJumpDestForLabel(const LabelStmt *S) {
265 JumpDest &Dest = LabelMap[S];
John McCallff8e1152010-07-23 21:56:41 +0000266 if (Dest.isValid()) return Dest;
John McCallf1549f62010-07-06 01:34:17 +0000267
268 // Create, but don't insert, the new block.
John McCallff8e1152010-07-23 21:56:41 +0000269 Dest = JumpDest(createBasicBlock(S->getName()),
270 EHScopeStack::stable_iterator::invalid(),
271 NextCleanupDestIndex++);
John McCallf1549f62010-07-06 01:34:17 +0000272 return Dest;
273}
274
Mike Stumpec9771d2009-02-08 09:22:19 +0000275void CodeGenFunction::EmitLabel(const LabelStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000276 JumpDest &Dest = LabelMap[&S];
277
John McCallff8e1152010-07-23 21:56:41 +0000278 // If we didn't need a forward reference to this label, just go
John McCallf1549f62010-07-06 01:34:17 +0000279 // ahead and create a destination at the current scope.
John McCallff8e1152010-07-23 21:56:41 +0000280 if (!Dest.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000281 Dest = getJumpDestInCurrentScope(S.getName());
282
283 // Otherwise, we need to give this label a target depth and remove
284 // it from the branch-fixups list.
285 } else {
John McCallff8e1152010-07-23 21:56:41 +0000286 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
287 Dest = JumpDest(Dest.getBlock(),
288 EHStack.stable_begin(),
289 Dest.getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000290
John McCallff8e1152010-07-23 21:56:41 +0000291 ResolveBranchFixups(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000292 }
293
John McCallff8e1152010-07-23 21:56:41 +0000294 EmitBlock(Dest.getBlock());
Chris Lattner91d723d2008-07-26 20:23:23 +0000295}
296
297
298void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
299 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 EmitStmt(S.getSubStmt());
301}
302
303void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000304 // If this code is reachable then emit a stop point (if generating
305 // debug info). We have to do this ourselves because we are on the
306 // "simple" statement path.
307 if (HaveInsertPoint())
308 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000309
John McCallf1549f62010-07-06 01:34:17 +0000310 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000311}
312
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000313
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000314void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
John McCall95c225d2010-10-28 08:53:48 +0000315 if (const LabelStmt *Target = S.getConstantTarget()) {
316 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
317 return;
318 }
319
Chris Lattner49c952f2009-11-06 18:10:47 +0000320 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000321 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
322 llvm::Type::getInt8PtrTy(VMContext),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000323 "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000324 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
325
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000326
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000327 // Get the basic block for the indirect goto.
328 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
329
330 // The first instruction in the block has to be the PHI for the switch dest,
331 // add an entry for this branch.
332 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
333
334 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000335}
336
Chris Lattner62b72f62008-11-11 07:24:28 +0000337void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 // C99 6.8.4.1: The first substatement is executed if the expression compares
339 // unequal to 0. The condition must be a scalar type.
John McCallf1549f62010-07-06 01:34:17 +0000340 RunCleanupsScope ConditionScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000341
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000342 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000343 EmitAutoVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattner9bc47e22008-11-12 07:46:33 +0000345 // If the condition constant folds and can be elided, try to avoid emitting
346 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000347 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000348 // Figure out which block (then or else) is executed.
349 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000350 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000351 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Chris Lattner62b72f62008-11-11 07:24:28 +0000353 // If the skipped block has no labels in it, just emit the executed block.
354 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000355 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000356 if (Executed) {
John McCallf1549f62010-07-06 01:34:17 +0000357 RunCleanupsScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000358 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000359 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000360 return;
361 }
362 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000363
364 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
365 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000366 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
367 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
368 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000370 ElseBlock = createBasicBlock("if.else");
371 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000374 EmitBlock(ThenBlock);
375 {
John McCallf1549f62010-07-06 01:34:17 +0000376 RunCleanupsScope ThenScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000377 EmitStmt(S.getThen());
378 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000379 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // Emit the 'else' code if present.
382 if (const Stmt *Else = S.getElse()) {
383 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000384 {
John McCallf1549f62010-07-06 01:34:17 +0000385 RunCleanupsScope ElseScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000386 EmitStmt(Else);
387 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000388 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 }
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000392 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000393}
394
395void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000396 // Emit the header for the loop, which will also become
397 // the continue target.
398 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
John McCallff8e1152010-07-23 21:56:41 +0000399 EmitBlock(LoopHeader.getBlock());
Mike Stump72cac2c2009-02-07 18:08:12 +0000400
John McCallf1549f62010-07-06 01:34:17 +0000401 // Create an exit block for when the condition fails, which will
402 // also become the break target.
403 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
Mike Stump72cac2c2009-02-07 18:08:12 +0000404
405 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000406 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Douglas Gregor5656e142009-11-24 21:15:44 +0000408 // C++ [stmt.while]p2:
409 // When the condition of a while statement is a declaration, the
410 // scope of the variable that is declared extends from its point
411 // of declaration (3.3.2) to the end of the while statement.
412 // [...]
413 // The object created in a condition is destroyed and created
414 // with each iteration of the loop.
John McCallf1549f62010-07-06 01:34:17 +0000415 RunCleanupsScope ConditionScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000416
John McCallf1549f62010-07-06 01:34:17 +0000417 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000418 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregor5656e142009-11-24 21:15:44 +0000419
Mike Stump16b16202009-02-07 17:18:33 +0000420 // Evaluate the conditional in the while header. C99 6.8.5.1: The
421 // evaluation of the controlling expression takes place before each
422 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000424
Devang Patel2c30d8f2007-10-09 20:51:27 +0000425 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000427 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000428 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000429 if (C->isOne())
430 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 // As long as the condition is true, go to the loop body.
John McCallf1549f62010-07-06 01:34:17 +0000433 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
434 if (EmitBoolCondBranch) {
John McCallff8e1152010-07-23 21:56:41 +0000435 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
John McCallf1549f62010-07-06 01:34:17 +0000436 if (ConditionScope.requiresCleanups())
437 ExitBlock = createBasicBlock("while.exit");
438
439 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
440
John McCallff8e1152010-07-23 21:56:41 +0000441 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000442 EmitBlock(ExitBlock);
443 EmitBranchThroughCleanup(LoopExit);
444 }
445 }
Douglas Gregor5656e142009-11-24 21:15:44 +0000446
John McCallf1549f62010-07-06 01:34:17 +0000447 // Emit the loop body. We have to emit this in a cleanup scope
448 // because it might be a singleton DeclStmt.
Douglas Gregor5656e142009-11-24 21:15:44 +0000449 {
John McCallf1549f62010-07-06 01:34:17 +0000450 RunCleanupsScope BodyScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000451 EmitBlock(LoopBody);
452 EmitStmt(S.getBody());
453 }
Chris Lattnerda138702007-07-16 21:28:45 +0000454
Mike Stump1eb44332009-09-09 15:08:12 +0000455 BreakContinueStack.pop_back();
456
John McCallf1549f62010-07-06 01:34:17 +0000457 // Immediately force cleanup.
458 ConditionScope.ForceCleanup();
Douglas Gregor5656e142009-11-24 21:15:44 +0000459
John McCallf1549f62010-07-06 01:34:17 +0000460 // Branch to the loop header again.
John McCallff8e1152010-07-23 21:56:41 +0000461 EmitBranch(LoopHeader.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000464 EmitBlock(LoopExit.getBlock(), true);
Douglas Gregor5656e142009-11-24 21:15:44 +0000465
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000466 // The LoopHeader typically is just a branch if we skipped emitting
467 // a branch, try to erase it.
John McCallf1549f62010-07-06 01:34:17 +0000468 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000469 SimplifyForwardingBlocks(LoopHeader.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000470}
471
472void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000473 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
474 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Chris Lattnerda138702007-07-16 21:28:45 +0000476 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000477 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000478
John McCallf1549f62010-07-06 01:34:17 +0000479 // Emit the body of the loop.
480 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
481 EmitBlock(LoopBody);
482 {
483 RunCleanupsScope BodyScope(*this);
484 EmitStmt(S.getBody());
485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Anders Carlssone4b6d342009-02-10 05:52:02 +0000487 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
John McCallff8e1152010-07-23 21:56:41 +0000489 EmitBlock(LoopCond.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
492 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 // Evaluate the conditional in the while header.
495 // C99 6.8.5p2/p4: The first substatement is executed if the expression
496 // compares unequal to 0. The condition must be a scalar type.
497 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000498
499 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
500 // to correctly handle break/continue though.
501 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000502 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000503 if (C->isZero())
504 EmitBoolCondBranch = false;
505
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000507 if (EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000508 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000511 EmitBlock(LoopExit.getBlock());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000512
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000513 // The DoCond block typically is just a branch if we skipped
514 // emitting a branch, try to erase it.
515 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000516 SimplifyForwardingBlocks(LoopCond.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000517}
518
519void CodeGenFunction::EmitForStmt(const ForStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000520 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
521
522 RunCleanupsScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000523
Devang Patel0554e0e2010-08-25 00:28:56 +0000524 CGDebugInfo *DI = getDebugInfo();
525 if (DI) {
526 DI->setLocation(S.getSourceRange().getBegin());
527 DI->EmitRegionStart(Builder);
528 }
529
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 // Evaluate the first part before the loop.
531 if (S.getInit())
532 EmitStmt(S.getInit());
533
534 // Start the loop with a block that tests the condition.
John McCallf1549f62010-07-06 01:34:17 +0000535 // If there's an increment, the continue scope will be overwritten
536 // later.
537 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
John McCallff8e1152010-07-23 21:56:41 +0000538 llvm::BasicBlock *CondBlock = Continue.getBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 EmitBlock(CondBlock);
540
Douglas Gregord9752062009-11-25 01:51:31 +0000541 // Create a cleanup scope for the condition variable cleanups.
John McCallf1549f62010-07-06 01:34:17 +0000542 RunCleanupsScope ConditionScope(*this);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000543
Douglas Gregord9752062009-11-25 01:51:31 +0000544 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000546 // If the for statement has a condition scope, emit the local variable
547 // declaration.
John McCallff8e1152010-07-23 21:56:41 +0000548 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Douglas Gregord9752062009-11-25 01:51:31 +0000549 if (S.getConditionVariable()) {
John McCallb6bbcc92010-10-15 04:57:14 +0000550 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000551 }
John McCallf1549f62010-07-06 01:34:17 +0000552
553 // If there are any cleanups between here and the loop-exit scope,
554 // create a block to stage a loop exit along.
555 if (ForScope.requiresCleanups())
556 ExitBlock = createBasicBlock("for.cond.cleanup");
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000557
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000559 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Chris Lattner31a09842008-11-12 08:04:58 +0000561 // C99 6.8.5p2/p4: The first substatement is executed if the expression
562 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000563 BoolCondVal = EvaluateExprAsBool(S.getCond());
John McCallf1549f62010-07-06 01:34:17 +0000564 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
565
John McCallff8e1152010-07-23 21:56:41 +0000566 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000567 EmitBlock(ExitBlock);
568 EmitBranchThroughCleanup(LoopExit);
569 }
Mike Stump1eb44332009-09-09 15:08:12 +0000570
571 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 } else {
573 // Treat it as a non-zero constant. Don't even create a new block for the
574 // body, just fall into it.
575 }
576
Mike Stump1eb44332009-09-09 15:08:12 +0000577 // If the for loop doesn't have an increment we can just use the
John McCallf1549f62010-07-06 01:34:17 +0000578 // condition as the continue block. Otherwise we'll need to create
579 // a block for it (in the current scope, i.e. in the scope of the
580 // condition), and that we will become our continue block.
Chris Lattnerda138702007-07-16 21:28:45 +0000581 if (S.getInc())
John McCallf1549f62010-07-06 01:34:17 +0000582 Continue = getJumpDestInCurrentScope("for.inc");
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattnerda138702007-07-16 21:28:45 +0000584 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000585 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Mike Stump3e9da662009-02-07 23:02:10 +0000586
Douglas Gregord9752062009-11-25 01:51:31 +0000587 {
588 // Create a separate cleanup scope for the body, in case it is not
589 // a compound statement.
John McCallf1549f62010-07-06 01:34:17 +0000590 RunCleanupsScope BodyScope(*this);
Douglas Gregord9752062009-11-25 01:51:31 +0000591 EmitStmt(S.getBody());
592 }
Chris Lattnerda138702007-07-16 21:28:45 +0000593
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000595 if (S.getInc()) {
John McCallff8e1152010-07-23 21:56:41 +0000596 EmitBlock(Continue.getBlock());
Chris Lattner883f6a72007-08-11 00:04:45 +0000597 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000598 }
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Douglas Gregor45d3fe12010-05-21 18:36:48 +0000600 BreakContinueStack.pop_back();
Douglas Gregord9752062009-11-25 01:51:31 +0000601
John McCallf1549f62010-07-06 01:34:17 +0000602 ConditionScope.ForceCleanup();
603 EmitBranch(CondBlock);
604
605 ForScope.ForceCleanup();
606
Devang Patelbbd9fa42009-10-06 18:36:08 +0000607 if (DI) {
608 DI->setLocation(S.getSourceRange().getEnd());
Devang Patel4d939e62010-07-20 22:20:10 +0000609 DI->EmitRegionEnd(Builder);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000610 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000611
Chris Lattnerda138702007-07-16 21:28:45 +0000612 // Emit the fall-through block.
John McCallff8e1152010-07-23 21:56:41 +0000613 EmitBlock(LoopExit.getBlock(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000614}
615
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000616void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
617 if (RV.isScalar()) {
618 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
619 } else if (RV.isAggregate()) {
620 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
621 } else {
622 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
623 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000624 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000625}
626
Reid Spencer5f016e22007-07-11 17:01:13 +0000627/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
628/// if the function returns void, or may be missing one if the function returns
629/// non-void. Fun stuff :).
630void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 // Emit the result value, even if unused, to evalute the side effects.
632 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000634 // FIXME: Clean this up by using an LValue for ReturnTemp,
635 // EmitStoreThroughLValue, and EmitAnyExpr.
Douglas Gregord86c4772010-05-15 06:46:45 +0000636 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
637 !Target.useGlobalsForAutomaticVariables()) {
638 // Apply the named return value optimization for this return statement,
639 // which means doing nothing: the appropriate result has already been
640 // constructed into the NRVO variable.
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000641
642 // If there is an NRVO flag for this variable, set it to 1 into indicate
643 // that the cleanup code should not destroy the variable.
644 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) {
645 const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext);
646 llvm::Value *One = llvm::ConstantInt::get(BoolTy, 1);
647 Builder.CreateStore(One, NRVOFlag);
648 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000649 } else if (!ReturnValue) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000650 // Make sure not to return anything, but evaluate the expression
651 // for side effects.
652 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000653 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000655 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000656 } else if (FnRetTy->isReferenceType()) {
657 // If this function returns a reference, take the address of the expression
658 // rather than the value.
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000659 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
Douglas Gregor33fd1fc2010-03-24 23:14:04 +0000660 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000661 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000662 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000663 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000664 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 } else {
John McCall558d2ab2010-09-15 10:14:12 +0000666 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, false, true));
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 }
Eli Friedman144ac612008-05-22 01:22:33 +0000668
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000669 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000670}
671
672void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000673 // As long as debug info is modeled with instructions, we have to ensure we
674 // have a place to insert here and write the stop point here.
675 if (getDebugInfo()) {
676 EnsureInsertPoint();
677 EmitStopPoint(&S);
678 }
679
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000680 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
681 I != E; ++I)
682 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000683}
Chris Lattnerda138702007-07-16 21:28:45 +0000684
Daniel Dunbar09124252008-11-12 08:21:33 +0000685void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000686 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
687
Daniel Dunbar09124252008-11-12 08:21:33 +0000688 // If this code is reachable then emit a stop point (if generating
689 // debug info). We have to do this ourselves because we are on the
690 // "simple" statement path.
691 if (HaveInsertPoint())
692 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000693
John McCallf1549f62010-07-06 01:34:17 +0000694 JumpDest Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000695 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000696}
697
Daniel Dunbar09124252008-11-12 08:21:33 +0000698void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000699 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
700
Daniel Dunbar09124252008-11-12 08:21:33 +0000701 // If this code is reachable then emit a stop point (if generating
702 // debug info). We have to do this ourselves because we are on the
703 // "simple" statement path.
704 if (HaveInsertPoint())
705 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000706
John McCallf1549f62010-07-06 01:34:17 +0000707 JumpDest Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000708 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000709}
Devang Patel51b09f22007-10-04 23:45:31 +0000710
Devang Patelc049e4f2007-10-08 20:57:48 +0000711/// EmitCaseStmtRange - If case statement range is not too big then
712/// add multiple cases to switch instruction, one for each value within
713/// the range. If range is too big then emit "if" condition check.
714void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000715 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000716
Anders Carlsson51fe9962008-11-22 21:04:56 +0000717 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
718 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000719
Daniel Dunbar16f23572008-07-25 01:11:38 +0000720 // Emit the code for this case. We do this first to make sure it is
721 // properly chained from our predecessor before generating the
722 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000723 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000724 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
725 EmitStmt(S.getSubStmt());
726
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000727 // If range is empty, do nothing.
728 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
729 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000730
731 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000732 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000733 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
734 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000735 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000736 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000737 LHS++;
738 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000739 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000740 }
741
Daniel Dunbar16f23572008-07-25 01:11:38 +0000742 // The range is too big. Emit "if" condition into a new block,
743 // making sure to save and restore the current insertion point.
744 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000745
Daniel Dunbar16f23572008-07-25 01:11:38 +0000746 // Push this test onto the chain of range checks (which terminates
747 // in the default basic block). The switch's default will be changed
748 // to the top of this chain after switch emission is complete.
749 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000750 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000751
Daniel Dunbar16f23572008-07-25 01:11:38 +0000752 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
753 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000754
755 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000756 llvm::Value *Diff =
757 Builder.CreateSub(SwitchInsn->getCondition(),
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000758 llvm::ConstantInt::get(VMContext, LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000759 llvm::Value *Cond =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000760 Builder.CreateICmpULE(Diff,
761 llvm::ConstantInt::get(VMContext, Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000762 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
763
Daniel Dunbar16f23572008-07-25 01:11:38 +0000764 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000765 if (RestoreBB)
766 Builder.SetInsertPoint(RestoreBB);
767 else
768 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000769}
770
771void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
772 if (S.getRHS()) {
773 EmitCaseStmtRange(S);
774 return;
775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000777 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000778 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000779 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000780 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Chris Lattner5512f282009-03-04 04:46:18 +0000782 // Recursively emitting the statement is acceptable, but is not wonderful for
783 // code where we have many case statements nested together, i.e.:
784 // case 1:
785 // case 2:
786 // case 3: etc.
787 // Handling this recursively will create a new block for each case statement
788 // that falls through to the next case which is IR intensive. It also causes
789 // deep recursion which can run into stack depth limitations. Handle
790 // sequential non-range case statements specially.
791 const CaseStmt *CurCase = &S;
792 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
793
794 // Otherwise, iteratively add consequtive cases to this switch stmt.
795 while (NextCase && NextCase->getRHS() == 0) {
796 CurCase = NextCase;
797 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000798 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000799
800 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
801 }
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattner5512f282009-03-04 04:46:18 +0000803 // Normal default recursion for non-cases.
804 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000805}
806
807void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000808 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000809 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000810 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000811 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000812 EmitStmt(S.getSubStmt());
813}
814
815void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000816 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
817
818 RunCleanupsScope ConditionScope(*this);
Douglas Gregord3d53012009-11-24 17:07:59 +0000819
820 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000821 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord3d53012009-11-24 17:07:59 +0000822
Devang Patel51b09f22007-10-04 23:45:31 +0000823 llvm::Value *CondV = EmitScalarExpr(S.getCond());
824
825 // Handle nested switch statements.
826 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000827 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000828
Daniel Dunbar16f23572008-07-25 01:11:38 +0000829 // Create basic block to hold stuff that comes after switch
830 // statement. We also need to create a default block now so that
831 // explicit case ranges tests can have a place to jump to on
832 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000833 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000834 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
835 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000836
Daniel Dunbar09124252008-11-12 08:21:33 +0000837 // Clear the insertion point to indicate we are in unreachable code.
838 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000839
Devang Patele9b8c0a2007-10-30 20:59:40 +0000840 // All break statements jump to NextBlock. If BreakContinueStack is non empty
841 // then reuse last ContinueBlock.
John McCallf1549f62010-07-06 01:34:17 +0000842 JumpDest OuterContinue;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000843 if (!BreakContinueStack.empty())
John McCallf1549f62010-07-06 01:34:17 +0000844 OuterContinue = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000845
John McCallf1549f62010-07-06 01:34:17 +0000846 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
Devang Patel51b09f22007-10-04 23:45:31 +0000847
848 // Emit switch body.
849 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Anders Carlssone4b6d342009-02-10 05:52:02 +0000851 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000852
Daniel Dunbar16f23572008-07-25 01:11:38 +0000853 // Update the default block in case explicit case range tests have
854 // been chained on top.
855 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000856
John McCallf1549f62010-07-06 01:34:17 +0000857 // If a default was never emitted:
Daniel Dunbar16f23572008-07-25 01:11:38 +0000858 if (!DefaultBlock->getParent()) {
John McCallf1549f62010-07-06 01:34:17 +0000859 // If we have cleanups, emit the default block so that there's a
860 // place to jump through the cleanups from.
861 if (ConditionScope.requiresCleanups()) {
862 EmitBlock(DefaultBlock);
863
864 // Otherwise, just forward the default block to the switch end.
865 } else {
John McCallff8e1152010-07-23 21:56:41 +0000866 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000867 delete DefaultBlock;
868 }
Daniel Dunbar16f23572008-07-25 01:11:38 +0000869 }
Devang Patel51b09f22007-10-04 23:45:31 +0000870
John McCallff8e1152010-07-23 21:56:41 +0000871 ConditionScope.ForceCleanup();
872
Daniel Dunbar16f23572008-07-25 01:11:38 +0000873 // Emit continuation.
John McCallff8e1152010-07-23 21:56:41 +0000874 EmitBlock(SwitchExit.getBlock(), true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000875
Devang Patel51b09f22007-10-04 23:45:31 +0000876 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000877 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000878}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000879
Chris Lattner2819fa82009-04-26 17:57:12 +0000880static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +0000881SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000882 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000883 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000885 while (*Constraint) {
886 switch (*Constraint) {
887 default:
John Thompson2f474ea2010-09-18 01:15:13 +0000888 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000889 break;
890 // Ignore these
891 case '*':
892 case '?':
893 case '!':
John Thompsonef44e112010-08-10 19:20:14 +0000894 case '=': // Will see this and the following in mult-alt constraints.
895 case '+':
896 break;
John Thompson2f474ea2010-09-18 01:15:13 +0000897 case ',':
898 Result += "|";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000899 break;
900 case 'g':
901 Result += "imr";
902 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000903 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000904 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000905 "Must pass output names to constraints with a symbolic name");
906 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +0000907 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000908 &(*OutCons)[0],
909 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000910 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000911 Result += llvm::utostr(Index);
912 break;
913 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000916 Constraint++;
917 }
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000919 return Result;
920}
921
Rafael Espindola03117d12011-01-01 21:12:33 +0000922/// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
923/// as using a particular register add that as a constraint that will be used
924/// in this asm stmt.
Rafael Espindola0ec89f92010-12-30 22:59:32 +0000925static std::string
Rafael Espindola03117d12011-01-01 21:12:33 +0000926AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
927 const TargetInfo &Target, CodeGenModule &CGM,
928 const AsmStmt &Stmt) {
Rafael Espindola0ec89f92010-12-30 22:59:32 +0000929 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
930 if (!AsmDeclRef)
931 return Constraint;
932 const ValueDecl &Value = *AsmDeclRef->getDecl();
933 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
934 if (!Variable)
935 return Constraint;
936 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
937 if (!Attr)
938 return Constraint;
939 llvm::StringRef Register = Attr->getLabel();
940 if (!Target.isValidGCCRegisterName(Register)) {
941 CGM.ErrorUnsupported(Variable, "__asm__");
942 return Constraint;
943 }
944 if (Constraint != "r") {
945 CGM.ErrorUnsupported(&Stmt, "__asm__");
946 return Constraint;
947 }
948 return "{" + Register.str() + "}";
949}
950
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000951llvm::Value*
952CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
953 const TargetInfo::ConstraintInfo &Info,
954 LValue InputValue, QualType InputType,
955 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000956 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +0000957 if (Info.allowsRegister() || !Info.allowsMemory()) {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000958 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
959 Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
Anders Carlsson63471722009-01-11 19:32:54 +0000960 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000961 const llvm::Type *Ty = ConvertType(InputType);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000962 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
963 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000964 Ty = llvm::IntegerType::get(VMContext, Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000965 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000967 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
968 Ty));
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000969 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000970 Arg = InputValue.getAddress();
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000971 ConstraintStr += '*';
972 }
Anders Carlsson63471722009-01-11 19:32:54 +0000973 }
974 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000975 Arg = InputValue.getAddress();
Anders Carlsson63471722009-01-11 19:32:54 +0000976 ConstraintStr += '*';
977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Anders Carlsson63471722009-01-11 19:32:54 +0000979 return Arg;
980}
981
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000982llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
983 const TargetInfo::ConstraintInfo &Info,
984 const Expr *InputExpr,
985 std::string &ConstraintStr) {
986 if (Info.allowsRegister() || !Info.allowsMemory())
987 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
988 return EmitScalarExpr(InputExpr);
989
990 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
991 LValue Dest = EmitLValue(InputExpr);
992 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
993}
994
Chris Lattner47fc7e92010-11-17 05:58:54 +0000995/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
Chris Lattner5d936532010-11-17 08:25:26 +0000996/// asm call instruction. The !srcloc MDNode contains a list of constant
997/// integers which are the source locations of the start of each line in the
998/// asm.
Chris Lattner47fc7e92010-11-17 05:58:54 +0000999static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1000 CodeGenFunction &CGF) {
Chris Lattner5d936532010-11-17 08:25:26 +00001001 llvm::SmallVector<llvm::Value *, 8> Locs;
1002 // Add the location of the first line to the MDNode.
1003 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1004 Str->getLocStart().getRawEncoding()));
1005 llvm::StringRef StrVal = Str->getString();
1006 if (!StrVal.empty()) {
1007 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1008 const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1009
1010 // Add the location of the start of each subsequent line of the asm to the
1011 // MDNode.
1012 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1013 if (StrVal[i] != '\n') continue;
1014 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1015 CGF.Target);
1016 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1017 LineLoc.getRawEncoding()));
1018 }
1019 }
1020
1021 return llvm::MDNode::get(CGF.getLLVMContext(), Locs.data(), Locs.size());
Chris Lattner47fc7e92010-11-17 05:58:54 +00001022}
1023
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001024void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +00001025 // Analyze the asm string to decompose it into its pieces. We know that Sema
1026 // has already done this, so it is guaranteed to be successful.
1027 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001028 unsigned DiagOffs;
1029 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner458cd9c2009-03-10 23:21:44 +00001031 // Assemble the pieces into the final asm string.
1032 std::string AsmString;
1033 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1034 if (Pieces[i].isString())
1035 AsmString += Pieces[i].getString();
1036 else if (Pieces[i].getModifier() == '\0')
1037 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1038 else
1039 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1040 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +00001041 }
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Chris Lattner481fef92009-05-03 07:05:00 +00001043 // Get all the output and input constraints together.
1044 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1045 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1046
Mike Stump1eb44332009-09-09 15:08:12 +00001047 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001048 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1049 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001050 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1051 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +00001052 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001053 }
1054
Chris Lattner481fef92009-05-03 07:05:00 +00001055 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1056 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1057 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001058 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1059 S.getNumOutputs(), Info);
1060 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +00001061 InputConstraintInfos.push_back(Info);
1062 }
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001064 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Chris Lattnerede9d902009-05-03 07:53:25 +00001066 std::vector<LValue> ResultRegDests;
1067 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001068 std::vector<const llvm::Type *> ResultRegTypes;
1069 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001070 std::vector<const llvm::Type*> ArgTypes;
1071 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001072
1073 // Keep track of inout constraints.
1074 std::string InOutConstraints;
1075 std::vector<llvm::Value*> InOutArgs;
1076 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +00001077
Mike Stump1eb44332009-09-09 15:08:12 +00001078 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001079 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +00001080
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001081 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001082 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001083 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner810f6d52009-03-13 17:38:01 +00001085 const Expr *OutExpr = S.getOutputExpr(i);
1086 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Rafael Espindola03117d12011-01-01 21:12:33 +00001088 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, Target,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001089 CGM, S);
1090
Chris Lattner810f6d52009-03-13 17:38:01 +00001091 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +00001092 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +00001093 Constraints += ',';
1094
Chris Lattnera077b5c2009-05-03 08:21:20 +00001095 // If this is a register output, then make the inline asm return it
1096 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +00001097 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001098 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +00001099 ResultRegQualTys.push_back(OutExpr->getType());
1100 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001101 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1102 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Chris Lattnera077b5c2009-05-03 08:21:20 +00001104 // If this output is tied to an input, and if the input is larger, then
1105 // we need to set the actual result type of the inline asm node to be the
1106 // same as the input type.
1107 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +00001108 unsigned InputNo;
1109 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1110 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001111 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001112 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001113 }
1114 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Chris Lattnera077b5c2009-05-03 08:21:20 +00001116 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001117 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Chris Lattnera077b5c2009-05-03 08:21:20 +00001119 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001120 if (getContext().getTypeSize(OutputType) < InputSize) {
1121 // Form the asm to return the value as a larger integer or fp type.
1122 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001123 }
1124 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001125 if (const llvm::Type* AdjTy =
1126 Target.adjustInlineAsmType(OutputConstraint, ResultRegTypes.back(),
1127 VMContext))
1128 ResultRegTypes.back() = AdjTy;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001129 } else {
1130 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001131 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001132 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001133 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001134 }
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Chris Lattner44def072009-04-26 07:16:29 +00001136 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001137 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001138
Anders Carlssonfca93612009-08-04 18:18:36 +00001139 const Expr *InputExpr = S.getOutputExpr(i);
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001140 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1141 InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Chris Lattner44def072009-04-26 07:16:29 +00001143 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001144 InOutConstraints += llvm::utostr(i);
1145 else
1146 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001147
Anders Carlssonfca93612009-08-04 18:18:36 +00001148 InOutArgTypes.push_back(Arg->getType());
1149 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001150 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001153 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001155 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1156 const Expr *InputExpr = S.getInputExpr(i);
1157
Chris Lattner481fef92009-05-03 07:05:00 +00001158 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1159
Chris Lattnerede9d902009-05-03 07:53:25 +00001160 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001161 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001163 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001164 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001165 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001166 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001167
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001168 InputConstraint =
Rafael Espindola03117d12011-01-01 21:12:33 +00001169 AddVariableConstraints(InputConstraint,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001170 *InputExpr->IgnoreParenNoopCasts(getContext()),
1171 Target, CGM, S);
1172
Anders Carlsson63471722009-01-11 19:32:54 +00001173 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Chris Lattner4df4ee02009-05-03 07:27:51 +00001175 // If this input argument is tied to a larger output result, extend the
1176 // input to be the same size as the output. The LLVM backend wants to see
1177 // the input and output of a matching constraint be the same size. Note
1178 // that GCC does not define what the top bits are here. We use zext because
1179 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1180 if (Info.hasTiedOperand()) {
1181 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001182 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001183 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Chris Lattneraab64d02010-04-23 17:27:29 +00001185 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001186 getContext().getTypeSize(InputTy)) {
1187 // Use ptrtoint as appropriate so that we can do our extension.
1188 if (isa<llvm::PointerType>(Arg->getType()))
Chris Lattner77b89b82010-06-27 07:15:29 +00001189 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001190 const llvm::Type *OutputTy = ConvertType(OutputType);
1191 if (isa<llvm::IntegerType>(OutputTy))
1192 Arg = Builder.CreateZExt(Arg, OutputTy);
1193 else
1194 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001195 }
1196 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001197 if (const llvm::Type* AdjTy =
1198 Target.adjustInlineAsmType(InputConstraint, Arg->getType(),
1199 VMContext))
1200 Arg = Builder.CreateBitCast(Arg, AdjTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001202 ArgTypes.push_back(Arg->getType());
1203 Args.push_back(Arg);
1204 Constraints += InputConstraint;
1205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Anders Carlssonf39a4212008-02-05 20:01:53 +00001207 // Append the "input" part of inout constraints last.
1208 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1209 ArgTypes.push_back(InOutArgTypes[i]);
1210 Args.push_back(InOutArgs[i]);
1211 }
1212 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001214 // Clobbers
1215 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001216 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001217
Anders Carlsson83c021c2010-01-30 19:12:25 +00001218 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Anders Carlssonea041752008-02-06 00:11:32 +00001220 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001221 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Anders Carlssonea041752008-02-06 00:11:32 +00001223 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001224 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001225 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001228 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001229 std::string MachineClobbers = Target.getClobbers();
1230 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001231 if (!Constraints.empty())
1232 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001233 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001234 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001235
1236 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001237 if (ResultRegTypes.empty())
Owen Anderson0032b272009-08-13 21:57:51 +00001238 ResultType = llvm::Type::getVoidTy(VMContext);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001239 else if (ResultRegTypes.size() == 1)
1240 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001241 else
Owen Anderson47a434f2009-08-05 23:18:46 +00001242 ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
1244 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001245 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001246
1247 llvm::InlineAsm *IA =
1248 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001249 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001250 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001251 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001253 // Slap the source location of the inline asm into a !srcloc metadata on the
1254 // call.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001255 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Chris Lattnera077b5c2009-05-03 08:21:20 +00001257 // Extract all of the register value results from the asm.
1258 std::vector<llvm::Value*> RegResults;
1259 if (ResultRegTypes.size() == 1) {
1260 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001261 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001262 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001263 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001264 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001265 }
1266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattnera077b5c2009-05-03 08:21:20 +00001268 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1269 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattnera077b5c2009-05-03 08:21:20 +00001271 // If the result type of the LLVM IR asm doesn't match the result type of
1272 // the expression, do the conversion.
1273 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1274 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001275
1276 // Truncate the integer result to the right size, note that TruncTy can be
1277 // a pointer.
1278 if (TruncTy->isFloatingPointTy())
1279 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001280 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001281 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1282 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext,
1283 (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001284 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001285 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1286 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1287 Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext,
1288 (unsigned)TmpSize));
1289 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1290 } else if (TruncTy->isIntegerTy()) {
1291 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001292 } else if (TruncTy->isVectorTy()) {
1293 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001294 }
1295 }
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Chris Lattnera077b5c2009-05-03 08:21:20 +00001297 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1298 ResultRegQualTys[i]);
1299 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001300}