blob: 26964529ea6ff9a251b8ade0e1880444bb619a66 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +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 Friedman17630752008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattnerd1af2d22007-05-29 23:17:50 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattnercd439292008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson468fa632009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stumpbee78dd2009-12-04 23:26:17 +000022#include "clang/AST/StmtCXX.h"
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000023#include "llvm/Target/TargetData.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000024using namespace clang;
25using namespace CodeGen;
26
Mike Stump11289f42009-09-09 15:08:12 +000027CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stump0c743272009-03-06 01:33:24 +000028 : BlockFunction(cgm, *this, Builder), CGM(cgm),
29 Target(CGM.getContext().Target),
Owen Andersonc9673d52009-07-08 20:52:20 +000030 Builder(cgm.getModule().getContext()),
Chris Lattner6c4d2552009-10-28 23:59:40 +000031 DebugInfo(0), IndirectBranch(0),
Chris Lattner2bb5cb42009-10-13 06:55:33 +000032 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson82ba57c2009-11-25 03:15:49 +000033 CXXThisDecl(0), CXXVTTDecl(0),
Eli Friedmand5bc94e2009-12-10 02:21:21 +000034 ConditionalBranchLevel(0), TerminateHandler(0),
35 UniqueAggrDestructorCount(0) {
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000036 LLVMIntTy = ConvertType(getContext().IntTy);
37 LLVMPointerWidth = Target.getPointerWidth(0);
Mike Stumpaff69af2009-12-09 03:35:49 +000038 Exceptions = getContext().getLangOptions().Exceptions;
Chris Lattner5696e7b2008-06-17 18:05:57 +000039}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000040
Chris Lattner6db1fb82007-06-02 22:49:07 +000041ASTContext &CodeGenFunction::getContext() const {
42 return CGM.getContext();
43}
44
Chris Lattnerd1af2d22007-05-29 23:17:50 +000045
Chris Lattnerac248202007-05-30 00:13:02 +000046llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
Chris Lattner23b7eb62007-06-15 23:05:46 +000047 llvm::BasicBlock *&BB = LabelMap[S];
Chris Lattnerac248202007-05-30 00:13:02 +000048 if (BB) return BB;
Mike Stump11289f42009-09-09 15:08:12 +000049
Chris Lattnerac248202007-05-30 00:13:02 +000050 // Create, but don't insert, the new block.
Daniel Dunbar75283ff2008-11-11 02:29:29 +000051 return BB = createBasicBlock(S->getName());
Chris Lattnerac248202007-05-30 00:13:02 +000052}
53
Daniel Dunbar22a87f92009-02-25 19:24:29 +000054llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
55 llvm::Value *Res = LocalDeclMap[VD];
56 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
57 return Res;
Lauro Ramos Venancio01a72ff2008-02-26 21:41:45 +000058}
Chris Lattnerac248202007-05-30 00:13:02 +000059
Daniel Dunbar22a87f92009-02-25 19:24:29 +000060llvm::Constant *
61CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
62 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson9396a892008-09-11 09:15:33 +000063}
64
Daniel Dunbaree3da872009-02-03 23:03:55 +000065const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
66 return CGM.getTypes().ConvertTypeForMem(T);
67}
68
Chris Lattnerf033c142007-06-22 19:05:19 +000069const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
70 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +000071}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000072
Chris Lattner54fb19e2007-06-22 22:02:34 +000073bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssonb05a3e52009-09-29 02:09:01 +000074 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
75 T->isMemberFunctionPointerType();
Chris Lattner54fb19e2007-06-22 22:02:34 +000076}
77
Daniel Dunbarfd346a32009-01-26 23:27:52 +000078void CodeGenFunction::EmitReturnBlock() {
79 // For cleanliness, we try to avoid emitting the return block for
80 // simple cases.
81 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
82
83 if (CurBB) {
84 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
85
Daniel Dunbarea3060a2009-07-19 08:24:34 +000086 // We have a valid insert point, reuse it if it is empty or there are no
87 // explicit jumps to the return block.
88 if (CurBB->empty() || ReturnBlock->use_empty()) {
89 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbarfd346a32009-01-26 23:27:52 +000090 delete ReturnBlock;
Daniel Dunbarea3060a2009-07-19 08:24:34 +000091 } else
Daniel Dunbarfd346a32009-01-26 23:27:52 +000092 EmitBlock(ReturnBlock);
93 return;
94 }
95
96 // Otherwise, if the return block is the target of a single direct
97 // branch then we can just put the code in that block instead. This
98 // cleans up functions which started with a unified return block.
99 if (ReturnBlock->hasOneUse()) {
Mike Stump11289f42009-09-09 15:08:12 +0000100 llvm::BranchInst *BI =
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000101 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
102 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
103 // Reset insertion point and delete the branch.
104 Builder.SetInsertPoint(BI->getParent());
105 BI->eraseFromParent();
106 delete ReturnBlock;
107 return;
108 }
109 }
110
Mike Stump18bb9282009-05-16 07:57:57 +0000111 // FIXME: We are at an unreachable point, there is no reason to emit the block
112 // unless it has uses. However, we still need a place to put the debug
113 // region.end for now.
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000114
115 EmitBlock(ReturnBlock);
116}
117
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000118void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000119 assert(BreakContinueStack.empty() &&
120 "mismatched push/pop in break/continue stack!");
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000121 assert(BlockScopes.empty() &&
122 "did not remove all blocks from block scope map!");
123 assert(CleanupEntries.empty() &&
124 "mismatched push/pop in cleanup stack!");
Mike Stump11289f42009-09-09 15:08:12 +0000125
126 // Emit function epilog (to return).
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000127 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000128
129 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000130 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000131 DI->setLocation(EndLoc);
132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Daniel Dunbard931a872009-02-02 22:03:45 +0000135 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Mike Stump1d849212009-12-07 23:38:24 +0000136 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000137
Chris Lattner6c4d2552009-10-28 23:59:40 +0000138 // If someone did an indirect goto, emit the indirect goto block at the end of
139 // the function.
140 if (IndirectBranch) {
141 EmitBlock(IndirectBranch->getParent());
142 Builder.ClearInsertionPoint();
143 }
144
Chris Lattnerc48023b2007-12-02 06:32:24 +0000145 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000146 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerc48023b2007-12-02 06:32:24 +0000147 AllocaInsertPt = 0;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000148 Ptr->eraseFromParent();
Chris Lattner6c4d2552009-10-28 23:59:40 +0000149
150 // If someone took the address of a label but never did an indirect goto, we
151 // made a zero entry PHI node, which is illegal, zap it now.
152 if (IndirectBranch) {
153 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
154 if (PN->getNumIncomingValues() == 0) {
155 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
156 PN->eraseFromParent();
157 }
158 }
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000159}
Chris Lattner308f4312007-05-29 23:50:05 +0000160
Anders Carlsson73fcc952009-09-11 00:07:24 +0000161void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000162 llvm::Function *Fn,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000163 const FunctionArgList &Args,
164 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000165 const Decl *D = GD.getDecl();
166
Anders Carlssonf4478e92009-02-09 20:20:56 +0000167 DidCallStackSave = false;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000168 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000169 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000170 CurFn = Fn;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000171 assert(CurFn->isDeclaration() && "Function already has body?");
172
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000173 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000174
Chris Lattner5696e7b2008-06-17 18:05:57 +0000175 // Create a marker to make it easy to insert allocas into the entryblock
176 // later. Don't create this with the builder, because we don't want it
177 // folded.
Owen Anderson41a75022009-08-13 21:57:51 +0000178 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stump1dbb8f72009-09-25 18:11:00 +0000179 AllocaInsertPt = new llvm::BitCastInst(Undef,
180 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner5696e7b2008-06-17 18:05:57 +0000181 EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000182 if (Builder.isNamePreserving())
183 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000184
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000185 ReturnBlock = createBasicBlock("return");
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner5696e7b2008-06-17 18:05:57 +0000187 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000188
Mike Stumpae2559a2009-10-23 01:52:13 +0000189 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
190
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000191 // Emit subprogram debug descriptor.
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000192 // FIXME: The cast here is a huge hack.
Anders Carlsson63784f42009-02-13 08:11:52 +0000193 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar354d2782008-10-18 18:22:23 +0000194 DI->setLocation(StartLoc);
Anders Carlssonfd384d82009-09-11 00:11:35 +0000195 if (isa<FunctionDecl>(D)) {
Mike Stumpae2559a2009-10-23 01:52:13 +0000196 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar354d2782008-10-18 18:22:23 +0000197 } else {
198 // Just use LLVM function name.
Benjamin Kramerba8451b2009-12-08 14:04:35 +0000199 DI->EmitFunctionStart(Fn->getName(), FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000200 }
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000201 }
202
Daniel Dunbard931a872009-02-02 22:03:45 +0000203 // FIXME: Leaked.
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000204 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Eli Friedman4b1942c2009-12-04 02:43:40 +0000205
206 if (RetTy->isVoidType()) {
207 // Void type; nothing to return.
208 ReturnValue = 0;
209 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
210 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
211 // Indirect aggregate return; emit returned value directly into sret slot.
212 // This reduces code size, and is also affects correctness in C++.
213 ReturnValue = CurFn->arg_begin();
214 } else {
215 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
216 }
217
Mike Stump1d849212009-12-07 23:38:24 +0000218 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbard931a872009-02-02 22:03:45 +0000219 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlssonc20879a2008-12-20 21:28:43 +0000221 // If any of the arguments have a variably modified type, make sure to
222 // emit the type size.
223 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
224 i != e; ++i) {
225 QualType Ty = i->second;
226
227 if (Ty->isVariablyModifiedType())
228 EmitVLASize(Ty);
229 }
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000230}
Eli Friedman3d421e12008-08-25 21:31:01 +0000231
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000232static bool NeedsVTTParameter(GlobalDecl GD) {
233 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
234
235 // We don't have any virtual bases, just return early.
236 if (!MD->getParent()->getNumVBases())
237 return false;
238
239 // Check if we have a base constructor.
240 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
241 return true;
242
243 // Check if we have a base destructor.
244 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
245 return true;
246
247 return false;
248}
249
Anders Carlsson73fcc952009-09-11 00:07:24 +0000250void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000251 llvm::Function *Fn) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000252 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
253
Anders Carlsson63784f42009-02-13 08:11:52 +0000254 // Check if we should generate debug info for this function.
Mike Stump3722f582009-08-26 22:31:08 +0000255 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlsson63784f42009-02-13 08:11:52 +0000256 DebugInfo = CGM.getDebugInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000257
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000258 FunctionArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000259
Mike Stumpbee78dd2009-12-04 23:26:17 +0000260 CurGD = GD;
261 OuterTryBlock = 0;
Anders Carlsson468fa632009-04-04 20:47:02 +0000262 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
263 if (MD->isInstance()) {
264 // Create the implicit 'this' decl.
265 // FIXME: I'm not entirely sure I like using a fake decl just for code
266 // generation. Maybe we can come up with a better way?
267 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +0000268 &getContext().Idents.get("this"),
Anders Carlsson468fa632009-04-04 20:47:02 +0000269 MD->getThisType(getContext()));
270 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000271
272 // Check if we need a VTT parameter as well.
273 if (NeedsVTTParameter(GD)) {
274 // FIXME: The comment about using a fake decl above applies here too.
275 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
276 CXXVTTDecl =
277 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
278 &getContext().Idents.get("vtt"), T);
279 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
280 }
Anders Carlsson468fa632009-04-04 20:47:02 +0000281 }
282 }
Mike Stump11289f42009-09-09 15:08:12 +0000283
Eli Friedman3d421e12008-08-25 21:31:01 +0000284 if (FD->getNumParams()) {
John McCall9dd450b2009-09-21 23:43:11 +0000285 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedman3d421e12008-08-25 21:31:01 +0000286 assert(FProto && "Function def must have prototype!");
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000287
288 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump11289f42009-09-09 15:08:12 +0000289 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000290 FProto->getArgType(i)));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000291 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000292
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000293 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000294 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson438cf922009-11-06 02:55:43 +0000295
296 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonddf57d32009-09-14 05:32:02 +0000297 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson438cf922009-11-06 02:55:43 +0000298 EmitStmt(S);
Anders Carlsson421a5c92009-11-06 04:19:02 +0000299
300 // If any of the member initializers are temporaries bound to references
301 // make sure to emit their destructors.
302 EmitCleanupBlocks(0);
303
Anders Carlsson438cf922009-11-06 02:55:43 +0000304 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
305 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
306 PushCleanupBlock(DtorEpilogue);
307
308 EmitStmt(S);
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000309
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000310 CleanupBlockInfo Info = PopCleanupBlock();
311
312 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
313 EmitBlock(DtorEpilogue);
Anders Carlssonddf57d32009-09-14 05:32:02 +0000314 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000315
316 if (Info.SwitchBlock)
317 EmitBlock(Info.SwitchBlock);
318 if (Info.EndBlock)
319 EmitBlock(Info.EndBlock);
Anders Carlsson438cf922009-11-06 02:55:43 +0000320 } else {
321 // Just a regular function, emit its body.
322 EmitStmt(S);
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000323 }
Anders Carlsson438cf922009-11-06 02:55:43 +0000324
Sebastian Redla7b98a72009-04-26 20:35:05 +0000325 FinishFunction(S->getRBracLoc());
Douglas Gregor369acf92009-10-01 20:44:19 +0000326 } else if (FD->isImplicit()) {
327 const CXXRecordDecl *ClassDecl =
328 cast<CXXRecordDecl>(FD->getDeclContext());
329 (void) ClassDecl;
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000330 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor369acf92009-10-01 20:44:19 +0000331 // FIXME: For C++0x, we want to look for implicit *definitions* of
332 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000333 if (CD->isCopyConstructor(getContext())) {
334 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000335 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000336 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000337 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000338 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000339 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000340 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000341 } else {
342 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000343 }
Douglas Gregor369acf92009-10-01 20:44:19 +0000344 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
345 assert(!ClassDecl->hasUserDeclaredDestructor() &&
346 "Cannot synthesize a non-implicit destructor");
347 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
348 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
349 assert(MD->isCopyAssignment() &&
350 !ClassDecl->hasUserDeclaredCopyAssignment() &&
351 "Cannot synthesize a method that is not an implicit-defined "
352 "copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000353 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000354 } else {
355 assert(false && "Cannot synthesize unknown implicit function");
356 }
Mike Stumpbee78dd2009-12-04 23:26:17 +0000357 } else if (const Stmt *S = FD->getBody()) {
358 if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) {
359 OuterTryBlock = TS;
360 StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc());
361 EmitStmt(TS);
362 FinishFunction(TS->getEndLoc());
363 }
Anders Carlsson73fcc952009-09-11 00:07:24 +0000364 }
Mike Stump11289f42009-09-09 15:08:12 +0000365
Anders Carlsson468fa632009-04-04 20:47:02 +0000366 // Destroy the 'this' declaration.
367 if (CXXThisDecl)
368 CXXThisDecl->Destroy(getContext());
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000369
370 // Destroy the VTT declaration.
371 if (CXXVTTDecl)
372 CXXVTTDecl->Destroy(getContext());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000373}
374
Chris Lattner5b1964b2008-11-11 07:41:27 +0000375/// ContainsLabel - Return true if the statement contains a label in it. If
376/// this statement is not executed normally, it not containing a label means
377/// that we can just remove the code.
378bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
379 // Null statement, not a label!
380 if (S == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattner5b1964b2008-11-11 07:41:27 +0000382 // If this is a label, we have to emit the code, consider something like:
383 // if (0) { ... foo: bar(); } goto foo;
384 if (isa<LabelStmt>(S))
385 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000386
Chris Lattner5b1964b2008-11-11 07:41:27 +0000387 // If this is a case/default statement, and we haven't seen a switch, we have
388 // to emit the code.
389 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
390 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattner5b1964b2008-11-11 07:41:27 +0000392 // If this is a switch statement, we want to ignore cases below it.
393 if (isa<SwitchStmt>(S))
394 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Chris Lattner5b1964b2008-11-11 07:41:27 +0000396 // Scan subexpressions for verboten labels.
397 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
398 I != E; ++I)
399 if (ContainsLabel(*I, IgnoreCaseStmts))
400 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattner5b1964b2008-11-11 07:41:27 +0000402 return false;
403}
404
Chris Lattnercd439292008-11-12 08:04:58 +0000405
406/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
407/// a constant, or if it does but contains a label, return 0. If it constant
408/// folds to 'true' and does not contain a label, return 1, if it constant folds
409/// to 'false' and does not contain a label, return -1.
410int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000411 // FIXME: Rename and handle conversion of other evaluatable things
412 // to bool.
Anders Carlsson86286452008-12-01 02:46:24 +0000413 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +0000414 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson86286452008-12-01 02:46:24 +0000415 Result.HasSideEffects)
Anders Carlsson4046e652008-11-22 22:32:07 +0000416 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattnercd439292008-11-12 08:04:58 +0000418 if (CodeGenFunction::ContainsLabel(Cond))
419 return 0; // Contains a label.
Mike Stump11289f42009-09-09 15:08:12 +0000420
Anders Carlsson86286452008-12-01 02:46:24 +0000421 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattnercd439292008-11-12 08:04:58 +0000422}
423
424
425/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
426/// statement) to the specified blocks. Based on the condition, this might try
427/// to simplify the codegen of the conditional based on the branch.
428///
429void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
430 llvm::BasicBlock *TrueBlock,
431 llvm::BasicBlock *FalseBlock) {
432 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
433 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattnercd439292008-11-12 08:04:58 +0000435 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
436 // Handle X && Y in a condition.
437 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
438 // If we have "1 && X", simplify the code. "0 && X" would have constant
439 // folded if the case was simple enough.
440 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
441 // br(1 && X) -> br(X).
442 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
443 }
Mike Stump11289f42009-09-09 15:08:12 +0000444
Chris Lattnercd439292008-11-12 08:04:58 +0000445 // If we have "X && 1", simplify the code to use an uncond branch.
446 // "X && 0" would have been constant folded to 0.
447 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
448 // br(X && 1) -> br(X).
449 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
450 }
Mike Stump11289f42009-09-09 15:08:12 +0000451
Chris Lattnercd439292008-11-12 08:04:58 +0000452 // Emit the LHS as a conditional. If the LHS conditional is false, we
453 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000454 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattnercd439292008-11-12 08:04:58 +0000455 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
456 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattnercd439292008-11-12 08:04:58 +0000458 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
459 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 Stump11289f42009-09-09 15:08:12 +0000467
Chris Lattnercd439292008-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 Stump11289f42009-09-09 15:08:12 +0000474
Chris Lattnercd439292008-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 Dunbara612e792008-11-13 01:38:36 +0000477 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattnercd439292008-11-12 08:04:58 +0000478 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
479 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattnercd439292008-11-12 08:04:58 +0000481 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
482 return;
483 }
Chris Lattnerd9537732008-11-12 08:13:36 +0000484 }
Mike Stump11289f42009-09-09 15:08:12 +0000485
Chris Lattnerd9537732008-11-12 08:13:36 +0000486 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
487 // br(!x, t, f) -> br(x, f, t)
488 if (CondUOp->getOpcode() == UnaryOperator::LNot)
489 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattnercd439292008-11-12 08:04:58 +0000490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +0000492 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
493 // Handle ?: operator.
494
495 // Just ignore GNU ?: extension.
496 if (CondOp->getLHS()) {
497 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
498 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
499 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
500 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
501 EmitBlock(LHSBlock);
502 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
503 EmitBlock(RHSBlock);
504 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
505 return;
506 }
507 }
508
Chris Lattnercd439292008-11-12 08:04:58 +0000509 // Emit the code with the fully general case.
510 llvm::Value *CondV = EvaluateExprAsBool(Cond);
511 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
512}
513
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000514/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +0000515/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000516void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
517 bool OmitOnError) {
518 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerfc944342007-12-02 01:43:38 +0000519}
520
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000521void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattnerdd7eaad2009-10-13 06:02:42 +0000522 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000523 if (DestPtr->getType() != BP)
524 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
525
526 // Get size and alignment info for this aggregate.
527 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
528
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000529 // Don't bother emitting a zero-byte memset.
530 if (TypeInfo.first == 0)
531 return;
Mike Stump11289f42009-09-09 15:08:12 +0000532
Anders Carlsson2e744e82008-08-30 19:51:14 +0000533 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +0000534 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000535 LLVMPointerWidth);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000536
537 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson41a75022009-08-13 21:57:51 +0000538 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000539 // TypeInfo.first describes size in bits.
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000540 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump11289f42009-09-09 15:08:12 +0000541 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000542 TypeInfo.second/8));
543}
544
Chris Lattner6c4d2552009-10-28 23:59:40 +0000545llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
546 // Make sure that there is a block for the indirect goto.
547 if (IndirectBranch == 0)
548 GetIndirectGotoBlock();
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000549
Chris Lattner6c4d2552009-10-28 23:59:40 +0000550 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000551
Chris Lattner6c4d2552009-10-28 23:59:40 +0000552 // Make sure the indirect branch includes all of the address-taken blocks.
553 IndirectBranch->addDestination(BB);
554 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000555}
556
557llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000558 // If we already made the indirect branch for indirect goto, return its block.
559 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000560
Chris Lattner6c4d2552009-10-28 23:59:40 +0000561 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000562
Chris Lattner6c4d2552009-10-28 23:59:40 +0000563 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattnera0c0d882009-10-28 20:36:47 +0000564
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000565 // Create the PHI node that indirect gotos will add entries to.
Chris Lattner6c4d2552009-10-28 23:59:40 +0000566 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000567
Chris Lattner6c4d2552009-10-28 23:59:40 +0000568 // Create the indirect branch instruction.
569 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
570 return IndirectBranch->getParent();
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000571}
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000572
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000573llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000574 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000575
Anders Carlssone388a5b2008-12-20 20:27:15 +0000576 assert(SizeEntry && "Did not emit size for type");
577 return SizeEntry;
578}
Anders Carlssonccbe9202008-12-12 07:19:02 +0000579
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000580llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson8a01b792008-12-20 20:46:34 +0000581 assert(Ty->isVariablyModifiedType() &&
582 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +0000583
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000584 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000585
Anders Carlsson8a01b792008-12-20 20:46:34 +0000586 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000587 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000588
Anders Carlsson5d985f52008-12-20 21:51:53 +0000589 if (!SizeEntry) {
Anders Carlsson31f86492009-02-05 19:43:10 +0000590 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000591
Chris Lattner8dc76262009-08-15 00:03:43 +0000592 // Get the element size;
593 QualType ElemTy = VAT->getElementType();
594 llvm::Value *ElemSize;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000595 if (ElemTy->isVariableArrayType())
596 ElemSize = EmitVLASize(ElemTy);
Chris Lattner8dc76262009-08-15 00:03:43 +0000597 else
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000598 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlsson5d985f52008-12-20 21:51:53 +0000599 getContext().getTypeSize(ElemTy) / 8);
Mike Stump11289f42009-09-09 15:08:12 +0000600
Anders Carlsson5d985f52008-12-20 21:51:53 +0000601 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson31f86492009-02-05 19:43:10 +0000602 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000603
Anders Carlsson5d985f52008-12-20 21:51:53 +0000604 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson8a01b792008-12-20 20:46:34 +0000605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Anders Carlsson8a01b792008-12-20 20:46:34 +0000607 return SizeEntry;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattner8dc76262009-08-15 00:03:43 +0000610 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
611 EmitVLASize(AT->getElementType());
612 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000613 }
614
Chris Lattner8dc76262009-08-15 00:03:43 +0000615 const PointerType *PT = Ty->getAs<PointerType>();
616 assert(PT && "unknown VM type!");
617 EmitVLASize(PT->getPointeeType());
Anders Carlsson8a01b792008-12-20 20:46:34 +0000618 return 0;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000619}
Eli Friedmanddea0ad2009-01-20 17:46:04 +0000620
621llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
622 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
623 return EmitScalarExpr(E);
624 }
625 return EmitLValue(E).getAddress();
626}
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000627
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000628void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump33270212009-12-02 07:41:41 +0000629 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpaff69af2009-12-09 03:35:49 +0000630 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump33270212009-12-02 07:41:41 +0000631 bool EHOnly) {
632 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpaff69af2009-12-09 03:35:49 +0000633 PreviousInvokeDest, EHOnly));
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000634}
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000635
Mike Stump11289f42009-09-09 15:08:12 +0000636void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
637 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000638 "Cleanup stack mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000639
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000640 while (CleanupEntries.size() > OldCleanupStackSize)
641 EmitCleanupBlock();
642}
643
Mike Stump11289f42009-09-09 15:08:12 +0000644CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000645 CleanupEntry &CE = CleanupEntries.back();
Mike Stump11289f42009-09-09 15:08:12 +0000646
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000647 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Anders Carlsson66c384a2009-02-08 07:46:24 +0000649 std::vector<llvm::BasicBlock *> Blocks;
650 std::swap(Blocks, CE.Blocks);
Mike Stump11289f42009-09-09 15:08:12 +0000651
Anders Carlsson66c384a2009-02-08 07:46:24 +0000652 std::vector<llvm::BranchInst *> BranchFixups;
653 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump11289f42009-09-09 15:08:12 +0000654
Mike Stump33270212009-12-02 07:41:41 +0000655 bool EHOnly = CE.EHOnly;
656
Mike Stumpaff69af2009-12-09 03:35:49 +0000657 setInvokeDest(CE.PreviousInvokeDest);
658
Anders Carlsson66c384a2009-02-08 07:46:24 +0000659 CleanupEntries.pop_back();
660
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000661 // Check if any branch fixups pointed to the scope we just popped. If so,
662 // we can remove them.
663 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
664 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
665 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000666
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000667 if (I == BlockScopes.end())
668 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000669
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000670 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump11289f42009-09-09 15:08:12 +0000671
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000672 if (I->second == CleanupEntries.size()) {
673 // We don't need to do this branch fixup.
674 BranchFixups[i] = BranchFixups.back();
675 BranchFixups.pop_back();
676 i--;
677 e--;
678 continue;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000679 }
680 }
Mike Stump11289f42009-09-09 15:08:12 +0000681
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000682 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlsson66c384a2009-02-08 07:46:24 +0000683 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000684 if (!BranchFixups.empty()) {
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000685 if (!SwitchBlock)
686 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlsson66c384a2009-02-08 07:46:24 +0000687 EndBlock = createBasicBlock("cleanup.end");
Mike Stump11289f42009-09-09 15:08:12 +0000688
Anders Carlsson66c384a2009-02-08 07:46:24 +0000689 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000690
Anders Carlsson66c384a2009-02-08 07:46:24 +0000691 Builder.SetInsertPoint(SwitchBlock);
692
Mike Stump33270212009-12-02 07:41:41 +0000693 llvm::Value *DestCodePtr
694 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
695 "cleanup.dst");
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000696 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000697
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000698 // Create a switch instruction to determine where to jump next.
Mike Stump11289f42009-09-09 15:08:12 +0000699 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000700 BranchFixups.size());
Anders Carlsson66c384a2009-02-08 07:46:24 +0000701
Anders Carlsson76180ea2009-02-08 22:13:37 +0000702 // Restore the current basic block (if any)
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000703 if (CurBB) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000704 Builder.SetInsertPoint(CurBB);
Mike Stump11289f42009-09-09 15:08:12 +0000705
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000706 // If we had a current basic block, we also need to emit an instruction
707 // to initialize the cleanup destination.
Owen Anderson41a75022009-08-13 21:57:51 +0000708 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000709 DestCodePtr);
710 } else
Anders Carlsson76180ea2009-02-08 22:13:37 +0000711 Builder.ClearInsertionPoint();
Anders Carlsson66c384a2009-02-08 07:46:24 +0000712
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000713 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
714 llvm::BranchInst *BI = BranchFixups[i];
715 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump11289f42009-09-09 15:08:12 +0000716
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000717 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000718 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000719
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000720 if (CleanupEntries.empty()) {
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000721 llvm::ConstantInt *ID;
Mike Stump11289f42009-09-09 15:08:12 +0000722
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000723 // Check if we already have a destination for this block.
724 if (Dest == SI->getDefaultDest())
Owen Anderson41a75022009-08-13 21:57:51 +0000725 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000726 else {
727 ID = SI->findCaseDest(Dest);
728 if (!ID) {
729 // No code found, get a new unique one by using the number of
730 // switch successors.
Mike Stump11289f42009-09-09 15:08:12 +0000731 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000732 SI->getNumSuccessors());
733 SI->addCase(ID, Dest);
734 }
735 }
Mike Stump11289f42009-09-09 15:08:12 +0000736
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000737 // Store the jump destination before the branch instruction.
738 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000739 } else {
740 // We need to jump through another cleanup block. Create a pad block
Mike Stump33270212009-12-02 07:41:41 +0000741 // with a branch instruction that jumps to the final destination and add
742 // it as a branch fixup to the current cleanup scope.
Mike Stump11289f42009-09-09 15:08:12 +0000743
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000744 // Create the pad block.
745 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000746
747 // Create a unique case ID.
Mike Stump33270212009-12-02 07:41:41 +0000748 llvm::ConstantInt *ID
749 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
750 SI->getNumSuccessors());
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000751
752 // Store the jump destination before the branch instruction.
753 new llvm::StoreInst(ID, DestCodePtr, BI);
754
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000755 // Add it as the destination.
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000756 SI->addCase(ID, CleanupPad);
Mike Stump11289f42009-09-09 15:08:12 +0000757
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000758 // Create the branch to the final destination.
759 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
760 CleanupPad->getInstList().push_back(BI);
Mike Stump11289f42009-09-09 15:08:12 +0000761
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000762 // And add it as a branch fixup.
763 CleanupEntries.back().BranchFixups.push_back(BI);
764 }
765 }
766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000768 // Remove all blocks from the block scope map.
769 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
770 assert(BlockScopes.count(Blocks[i]) &&
771 "Did not find block in scope map!");
Mike Stump11289f42009-09-09 15:08:12 +0000772
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000773 BlockScopes.erase(Blocks[i]);
774 }
Mike Stump11289f42009-09-09 15:08:12 +0000775
Mike Stump33270212009-12-02 07:41:41 +0000776 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000777}
778
Mike Stump11289f42009-09-09 15:08:12 +0000779void CodeGenFunction::EmitCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000780 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000781
Mike Stump33270212009-12-02 07:41:41 +0000782 if (Info.EHOnly) {
783 // FIXME: Add this to the exceptional edge
784 if (Info.CleanupBlock->getNumUses() == 0)
785 delete Info.CleanupBlock;
786 return;
787 }
788
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000789 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000790 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000791 Info.CleanupBlock->getNumUses() == 0) {
792 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
793 delete Info.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000794 } else
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000795 EmitBlock(Info.CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000796
Anders Carlsson66c384a2009-02-08 07:46:24 +0000797 if (Info.SwitchBlock)
798 EmitBlock(Info.SwitchBlock);
799 if (Info.EndBlock)
800 EmitBlock(Info.EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000801}
802
Mike Stump11289f42009-09-09 15:08:12 +0000803void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
804 assert(!CleanupEntries.empty() &&
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000805 "Trying to add branch fixup without cleanup block!");
Mike Stump11289f42009-09-09 15:08:12 +0000806
Mike Stump18bb9282009-05-16 07:57:57 +0000807 // FIXME: We could be more clever here and check if there's already a branch
808 // fixup for this destination and recycle it.
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000809 CleanupEntries.back().BranchFixups.push_back(BI);
810}
811
Mike Stump11289f42009-09-09 15:08:12 +0000812void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000813 if (!HaveInsertPoint())
814 return;
Mike Stump11289f42009-09-09 15:08:12 +0000815
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000816 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Anders Carlsson76180ea2009-02-08 22:13:37 +0000818 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000819
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000820 // The stack is empty, no need to do any cleanup.
821 if (CleanupEntries.empty())
822 return;
Mike Stump11289f42009-09-09 15:08:12 +0000823
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000824 if (!Dest->getParent()) {
825 // We are trying to branch to a block that hasn't been inserted yet.
826 AddBranchFixup(BI);
827 return;
828 }
Mike Stump11289f42009-09-09 15:08:12 +0000829
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000830 BlockScopeMap::iterator I = BlockScopes.find(Dest);
831 if (I == BlockScopes.end()) {
832 // We are trying to jump to a block that is outside of any cleanup scope.
833 AddBranchFixup(BI);
834 return;
835 }
Mike Stump11289f42009-09-09 15:08:12 +0000836
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000837 assert(I->second < CleanupEntries.size() &&
838 "Trying to branch into cleanup region");
Mike Stump11289f42009-09-09 15:08:12 +0000839
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000840 if (I->second == CleanupEntries.size() - 1) {
841 // We have a branch to a block in the same scope.
842 return;
843 }
Mike Stump11289f42009-09-09 15:08:12 +0000844
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000845 AddBranchFixup(BI);
846}