blob: 475c7bfefd1d137c5ac881ad964019e8bb0c94df [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
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 coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
Mike Stump1eb44332009-09-09 15:08:12 +000026CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
Chris Lattnerd9becd12009-10-28 23:59:40 +000030 DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000031 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson2b77ba82009-04-04 20:47:02 +000032 CXXThisDecl(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000033 LLVMIntTy = ConvertType(getContext().IntTy);
34 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000035}
Reid Spencer5f016e22007-07-11 17:01:13 +000036
37ASTContext &CodeGenFunction::getContext() const {
38 return CGM.getContext();
39}
40
41
42llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
43 llvm::BasicBlock *&BB = LabelMap[S];
44 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000045
Reid Spencer5f016e22007-07-11 17:01:13 +000046 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000047 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Daniel Dunbar0096acf2009-02-25 19:24:29 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
51 llvm::Value *Res = LocalDeclMap[VD];
52 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
53 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000054}
Reid Spencer5f016e22007-07-11 17:01:13 +000055
Daniel Dunbar0096acf2009-02-25 19:24:29 +000056llvm::Constant *
57CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
58 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000059}
60
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000061const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
62 return CGM.getTypes().ConvertTypeForMem(T);
63}
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
66 return CGM.getTypes().ConvertType(T);
67}
68
69bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000070 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
71 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000072}
73
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000074void CodeGenFunction::EmitReturnBlock() {
75 // For cleanliness, we try to avoid emitting the return block for
76 // simple cases.
77 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
78
79 if (CurBB) {
80 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
81
Daniel Dunbar96e18b02009-07-19 08:24:34 +000082 // We have a valid insert point, reuse it if it is empty or there are no
83 // explicit jumps to the return block.
84 if (CurBB->empty() || ReturnBlock->use_empty()) {
85 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000086 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000087 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000088 EmitBlock(ReturnBlock);
89 return;
90 }
91
92 // Otherwise, if the return block is the target of a single direct
93 // branch then we can just put the code in that block instead. This
94 // cleans up functions which started with a unified return block.
95 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000096 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000097 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
98 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
99 // Reset insertion point and delete the branch.
100 Builder.SetInsertPoint(BI->getParent());
101 BI->eraseFromParent();
102 delete ReturnBlock;
103 return;
104 }
105 }
106
Mike Stumpf5408fe2009-05-16 07:57:57 +0000107 // FIXME: We are at an unreachable point, there is no reason to emit the block
108 // unless it has uses. However, we still need a place to put the debug
109 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000110
111 EmitBlock(ReturnBlock);
112}
113
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000114void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000115 assert(BreakContinueStack.empty() &&
116 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000117 assert(BlockScopes.empty() &&
118 "did not remove all blocks from block scope map!");
119 assert(CleanupEntries.empty() &&
120 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000121
122 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000123 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000124
125 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000126 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000127 DI->setLocation(EndLoc);
128 DI->EmitRegionEnd(CurFn, Builder);
129 }
130
Daniel Dunbar88b53962009-02-02 22:03:45 +0000131 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000132
Chris Lattnerd9becd12009-10-28 23:59:40 +0000133 // If someone did an indirect goto, emit the indirect goto block at the end of
134 // the function.
135 if (IndirectBranch) {
136 EmitBlock(IndirectBranch->getParent());
137 Builder.ClearInsertionPoint();
138 }
139
Chris Lattner5a2fa142007-12-02 06:32:24 +0000140 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000141 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000142 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000143 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000144
145 // If someone took the address of a label but never did an indirect goto, we
146 // made a zero entry PHI node, which is illegal, zap it now.
147 if (IndirectBranch) {
148 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
149 if (PN->getNumIncomingValues() == 0) {
150 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
151 PN->eraseFromParent();
152 }
153 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000154}
155
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000156void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000157 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000158 const FunctionArgList &Args,
159 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000160 const Decl *D = GD.getDecl();
161
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000162 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000163 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000164 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000165 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000166 assert(CurFn->isDeclaration() && "Function already has body?");
167
Daniel Dunbar55e87422008-11-11 02:29:29 +0000168 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000169
Chris Lattner41110242008-06-17 18:05:57 +0000170 // Create a marker to make it easy to insert allocas into the entryblock
171 // later. Don't create this with the builder, because we don't want it
172 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000173 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000174 AllocaInsertPt = new llvm::BitCastInst(Undef,
175 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000176 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000177 if (Builder.isNamePreserving())
178 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Daniel Dunbar55e87422008-11-11 02:29:29 +0000180 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000181 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000182 if (!RetTy->isVoidType())
183 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattner41110242008-06-17 18:05:57 +0000185 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Mike Stump91cc8152009-10-23 01:52:13 +0000187 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
188
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000189 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000190 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000191 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000192 DI->setLocation(StartLoc);
Anders Carlsson1860a312009-09-11 00:11:35 +0000193 if (isa<FunctionDecl>(D)) {
Mike Stump91cc8152009-10-23 01:52:13 +0000194 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000195 } else {
196 // Just use LLVM function name.
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000198 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump1eb44332009-09-09 15:08:12 +0000199 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stump91cc8152009-10-23 01:52:13 +0000200 FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000201 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000202 }
203
Daniel Dunbar88b53962009-02-02 22:03:45 +0000204 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000205 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000206 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Anders Carlsson751358f2008-12-20 21:28:43 +0000208 // If any of the arguments have a variably modified type, make sure to
209 // emit the type size.
210 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
211 i != e; ++i) {
212 QualType Ty = i->second;
213
214 if (Ty->isVariablyModifiedType())
215 EmitVLASize(Ty);
216 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000217}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000218
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000219void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000220 llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000221 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
222
Anders Carlssone896d982009-02-13 08:11:52 +0000223 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000224 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000225 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Daniel Dunbar7c086512008-09-09 23:14:03 +0000227 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000229 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
230 if (MD->isInstance()) {
231 // Create the implicit 'this' decl.
232 // FIXME: I'm not entirely sure I like using a fake decl just for code
233 // generation. Maybe we can come up with a better way?
234 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000235 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000236 MD->getThisType(getContext()));
237 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
238 }
239 }
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000241 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000242 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000243 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000244
245 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000246 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000247 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000248 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000249
Sebastian Redld3a413d2009-04-26 20:35:05 +0000250 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000251 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000252 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000253
254 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000255 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000256 EmitStmt(S);
Anders Carlsson5e1b9182009-11-06 04:19:02 +0000257
258 // If any of the member initializers are temporaries bound to references
259 // make sure to emit their destructors.
260 EmitCleanupBlocks(0);
261
Anders Carlsson4365bba2009-11-06 02:55:43 +0000262 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
263 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
264 PushCleanupBlock(DtorEpilogue);
265
266 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000267
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000268 CleanupBlockInfo Info = PopCleanupBlock();
269
270 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
271 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000272 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000273
274 if (Info.SwitchBlock)
275 EmitBlock(Info.SwitchBlock);
276 if (Info.EndBlock)
277 EmitBlock(Info.EndBlock);
Anders Carlsson4365bba2009-11-06 02:55:43 +0000278 } else {
279 // Just a regular function, emit its body.
280 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000281 }
Anders Carlsson4365bba2009-11-06 02:55:43 +0000282
Sebastian Redld3a413d2009-04-26 20:35:05 +0000283 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000284 } else if (FD->isImplicit()) {
285 const CXXRecordDecl *ClassDecl =
286 cast<CXXRecordDecl>(FD->getDeclContext());
287 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000288 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000289 // FIXME: For C++0x, we want to look for implicit *definitions* of
290 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian98896522009-08-06 23:38:16 +0000291 if (CD->isCopyConstructor(getContext())) {
292 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000293 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000294 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000295 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000296 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000297 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000298 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000299 } else {
300 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000301 }
Douglas Gregor45132722009-10-01 20:44:19 +0000302 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
303 assert(!ClassDecl->hasUserDeclaredDestructor() &&
304 "Cannot synthesize a non-implicit destructor");
305 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
306 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
307 assert(MD->isCopyAssignment() &&
308 !ClassDecl->hasUserDeclaredCopyAssignment() &&
309 "Cannot synthesize a method that is not an implicit-defined "
310 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000311 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000312 } else {
313 assert(false && "Cannot synthesize unknown implicit function");
314 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000315 }
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000317 // Destroy the 'this' declaration.
318 if (CXXThisDecl)
319 CXXThisDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000320}
321
Chris Lattner0946ccd2008-11-11 07:41:27 +0000322/// ContainsLabel - Return true if the statement contains a label in it. If
323/// this statement is not executed normally, it not containing a label means
324/// that we can just remove the code.
325bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
326 // Null statement, not a label!
327 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattner0946ccd2008-11-11 07:41:27 +0000329 // If this is a label, we have to emit the code, consider something like:
330 // if (0) { ... foo: bar(); } goto foo;
331 if (isa<LabelStmt>(S))
332 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner0946ccd2008-11-11 07:41:27 +0000334 // If this is a case/default statement, and we haven't seen a switch, we have
335 // to emit the code.
336 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
337 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner0946ccd2008-11-11 07:41:27 +0000339 // If this is a switch statement, we want to ignore cases below it.
340 if (isa<SwitchStmt>(S))
341 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Chris Lattner0946ccd2008-11-11 07:41:27 +0000343 // Scan subexpressions for verboten labels.
344 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
345 I != E; ++I)
346 if (ContainsLabel(*I, IgnoreCaseStmts))
347 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattner0946ccd2008-11-11 07:41:27 +0000349 return false;
350}
351
Chris Lattner31a09842008-11-12 08:04:58 +0000352
353/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
354/// a constant, or if it does but contains a label, return 0. If it constant
355/// folds to 'true' and does not contain a label, return 1, if it constant folds
356/// to 'false' and does not contain a label, return -1.
357int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000358 // FIXME: Rename and handle conversion of other evaluatable things
359 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000360 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000361 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000362 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000363 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Chris Lattner31a09842008-11-12 08:04:58 +0000365 if (CodeGenFunction::ContainsLabel(Cond))
366 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Anders Carlsson64712f12008-12-01 02:46:24 +0000368 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000369}
370
371
372/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
373/// statement) to the specified blocks. Based on the condition, this might try
374/// to simplify the codegen of the conditional based on the branch.
375///
376void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
377 llvm::BasicBlock *TrueBlock,
378 llvm::BasicBlock *FalseBlock) {
379 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
380 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner31a09842008-11-12 08:04:58 +0000382 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
383 // Handle X && Y in a condition.
384 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
385 // If we have "1 && X", simplify the code. "0 && X" would have constant
386 // folded if the case was simple enough.
387 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
388 // br(1 && X) -> br(X).
389 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
390 }
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner31a09842008-11-12 08:04:58 +0000392 // If we have "X && 1", simplify the code to use an uncond branch.
393 // "X && 0" would have been constant folded to 0.
394 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
395 // br(X && 1) -> br(X).
396 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner31a09842008-11-12 08:04:58 +0000399 // Emit the LHS as a conditional. If the LHS conditional is false, we
400 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000401 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000402 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
403 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner31a09842008-11-12 08:04:58 +0000405 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
406 return;
407 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
408 // If we have "0 || X", simplify the code. "1 || X" would have constant
409 // folded if the case was simple enough.
410 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
411 // br(0 || X) -> br(X).
412 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner31a09842008-11-12 08:04:58 +0000415 // If we have "X || 0", simplify the code to use an uncond branch.
416 // "X || 1" would have been constant folded to 1.
417 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
418 // br(X || 0) -> br(X).
419 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner31a09842008-11-12 08:04:58 +0000422 // Emit the LHS as a conditional. If the LHS conditional is true, we
423 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000424 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000425 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
426 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattner31a09842008-11-12 08:04:58 +0000428 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
429 return;
430 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000431 }
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner552f4c42008-11-12 08:13:36 +0000433 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
434 // br(!x, t, f) -> br(x, f, t)
435 if (CondUOp->getOpcode() == UnaryOperator::LNot)
436 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Daniel Dunbar09b14892008-11-12 10:30:32 +0000439 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
440 // Handle ?: operator.
441
442 // Just ignore GNU ?: extension.
443 if (CondOp->getLHS()) {
444 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
445 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
446 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
447 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
448 EmitBlock(LHSBlock);
449 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
450 EmitBlock(RHSBlock);
451 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
452 return;
453 }
454 }
455
Chris Lattner31a09842008-11-12 08:04:58 +0000456 // Emit the code with the fully general case.
457 llvm::Value *CondV = EvaluateExprAsBool(Cond);
458 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
459}
460
Daniel Dunbar488e9932008-08-16 00:56:44 +0000461/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000462/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000463void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
464 bool OmitOnError) {
465 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000466}
467
Chris Lattner88207c92009-04-21 17:59:23 +0000468void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000469 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000470 if (DestPtr->getType() != BP)
471 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
472
473 // Get size and alignment info for this aggregate.
474 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
475
Chris Lattner88207c92009-04-21 17:59:23 +0000476 // Don't bother emitting a zero-byte memset.
477 if (TypeInfo.first == 0)
478 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000480 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000482 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000483
484 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000485 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000486 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000487 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000488 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000489 TypeInfo.second/8));
490}
491
Chris Lattnerd9becd12009-10-28 23:59:40 +0000492llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
493 // Make sure that there is a block for the indirect goto.
494 if (IndirectBranch == 0)
495 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000496
Chris Lattnerd9becd12009-10-28 23:59:40 +0000497 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000498
Chris Lattnerd9becd12009-10-28 23:59:40 +0000499 // Make sure the indirect branch includes all of the address-taken blocks.
500 IndirectBranch->addDestination(BB);
501 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000502}
503
504llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000505 // If we already made the indirect branch for indirect goto, return its block.
506 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000507
Chris Lattnerd9becd12009-10-28 23:59:40 +0000508 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000509
Chris Lattnerd9becd12009-10-28 23:59:40 +0000510 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000511
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000512 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000513 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000514
Chris Lattnerd9becd12009-10-28 23:59:40 +0000515 // Create the indirect branch instruction.
516 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
517 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000518}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000519
Daniel Dunbard286f052009-07-19 06:58:07 +0000520llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000521 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Anders Carlssonf666b772008-12-20 20:27:15 +0000523 assert(SizeEntry && "Did not emit size for type");
524 return SizeEntry;
525}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000526
Daniel Dunbard286f052009-07-19 06:58:07 +0000527llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000528 assert(Ty->isVariablyModifiedType() &&
529 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Daniel Dunbard286f052009-07-19 06:58:07 +0000531 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Anders Carlsson60d35412008-12-20 20:46:34 +0000533 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000534 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000536 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000537 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000539 // Get the element size;
540 QualType ElemTy = VAT->getElementType();
541 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000542 if (ElemTy->isVariableArrayType())
543 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000544 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000545 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000546 getContext().getTypeSize(ElemTy) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000548 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000549 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000551 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Anders Carlsson60d35412008-12-20 20:46:34 +0000554 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000557 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
558 EmitVLASize(AT->getElementType());
559 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000560 }
561
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000562 const PointerType *PT = Ty->getAs<PointerType>();
563 assert(PT && "unknown VM type!");
564 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000565 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000566}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000567
568llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
569 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
570 return EmitScalarExpr(E);
571 }
572 return EmitLValue(E).getAddress();
573}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000574
Fariborz Jahanian77996212009-11-04 17:57:40 +0000575void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
576 llvm::BasicBlock *CleanupExitBlock) {
577 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000578}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000579
Mike Stump1eb44332009-09-09 15:08:12 +0000580void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
581 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000582 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Anders Carlssonc71c8452009-02-07 23:50:39 +0000584 while (CleanupEntries.size() > OldCleanupStackSize)
585 EmitCleanupBlock();
586}
587
Mike Stump1eb44332009-09-09 15:08:12 +0000588CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000589 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Fariborz Jahanian77996212009-11-04 17:57:40 +0000591 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000593 std::vector<llvm::BasicBlock *> Blocks;
594 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000596 std::vector<llvm::BranchInst *> BranchFixups;
597 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000599 CleanupEntries.pop_back();
600
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000601 // Check if any branch fixups pointed to the scope we just popped. If so,
602 // we can remove them.
603 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
604 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
605 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000607 if (I == BlockScopes.end())
608 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000610 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000612 if (I->second == CleanupEntries.size()) {
613 // We don't need to do this branch fixup.
614 BranchFixups[i] = BranchFixups.back();
615 BranchFixups.pop_back();
616 i--;
617 e--;
618 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000619 }
620 }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Fariborz Jahanian77996212009-11-04 17:57:40 +0000622 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000623 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000624 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000625 if (!SwitchBlock)
626 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000627 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000629 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000631 Builder.SetInsertPoint(SwitchBlock);
632
Mike Stump1eb44332009-09-09 15:08:12 +0000633 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000634 "cleanup.dst");
635 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000637 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000638 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000639 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000640
Anders Carlsson46831a92009-02-08 22:13:37 +0000641 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000642 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000643 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000645 // If we had a current basic block, we also need to emit an instruction
646 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000647 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000648 DestCodePtr);
649 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000650 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000651
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000652 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
653 llvm::BranchInst *BI = BranchFixups[i];
654 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000656 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000657 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000659 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000660 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Anders Carlssoncc899202009-02-08 22:46:50 +0000662 // Check if we already have a destination for this block.
663 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000664 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000665 else {
666 ID = SI->findCaseDest(Dest);
667 if (!ID) {
668 // No code found, get a new unique one by using the number of
669 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000670 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000671 SI->getNumSuccessors());
672 SI->addCase(ID, Dest);
673 }
674 }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Anders Carlssoncc899202009-02-08 22:46:50 +0000676 // Store the jump destination before the branch instruction.
677 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000678 } else {
679 // We need to jump through another cleanup block. Create a pad block
680 // with a branch instruction that jumps to the final destination and
681 // add it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000683 // Create the pad block.
684 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000685
686 // Create a unique case ID.
Mike Stump1eb44332009-09-09 15:08:12 +0000687 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000688 SI->getNumSuccessors());
689
690 // Store the jump destination before the branch instruction.
691 new llvm::StoreInst(ID, DestCodePtr, BI);
692
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000693 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000694 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000696 // Create the branch to the final destination.
697 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
698 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000700 // And add it as a branch fixup.
701 CleanupEntries.back().BranchFixups.push_back(BI);
702 }
703 }
704 }
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000706 // Remove all blocks from the block scope map.
707 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
708 assert(BlockScopes.count(Blocks[i]) &&
709 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000711 BlockScopes.erase(Blocks[i]);
712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Fariborz Jahanian77996212009-11-04 17:57:40 +0000714 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000715}
716
Mike Stump1eb44332009-09-09 15:08:12 +0000717void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000718 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000720 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000721 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000722 Info.CleanupBlock->getNumUses() == 0) {
723 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
724 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000725 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000726 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000728 if (Info.SwitchBlock)
729 EmitBlock(Info.SwitchBlock);
730 if (Info.EndBlock)
731 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000732}
733
Mike Stump1eb44332009-09-09 15:08:12 +0000734void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
735 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000736 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Mike Stumpf5408fe2009-05-16 07:57:57 +0000738 // FIXME: We could be more clever here and check if there's already a branch
739 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000740 CleanupEntries.back().BranchFixups.push_back(BI);
741}
742
Mike Stump1eb44332009-09-09 15:08:12 +0000743void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000744 if (!HaveInsertPoint())
745 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Anders Carlsson87eaf172009-02-08 00:50:42 +0000747 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Anders Carlsson46831a92009-02-08 22:13:37 +0000749 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Anders Carlsson87eaf172009-02-08 00:50:42 +0000751 // The stack is empty, no need to do any cleanup.
752 if (CleanupEntries.empty())
753 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Anders Carlsson87eaf172009-02-08 00:50:42 +0000755 if (!Dest->getParent()) {
756 // We are trying to branch to a block that hasn't been inserted yet.
757 AddBranchFixup(BI);
758 return;
759 }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Anders Carlsson87eaf172009-02-08 00:50:42 +0000761 BlockScopeMap::iterator I = BlockScopes.find(Dest);
762 if (I == BlockScopes.end()) {
763 // We are trying to jump to a block that is outside of any cleanup scope.
764 AddBranchFixup(BI);
765 return;
766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Anders Carlsson87eaf172009-02-08 00:50:42 +0000768 assert(I->second < CleanupEntries.size() &&
769 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Anders Carlsson87eaf172009-02-08 00:50:42 +0000771 if (I->second == CleanupEntries.size() - 1) {
772 // We have a branch to a block in the same scope.
773 return;
774 }
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Anders Carlsson87eaf172009-02-08 00:50:42 +0000776 AddBranchFixup(BI);
777}