blob: d803a05aa95e63eae608274d14ca96faeba95596 [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),
John McCall25049412010-02-16 22:04:33 +000033 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
Mike Stump15037ca2009-12-15 00:35:12 +000034 ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
Mike Stumpbe07f602009-12-14 21:58:14 +000035 UniqueAggrDestructorCount(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000036 LLVMIntTy = ConvertType(getContext().IntTy);
37 LLVMPointerWidth = Target.getPointerWidth(0);
Mike Stumpd88ea562009-12-09 03:35:49 +000038 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000039 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Chris Lattner41110242008-06-17 18:05:57 +000040}
Reid Spencer5f016e22007-07-11 17:01:13 +000041
42ASTContext &CodeGenFunction::getContext() const {
43 return CGM.getContext();
44}
45
46
47llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
48 llvm::BasicBlock *&BB = LabelMap[S];
49 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Reid Spencer5f016e22007-07-11 17:01:13 +000051 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000052 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000053}
54
Daniel Dunbar0096acf2009-02-25 19:24:29 +000055llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
56 llvm::Value *Res = LocalDeclMap[VD];
57 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
58 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000059}
Reid Spencer5f016e22007-07-11 17:01:13 +000060
Daniel Dunbar0096acf2009-02-25 19:24:29 +000061llvm::Constant *
62CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
63 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000064}
65
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000066const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
67 return CGM.getTypes().ConvertTypeForMem(T);
68}
69
Reid Spencer5f016e22007-07-11 17:01:13 +000070const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
71 return CGM.getTypes().ConvertType(T);
72}
73
74bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000075 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
76 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000077}
78
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000079void CodeGenFunction::EmitReturnBlock() {
80 // For cleanliness, we try to avoid emitting the return block for
81 // simple cases.
82 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
83
84 if (CurBB) {
85 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86
Daniel Dunbar96e18b02009-07-19 08:24:34 +000087 // We have a valid insert point, reuse it if it is empty or there are no
88 // explicit jumps to the return block.
89 if (CurBB->empty() || ReturnBlock->use_empty()) {
90 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000091 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000092 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000093 EmitBlock(ReturnBlock);
94 return;
95 }
96
97 // Otherwise, if the return block is the target of a single direct
98 // branch then we can just put the code in that block instead. This
99 // cleans up functions which started with a unified return block.
100 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000101 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000102 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
103 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
104 // Reset insertion point and delete the branch.
105 Builder.SetInsertPoint(BI->getParent());
106 BI->eraseFromParent();
107 delete ReturnBlock;
108 return;
109 }
110 }
111
Mike Stumpf5408fe2009-05-16 07:57:57 +0000112 // FIXME: We are at an unreachable point, there is no reason to emit the block
113 // unless it has uses. However, we still need a place to put the debug
114 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000115
116 EmitBlock(ReturnBlock);
117}
118
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000119void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000120 assert(BreakContinueStack.empty() &&
121 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000122 assert(BlockScopes.empty() &&
123 "did not remove all blocks from block scope map!");
124 assert(CleanupEntries.empty() &&
125 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000126
127 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000128 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000129
130 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000131 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000132 DI->setLocation(EndLoc);
133 DI->EmitRegionEnd(CurFn, Builder);
134 }
135
Daniel Dunbar88b53962009-02-02 22:03:45 +0000136 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000137 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000138
Chris Lattnerd9becd12009-10-28 23:59:40 +0000139 // If someone did an indirect goto, emit the indirect goto block at the end of
140 // the function.
141 if (IndirectBranch) {
142 EmitBlock(IndirectBranch->getParent());
143 Builder.ClearInsertionPoint();
144 }
145
Chris Lattner5a2fa142007-12-02 06:32:24 +0000146 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000147 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000148 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000149 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000150
151 // If someone took the address of a label but never did an indirect goto, we
152 // made a zero entry PHI node, which is illegal, zap it now.
153 if (IndirectBranch) {
154 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
155 if (PN->getNumIncomingValues() == 0) {
156 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
157 PN->eraseFromParent();
158 }
159 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000160}
161
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000162void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000163 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000164 const FunctionArgList &Args,
165 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000166 const Decl *D = GD.getDecl();
167
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000168 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000169 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000170 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000171 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000172 assert(CurFn->isDeclaration() && "Function already has body?");
173
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000174 // Pass inline keyword to optimizer if it appears explicitly on any
175 // declaration.
176 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
177 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
178 RE = FD->redecls_end(); RI != RE; ++RI)
179 if (RI->isInlineSpecified()) {
180 Fn->addFnAttr(llvm::Attribute::InlineHint);
181 break;
182 }
183
Daniel Dunbar55e87422008-11-11 02:29:29 +0000184 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000185
Chris Lattner41110242008-06-17 18:05:57 +0000186 // Create a marker to make it easy to insert allocas into the entryblock
187 // later. Don't create this with the builder, because we don't want it
188 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000189 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000190 AllocaInsertPt = new llvm::BitCastInst(Undef,
191 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000192 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000193 if (Builder.isNamePreserving())
194 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Daniel Dunbar55e87422008-11-11 02:29:29 +0000196 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner41110242008-06-17 18:05:57 +0000198 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Mike Stump91cc8152009-10-23 01:52:13 +0000200 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
201
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000202 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000203 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000204 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000205 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000206 }
207
Daniel Dunbar88b53962009-02-02 22:03:45 +0000208 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000209 // CC info is ignored, hopefully?
210 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
211 CC_Default, false);
Eli Friedmanb17daf92009-12-04 02:43:40 +0000212
213 if (RetTy->isVoidType()) {
214 // Void type; nothing to return.
215 ReturnValue = 0;
216 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
217 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
218 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000219 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000220 ReturnValue = CurFn->arg_begin();
221 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000222 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000223 }
224
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000225 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000226 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000227
John McCall25049412010-02-16 22:04:33 +0000228 if (CXXThisDecl)
229 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
230 if (CXXVTTDecl)
231 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
232
Anders Carlsson751358f2008-12-20 21:28:43 +0000233 // If any of the arguments have a variably modified type, make sure to
234 // emit the type size.
235 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
236 i != e; ++i) {
237 QualType Ty = i->second;
238
239 if (Ty->isVariablyModifiedType())
240 EmitVLASize(Ty);
241 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000242}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000243
Anders Carlssonc997d422010-01-02 01:01:18 +0000244void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000245 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
246
Anders Carlssone896d982009-02-13 08:11:52 +0000247 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000248 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000249 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Daniel Dunbar7c086512008-09-09 23:14:03 +0000251 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000253 CurGD = GD;
254 OuterTryBlock = 0;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000255 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
256 if (MD->isInstance()) {
257 // Create the implicit 'this' decl.
258 // FIXME: I'm not entirely sure I like using a fake decl just for code
259 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000260 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
261 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000262 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000263 MD->getThisType(getContext()));
264 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000265
266 // Check if we need a VTT parameter as well.
Anders Carlssonc997d422010-01-02 01:01:18 +0000267 if (CGVtableInfo::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000268 // FIXME: The comment about using a fake decl above applies here too.
269 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
270 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000271 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000272 &getContext().Idents.get("vtt"), T);
273 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
274 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000275 }
276 }
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000278 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000279 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000280 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000281
282 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000283 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000284 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000285 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000286
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000287 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000288 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000289
290 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000291 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000292 EmitStmt(S);
Anders Carlsson5e1b9182009-11-06 04:19:02 +0000293
294 // If any of the member initializers are temporaries bound to references
295 // make sure to emit their destructors.
296 EmitCleanupBlocks(0);
297
Anders Carlsson4365bba2009-11-06 02:55:43 +0000298 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
299 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
300 PushCleanupBlock(DtorEpilogue);
301
Anders Carlsson1851a122010-02-07 19:45:40 +0000302 InitializeVtablePtrs(DD->getParent());
303
Anders Carlsson4365bba2009-11-06 02:55:43 +0000304 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000305
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000306 CleanupBlockInfo Info = PopCleanupBlock();
307
308 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
309 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000310 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000311
312 if (Info.SwitchBlock)
313 EmitBlock(Info.SwitchBlock);
314 if (Info.EndBlock)
315 EmitBlock(Info.EndBlock);
Anders Carlsson4365bba2009-11-06 02:55:43 +0000316 } else {
317 // Just a regular function, emit its body.
318 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000319 }
Anders Carlsson4365bba2009-11-06 02:55:43 +0000320
Sebastian Redld3a413d2009-04-26 20:35:05 +0000321 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000322 } else if (FD->isImplicit()) {
323 const CXXRecordDecl *ClassDecl =
324 cast<CXXRecordDecl>(FD->getDeclContext());
325 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000326 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000327 // FIXME: For C++0x, we want to look for implicit *definitions* of
328 // these special member functions, rather than implicit *declarations*.
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000329 if (CD->isCopyConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000330 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000331 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000332 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000333 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000334 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000335 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000336 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000337 } else {
338 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000339 }
Douglas Gregor45132722009-10-01 20:44:19 +0000340 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
341 assert(!ClassDecl->hasUserDeclaredDestructor() &&
342 "Cannot synthesize a non-implicit destructor");
343 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
344 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
345 assert(MD->isCopyAssignment() &&
346 !ClassDecl->hasUserDeclaredCopyAssignment() &&
347 "Cannot synthesize a method that is not an implicit-defined "
348 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000349 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000350 } else {
351 assert(false && "Cannot synthesize unknown implicit function");
352 }
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000353 } else if (const Stmt *S = FD->getBody()) {
354 if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) {
355 OuterTryBlock = TS;
356 StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc());
357 EmitStmt(TS);
358 FinishFunction(TS->getEndLoc());
359 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000362 // Destroy the 'this' declaration.
363 if (CXXThisDecl)
364 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000365
366 // Destroy the VTT declaration.
367 if (CXXVTTDecl)
368 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000369}
370
Chris Lattner0946ccd2008-11-11 07:41:27 +0000371/// ContainsLabel - Return true if the statement contains a label in it. If
372/// this statement is not executed normally, it not containing a label means
373/// that we can just remove the code.
374bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
375 // Null statement, not a label!
376 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Chris Lattner0946ccd2008-11-11 07:41:27 +0000378 // If this is a label, we have to emit the code, consider something like:
379 // if (0) { ... foo: bar(); } goto foo;
380 if (isa<LabelStmt>(S))
381 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Chris Lattner0946ccd2008-11-11 07:41:27 +0000383 // If this is a case/default statement, and we haven't seen a switch, we have
384 // to emit the code.
385 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
386 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Chris Lattner0946ccd2008-11-11 07:41:27 +0000388 // If this is a switch statement, we want to ignore cases below it.
389 if (isa<SwitchStmt>(S))
390 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner0946ccd2008-11-11 07:41:27 +0000392 // Scan subexpressions for verboten labels.
393 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
394 I != E; ++I)
395 if (ContainsLabel(*I, IgnoreCaseStmts))
396 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner0946ccd2008-11-11 07:41:27 +0000398 return false;
399}
400
Chris Lattner31a09842008-11-12 08:04:58 +0000401
402/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
403/// a constant, or if it does but contains a label, return 0. If it constant
404/// folds to 'true' and does not contain a label, return 1, if it constant folds
405/// to 'false' and does not contain a label, return -1.
406int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000407 // FIXME: Rename and handle conversion of other evaluatable things
408 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000409 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000410 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000411 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000412 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner31a09842008-11-12 08:04:58 +0000414 if (CodeGenFunction::ContainsLabel(Cond))
415 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Anders Carlsson64712f12008-12-01 02:46:24 +0000417 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000418}
419
420
421/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
422/// statement) to the specified blocks. Based on the condition, this might try
423/// to simplify the codegen of the conditional based on the branch.
424///
425void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
426 llvm::BasicBlock *TrueBlock,
427 llvm::BasicBlock *FalseBlock) {
428 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
429 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner31a09842008-11-12 08:04:58 +0000431 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
432 // Handle X && Y in a condition.
433 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
434 // If we have "1 && X", simplify the code. "0 && X" would have constant
435 // folded if the case was simple enough.
436 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
437 // br(1 && X) -> br(X).
438 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner31a09842008-11-12 08:04:58 +0000441 // If we have "X && 1", simplify the code to use an uncond branch.
442 // "X && 0" would have been constant folded to 0.
443 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
444 // br(X && 1) -> br(X).
445 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
446 }
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner31a09842008-11-12 08:04:58 +0000448 // Emit the LHS as a conditional. If the LHS conditional is false, we
449 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000450 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000451 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
452 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Anders Carlsson08e9e452010-01-24 00:20:05 +0000454 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000455 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000456 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000457 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000458
Chris Lattner31a09842008-11-12 08:04:58 +0000459 return;
460 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
461 // If we have "0 || X", simplify the code. "1 || X" would have constant
462 // folded if the case was simple enough.
463 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
464 // br(0 || X) -> br(X).
465 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
466 }
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattner31a09842008-11-12 08:04:58 +0000468 // If we have "X || 0", simplify the code to use an uncond branch.
469 // "X || 1" would have been constant folded to 1.
470 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
471 // br(X || 0) -> br(X).
472 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Chris Lattner31a09842008-11-12 08:04:58 +0000475 // Emit the LHS as a conditional. If the LHS conditional is true, we
476 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000477 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000478 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
479 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Anders Carlsson08e9e452010-01-24 00:20:05 +0000481 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000482 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000483 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000484 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000485
Chris Lattner31a09842008-11-12 08:04:58 +0000486 return;
487 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattner552f4c42008-11-12 08:13:36 +0000490 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
491 // br(!x, t, f) -> br(x, f, t)
492 if (CondUOp->getOpcode() == UnaryOperator::LNot)
493 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Daniel Dunbar09b14892008-11-12 10:30:32 +0000496 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
497 // Handle ?: operator.
498
499 // Just ignore GNU ?: extension.
500 if (CondOp->getLHS()) {
501 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
502 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
503 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
504 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
505 EmitBlock(LHSBlock);
506 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
507 EmitBlock(RHSBlock);
508 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
509 return;
510 }
511 }
512
Chris Lattner31a09842008-11-12 08:04:58 +0000513 // Emit the code with the fully general case.
514 llvm::Value *CondV = EvaluateExprAsBool(Cond);
515 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
516}
517
Daniel Dunbar488e9932008-08-16 00:56:44 +0000518/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000519/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000520void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
521 bool OmitOnError) {
522 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000523}
524
Chris Lattner88207c92009-04-21 17:59:23 +0000525void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000526 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000527 if (DestPtr->getType() != BP)
528 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
529
530 // Get size and alignment info for this aggregate.
531 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
532
Chris Lattner88207c92009-04-21 17:59:23 +0000533 // Don't bother emitting a zero-byte memset.
534 if (TypeInfo.first == 0)
535 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000537 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000538 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000539 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000540
541 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000542 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000543 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000544 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000545 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000546 TypeInfo.second/8));
547}
548
Chris Lattnerd9becd12009-10-28 23:59:40 +0000549llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
550 // Make sure that there is a block for the indirect goto.
551 if (IndirectBranch == 0)
552 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000553
Chris Lattnerd9becd12009-10-28 23:59:40 +0000554 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000555
Chris Lattnerd9becd12009-10-28 23:59:40 +0000556 // Make sure the indirect branch includes all of the address-taken blocks.
557 IndirectBranch->addDestination(BB);
558 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000559}
560
561llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000562 // If we already made the indirect branch for indirect goto, return its block.
563 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000564
Chris Lattnerd9becd12009-10-28 23:59:40 +0000565 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000566
Chris Lattnerd9becd12009-10-28 23:59:40 +0000567 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000568
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000569 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000570 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000571
Chris Lattnerd9becd12009-10-28 23:59:40 +0000572 // Create the indirect branch instruction.
573 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
574 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000575}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000576
Daniel Dunbard286f052009-07-19 06:58:07 +0000577llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000578 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Anders Carlssonf666b772008-12-20 20:27:15 +0000580 assert(SizeEntry && "Did not emit size for type");
581 return SizeEntry;
582}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000583
Daniel Dunbard286f052009-07-19 06:58:07 +0000584llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000585 assert(Ty->isVariablyModifiedType() &&
586 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Daniel Dunbard286f052009-07-19 06:58:07 +0000588 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Anders Carlsson60d35412008-12-20 20:46:34 +0000590 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000591 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000593 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000594 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000596 // Get the element size;
597 QualType ElemTy = VAT->getElementType();
598 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000599 if (ElemTy->isVariableArrayType())
600 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000601 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000602 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000603 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000605 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000606 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000608 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000609 }
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Anders Carlsson60d35412008-12-20 20:46:34 +0000611 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000614 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
615 EmitVLASize(AT->getElementType());
616 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000617 }
618
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000619 const PointerType *PT = Ty->getAs<PointerType>();
620 assert(PT && "unknown VM type!");
621 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000622 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000623}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000624
625llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
626 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
627 return EmitScalarExpr(E);
628 }
629 return EmitLValue(E).getAddress();
630}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000631
Fariborz Jahanian77996212009-11-04 17:57:40 +0000632void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000633 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000634 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump99533832009-12-02 07:41:41 +0000635 bool EHOnly) {
636 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000637 PreviousInvokeDest, EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000638}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000639
Mike Stump1eb44332009-09-09 15:08:12 +0000640void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
641 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000642 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Anders Carlssonc71c8452009-02-07 23:50:39 +0000644 while (CleanupEntries.size() > OldCleanupStackSize)
645 EmitCleanupBlock();
646}
647
Mike Stump1eb44332009-09-09 15:08:12 +0000648CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000649 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Fariborz Jahanian77996212009-11-04 17:57:40 +0000651 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000653 std::vector<llvm::BasicBlock *> Blocks;
654 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000656 std::vector<llvm::BranchInst *> BranchFixups;
657 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Mike Stump99533832009-12-02 07:41:41 +0000659 bool EHOnly = CE.EHOnly;
660
Mike Stumpd88ea562009-12-09 03:35:49 +0000661 setInvokeDest(CE.PreviousInvokeDest);
662
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000663 CleanupEntries.pop_back();
664
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000665 // Check if any branch fixups pointed to the scope we just popped. If so,
666 // we can remove them.
667 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
668 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
669 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000671 if (I == BlockScopes.end())
672 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000674 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000676 if (I->second == CleanupEntries.size()) {
677 // We don't need to do this branch fixup.
678 BranchFixups[i] = BranchFixups.back();
679 BranchFixups.pop_back();
680 i--;
681 e--;
682 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000683 }
684 }
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Fariborz Jahanian77996212009-11-04 17:57:40 +0000686 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000687 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000688 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000689 if (!SwitchBlock)
690 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000691 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000693 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000695 Builder.SetInsertPoint(SwitchBlock);
696
Mike Stump99533832009-12-02 07:41:41 +0000697 llvm::Value *DestCodePtr
698 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
699 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000700 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000702 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000703 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000704 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000705
Anders Carlsson46831a92009-02-08 22:13:37 +0000706 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000707 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000708 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000710 // If we had a current basic block, we also need to emit an instruction
711 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000712 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000713 DestCodePtr);
714 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000715 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000716
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000717 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
718 llvm::BranchInst *BI = BranchFixups[i];
719 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000721 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000722 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000724 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000725 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Anders Carlssoncc899202009-02-08 22:46:50 +0000727 // Check if we already have a destination for this block.
728 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000729 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000730 else {
731 ID = SI->findCaseDest(Dest);
732 if (!ID) {
733 // No code found, get a new unique one by using the number of
734 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000735 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000736 SI->getNumSuccessors());
737 SI->addCase(ID, Dest);
738 }
739 }
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Anders Carlssoncc899202009-02-08 22:46:50 +0000741 // Store the jump destination before the branch instruction.
742 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000743 } else {
744 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000745 // with a branch instruction that jumps to the final destination and add
746 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000748 // Create the pad block.
749 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000750
751 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000752 llvm::ConstantInt *ID
753 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
754 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000755
756 // Store the jump destination before the branch instruction.
757 new llvm::StoreInst(ID, DestCodePtr, BI);
758
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000759 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000760 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000762 // Create the branch to the final destination.
763 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
764 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000766 // And add it as a branch fixup.
767 CleanupEntries.back().BranchFixups.push_back(BI);
768 }
769 }
770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000772 // Remove all blocks from the block scope map.
773 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
774 assert(BlockScopes.count(Blocks[i]) &&
775 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000777 BlockScopes.erase(Blocks[i]);
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Mike Stump99533832009-12-02 07:41:41 +0000780 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000781}
782
Mike Stump1eb44332009-09-09 15:08:12 +0000783void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000784 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Mike Stump99533832009-12-02 07:41:41 +0000786 if (Info.EHOnly) {
787 // FIXME: Add this to the exceptional edge
788 if (Info.CleanupBlock->getNumUses() == 0)
789 delete Info.CleanupBlock;
790 return;
791 }
792
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000793 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000794 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000795 Info.CleanupBlock->getNumUses() == 0) {
796 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
797 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000798 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000799 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000801 if (Info.SwitchBlock)
802 EmitBlock(Info.SwitchBlock);
803 if (Info.EndBlock)
804 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000805}
806
Mike Stump1eb44332009-09-09 15:08:12 +0000807void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
808 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000809 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Mike Stumpf5408fe2009-05-16 07:57:57 +0000811 // FIXME: We could be more clever here and check if there's already a branch
812 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000813 CleanupEntries.back().BranchFixups.push_back(BI);
814}
815
Mike Stump1eb44332009-09-09 15:08:12 +0000816void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000817 if (!HaveInsertPoint())
818 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Anders Carlsson87eaf172009-02-08 00:50:42 +0000820 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Anders Carlsson46831a92009-02-08 22:13:37 +0000822 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Anders Carlsson87eaf172009-02-08 00:50:42 +0000824 // The stack is empty, no need to do any cleanup.
825 if (CleanupEntries.empty())
826 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Anders Carlsson87eaf172009-02-08 00:50:42 +0000828 if (!Dest->getParent()) {
829 // We are trying to branch to a block that hasn't been inserted yet.
830 AddBranchFixup(BI);
831 return;
832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Anders Carlsson87eaf172009-02-08 00:50:42 +0000834 BlockScopeMap::iterator I = BlockScopes.find(Dest);
835 if (I == BlockScopes.end()) {
836 // We are trying to jump to a block that is outside of any cleanup scope.
837 AddBranchFixup(BI);
838 return;
839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Anders Carlsson87eaf172009-02-08 00:50:42 +0000841 assert(I->second < CleanupEntries.size() &&
842 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Anders Carlsson87eaf172009-02-08 00:50:42 +0000844 if (I->second == CleanupEntries.size() - 1) {
845 // We have a branch to a block in the same scope.
846 return;
847 }
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Anders Carlsson87eaf172009-02-08 00:50:42 +0000849 AddBranchFixup(BI);
850}