blob: 5db441197e1f3a30e9401149dd233b6d570ab3e8 [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),
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
Daniel Dunbar55e87422008-11-11 02:29:29 +0000174 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000175
Chris Lattner41110242008-06-17 18:05:57 +0000176 // Create a marker to make it easy to insert allocas into the entryblock
177 // later. Don't create this with the builder, because we don't want it
178 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000179 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000180 AllocaInsertPt = new llvm::BitCastInst(Undef,
181 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000182 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000183 if (Builder.isNamePreserving())
184 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Daniel Dunbar55e87422008-11-11 02:29:29 +0000186 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattner41110242008-06-17 18:05:57 +0000188 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Mike Stump91cc8152009-10-23 01:52:13 +0000190 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
191
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000192 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000193 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000194 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000195 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000196 }
197
Daniel Dunbar88b53962009-02-02 22:03:45 +0000198 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000199 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Eli Friedmanb17daf92009-12-04 02:43:40 +0000200
201 if (RetTy->isVoidType()) {
202 // Void type; nothing to return.
203 ReturnValue = 0;
204 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
205 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
206 // Indirect aggregate return; emit returned value directly into sret slot.
207 // This reduces code size, and is also affects correctness in C++.
208 ReturnValue = CurFn->arg_begin();
209 } else {
210 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
211 }
212
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000213 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000214 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Anders Carlsson751358f2008-12-20 21:28:43 +0000216 // If any of the arguments have a variably modified type, make sure to
217 // emit the type size.
218 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
219 i != e; ++i) {
220 QualType Ty = i->second;
221
222 if (Ty->isVariablyModifiedType())
223 EmitVLASize(Ty);
224 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000225}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000226
Anders Carlssonc997d422010-01-02 01:01:18 +0000227void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000228 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
229
Anders Carlssone896d982009-02-13 08:11:52 +0000230 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000231 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000232 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Daniel Dunbar7c086512008-09-09 23:14:03 +0000234 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000236 CurGD = GD;
237 OuterTryBlock = 0;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000238 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
239 if (MD->isInstance()) {
240 // Create the implicit 'this' decl.
241 // FIXME: I'm not entirely sure I like using a fake decl just for code
242 // generation. Maybe we can come up with a better way?
243 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000244 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000245 MD->getThisType(getContext()));
246 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000247
248 // Check if we need a VTT parameter as well.
Anders Carlssonc997d422010-01-02 01:01:18 +0000249 if (CGVtableInfo::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000250 // FIXME: The comment about using a fake decl above applies here too.
251 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
252 CXXVTTDecl =
253 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
254 &getContext().Idents.get("vtt"), T);
255 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
256 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000257 }
258 }
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000260 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000261 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000262 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000263
264 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000265 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000266 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000267 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000268
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000269 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000270 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000271
272 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000273 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000274 EmitStmt(S);
Anders Carlsson5e1b9182009-11-06 04:19:02 +0000275
276 // If any of the member initializers are temporaries bound to references
277 // make sure to emit their destructors.
278 EmitCleanupBlocks(0);
279
Anders Carlsson4365bba2009-11-06 02:55:43 +0000280 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
281 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
282 PushCleanupBlock(DtorEpilogue);
283
284 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000285
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000286 CleanupBlockInfo Info = PopCleanupBlock();
287
288 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
289 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000290 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000291
292 if (Info.SwitchBlock)
293 EmitBlock(Info.SwitchBlock);
294 if (Info.EndBlock)
295 EmitBlock(Info.EndBlock);
Anders Carlsson4365bba2009-11-06 02:55:43 +0000296 } else {
297 // Just a regular function, emit its body.
298 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000299 }
Anders Carlsson4365bba2009-11-06 02:55:43 +0000300
Sebastian Redld3a413d2009-04-26 20:35:05 +0000301 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000302 } else if (FD->isImplicit()) {
303 const CXXRecordDecl *ClassDecl =
304 cast<CXXRecordDecl>(FD->getDeclContext());
305 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000306 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000307 // FIXME: For C++0x, we want to look for implicit *definitions* of
308 // these special member functions, rather than implicit *declarations*.
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000309 if (CD->isCopyConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000310 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000311 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000312 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000313 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000314 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000315 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000316 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000317 } else {
318 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000319 }
Douglas Gregor45132722009-10-01 20:44:19 +0000320 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
321 assert(!ClassDecl->hasUserDeclaredDestructor() &&
322 "Cannot synthesize a non-implicit destructor");
323 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
324 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
325 assert(MD->isCopyAssignment() &&
326 !ClassDecl->hasUserDeclaredCopyAssignment() &&
327 "Cannot synthesize a method that is not an implicit-defined "
328 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000329 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000330 } else {
331 assert(false && "Cannot synthesize unknown implicit function");
332 }
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000333 } else if (const Stmt *S = FD->getBody()) {
334 if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) {
335 OuterTryBlock = TS;
336 StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc());
337 EmitStmt(TS);
338 FinishFunction(TS->getEndLoc());
339 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000340 }
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000342 // Destroy the 'this' declaration.
343 if (CXXThisDecl)
344 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000345
346 // Destroy the VTT declaration.
347 if (CXXVTTDecl)
348 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000349}
350
Chris Lattner0946ccd2008-11-11 07:41:27 +0000351/// ContainsLabel - Return true if the statement contains a label in it. If
352/// this statement is not executed normally, it not containing a label means
353/// that we can just remove the code.
354bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
355 // Null statement, not a label!
356 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattner0946ccd2008-11-11 07:41:27 +0000358 // If this is a label, we have to emit the code, consider something like:
359 // if (0) { ... foo: bar(); } goto foo;
360 if (isa<LabelStmt>(S))
361 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner0946ccd2008-11-11 07:41:27 +0000363 // If this is a case/default statement, and we haven't seen a switch, we have
364 // to emit the code.
365 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
366 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chris Lattner0946ccd2008-11-11 07:41:27 +0000368 // If this is a switch statement, we want to ignore cases below it.
369 if (isa<SwitchStmt>(S))
370 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner0946ccd2008-11-11 07:41:27 +0000372 // Scan subexpressions for verboten labels.
373 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
374 I != E; ++I)
375 if (ContainsLabel(*I, IgnoreCaseStmts))
376 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Chris Lattner0946ccd2008-11-11 07:41:27 +0000378 return false;
379}
380
Chris Lattner31a09842008-11-12 08:04:58 +0000381
382/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
383/// a constant, or if it does but contains a label, return 0. If it constant
384/// folds to 'true' and does not contain a label, return 1, if it constant folds
385/// to 'false' and does not contain a label, return -1.
386int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000387 // FIXME: Rename and handle conversion of other evaluatable things
388 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000389 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000391 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000392 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Chris Lattner31a09842008-11-12 08:04:58 +0000394 if (CodeGenFunction::ContainsLabel(Cond))
395 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Anders Carlsson64712f12008-12-01 02:46:24 +0000397 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000398}
399
400
401/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
402/// statement) to the specified blocks. Based on the condition, this might try
403/// to simplify the codegen of the conditional based on the branch.
404///
405void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
406 llvm::BasicBlock *TrueBlock,
407 llvm::BasicBlock *FalseBlock) {
408 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
409 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattner31a09842008-11-12 08:04:58 +0000411 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
412 // Handle X && Y in a condition.
413 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
414 // If we have "1 && X", simplify the code. "0 && X" would have constant
415 // folded if the case was simple enough.
416 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
417 // br(1 && X) -> br(X).
418 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
419 }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Chris Lattner31a09842008-11-12 08:04:58 +0000421 // If we have "X && 1", simplify the code to use an uncond branch.
422 // "X && 0" would have been constant folded to 0.
423 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
424 // br(X && 1) -> br(X).
425 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattner31a09842008-11-12 08:04:58 +0000428 // Emit the LHS as a conditional. If the LHS conditional is false, we
429 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000430 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000431 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
432 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Anders Carlsson08e9e452010-01-24 00:20:05 +0000434 // Any temporaries created here are conditional.
435 StartConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000436 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson08e9e452010-01-24 00:20:05 +0000437 FinishConditionalBranch();
438
Chris Lattner31a09842008-11-12 08:04:58 +0000439 return;
440 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
441 // If we have "0 || X", simplify the code. "1 || X" would have constant
442 // folded if the case was simple enough.
443 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
444 // br(0 || X) -> br(X).
445 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
446 }
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner31a09842008-11-12 08:04:58 +0000448 // If we have "X || 0", simplify the code to use an uncond branch.
449 // "X || 1" would have been constant folded to 1.
450 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
451 // br(X || 0) -> br(X).
452 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattner31a09842008-11-12 08:04:58 +0000455 // Emit the LHS as a conditional. If the LHS conditional is true, we
456 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000457 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000458 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
459 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Anders Carlsson08e9e452010-01-24 00:20:05 +0000461 // Any temporaries created here are conditional.
462 StartConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000463 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson08e9e452010-01-24 00:20:05 +0000464 FinishConditionalBranch();
465
Chris Lattner31a09842008-11-12 08:04:58 +0000466 return;
467 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Chris Lattner552f4c42008-11-12 08:13:36 +0000470 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
471 // br(!x, t, f) -> br(x, f, t)
472 if (CondUOp->getOpcode() == UnaryOperator::LNot)
473 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Daniel Dunbar09b14892008-11-12 10:30:32 +0000476 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
477 // Handle ?: operator.
478
479 // Just ignore GNU ?: extension.
480 if (CondOp->getLHS()) {
481 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
482 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
483 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
484 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
485 EmitBlock(LHSBlock);
486 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
487 EmitBlock(RHSBlock);
488 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
489 return;
490 }
491 }
492
Chris Lattner31a09842008-11-12 08:04:58 +0000493 // Emit the code with the fully general case.
494 llvm::Value *CondV = EvaluateExprAsBool(Cond);
495 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
496}
497
Daniel Dunbar488e9932008-08-16 00:56:44 +0000498/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000499/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000500void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
501 bool OmitOnError) {
502 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000503}
504
Chris Lattner88207c92009-04-21 17:59:23 +0000505void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000506 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000507 if (DestPtr->getType() != BP)
508 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
509
510 // Get size and alignment info for this aggregate.
511 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
512
Chris Lattner88207c92009-04-21 17:59:23 +0000513 // Don't bother emitting a zero-byte memset.
514 if (TypeInfo.first == 0)
515 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000517 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000518 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000519 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000520
521 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000522 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000523 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000524 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000525 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000526 TypeInfo.second/8));
527}
528
Chris Lattnerd9becd12009-10-28 23:59:40 +0000529llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
530 // Make sure that there is a block for the indirect goto.
531 if (IndirectBranch == 0)
532 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000533
Chris Lattnerd9becd12009-10-28 23:59:40 +0000534 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000535
Chris Lattnerd9becd12009-10-28 23:59:40 +0000536 // Make sure the indirect branch includes all of the address-taken blocks.
537 IndirectBranch->addDestination(BB);
538 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000539}
540
541llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000542 // If we already made the indirect branch for indirect goto, return its block.
543 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000544
Chris Lattnerd9becd12009-10-28 23:59:40 +0000545 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000546
Chris Lattnerd9becd12009-10-28 23:59:40 +0000547 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000548
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000549 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000550 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000551
Chris Lattnerd9becd12009-10-28 23:59:40 +0000552 // Create the indirect branch instruction.
553 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
554 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000555}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000556
Daniel Dunbard286f052009-07-19 06:58:07 +0000557llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000558 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Anders Carlssonf666b772008-12-20 20:27:15 +0000560 assert(SizeEntry && "Did not emit size for type");
561 return SizeEntry;
562}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000563
Daniel Dunbard286f052009-07-19 06:58:07 +0000564llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000565 assert(Ty->isVariablyModifiedType() &&
566 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Daniel Dunbard286f052009-07-19 06:58:07 +0000568 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Anders Carlsson60d35412008-12-20 20:46:34 +0000570 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000571 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000573 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000574 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000576 // Get the element size;
577 QualType ElemTy = VAT->getElementType();
578 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000579 if (ElemTy->isVariableArrayType())
580 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000581 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000582 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000583 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000585 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000586 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000588 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000589 }
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Anders Carlsson60d35412008-12-20 20:46:34 +0000591 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000592 }
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000594 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
595 EmitVLASize(AT->getElementType());
596 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000597 }
598
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000599 const PointerType *PT = Ty->getAs<PointerType>();
600 assert(PT && "unknown VM type!");
601 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000602 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000603}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000604
605llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
606 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
607 return EmitScalarExpr(E);
608 }
609 return EmitLValue(E).getAddress();
610}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000611
Fariborz Jahanian77996212009-11-04 17:57:40 +0000612void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000613 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000614 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump99533832009-12-02 07:41:41 +0000615 bool EHOnly) {
616 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000617 PreviousInvokeDest, EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000618}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000619
Mike Stump1eb44332009-09-09 15:08:12 +0000620void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
621 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000622 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Anders Carlssonc71c8452009-02-07 23:50:39 +0000624 while (CleanupEntries.size() > OldCleanupStackSize)
625 EmitCleanupBlock();
626}
627
Mike Stump1eb44332009-09-09 15:08:12 +0000628CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000629 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Fariborz Jahanian77996212009-11-04 17:57:40 +0000631 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000633 std::vector<llvm::BasicBlock *> Blocks;
634 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000636 std::vector<llvm::BranchInst *> BranchFixups;
637 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Mike Stump99533832009-12-02 07:41:41 +0000639 bool EHOnly = CE.EHOnly;
640
Mike Stumpd88ea562009-12-09 03:35:49 +0000641 setInvokeDest(CE.PreviousInvokeDest);
642
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000643 CleanupEntries.pop_back();
644
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000645 // Check if any branch fixups pointed to the scope we just popped. If so,
646 // we can remove them.
647 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
648 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
649 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000651 if (I == BlockScopes.end())
652 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000654 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000656 if (I->second == CleanupEntries.size()) {
657 // We don't need to do this branch fixup.
658 BranchFixups[i] = BranchFixups.back();
659 BranchFixups.pop_back();
660 i--;
661 e--;
662 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000663 }
664 }
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Fariborz Jahanian77996212009-11-04 17:57:40 +0000666 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000667 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000668 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000669 if (!SwitchBlock)
670 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000671 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000673 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000675 Builder.SetInsertPoint(SwitchBlock);
676
Mike Stump99533832009-12-02 07:41:41 +0000677 llvm::Value *DestCodePtr
678 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
679 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000680 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000682 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000683 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000684 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000685
Anders Carlsson46831a92009-02-08 22:13:37 +0000686 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000687 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000688 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000690 // If we had a current basic block, we also need to emit an instruction
691 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000692 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000693 DestCodePtr);
694 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000695 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000696
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000697 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
698 llvm::BranchInst *BI = BranchFixups[i];
699 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000701 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000702 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000704 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000705 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Anders Carlssoncc899202009-02-08 22:46:50 +0000707 // Check if we already have a destination for this block.
708 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000709 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000710 else {
711 ID = SI->findCaseDest(Dest);
712 if (!ID) {
713 // No code found, get a new unique one by using the number of
714 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000715 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000716 SI->getNumSuccessors());
717 SI->addCase(ID, Dest);
718 }
719 }
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Anders Carlssoncc899202009-02-08 22:46:50 +0000721 // Store the jump destination before the branch instruction.
722 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000723 } else {
724 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000725 // with a branch instruction that jumps to the final destination and add
726 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000728 // Create the pad block.
729 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000730
731 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000732 llvm::ConstantInt *ID
733 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
734 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000735
736 // Store the jump destination before the branch instruction.
737 new llvm::StoreInst(ID, DestCodePtr, BI);
738
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000739 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000740 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000742 // Create the branch to the final destination.
743 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
744 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000746 // And add it as a branch fixup.
747 CleanupEntries.back().BranchFixups.push_back(BI);
748 }
749 }
750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000752 // Remove all blocks from the block scope map.
753 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
754 assert(BlockScopes.count(Blocks[i]) &&
755 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000757 BlockScopes.erase(Blocks[i]);
758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Mike Stump99533832009-12-02 07:41:41 +0000760 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000761}
762
Mike Stump1eb44332009-09-09 15:08:12 +0000763void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000764 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Mike Stump99533832009-12-02 07:41:41 +0000766 if (Info.EHOnly) {
767 // FIXME: Add this to the exceptional edge
768 if (Info.CleanupBlock->getNumUses() == 0)
769 delete Info.CleanupBlock;
770 return;
771 }
772
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000773 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000774 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000775 Info.CleanupBlock->getNumUses() == 0) {
776 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
777 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000778 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000779 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000781 if (Info.SwitchBlock)
782 EmitBlock(Info.SwitchBlock);
783 if (Info.EndBlock)
784 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000785}
786
Mike Stump1eb44332009-09-09 15:08:12 +0000787void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
788 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000789 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Mike Stumpf5408fe2009-05-16 07:57:57 +0000791 // FIXME: We could be more clever here and check if there's already a branch
792 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000793 CleanupEntries.back().BranchFixups.push_back(BI);
794}
795
Mike Stump1eb44332009-09-09 15:08:12 +0000796void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000797 if (!HaveInsertPoint())
798 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Anders Carlsson87eaf172009-02-08 00:50:42 +0000800 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Anders Carlsson46831a92009-02-08 22:13:37 +0000802 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Anders Carlsson87eaf172009-02-08 00:50:42 +0000804 // The stack is empty, no need to do any cleanup.
805 if (CleanupEntries.empty())
806 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Anders Carlsson87eaf172009-02-08 00:50:42 +0000808 if (!Dest->getParent()) {
809 // We are trying to branch to a block that hasn't been inserted yet.
810 AddBranchFixup(BI);
811 return;
812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Anders Carlsson87eaf172009-02-08 00:50:42 +0000814 BlockScopeMap::iterator I = BlockScopes.find(Dest);
815 if (I == BlockScopes.end()) {
816 // We are trying to jump to a block that is outside of any cleanup scope.
817 AddBranchFixup(BI);
818 return;
819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Anders Carlsson87eaf172009-02-08 00:50:42 +0000821 assert(I->second < CleanupEntries.size() &&
822 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Anders Carlsson87eaf172009-02-08 00:50:42 +0000824 if (I->second == CleanupEntries.size() - 1) {
825 // We have a branch to a block in the same scope.
826 return;
827 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Anders Carlsson87eaf172009-02-08 00:50:42 +0000829 AddBranchFixup(BI);
830}