blob: d35c9621129fc574a7eb773b2999e961814c5267 [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 Stump6a1e0eb2009-12-04 23:26:17 +000022#include "clang/AST/StmtCXX.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000023#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
Mike Stump1eb44332009-09-09 15:08:12 +000027CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000028 : BlockFunction(cgm, *this, Builder), CGM(cgm),
29 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000030 Builder(cgm.getModule().getContext()),
Chris Lattnerd9becd12009-10-28 23:59:40 +000031 DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000032 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlssonf6c56e22009-11-25 03:15:49 +000033 CXXThisDecl(0), CXXVTTDecl(0),
Anders Carlssona36bf8f2009-11-20 17:27:56 +000034 ConditionalBranchLevel(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000035 LLVMIntTy = ConvertType(getContext().IntTy);
36 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000037}
Reid Spencer5f016e22007-07-11 17:01:13 +000038
39ASTContext &CodeGenFunction::getContext() const {
40 return CGM.getContext();
41}
42
43
44llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
45 llvm::BasicBlock *&BB = LabelMap[S];
46 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000047
Reid Spencer5f016e22007-07-11 17:01:13 +000048 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000049 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
Daniel Dunbar0096acf2009-02-25 19:24:29 +000052llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
53 llvm::Value *Res = LocalDeclMap[VD];
54 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
55 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000056}
Reid Spencer5f016e22007-07-11 17:01:13 +000057
Daniel Dunbar0096acf2009-02-25 19:24:29 +000058llvm::Constant *
59CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
60 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000061}
62
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000063const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
64 return CGM.getTypes().ConvertTypeForMem(T);
65}
66
Reid Spencer5f016e22007-07-11 17:01:13 +000067const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
68 return CGM.getTypes().ConvertType(T);
69}
70
71bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000072 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
73 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000074}
75
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000076void CodeGenFunction::EmitReturnBlock() {
77 // For cleanliness, we try to avoid emitting the return block for
78 // simple cases.
79 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
80
81 if (CurBB) {
82 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
83
Daniel Dunbar96e18b02009-07-19 08:24:34 +000084 // We have a valid insert point, reuse it if it is empty or there are no
85 // explicit jumps to the return block.
86 if (CurBB->empty() || ReturnBlock->use_empty()) {
87 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000088 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000089 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000090 EmitBlock(ReturnBlock);
91 return;
92 }
93
94 // Otherwise, if the return block is the target of a single direct
95 // branch then we can just put the code in that block instead. This
96 // cleans up functions which started with a unified return block.
97 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000098 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000099 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
100 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
101 // Reset insertion point and delete the branch.
102 Builder.SetInsertPoint(BI->getParent());
103 BI->eraseFromParent();
104 delete ReturnBlock;
105 return;
106 }
107 }
108
Mike Stumpf5408fe2009-05-16 07:57:57 +0000109 // FIXME: We are at an unreachable point, there is no reason to emit the block
110 // unless it has uses. However, we still need a place to put the debug
111 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000112
113 EmitBlock(ReturnBlock);
114}
115
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000116void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000117 assert(BreakContinueStack.empty() &&
118 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000119 assert(BlockScopes.empty() &&
120 "did not remove all blocks from block scope map!");
121 assert(CleanupEntries.empty() &&
122 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000123
124 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000125 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000126
127 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000128 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000129 DI->setLocation(EndLoc);
130 DI->EmitRegionEnd(CurFn, Builder);
131 }
132
Daniel Dunbar88b53962009-02-02 22:03:45 +0000133 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000134
Chris Lattnerd9becd12009-10-28 23:59:40 +0000135 // If someone did an indirect goto, emit the indirect goto block at the end of
136 // the function.
137 if (IndirectBranch) {
138 EmitBlock(IndirectBranch->getParent());
139 Builder.ClearInsertionPoint();
140 }
141
Chris Lattner5a2fa142007-12-02 06:32:24 +0000142 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000143 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000144 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000145 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000146
147 // If someone took the address of a label but never did an indirect goto, we
148 // made a zero entry PHI node, which is illegal, zap it now.
149 if (IndirectBranch) {
150 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
151 if (PN->getNumIncomingValues() == 0) {
152 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
153 PN->eraseFromParent();
154 }
155 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000156}
157
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000158void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000159 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000160 const FunctionArgList &Args,
161 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000162 const Decl *D = GD.getDecl();
163
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000164 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000165 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000166 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000167 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000168 assert(CurFn->isDeclaration() && "Function already has body?");
169
Daniel Dunbar55e87422008-11-11 02:29:29 +0000170 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000171
Chris Lattner41110242008-06-17 18:05:57 +0000172 // Create a marker to make it easy to insert allocas into the entryblock
173 // later. Don't create this with the builder, because we don't want it
174 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000175 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000176 AllocaInsertPt = new llvm::BitCastInst(Undef,
177 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000178 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000179 if (Builder.isNamePreserving())
180 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Daniel Dunbar55e87422008-11-11 02:29:29 +0000182 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner41110242008-06-17 18:05:57 +0000184 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Mike Stump91cc8152009-10-23 01:52:13 +0000186 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
187
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000188 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000189 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000190 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000191 DI->setLocation(StartLoc);
Anders Carlsson1860a312009-09-11 00:11:35 +0000192 if (isa<FunctionDecl>(D)) {
Mike Stump91cc8152009-10-23 01:52:13 +0000193 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000194 } else {
195 // Just use LLVM function name.
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000197 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump1eb44332009-09-09 15:08:12 +0000198 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stump91cc8152009-10-23 01:52:13 +0000199 FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000200 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000201 }
202
Daniel Dunbar88b53962009-02-02 22:03:45 +0000203 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000204 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Eli Friedmanb17daf92009-12-04 02:43:40 +0000205
206 if (RetTy->isVoidType()) {
207 // Void type; nothing to return.
208 ReturnValue = 0;
209 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
210 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
211 // Indirect aggregate return; emit returned value directly into sret slot.
212 // This reduces code size, and is also affects correctness in C++.
213 ReturnValue = CurFn->arg_begin();
214 } else {
215 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
216 }
217
Daniel Dunbar88b53962009-02-02 22:03:45 +0000218 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Anders Carlsson751358f2008-12-20 21:28:43 +0000220 // If any of the arguments have a variably modified type, make sure to
221 // emit the type size.
222 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
223 i != e; ++i) {
224 QualType Ty = i->second;
225
226 if (Ty->isVariablyModifiedType())
227 EmitVLASize(Ty);
228 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000229}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000230
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000231static bool NeedsVTTParameter(GlobalDecl GD) {
232 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
233
234 // We don't have any virtual bases, just return early.
235 if (!MD->getParent()->getNumVBases())
236 return false;
237
238 // Check if we have a base constructor.
239 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
240 return true;
241
242 // Check if we have a base destructor.
243 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
244 return true;
245
246 return false;
247}
248
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000249void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000250 llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000251 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
252
Anders Carlssone896d982009-02-13 08:11:52 +0000253 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000254 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000255 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Daniel Dunbar7c086512008-09-09 23:14:03 +0000257 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000259 CurGD = GD;
260 OuterTryBlock = 0;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000261 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
262 if (MD->isInstance()) {
263 // Create the implicit 'this' decl.
264 // FIXME: I'm not entirely sure I like using a fake decl just for code
265 // generation. Maybe we can come up with a better way?
266 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000267 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000268 MD->getThisType(getContext()));
269 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000270
271 // Check if we need a VTT parameter as well.
272 if (NeedsVTTParameter(GD)) {
273 // FIXME: The comment about using a fake decl above applies here too.
274 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
275 CXXVTTDecl =
276 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
277 &getContext().Idents.get("vtt"), T);
278 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
279 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000280 }
281 }
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000283 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000284 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000285 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000286
287 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000288 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000289 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000290 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000291
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000292 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000293 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000294
295 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000296 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000297 EmitStmt(S);
Anders Carlsson5e1b9182009-11-06 04:19:02 +0000298
299 // If any of the member initializers are temporaries bound to references
300 // make sure to emit their destructors.
301 EmitCleanupBlocks(0);
302
Anders Carlsson4365bba2009-11-06 02:55:43 +0000303 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
304 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
305 PushCleanupBlock(DtorEpilogue);
306
307 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000308
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000309 CleanupBlockInfo Info = PopCleanupBlock();
310
311 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
312 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000313 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000314
315 if (Info.SwitchBlock)
316 EmitBlock(Info.SwitchBlock);
317 if (Info.EndBlock)
318 EmitBlock(Info.EndBlock);
Anders Carlsson4365bba2009-11-06 02:55:43 +0000319 } else {
320 // Just a regular function, emit its body.
321 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000322 }
Anders Carlsson4365bba2009-11-06 02:55:43 +0000323
Sebastian Redld3a413d2009-04-26 20:35:05 +0000324 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000325 } else if (FD->isImplicit()) {
326 const CXXRecordDecl *ClassDecl =
327 cast<CXXRecordDecl>(FD->getDeclContext());
328 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000329 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000330 // FIXME: For C++0x, we want to look for implicit *definitions* of
331 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian98896522009-08-06 23:38:16 +0000332 if (CD->isCopyConstructor(getContext())) {
333 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000334 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000335 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000336 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000337 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000338 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000339 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000340 } else {
341 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000342 }
Douglas Gregor45132722009-10-01 20:44:19 +0000343 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
344 assert(!ClassDecl->hasUserDeclaredDestructor() &&
345 "Cannot synthesize a non-implicit destructor");
346 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
347 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
348 assert(MD->isCopyAssignment() &&
349 !ClassDecl->hasUserDeclaredCopyAssignment() &&
350 "Cannot synthesize a method that is not an implicit-defined "
351 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000352 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000353 } else {
354 assert(false && "Cannot synthesize unknown implicit function");
355 }
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000356 } else if (const Stmt *S = FD->getBody()) {
357 if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) {
358 OuterTryBlock = TS;
359 StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc());
360 EmitStmt(TS);
361 FinishFunction(TS->getEndLoc());
362 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000363 }
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000365 // Destroy the 'this' declaration.
366 if (CXXThisDecl)
367 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000368
369 // Destroy the VTT declaration.
370 if (CXXVTTDecl)
371 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000372}
373
Chris Lattner0946ccd2008-11-11 07:41:27 +0000374/// ContainsLabel - Return true if the statement contains a label in it. If
375/// this statement is not executed normally, it not containing a label means
376/// that we can just remove the code.
377bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
378 // Null statement, not a label!
379 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattner0946ccd2008-11-11 07:41:27 +0000381 // If this is a label, we have to emit the code, consider something like:
382 // if (0) { ... foo: bar(); } goto foo;
383 if (isa<LabelStmt>(S))
384 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattner0946ccd2008-11-11 07:41:27 +0000386 // If this is a case/default statement, and we haven't seen a switch, we have
387 // to emit the code.
388 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
389 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner0946ccd2008-11-11 07:41:27 +0000391 // If this is a switch statement, we want to ignore cases below it.
392 if (isa<SwitchStmt>(S))
393 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner0946ccd2008-11-11 07:41:27 +0000395 // Scan subexpressions for verboten labels.
396 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
397 I != E; ++I)
398 if (ContainsLabel(*I, IgnoreCaseStmts))
399 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner0946ccd2008-11-11 07:41:27 +0000401 return false;
402}
403
Chris Lattner31a09842008-11-12 08:04:58 +0000404
405/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
406/// a constant, or if it does but contains a label, return 0. If it constant
407/// folds to 'true' and does not contain a label, return 1, if it constant folds
408/// to 'false' and does not contain a label, return -1.
409int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000410 // FIXME: Rename and handle conversion of other evaluatable things
411 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000412 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000413 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000414 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000415 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner31a09842008-11-12 08:04:58 +0000417 if (CodeGenFunction::ContainsLabel(Cond))
418 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Anders Carlsson64712f12008-12-01 02:46:24 +0000420 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000421}
422
423
424/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
425/// statement) to the specified blocks. Based on the condition, this might try
426/// to simplify the codegen of the conditional based on the branch.
427///
428void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
429 llvm::BasicBlock *TrueBlock,
430 llvm::BasicBlock *FalseBlock) {
431 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
432 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner31a09842008-11-12 08:04:58 +0000434 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
435 // Handle X && Y in a condition.
436 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
437 // If we have "1 && X", simplify the code. "0 && X" would have constant
438 // folded if the case was simple enough.
439 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
440 // br(1 && X) -> br(X).
441 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
442 }
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner31a09842008-11-12 08:04:58 +0000444 // If we have "X && 1", simplify the code to use an uncond branch.
445 // "X && 0" would have been constant folded to 0.
446 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
447 // br(X && 1) -> br(X).
448 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
449 }
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner31a09842008-11-12 08:04:58 +0000451 // Emit the LHS as a conditional. If the LHS conditional is false, we
452 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000453 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000454 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
455 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner31a09842008-11-12 08:04:58 +0000457 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
458 return;
459 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
460 // If we have "0 || X", simplify the code. "1 || X" would have constant
461 // folded if the case was simple enough.
462 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
463 // br(0 || X) -> br(X).
464 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
465 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Chris Lattner31a09842008-11-12 08:04:58 +0000467 // If we have "X || 0", simplify the code to use an uncond branch.
468 // "X || 1" would have been constant folded to 1.
469 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
470 // br(X || 0) -> br(X).
471 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner31a09842008-11-12 08:04:58 +0000474 // Emit the LHS as a conditional. If the LHS conditional is true, we
475 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000476 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000477 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
478 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner31a09842008-11-12 08:04:58 +0000480 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
481 return;
482 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattner552f4c42008-11-12 08:13:36 +0000485 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
486 // br(!x, t, f) -> br(x, f, t)
487 if (CondUOp->getOpcode() == UnaryOperator::LNot)
488 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Daniel Dunbar09b14892008-11-12 10:30:32 +0000491 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
492 // Handle ?: operator.
493
494 // Just ignore GNU ?: extension.
495 if (CondOp->getLHS()) {
496 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
497 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
498 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
499 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
500 EmitBlock(LHSBlock);
501 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
502 EmitBlock(RHSBlock);
503 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
504 return;
505 }
506 }
507
Chris Lattner31a09842008-11-12 08:04:58 +0000508 // Emit the code with the fully general case.
509 llvm::Value *CondV = EvaluateExprAsBool(Cond);
510 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
511}
512
Daniel Dunbar488e9932008-08-16 00:56:44 +0000513/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000514/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000515void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
516 bool OmitOnError) {
517 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000518}
519
Chris Lattner88207c92009-04-21 17:59:23 +0000520void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000521 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000522 if (DestPtr->getType() != BP)
523 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
524
525 // Get size and alignment info for this aggregate.
526 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
527
Chris Lattner88207c92009-04-21 17:59:23 +0000528 // Don't bother emitting a zero-byte memset.
529 if (TypeInfo.first == 0)
530 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000532 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000533 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000534 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000535
536 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000537 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000538 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000539 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000540 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000541 TypeInfo.second/8));
542}
543
Chris Lattnerd9becd12009-10-28 23:59:40 +0000544llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
545 // Make sure that there is a block for the indirect goto.
546 if (IndirectBranch == 0)
547 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000548
Chris Lattnerd9becd12009-10-28 23:59:40 +0000549 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000550
Chris Lattnerd9becd12009-10-28 23:59:40 +0000551 // Make sure the indirect branch includes all of the address-taken blocks.
552 IndirectBranch->addDestination(BB);
553 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000554}
555
556llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000557 // If we already made the indirect branch for indirect goto, return its block.
558 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000559
Chris Lattnerd9becd12009-10-28 23:59:40 +0000560 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000561
Chris Lattnerd9becd12009-10-28 23:59:40 +0000562 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000563
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000564 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000565 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000566
Chris Lattnerd9becd12009-10-28 23:59:40 +0000567 // Create the indirect branch instruction.
568 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
569 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000570}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000571
Daniel Dunbard286f052009-07-19 06:58:07 +0000572llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000573 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Anders Carlssonf666b772008-12-20 20:27:15 +0000575 assert(SizeEntry && "Did not emit size for type");
576 return SizeEntry;
577}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000578
Daniel Dunbard286f052009-07-19 06:58:07 +0000579llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000580 assert(Ty->isVariablyModifiedType() &&
581 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Daniel Dunbard286f052009-07-19 06:58:07 +0000583 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Anders Carlsson60d35412008-12-20 20:46:34 +0000585 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000586 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000588 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000589 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000591 // Get the element size;
592 QualType ElemTy = VAT->getElementType();
593 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000594 if (ElemTy->isVariableArrayType())
595 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000596 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000597 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000598 getContext().getTypeSize(ElemTy) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000600 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000601 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000603 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000604 }
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Anders Carlsson60d35412008-12-20 20:46:34 +0000606 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000607 }
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000609 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
610 EmitVLASize(AT->getElementType());
611 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000612 }
613
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000614 const PointerType *PT = Ty->getAs<PointerType>();
615 assert(PT && "unknown VM type!");
616 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000617 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000618}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000619
620llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
621 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
622 return EmitScalarExpr(E);
623 }
624 return EmitLValue(E).getAddress();
625}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000626
Fariborz Jahanian77996212009-11-04 17:57:40 +0000627void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000628 llvm::BasicBlock *CleanupExitBlock,
629 bool EHOnly) {
630 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
631 EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000632}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000633
Mike Stump1eb44332009-09-09 15:08:12 +0000634void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
635 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000636 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Anders Carlssonc71c8452009-02-07 23:50:39 +0000638 while (CleanupEntries.size() > OldCleanupStackSize)
639 EmitCleanupBlock();
640}
641
Mike Stump1eb44332009-09-09 15:08:12 +0000642CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000643 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Fariborz Jahanian77996212009-11-04 17:57:40 +0000645 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000647 std::vector<llvm::BasicBlock *> Blocks;
648 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000650 std::vector<llvm::BranchInst *> BranchFixups;
651 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Mike Stump99533832009-12-02 07:41:41 +0000653 bool EHOnly = CE.EHOnly;
654
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000655 CleanupEntries.pop_back();
656
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000657 // Check if any branch fixups pointed to the scope we just popped. If so,
658 // we can remove them.
659 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
660 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
661 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000663 if (I == BlockScopes.end())
664 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000666 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000668 if (I->second == CleanupEntries.size()) {
669 // We don't need to do this branch fixup.
670 BranchFixups[i] = BranchFixups.back();
671 BranchFixups.pop_back();
672 i--;
673 e--;
674 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000675 }
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Fariborz Jahanian77996212009-11-04 17:57:40 +0000678 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000679 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000680 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000681 if (!SwitchBlock)
682 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000683 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000685 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000687 Builder.SetInsertPoint(SwitchBlock);
688
Mike Stump99533832009-12-02 07:41:41 +0000689 llvm::Value *DestCodePtr
690 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
691 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000692 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000694 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000695 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000696 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000697
Anders Carlsson46831a92009-02-08 22:13:37 +0000698 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000699 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000700 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000702 // If we had a current basic block, we also need to emit an instruction
703 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000704 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000705 DestCodePtr);
706 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000707 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000708
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000709 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
710 llvm::BranchInst *BI = BranchFixups[i];
711 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000713 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000714 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000716 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000717 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Anders Carlssoncc899202009-02-08 22:46:50 +0000719 // Check if we already have a destination for this block.
720 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000721 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000722 else {
723 ID = SI->findCaseDest(Dest);
724 if (!ID) {
725 // No code found, get a new unique one by using the number of
726 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000727 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000728 SI->getNumSuccessors());
729 SI->addCase(ID, Dest);
730 }
731 }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Anders Carlssoncc899202009-02-08 22:46:50 +0000733 // Store the jump destination before the branch instruction.
734 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000735 } else {
736 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000737 // with a branch instruction that jumps to the final destination and add
738 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000740 // Create the pad block.
741 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000742
743 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000744 llvm::ConstantInt *ID
745 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
746 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000747
748 // Store the jump destination before the branch instruction.
749 new llvm::StoreInst(ID, DestCodePtr, BI);
750
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000751 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000752 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000754 // Create the branch to the final destination.
755 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
756 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000758 // And add it as a branch fixup.
759 CleanupEntries.back().BranchFixups.push_back(BI);
760 }
761 }
762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000764 // Remove all blocks from the block scope map.
765 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
766 assert(BlockScopes.count(Blocks[i]) &&
767 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000769 BlockScopes.erase(Blocks[i]);
770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Mike Stump99533832009-12-02 07:41:41 +0000772 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000773}
774
Mike Stump1eb44332009-09-09 15:08:12 +0000775void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000776 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Mike Stump99533832009-12-02 07:41:41 +0000778 if (Info.EHOnly) {
779 // FIXME: Add this to the exceptional edge
780 if (Info.CleanupBlock->getNumUses() == 0)
781 delete Info.CleanupBlock;
782 return;
783 }
784
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000785 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000786 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000787 Info.CleanupBlock->getNumUses() == 0) {
788 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
789 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000790 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000791 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000793 if (Info.SwitchBlock)
794 EmitBlock(Info.SwitchBlock);
795 if (Info.EndBlock)
796 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000797}
798
Mike Stump1eb44332009-09-09 15:08:12 +0000799void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
800 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000801 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Mike Stumpf5408fe2009-05-16 07:57:57 +0000803 // FIXME: We could be more clever here and check if there's already a branch
804 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000805 CleanupEntries.back().BranchFixups.push_back(BI);
806}
807
Mike Stump1eb44332009-09-09 15:08:12 +0000808void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000809 if (!HaveInsertPoint())
810 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Anders Carlsson87eaf172009-02-08 00:50:42 +0000812 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Anders Carlsson46831a92009-02-08 22:13:37 +0000814 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Anders Carlsson87eaf172009-02-08 00:50:42 +0000816 // The stack is empty, no need to do any cleanup.
817 if (CleanupEntries.empty())
818 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Anders Carlsson87eaf172009-02-08 00:50:42 +0000820 if (!Dest->getParent()) {
821 // We are trying to branch to a block that hasn't been inserted yet.
822 AddBranchFixup(BI);
823 return;
824 }
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Anders Carlsson87eaf172009-02-08 00:50:42 +0000826 BlockScopeMap::iterator I = BlockScopes.find(Dest);
827 if (I == BlockScopes.end()) {
828 // We are trying to jump to a block that is outside of any cleanup scope.
829 AddBranchFixup(BI);
830 return;
831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Anders Carlsson87eaf172009-02-08 00:50:42 +0000833 assert(I->second < CleanupEntries.size() &&
834 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Anders Carlsson87eaf172009-02-08 00:50:42 +0000836 if (I->second == CleanupEntries.size() - 1) {
837 // We have a branch to a block in the same scope.
838 return;
839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Anders Carlsson87eaf172009-02-08 00:50:42 +0000841 AddBranchFixup(BI);
842}