blob: 51d084e1d301860663d02c4396781e3afe205298 [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"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000017#include "CGDebugInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "CGException.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000020#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000023#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000024#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000025#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000026#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000027#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29using namespace CodeGen;
30
Mike Stump1eb44332009-09-09 15:08:12 +000031CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000032 : BlockFunction(cgm, *this, Builder), CGM(cgm),
33 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000034 Builder(cgm.getModule().getContext()),
John McCallff8e1152010-07-23 21:56:41 +000035 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
John McCallf1549f62010-07-06 01:34:17 +000036 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
John McCallff8e1152010-07-23 21:56:41 +000037 SwitchInsn(0), CaseRangeBlock(0),
John McCallf1549f62010-07-06 01:34:17 +000038 DidCallStackSave(false), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000039 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCallf1549f62010-07-06 01:34:17 +000040 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
Chris Lattner83252dc2010-07-20 21:07:09 +000041 TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000042
43 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000044 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000045 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
46 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
47 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
48 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
49
Mike Stumpd88ea562009-12-09 03:35:49 +000050 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000051 CatchUndefined = getContext().getLangOptions().CatchUndefined;
John McCall4c40d982010-08-31 07:33:07 +000052 CGM.getCXXABI().getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000053}
Reid Spencer5f016e22007-07-11 17:01:13 +000054
55ASTContext &CodeGenFunction::getContext() const {
56 return CGM.getContext();
57}
58
59
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000060const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61 return CGM.getTypes().ConvertTypeForMem(T);
62}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65 return CGM.getTypes().ConvertType(T);
66}
67
68bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000069 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
John McCalld608cdb2010-08-22 10:59:02 +000070 T->isObjCObjectType();
Reid Spencer5f016e22007-07-11 17:01:13 +000071}
72
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000073void CodeGenFunction::EmitReturnBlock() {
74 // For cleanliness, we try to avoid emitting the return block for
75 // simple cases.
76 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
77
78 if (CurBB) {
79 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
80
Daniel Dunbar96e18b02009-07-19 08:24:34 +000081 // We have a valid insert point, reuse it if it is empty or there are no
82 // explicit jumps to the return block.
John McCallff8e1152010-07-23 21:56:41 +000083 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
84 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
85 delete ReturnBlock.getBlock();
Daniel Dunbar96e18b02009-07-19 08:24:34 +000086 } else
John McCallff8e1152010-07-23 21:56:41 +000087 EmitBlock(ReturnBlock.getBlock());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000088 return;
89 }
90
91 // Otherwise, if the return block is the target of a single direct
92 // branch then we can just put the code in that block instead. This
93 // cleans up functions which started with a unified return block.
John McCallff8e1152010-07-23 21:56:41 +000094 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000095 llvm::BranchInst *BI =
John McCallff8e1152010-07-23 21:56:41 +000096 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
John McCallf1549f62010-07-06 01:34:17 +000097 if (BI && BI->isUnconditional() &&
John McCallff8e1152010-07-23 21:56:41 +000098 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000099 // Reset insertion point and delete the branch.
100 Builder.SetInsertPoint(BI->getParent());
101 BI->eraseFromParent();
John McCallff8e1152010-07-23 21:56:41 +0000102 delete ReturnBlock.getBlock();
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000103 return;
104 }
105 }
106
Mike Stumpf5408fe2009-05-16 07:57:57 +0000107 // FIXME: We are at an unreachable point, there is no reason to emit the block
108 // unless it has uses. However, we still need a place to put the debug
109 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000110
John McCallff8e1152010-07-23 21:56:41 +0000111 EmitBlock(ReturnBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000112}
113
114static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
115 if (!BB) return;
116 if (!BB->use_empty())
117 return CGF.CurFn->getBasicBlockList().push_back(BB);
118 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000119}
120
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000121void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000122 assert(BreakContinueStack.empty() &&
123 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000124
125 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000126 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000127
Chris Lattner7255a2d2010-06-22 00:03:40 +0000128 EmitFunctionInstrumentation("__cyg_profile_func_exit");
129
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000130 // 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);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000133 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000134 }
135
Chris Lattner35b21b82010-06-27 01:06:27 +0000136 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000137 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000138
John McCallf1549f62010-07-06 01:34:17 +0000139 assert(EHStack.empty() &&
140 "did not remove all scopes from cleanup stack!");
141
Chris Lattnerd9becd12009-10-28 23:59:40 +0000142 // If someone did an indirect goto, emit the indirect goto block at the end of
143 // the function.
144 if (IndirectBranch) {
145 EmitBlock(IndirectBranch->getParent());
146 Builder.ClearInsertionPoint();
147 }
148
Chris Lattner5a2fa142007-12-02 06:32:24 +0000149 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000150 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000151 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000152 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000153
154 // If someone took the address of a label but never did an indirect goto, we
155 // made a zero entry PHI node, which is illegal, zap it now.
156 if (IndirectBranch) {
157 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
158 if (PN->getNumIncomingValues() == 0) {
159 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
160 PN->eraseFromParent();
161 }
162 }
John McCallf1549f62010-07-06 01:34:17 +0000163
John McCallff8e1152010-07-23 21:56:41 +0000164 EmitIfUsed(*this, RethrowBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000165 EmitIfUsed(*this, TerminateLandingPad);
166 EmitIfUsed(*this, TerminateHandler);
167 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000168
169 if (CGM.getCodeGenOpts().EmitDeclMetadata)
170 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000171}
172
Chris Lattner7255a2d2010-06-22 00:03:40 +0000173/// ShouldInstrumentFunction - Return true if the current function should be
174/// instrumented with __cyg_profile_func_* calls
175bool CodeGenFunction::ShouldInstrumentFunction() {
176 if (!CGM.getCodeGenOpts().InstrumentFunctions)
177 return false;
178 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
179 return false;
180 return true;
181}
182
183/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
184/// instrumentation function with the current function and the call site, if
185/// function instrumentation is enabled.
186void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
187 if (!ShouldInstrumentFunction())
188 return;
189
Chris Lattner8dab6572010-06-23 05:21:28 +0000190 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000191 const llvm::FunctionType *FunctionTy;
192 std::vector<const llvm::Type*> ProfileFuncArgs;
193
Chris Lattner8dab6572010-06-23 05:21:28 +0000194 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
195 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
196 ProfileFuncArgs.push_back(PointerTy);
197 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000198 FunctionTy = llvm::FunctionType::get(
199 llvm::Type::getVoidTy(VMContext),
200 ProfileFuncArgs, false);
201
202 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
203 llvm::CallInst *CallSite = Builder.CreateCall(
204 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000205 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000206 "callsite");
207
Chris Lattner8dab6572010-06-23 05:21:28 +0000208 Builder.CreateCall2(F,
209 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
210 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000211}
212
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000213void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000214 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000215 const FunctionArgList &Args,
216 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000217 const Decl *D = GD.getDecl();
218
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000219 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000220 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000221 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000222 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000223 assert(CurFn->isDeclaration() && "Function already has body?");
224
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000225 // Pass inline keyword to optimizer if it appears explicitly on any
226 // declaration.
227 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
228 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
229 RE = FD->redecls_end(); RI != RE; ++RI)
230 if (RI->isInlineSpecified()) {
231 Fn->addFnAttr(llvm::Attribute::InlineHint);
232 break;
233 }
234
Daniel Dunbar55e87422008-11-11 02:29:29 +0000235 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000236
Chris Lattner41110242008-06-17 18:05:57 +0000237 // Create a marker to make it easy to insert allocas into the entryblock
238 // later. Don't create this with the builder, because we don't want it
239 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000240 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
241 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000242 if (Builder.isNamePreserving())
243 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
John McCallf1549f62010-07-06 01:34:17 +0000245 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattner41110242008-06-17 18:05:57 +0000247 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Douglas Gregorce056bc2010-02-21 22:15:06 +0000249 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
250 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000251 /*FIXME?*/
252 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000253
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000254 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000255 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000256 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000257 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000258 }
259
Chris Lattner7255a2d2010-06-22 00:03:40 +0000260 EmitFunctionInstrumentation("__cyg_profile_func_enter");
261
Daniel Dunbar88b53962009-02-02 22:03:45 +0000262 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000263 // CC info is ignored, hopefully?
264 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000265 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000266
267 if (RetTy->isVoidType()) {
268 // Void type; nothing to return.
269 ReturnValue = 0;
270 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
271 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
272 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000273 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000274 ReturnValue = CurFn->arg_begin();
275 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000276 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000277 }
278
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000279 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000280 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
John McCall4c40d982010-08-31 07:33:07 +0000282 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
283 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
John McCall25049412010-02-16 22:04:33 +0000284
Anders Carlsson751358f2008-12-20 21:28:43 +0000285 // If any of the arguments have a variably modified type, make sure to
286 // emit the type size.
287 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
288 i != e; ++i) {
289 QualType Ty = i->second;
290
291 if (Ty->isVariablyModifiedType())
292 EmitVLASize(Ty);
293 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000294}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000295
John McCall9fc6a772010-02-19 09:25:03 +0000296void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
297 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000298 assert(FD->getBody());
299 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000300}
301
John McCall39dad532010-08-03 22:46:07 +0000302/// Tries to mark the given function nounwind based on the
303/// non-existence of any throwing calls within it. We believe this is
304/// lightweight enough to do at -O0.
305static void TryMarkNoThrow(llvm::Function *F) {
John McCallb3a29f12010-08-11 22:38:33 +0000306 // LLVM treats 'nounwind' on a function as part of the type, so we
307 // can't do this on functions that can be overwritten.
308 if (F->mayBeOverridden()) return;
309
John McCall39dad532010-08-03 22:46:07 +0000310 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
311 for (llvm::BasicBlock::iterator
312 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
313 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
314 if (!Call->doesNotThrow())
315 return;
316 F->setDoesNotThrow(true);
317}
318
Anders Carlssonc997d422010-01-02 01:01:18 +0000319void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000320 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
321
Anders Carlssone896d982009-02-13 08:11:52 +0000322 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000323 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000324 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Daniel Dunbar7c086512008-09-09 23:14:03 +0000326 FunctionArgList Args;
John McCall4c40d982010-08-31 07:33:07 +0000327 QualType ResTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000329 CurGD = GD;
John McCall4c40d982010-08-31 07:33:07 +0000330 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
331 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000333 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000334 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000335 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000336
337 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000338 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000339 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000340 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000341
John McCalla355e072010-02-18 03:17:58 +0000342 SourceRange BodyRange;
343 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000344
John McCalla355e072010-02-18 03:17:58 +0000345 // Emit the standard function prologue.
John McCall4c40d982010-08-31 07:33:07 +0000346 StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000347
John McCalla355e072010-02-18 03:17:58 +0000348 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000349 if (isa<CXXDestructorDecl>(FD))
350 EmitDestructorBody(Args);
351 else if (isa<CXXConstructorDecl>(FD))
352 EmitConstructorBody(Args);
353 else
354 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000355
John McCalla355e072010-02-18 03:17:58 +0000356 // Emit the standard function epilogue.
357 FinishFunction(BodyRange.getEnd());
John McCall39dad532010-08-03 22:46:07 +0000358
359 // If we haven't marked the function nothrow through other means, do
360 // a quick pass now to see if we can.
361 if (!CurFn->doesNotThrow())
362 TryMarkNoThrow(CurFn);
Chris Lattner41110242008-06-17 18:05:57 +0000363}
364
Chris Lattner0946ccd2008-11-11 07:41:27 +0000365/// ContainsLabel - Return true if the statement contains a label in it. If
366/// this statement is not executed normally, it not containing a label means
367/// that we can just remove the code.
368bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
369 // Null statement, not a label!
370 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner0946ccd2008-11-11 07:41:27 +0000372 // If this is a label, we have to emit the code, consider something like:
373 // if (0) { ... foo: bar(); } goto foo;
374 if (isa<LabelStmt>(S))
375 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0946ccd2008-11-11 07:41:27 +0000377 // If this is a case/default statement, and we haven't seen a switch, we have
378 // to emit the code.
379 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
380 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner0946ccd2008-11-11 07:41:27 +0000382 // If this is a switch statement, we want to ignore cases below it.
383 if (isa<SwitchStmt>(S))
384 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattner0946ccd2008-11-11 07:41:27 +0000386 // Scan subexpressions for verboten labels.
387 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
388 I != E; ++I)
389 if (ContainsLabel(*I, IgnoreCaseStmts))
390 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner0946ccd2008-11-11 07:41:27 +0000392 return false;
393}
394
Chris Lattner31a09842008-11-12 08:04:58 +0000395
396/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
397/// a constant, or if it does but contains a label, return 0. If it constant
398/// folds to 'true' and does not contain a label, return 1, if it constant folds
399/// to 'false' and does not contain a label, return -1.
400int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000401 // FIXME: Rename and handle conversion of other evaluatable things
402 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000403 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000404 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000405 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000406 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner31a09842008-11-12 08:04:58 +0000408 if (CodeGenFunction::ContainsLabel(Cond))
409 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Anders Carlsson64712f12008-12-01 02:46:24 +0000411 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000412}
413
414
415/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
416/// statement) to the specified blocks. Based on the condition, this might try
417/// to simplify the codegen of the conditional based on the branch.
418///
419void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
420 llvm::BasicBlock *TrueBlock,
421 llvm::BasicBlock *FalseBlock) {
422 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
423 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner31a09842008-11-12 08:04:58 +0000425 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
426 // Handle X && Y in a condition.
John McCall2de56d12010-08-25 11:45:40 +0000427 if (CondBOp->getOpcode() == BO_LAnd) {
Chris Lattner31a09842008-11-12 08:04:58 +0000428 // If we have "1 && X", simplify the code. "0 && X" would have constant
429 // folded if the case was simple enough.
430 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
431 // br(1 && X) -> br(X).
432 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner31a09842008-11-12 08:04:58 +0000435 // If we have "X && 1", simplify the code to use an uncond branch.
436 // "X && 0" would have been constant folded to 0.
437 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
438 // br(X && 1) -> br(X).
439 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner31a09842008-11-12 08:04:58 +0000442 // Emit the LHS as a conditional. If the LHS conditional is false, we
443 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000444 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000445 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
446 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Anders Carlsson08e9e452010-01-24 00:20:05 +0000448 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000449 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000450 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000451 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000452
Chris Lattner31a09842008-11-12 08:04:58 +0000453 return;
John McCall2de56d12010-08-25 11:45:40 +0000454 } else if (CondBOp->getOpcode() == BO_LOr) {
Chris Lattner31a09842008-11-12 08:04:58 +0000455 // If we have "0 || X", simplify the code. "1 || X" would have constant
456 // folded if the case was simple enough.
457 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
458 // br(0 || X) -> br(X).
459 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner31a09842008-11-12 08:04:58 +0000462 // If we have "X || 0", simplify the code to use an uncond branch.
463 // "X || 1" would have been constant folded to 1.
464 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
465 // br(X || 0) -> br(X).
466 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chris Lattner31a09842008-11-12 08:04:58 +0000469 // Emit the LHS as a conditional. If the LHS conditional is true, we
470 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000471 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000472 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
473 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Anders Carlsson08e9e452010-01-24 00:20:05 +0000475 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000476 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000477 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000478 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000479
Chris Lattner31a09842008-11-12 08:04:58 +0000480 return;
481 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Chris Lattner552f4c42008-11-12 08:13:36 +0000484 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
485 // br(!x, t, f) -> br(x, f, t)
John McCall2de56d12010-08-25 11:45:40 +0000486 if (CondUOp->getOpcode() == UO_LNot)
Chris Lattner552f4c42008-11-12 08:13:36 +0000487 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Daniel Dunbar09b14892008-11-12 10:30:32 +0000490 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
491 // Handle ?: operator.
492
493 // Just ignore GNU ?: extension.
494 if (CondOp->getLHS()) {
495 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
496 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
497 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
498 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
499 EmitBlock(LHSBlock);
500 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
501 EmitBlock(RHSBlock);
502 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
503 return;
504 }
505 }
506
Chris Lattner31a09842008-11-12 08:04:58 +0000507 // Emit the code with the fully general case.
508 llvm::Value *CondV = EvaluateExprAsBool(Cond);
509 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
510}
511
Daniel Dunbar488e9932008-08-16 00:56:44 +0000512/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000513/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000514void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
515 bool OmitOnError) {
516 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000517}
518
Anders Carlsson1884eb02010-05-22 17:35:42 +0000519void
520CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000521 // Ignore empty classes in C++.
522 if (getContext().getLangOptions().CPlusPlus) {
523 if (const RecordType *RT = Ty->getAs<RecordType>()) {
524 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
525 return;
526 }
527 }
John McCall90217182010-08-07 08:21:30 +0000528
529 // Cast the dest ptr to the appropriate i8 pointer type.
530 unsigned DestAS =
531 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
532 const llvm::Type *BP =
533 llvm::Type::getInt8PtrTy(VMContext, DestAS);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000534 if (DestPtr->getType() != BP)
535 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
536
537 // Get size and alignment info for this aggregate.
538 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
John McCall90217182010-08-07 08:21:30 +0000539 uint64_t Size = TypeInfo.first;
540 unsigned Align = TypeInfo.second;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000541
Chris Lattner88207c92009-04-21 17:59:23 +0000542 // Don't bother emitting a zero-byte memset.
John McCall90217182010-08-07 08:21:30 +0000543 if (Size == 0)
Chris Lattner88207c92009-04-21 17:59:23 +0000544 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000545
John McCall90217182010-08-07 08:21:30 +0000546 llvm::ConstantInt *SizeVal = llvm::ConstantInt::get(IntPtrTy, Size / 8);
547 llvm::ConstantInt *AlignVal = Builder.getInt32(Align / 8);
548
549 // If the type contains a pointer to data member we can't memset it to zero.
550 // Instead, create a null constant and copy it to the destination.
John McCallf16aa102010-08-22 21:01:12 +0000551 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall90217182010-08-07 08:21:30 +0000552 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
553
554 llvm::GlobalVariable *NullVariable =
555 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
556 /*isConstant=*/true,
557 llvm::GlobalVariable::PrivateLinkage,
558 NullConstant, llvm::Twine());
559 llvm::Value *SrcPtr =
560 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
561
562 // FIXME: variable-size types?
563
564 // Get and call the appropriate llvm.memcpy overload.
565 llvm::Constant *Memcpy =
566 CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), IntPtrTy);
567 Builder.CreateCall5(Memcpy, DestPtr, SrcPtr, SizeVal, AlignVal,
568 /*volatile*/ Builder.getFalse());
569 return;
570 }
571
572 // Otherwise, just memset the whole thing to zero. This is legal
573 // because in LLVM, all default initializers (other than the ones we just
574 // handled above) are guaranteed to have a bit pattern of all zeros.
575
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000576 // FIXME: Handle variable sized types.
Chris Lattner77b89b82010-06-27 07:15:29 +0000577 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
John McCall90217182010-08-07 08:21:30 +0000578 Builder.getInt8(0),
579 SizeVal, AlignVal, /*volatile*/ Builder.getFalse());
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000580}
581
Chris Lattnerd9becd12009-10-28 23:59:40 +0000582llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
583 // Make sure that there is a block for the indirect goto.
584 if (IndirectBranch == 0)
585 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000586
John McCallff8e1152010-07-23 21:56:41 +0000587 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000588
Chris Lattnerd9becd12009-10-28 23:59:40 +0000589 // Make sure the indirect branch includes all of the address-taken blocks.
590 IndirectBranch->addDestination(BB);
591 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000592}
593
594llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000595 // If we already made the indirect branch for indirect goto, return its block.
596 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000597
Chris Lattnerd9becd12009-10-28 23:59:40 +0000598 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000599
Chris Lattnerd9becd12009-10-28 23:59:40 +0000600 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000601
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000602 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000603 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000604
Chris Lattnerd9becd12009-10-28 23:59:40 +0000605 // Create the indirect branch instruction.
606 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
607 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000608}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000609
Daniel Dunbard286f052009-07-19 06:58:07 +0000610llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000611 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Anders Carlssonf666b772008-12-20 20:27:15 +0000613 assert(SizeEntry && "Did not emit size for type");
614 return SizeEntry;
615}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000616
Daniel Dunbard286f052009-07-19 06:58:07 +0000617llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000618 assert(Ty->isVariablyModifiedType() &&
619 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Daniel Dunbard286f052009-07-19 06:58:07 +0000621 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Anders Carlsson60d35412008-12-20 20:46:34 +0000623 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000624 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000626 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000627 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000629 // Get the element size;
630 QualType ElemTy = VAT->getElementType();
631 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000632 if (ElemTy->isVariableArrayType())
633 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000634 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000635 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000636 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000638 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000639 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000641 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000642 }
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Anders Carlsson60d35412008-12-20 20:46:34 +0000644 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000647 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
648 EmitVLASize(AT->getElementType());
649 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 }
651
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000652 const PointerType *PT = Ty->getAs<PointerType>();
653 assert(PT && "unknown VM type!");
654 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000655 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000656}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000657
658llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Chris Lattnerfbe02ff2010-06-27 07:40:06 +0000659 if (CGM.getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000660 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000661 return EmitLValue(E).getAddress();
662}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000663
John McCallf1549f62010-07-06 01:34:17 +0000664/// Pops cleanup blocks until the given savepoint is reached.
665void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
666 assert(Old.isValid());
667
John McCallff8e1152010-07-23 21:56:41 +0000668 while (EHStack.stable_begin() != Old) {
669 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
670
671 // As long as Old strictly encloses the scope's enclosing normal
672 // cleanup, we're going to emit another normal cleanup which
673 // fallthrough can propagate through.
674 bool FallThroughIsBranchThrough =
675 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
676
677 PopCleanupBlock(FallThroughIsBranchThrough);
678 }
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000679}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000680
John McCallff8e1152010-07-23 21:56:41 +0000681static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
682 EHCleanupScope &Scope) {
683 assert(Scope.isNormalCleanup());
684 llvm::BasicBlock *Entry = Scope.getNormalBlock();
685 if (!Entry) {
686 Entry = CGF.createBasicBlock("cleanup");
687 Scope.setNormalBlock(Entry);
Mike Stump99533832009-12-02 07:41:41 +0000688 }
John McCallff8e1152010-07-23 21:56:41 +0000689 return Entry;
690}
Mike Stump99533832009-12-02 07:41:41 +0000691
John McCallff8e1152010-07-23 21:56:41 +0000692static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF,
693 EHCleanupScope &Scope) {
694 assert(Scope.isEHCleanup());
695 llvm::BasicBlock *Entry = Scope.getEHBlock();
696 if (!Entry) {
697 Entry = CGF.createBasicBlock("eh.cleanup");
698 Scope.setEHBlock(Entry);
699 }
700 return Entry;
701}
Devang Patelcd9199e2010-04-13 00:08:43 +0000702
John McCallff8e1152010-07-23 21:56:41 +0000703/// Transitions the terminator of the given exit-block of a cleanup to
704/// be a cleanup switch.
705static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
706 llvm::BasicBlock *Block) {
707 // If it's a branch, turn it into a switch whose default
708 // destination is its original target.
709 llvm::TerminatorInst *Term = Block->getTerminator();
710 assert(Term && "can't transition block without terminator");
711
712 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
713 assert(Br->isUnconditional());
714 llvm::LoadInst *Load =
715 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
716 llvm::SwitchInst *Switch =
717 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
718 Br->eraseFromParent();
719 return Switch;
720 } else {
721 return cast<llvm::SwitchInst>(Term);
722 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000723}
724
John McCallf1549f62010-07-06 01:34:17 +0000725/// Attempts to reduce a cleanup's entry block to a fallthrough. This
726/// is basically llvm::MergeBlockIntoPredecessor, except
John McCallff8e1152010-07-23 21:56:41 +0000727/// simplified/optimized for the tighter constraints on cleanup blocks.
728///
729/// Returns the new block, whatever it is.
730static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
731 llvm::BasicBlock *Entry) {
John McCallf1549f62010-07-06 01:34:17 +0000732 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
John McCallff8e1152010-07-23 21:56:41 +0000733 if (!Pred) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
John McCallf1549f62010-07-06 01:34:17 +0000735 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
John McCallff8e1152010-07-23 21:56:41 +0000736 if (!Br || Br->isConditional()) return Entry;
John McCallf1549f62010-07-06 01:34:17 +0000737 assert(Br->getSuccessor(0) == Entry);
738
739 // If we were previously inserting at the end of the cleanup entry
740 // block, we'll need to continue inserting at the end of the
741 // predecessor.
742 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
743 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
744
745 // Kill the branch.
746 Br->eraseFromParent();
747
748 // Merge the blocks.
749 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
750
751 // Kill the entry block.
752 Entry->eraseFromParent();
753
754 if (WasInsertBlock)
755 CGF.Builder.SetInsertPoint(Pred);
Anders Carlsson87eaf172009-02-08 00:50:42 +0000756
John McCallff8e1152010-07-23 21:56:41 +0000757 return Pred;
John McCallf1549f62010-07-06 01:34:17 +0000758}
759
John McCall1f0fca52010-07-21 07:22:38 +0000760static void EmitCleanup(CodeGenFunction &CGF,
761 EHScopeStack::Cleanup *Fn,
762 bool ForEH) {
John McCallda65ea82010-07-13 20:32:21 +0000763 if (ForEH) CGF.EHStack.pushTerminate();
764 Fn->Emit(CGF, ForEH);
765 if (ForEH) CGF.EHStack.popTerminate();
766 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
767}
768
John McCall1f0fca52010-07-21 07:22:38 +0000769/// Pops a cleanup block. If the block includes a normal cleanup, the
770/// current insertion point is threaded through the cleanup, as are
771/// any branch fixups on the cleanup.
John McCallff8e1152010-07-23 21:56:41 +0000772void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCall1f0fca52010-07-21 07:22:38 +0000773 assert(!EHStack.empty() && "cleanup stack is empty!");
774 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
775 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
776 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
John McCall838d7962010-08-14 07:46:19 +0000777 assert(Scope.isActive() && "cleanup was still inactive when popped!");
John McCallda65ea82010-07-13 20:32:21 +0000778
779 // Check whether we need an EH cleanup. This is only true if we've
780 // generated a lazy EH cleanup block.
John McCallff8e1152010-07-23 21:56:41 +0000781 bool RequiresEHCleanup = Scope.hasEHBranches();
John McCallda65ea82010-07-13 20:32:21 +0000782
783 // Check the three conditions which might require a normal cleanup:
784
785 // - whether there are branch fix-ups through this cleanup
786 unsigned FixupDepth = Scope.getFixupDepth();
John McCall1f0fca52010-07-21 07:22:38 +0000787 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
John McCallda65ea82010-07-13 20:32:21 +0000788
John McCallff8e1152010-07-23 21:56:41 +0000789 // - whether there are branch-throughs or branch-afters
790 bool HasExistingBranches = Scope.hasBranches();
John McCallda65ea82010-07-13 20:32:21 +0000791
792 // - whether there's a fallthrough
John McCall1f0fca52010-07-21 07:22:38 +0000793 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
John McCallda65ea82010-07-13 20:32:21 +0000794 bool HasFallthrough = (FallthroughSource != 0);
795
796 bool RequiresNormalCleanup = false;
797 if (Scope.isNormalCleanup() &&
798 (HasFixups || HasExistingBranches || HasFallthrough)) {
799 RequiresNormalCleanup = true;
800 }
801
802 // If we don't need the cleanup at all, we're done.
803 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallff8e1152010-07-23 21:56:41 +0000804 EHStack.popCleanup(); // safe because there are no fixups
John McCall1f0fca52010-07-21 07:22:38 +0000805 assert(EHStack.getNumBranchFixups() == 0 ||
806 EHStack.hasNormalCleanups());
John McCallda65ea82010-07-13 20:32:21 +0000807 return;
808 }
809
810 // Copy the cleanup emission data out. Note that SmallVector
811 // guarantees maximal alignment for its buffer regardless of its
812 // type parameter.
813 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
814 CleanupBuffer.reserve(Scope.getCleanupSize());
815 memcpy(CleanupBuffer.data(),
816 Scope.getCleanupBuffer(), Scope.getCleanupSize());
817 CleanupBuffer.set_size(Scope.getCleanupSize());
John McCall1f0fca52010-07-21 07:22:38 +0000818 EHScopeStack::Cleanup *Fn =
819 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
John McCallda65ea82010-07-13 20:32:21 +0000820
John McCallff8e1152010-07-23 21:56:41 +0000821 // We want to emit the EH cleanup after the normal cleanup, but go
822 // ahead and do the setup for the EH cleanup while the scope is still
823 // alive.
824 llvm::BasicBlock *EHEntry = 0;
825 llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend;
826 if (RequiresEHCleanup) {
827 EHEntry = CreateEHEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000828
John McCallff8e1152010-07-23 21:56:41 +0000829 // Figure out the branch-through dest if necessary.
830 llvm::BasicBlock *EHBranchThroughDest = 0;
831 if (Scope.hasEHBranchThroughs()) {
832 assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end());
833 EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup());
834 EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S));
835 }
836
837 // If we have exactly one branch-after and no branch-throughs, we
838 // can dispatch it without a switch.
John McCall7cd4b062010-07-26 22:44:58 +0000839 if (!Scope.hasEHBranchThroughs() &&
John McCallff8e1152010-07-23 21:56:41 +0000840 Scope.getNumEHBranchAfters() == 1) {
841 assert(!EHBranchThroughDest);
842
843 // TODO: remove the spurious eh.cleanup.dest stores if this edge
844 // never went through any switches.
845 llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0);
846 EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest));
847
848 // Otherwise, if we have any branch-afters, we need a switch.
849 } else if (Scope.getNumEHBranchAfters()) {
850 // The default of the switch belongs to the branch-throughs if
851 // they exist.
852 llvm::BasicBlock *Default =
853 (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock());
854
855 const unsigned SwitchCapacity = Scope.getNumEHBranchAfters();
856
857 llvm::LoadInst *Load =
858 new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest");
859 llvm::SwitchInst *Switch =
860 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
861
862 EHInstsToAppend.push_back(Load);
863 EHInstsToAppend.push_back(Switch);
864
865 for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I)
866 Switch->addCase(Scope.getEHBranchAfterIndex(I),
867 Scope.getEHBranchAfterBlock(I));
868
869 // Otherwise, we have only branch-throughs; jump to the next EH
870 // cleanup.
871 } else {
872 assert(EHBranchThroughDest);
873 EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest));
874 }
875 }
876
877 if (!RequiresNormalCleanup) {
878 EHStack.popCleanup();
879 } else {
880 // As a kindof crazy internal case, branch-through fall-throughs
881 // leave the insertion point set to the end of the last cleanup.
882 bool HasPrebranchedFallthrough =
883 (HasFallthrough && FallthroughSource->getTerminator());
884 assert(!HasPrebranchedFallthrough ||
885 FallthroughSource->getTerminator()->getSuccessor(0)
886 == Scope.getNormalBlock());
887
John McCallda65ea82010-07-13 20:32:21 +0000888 // If we have a fallthrough and no other need for the cleanup,
889 // emit it directly.
John McCallff8e1152010-07-23 21:56:41 +0000890 if (HasFallthrough && !HasPrebranchedFallthrough &&
891 !HasFixups && !HasExistingBranches) {
892
893 // Fixups can cause us to optimistically create a normal block,
894 // only to later have no real uses for it. Just delete it in
895 // this case.
896 // TODO: we can potentially simplify all the uses after this.
897 if (Scope.getNormalBlock()) {
898 Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock());
899 delete Scope.getNormalBlock();
900 }
901
902 EHStack.popCleanup();
903
John McCall1f0fca52010-07-21 07:22:38 +0000904 EmitCleanup(*this, Fn, /*ForEH*/ false);
John McCallda65ea82010-07-13 20:32:21 +0000905
906 // Otherwise, the best approach is to thread everything through
907 // the cleanup block and then try to clean up after ourselves.
908 } else {
909 // Force the entry block to exist.
John McCallff8e1152010-07-23 21:56:41 +0000910 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000911
John McCallff8e1152010-07-23 21:56:41 +0000912 // If there's a fallthrough, we need to store the cleanup
913 // destination index. For fall-throughs this is always zero.
914 if (HasFallthrough && !HasPrebranchedFallthrough)
915 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
916
917 // Emit the entry block. This implicitly branches to it if we
918 // have fallthrough. All the fixups and existing branches should
919 // already be branched to it.
John McCall1f0fca52010-07-21 07:22:38 +0000920 EmitBlock(NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +0000921
John McCallff8e1152010-07-23 21:56:41 +0000922 bool HasEnclosingCleanups =
923 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
John McCallda65ea82010-07-13 20:32:21 +0000924
John McCallff8e1152010-07-23 21:56:41 +0000925 // Compute the branch-through dest if we need it:
926 // - if there are branch-throughs threaded through the scope
927 // - if fall-through is a branch-through
928 // - if there are fixups that will be optimistically forwarded
929 // to the enclosing cleanup
930 llvm::BasicBlock *BranchThroughDest = 0;
931 if (Scope.hasBranchThroughs() ||
932 (HasFallthrough && FallthroughIsBranchThrough) ||
933 (HasFixups && HasEnclosingCleanups)) {
934 assert(HasEnclosingCleanups);
935 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
936 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
John McCallda65ea82010-07-13 20:32:21 +0000937 }
938
John McCallff8e1152010-07-23 21:56:41 +0000939 llvm::BasicBlock *FallthroughDest = 0;
940 llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend;
941
942 // If there's exactly one branch-after and no other threads,
943 // we can route it without a switch.
944 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
945 Scope.getNumBranchAfters() == 1) {
946 assert(!BranchThroughDest);
947
948 // TODO: clean up the possibly dead stores to the cleanup dest slot.
949 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
950 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
951
952 // Build a switch-out if we need it:
953 // - if there are branch-afters threaded through the scope
954 // - if fall-through is a branch-after
955 // - if there are fixups that have nowhere left to go and
956 // so must be immediately resolved
957 } else if (Scope.getNumBranchAfters() ||
958 (HasFallthrough && !FallthroughIsBranchThrough) ||
959 (HasFixups && !HasEnclosingCleanups)) {
960
961 llvm::BasicBlock *Default =
962 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
963
964 // TODO: base this on the number of branch-afters and fixups
965 const unsigned SwitchCapacity = 10;
966
967 llvm::LoadInst *Load =
968 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
969 llvm::SwitchInst *Switch =
970 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
971
972 InstsToAppend.push_back(Load);
973 InstsToAppend.push_back(Switch);
974
975 // Branch-after fallthrough.
976 if (HasFallthrough && !FallthroughIsBranchThrough) {
977 FallthroughDest = createBasicBlock("cleanup.cont");
978 Switch->addCase(Builder.getInt32(0), FallthroughDest);
979 }
980
981 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
982 Switch->addCase(Scope.getBranchAfterIndex(I),
983 Scope.getBranchAfterBlock(I));
984 }
985
986 if (HasFixups && !HasEnclosingCleanups)
987 ResolveAllBranchFixups(Switch);
988 } else {
989 // We should always have a branch-through destination in this case.
990 assert(BranchThroughDest);
991 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
992 }
993
994 // We're finally ready to pop the cleanup.
995 EHStack.popCleanup();
996 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
997
998 EmitCleanup(*this, Fn, /*ForEH*/ false);
999
1000 // Append the prepared cleanup prologue from above.
1001 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
1002 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
1003 NormalExit->getInstList().push_back(InstsToAppend[I]);
1004
1005 // Optimistically hope that any fixups will continue falling through.
John McCall1f0fca52010-07-21 07:22:38 +00001006 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
John McCallff8e1152010-07-23 21:56:41 +00001007 I < E; ++I) {
1008 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
1009 if (!Fixup.Destination) continue;
1010 if (!Fixup.OptimisticBranchBlock) {
1011 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
1012 getNormalCleanupDestSlot(),
1013 Fixup.InitialBranch);
1014 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
1015 }
1016 Fixup.OptimisticBranchBlock = NormalExit;
1017 }
1018
1019 if (FallthroughDest)
1020 EmitBlock(FallthroughDest);
1021 else if (!HasFallthrough)
1022 Builder.ClearInsertionPoint();
John McCallda65ea82010-07-13 20:32:21 +00001023
John McCallff8e1152010-07-23 21:56:41 +00001024 // Check whether we can merge NormalEntry into a single predecessor.
1025 // This might invalidate (non-IR) pointers to NormalEntry.
1026 llvm::BasicBlock *NewNormalEntry =
1027 SimplifyCleanupEntry(*this, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001028
John McCallff8e1152010-07-23 21:56:41 +00001029 // If it did invalidate those pointers, and NormalEntry was the same
1030 // as NormalExit, go back and patch up the fixups.
1031 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1032 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1033 I < E; ++I)
1034 CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCallda65ea82010-07-13 20:32:21 +00001035 }
1036 }
1037
John McCallff8e1152010-07-23 21:56:41 +00001038 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1039
John McCallda65ea82010-07-13 20:32:21 +00001040 // Emit the EH cleanup if required.
1041 if (RequiresEHCleanup) {
John McCall1f0fca52010-07-21 07:22:38 +00001042 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallff8e1152010-07-23 21:56:41 +00001043
John McCall1f0fca52010-07-21 07:22:38 +00001044 EmitBlock(EHEntry);
John McCallff8e1152010-07-23 21:56:41 +00001045 EmitCleanup(*this, Fn, /*ForEH*/ true);
1046
1047 // Append the prepared cleanup prologue from above.
1048 llvm::BasicBlock *EHExit = Builder.GetInsertBlock();
1049 for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I)
1050 EHExit->getInstList().push_back(EHInstsToAppend[I]);
1051
John McCall1f0fca52010-07-21 07:22:38 +00001052 Builder.restoreIP(SavedIP);
John McCallff8e1152010-07-23 21:56:41 +00001053
1054 SimplifyCleanupEntry(*this, EHEntry);
John McCallda65ea82010-07-13 20:32:21 +00001055 }
1056}
1057
John McCallff8e1152010-07-23 21:56:41 +00001058/// Terminate the current block by emitting a branch which might leave
1059/// the current cleanup-protected scope. The target scope may not yet
1060/// be known, in which case this will require a fixup.
1061///
1062/// As a side-effect, this method clears the insertion point.
John McCallf1549f62010-07-06 01:34:17 +00001063void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall413e6772010-07-28 01:07:35 +00001064 assert(Dest.getScopeDepth().encloses(EHStack.getInnermostNormalCleanup())
1065 && "stale jump destination");
1066
Anders Carlsson46831a92009-02-08 22:13:37 +00001067 if (!HaveInsertPoint())
1068 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001069
John McCallf1549f62010-07-06 01:34:17 +00001070 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001071 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001072
John McCall838d7962010-08-14 07:46:19 +00001073 // Calculate the innermost active normal cleanup.
1074 EHScopeStack::stable_iterator
1075 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1076
1077 // If we're not in an active normal cleanup scope, or if the
1078 // destination scope is within the innermost active normal cleanup
1079 // scope, we don't need to worry about fixups.
1080 if (TopCleanup == EHStack.stable_end() ||
1081 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
John McCallf1549f62010-07-06 01:34:17 +00001082 Builder.ClearInsertionPoint();
1083 return;
1084 }
1085
John McCallf1549f62010-07-06 01:34:17 +00001086 // If we can't resolve the destination cleanup scope, just add this
John McCallff8e1152010-07-23 21:56:41 +00001087 // to the current cleanup scope as a branch fixup.
1088 if (!Dest.getScopeDepth().isValid()) {
1089 BranchFixup &Fixup = EHStack.addBranchFixup();
1090 Fixup.Destination = Dest.getBlock();
1091 Fixup.DestinationIndex = Dest.getDestIndex();
1092 Fixup.InitialBranch = BI;
1093 Fixup.OptimisticBranchBlock = 0;
1094
John McCallf1549f62010-07-06 01:34:17 +00001095 Builder.ClearInsertionPoint();
1096 return;
1097 }
1098
John McCallff8e1152010-07-23 21:56:41 +00001099 // Otherwise, thread through all the normal cleanups in scope.
1100
1101 // Store the index at the start.
1102 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1103 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
1104
1105 // Adjust BI to point to the first cleanup block.
1106 {
1107 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001108 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001109 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1110 }
1111
1112 // Add this destination to all the scopes involved.
John McCall838d7962010-08-14 07:46:19 +00001113 EHScopeStack::stable_iterator I = TopCleanup;
John McCallff8e1152010-07-23 21:56:41 +00001114 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1115 if (E.strictlyEncloses(I)) {
1116 while (true) {
1117 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1118 assert(Scope.isNormalCleanup());
1119 I = Scope.getEnclosingNormalCleanup();
1120
1121 // If this is the last cleanup we're propagating through, tell it
1122 // that there's a resolved jump moving through it.
1123 if (!E.strictlyEncloses(I)) {
1124 Scope.addBranchAfter(Index, Dest.getBlock());
1125 break;
John McCallda65ea82010-07-13 20:32:21 +00001126 }
John McCallff8e1152010-07-23 21:56:41 +00001127
1128 // Otherwise, tell the scope that there's a jump propoagating
1129 // through it. If this isn't new information, all the rest of
1130 // the work has been done before.
1131 if (!Scope.addBranchThrough(Dest.getBlock()))
1132 break;
John McCallf1549f62010-07-06 01:34:17 +00001133 }
1134 }
1135
Anders Carlsson46831a92009-02-08 22:13:37 +00001136 Builder.ClearInsertionPoint();
John McCallf1549f62010-07-06 01:34:17 +00001137}
Mike Stump1eb44332009-09-09 15:08:12 +00001138
John McCallff8e1152010-07-23 21:56:41 +00001139void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) {
1140 // We should never get invalid scope depths for an UnwindDest; that
1141 // implies that the destination wasn't set up correctly.
1142 assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?");
1143
John McCallf1549f62010-07-06 01:34:17 +00001144 if (!HaveInsertPoint())
Anders Carlsson87eaf172009-02-08 00:50:42 +00001145 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001146
John McCallf1549f62010-07-06 01:34:17 +00001147 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001148 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001149
John McCall838d7962010-08-14 07:46:19 +00001150 // Calculate the innermost active cleanup.
1151 EHScopeStack::stable_iterator
1152 InnermostCleanup = EHStack.getInnermostActiveEHCleanup();
1153
John McCallff8e1152010-07-23 21:56:41 +00001154 // If the destination is in the same EH cleanup scope as us, we
1155 // don't need to thread through anything.
John McCall838d7962010-08-14 07:46:19 +00001156 if (InnermostCleanup.encloses(Dest.getScopeDepth())) {
John McCallf1549f62010-07-06 01:34:17 +00001157 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001158 return;
1159 }
John McCall838d7962010-08-14 07:46:19 +00001160 assert(InnermostCleanup != EHStack.stable_end());
Mike Stump1eb44332009-09-09 15:08:12 +00001161
John McCallff8e1152010-07-23 21:56:41 +00001162 // Store the index at the start.
1163 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1164 new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI);
John McCallf1549f62010-07-06 01:34:17 +00001165
John McCallff8e1152010-07-23 21:56:41 +00001166 // Adjust BI to point to the first cleanup block.
1167 {
1168 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001169 cast<EHCleanupScope>(*EHStack.find(InnermostCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001170 BI->setSuccessor(0, CreateEHEntry(*this, Scope));
1171 }
1172
1173 // Add this destination to all the scopes involved.
1174 for (EHScopeStack::stable_iterator
John McCall838d7962010-08-14 07:46:19 +00001175 I = InnermostCleanup, E = Dest.getScopeDepth(); ; ) {
John McCallff8e1152010-07-23 21:56:41 +00001176 assert(E.strictlyEncloses(I));
1177 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1178 assert(Scope.isEHCleanup());
1179 I = Scope.getEnclosingEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +00001180
John McCallff8e1152010-07-23 21:56:41 +00001181 // If this is the last cleanup we're propagating through, add this
1182 // as a branch-after.
1183 if (I == E) {
1184 Scope.addEHBranchAfter(Index, Dest.getBlock());
1185 break;
John McCallf1549f62010-07-06 01:34:17 +00001186 }
John McCallff8e1152010-07-23 21:56:41 +00001187
1188 // Otherwise, add it as a branch-through. If this isn't new
1189 // information, all the rest of the work has been done before.
1190 if (!Scope.addEHBranchThrough(Dest.getBlock()))
1191 break;
Anders Carlsson87eaf172009-02-08 00:50:42 +00001192 }
John McCallf1549f62010-07-06 01:34:17 +00001193
1194 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001195}
John McCallff8e1152010-07-23 21:56:41 +00001196
1197/// All the branch fixups on the EH stack have propagated out past the
1198/// outermost normal cleanup; resolve them all by adding cases to the
1199/// given switch instruction.
1200void CodeGenFunction::ResolveAllBranchFixups(llvm::SwitchInst *Switch) {
1201 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
1202
1203 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1204 // Skip this fixup if its destination isn't set or if we've
1205 // already treated it.
1206 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1207 if (Fixup.Destination == 0) continue;
1208 if (!CasesAdded.insert(Fixup.Destination)) continue;
1209
1210 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex),
1211 Fixup.Destination);
1212 }
1213
1214 EHStack.clearFixups();
1215}
1216
1217void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
1218 assert(Block && "resolving a null target block");
1219 if (!EHStack.getNumBranchFixups()) return;
1220
1221 assert(EHStack.hasNormalCleanups() &&
1222 "branch fixups exist with no normal cleanups on stack");
1223
1224 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
1225 bool ResolvedAny = false;
1226
1227 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1228 // Skip this fixup if its destination doesn't match.
1229 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1230 if (Fixup.Destination != Block) continue;
1231
1232 Fixup.Destination = 0;
1233 ResolvedAny = true;
1234
1235 // If it doesn't have an optimistic branch block, LatestBranch is
1236 // already pointing to the right place.
1237 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
1238 if (!BranchBB)
1239 continue;
1240
1241 // Don't process the same optimistic branch block twice.
1242 if (!ModifiedOptimisticBlocks.insert(BranchBB))
1243 continue;
1244
1245 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
1246
1247 // Add a case to the switch.
1248 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
1249 }
1250
1251 if (ResolvedAny)
1252 EHStack.popNullFixups();
1253}
1254
John McCallcd2d2b72010-08-13 21:20:51 +00001255/// Activate a cleanup that was created in an inactivated state.
1256void CodeGenFunction::ActivateCleanup(EHScopeStack::stable_iterator C) {
1257 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1258 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1259 assert(!Scope.isActive() && "double activation");
1260
1261 // Calculate whether the cleanup was used:
1262 bool Used = false;
1263
1264 // - as a normal cleanup
1265 if (Scope.isNormalCleanup()) {
1266 bool NormalUsed = false;
1267 if (Scope.getNormalBlock()) {
1268 NormalUsed = true;
1269 } else {
1270 // Check whether any enclosed cleanups were needed.
1271 for (EHScopeStack::stable_iterator
1272 I = EHStack.getInnermostNormalCleanup(); I != C; ) {
1273 assert(C.strictlyEncloses(I));
1274 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1275 if (S.getNormalBlock()) {
1276 NormalUsed = true;
1277 break;
1278 }
1279 I = S.getEnclosingNormalCleanup();
1280 }
1281 }
1282
1283 if (NormalUsed)
1284 Used = true;
1285 else
1286 Scope.setActivatedBeforeNormalUse(true);
1287 }
1288
1289 // - as an EH cleanup
1290 if (Scope.isEHCleanup()) {
1291 bool EHUsed = false;
1292 if (Scope.getEHBlock()) {
1293 EHUsed = true;
1294 } else {
1295 // Check whether any enclosed cleanups were needed.
1296 for (EHScopeStack::stable_iterator
1297 I = EHStack.getInnermostEHCleanup(); I != C; ) {
1298 assert(C.strictlyEncloses(I));
1299 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1300 if (S.getEHBlock()) {
1301 EHUsed = true;
1302 break;
1303 }
1304 I = S.getEnclosingEHCleanup();
1305 }
1306 }
1307
1308 if (EHUsed)
1309 Used = true;
1310 else
1311 Scope.setActivatedBeforeEHUse(true);
1312 }
1313
1314 llvm::AllocaInst *Var = EHCleanupScope::activeSentinel();
1315 if (Used) {
1316 Var = CreateTempAlloca(Builder.getInt1Ty());
1317 InitTempAlloca(Var, Builder.getFalse());
1318 }
1319 Scope.setActiveVar(Var);
1320}
1321
John McCallff8e1152010-07-23 21:56:41 +00001322llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1323 if (!NormalCleanupDest)
1324 NormalCleanupDest =
1325 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1326 return NormalCleanupDest;
1327}
1328
1329llvm::Value *CodeGenFunction::getEHCleanupDestSlot() {
1330 if (!EHCleanupDest)
1331 EHCleanupDest =
1332 CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot");
1333 return EHCleanupDest;
1334}
Devang Patel8d308382010-08-10 07:24:25 +00001335
1336void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
Devang Patel25c2c8f2010-08-10 17:53:33 +00001337 llvm::ConstantInt *Init) {
1338 assert (Init && "Invalid DeclRefExpr initializer!");
1339 if (CGDebugInfo *Dbg = getDebugInfo())
1340 Dbg->EmitGlobalVariable(E->getDecl(), Init, Builder);
Devang Patel8d308382010-08-10 07:24:25 +00001341}