blob: 7bd0c3da9ea79c93f1ad96d173992ca62ba19440 [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
John McCall8abdbd82010-09-18 02:24:39 +000031static void ResolveAllBranchFixups(CodeGenFunction &CGF,
32 llvm::SwitchInst *Switch,
33 llvm::BasicBlock *CleanupEntry);
34
Mike Stump1eb44332009-09-09 15:08:12 +000035CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000036 : BlockFunction(cgm, *this, Builder), CGM(cgm),
37 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000038 Builder(cgm.getModule().getContext()),
John McCallff8e1152010-07-23 21:56:41 +000039 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
John McCallf1549f62010-07-06 01:34:17 +000040 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
John McCallff8e1152010-07-23 21:56:41 +000041 SwitchInsn(0), CaseRangeBlock(0),
John McCallf1549f62010-07-06 01:34:17 +000042 DidCallStackSave(false), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000043 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCallf1549f62010-07-06 01:34:17 +000044 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
Chris Lattner83252dc2010-07-20 21:07:09 +000045 TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000046
47 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000048 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000049 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
50 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
51 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
52 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
53
Mike Stumpd88ea562009-12-09 03:35:49 +000054 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000055 CatchUndefined = getContext().getLangOptions().CatchUndefined;
John McCall4c40d982010-08-31 07:33:07 +000056 CGM.getCXXABI().getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000057}
Reid Spencer5f016e22007-07-11 17:01:13 +000058
59ASTContext &CodeGenFunction::getContext() const {
60 return CGM.getContext();
61}
62
63
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000064const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
65 return CGM.getTypes().ConvertTypeForMem(T);
66}
67
Reid Spencer5f016e22007-07-11 17:01:13 +000068const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
69 return CGM.getTypes().ConvertType(T);
70}
71
72bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000073 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
John McCalld608cdb2010-08-22 10:59:02 +000074 T->isObjCObjectType();
Reid Spencer5f016e22007-07-11 17:01:13 +000075}
76
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000077void CodeGenFunction::EmitReturnBlock() {
78 // For cleanliness, we try to avoid emitting the return block for
79 // simple cases.
80 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
81
82 if (CurBB) {
83 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
84
Daniel Dunbar96e18b02009-07-19 08:24:34 +000085 // We have a valid insert point, reuse it if it is empty or there are no
86 // explicit jumps to the return block.
John McCallff8e1152010-07-23 21:56:41 +000087 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
88 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
89 delete ReturnBlock.getBlock();
Daniel Dunbar96e18b02009-07-19 08:24:34 +000090 } else
John McCallff8e1152010-07-23 21:56:41 +000091 EmitBlock(ReturnBlock.getBlock());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000092 return;
93 }
94
95 // Otherwise, if the return block is the target of a single direct
96 // branch then we can just put the code in that block instead. This
97 // cleans up functions which started with a unified return block.
John McCallff8e1152010-07-23 21:56:41 +000098 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000099 llvm::BranchInst *BI =
John McCallff8e1152010-07-23 21:56:41 +0000100 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
John McCallf1549f62010-07-06 01:34:17 +0000101 if (BI && BI->isUnconditional() &&
John McCallff8e1152010-07-23 21:56:41 +0000102 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000103 // Reset insertion point and delete the branch.
104 Builder.SetInsertPoint(BI->getParent());
105 BI->eraseFromParent();
John McCallff8e1152010-07-23 21:56:41 +0000106 delete ReturnBlock.getBlock();
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000107 return;
108 }
109 }
110
Mike Stumpf5408fe2009-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 Dunbar1c1d6072009-01-26 23:27:52 +0000114
John McCallff8e1152010-07-23 21:56:41 +0000115 EmitBlock(ReturnBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000116}
117
118static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
119 if (!BB) return;
120 if (!BB->use_empty())
121 return CGF.CurFn->getBasicBlockList().push_back(BB);
122 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000123}
124
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000125void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000126 assert(BreakContinueStack.empty() &&
127 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000128
129 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000130 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000131
Chris Lattner7255a2d2010-06-22 00:03:40 +0000132 EmitFunctionInstrumentation("__cyg_profile_func_exit");
133
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000134 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000135 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000136 DI->setLocation(EndLoc);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000137 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000138 }
139
Chris Lattner35b21b82010-06-27 01:06:27 +0000140 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000141 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000142
John McCallf1549f62010-07-06 01:34:17 +0000143 assert(EHStack.empty() &&
144 "did not remove all scopes from cleanup stack!");
145
Chris Lattnerd9becd12009-10-28 23:59:40 +0000146 // If someone did an indirect goto, emit the indirect goto block at the end of
147 // the function.
148 if (IndirectBranch) {
149 EmitBlock(IndirectBranch->getParent());
150 Builder.ClearInsertionPoint();
151 }
152
Chris Lattner5a2fa142007-12-02 06:32:24 +0000153 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000154 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000155 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000156 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000157
158 // If someone took the address of a label but never did an indirect goto, we
159 // made a zero entry PHI node, which is illegal, zap it now.
160 if (IndirectBranch) {
161 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
162 if (PN->getNumIncomingValues() == 0) {
163 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
164 PN->eraseFromParent();
165 }
166 }
John McCallf1549f62010-07-06 01:34:17 +0000167
John McCallff8e1152010-07-23 21:56:41 +0000168 EmitIfUsed(*this, RethrowBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000169 EmitIfUsed(*this, TerminateLandingPad);
170 EmitIfUsed(*this, TerminateHandler);
171 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000172
173 if (CGM.getCodeGenOpts().EmitDeclMetadata)
174 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000175}
176
Chris Lattner7255a2d2010-06-22 00:03:40 +0000177/// ShouldInstrumentFunction - Return true if the current function should be
178/// instrumented with __cyg_profile_func_* calls
179bool CodeGenFunction::ShouldInstrumentFunction() {
180 if (!CGM.getCodeGenOpts().InstrumentFunctions)
181 return false;
182 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
183 return false;
184 return true;
185}
186
187/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
188/// instrumentation function with the current function and the call site, if
189/// function instrumentation is enabled.
190void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
191 if (!ShouldInstrumentFunction())
192 return;
193
Chris Lattner8dab6572010-06-23 05:21:28 +0000194 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000195 const llvm::FunctionType *FunctionTy;
196 std::vector<const llvm::Type*> ProfileFuncArgs;
197
Chris Lattner8dab6572010-06-23 05:21:28 +0000198 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
199 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
200 ProfileFuncArgs.push_back(PointerTy);
201 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000202 FunctionTy = llvm::FunctionType::get(
203 llvm::Type::getVoidTy(VMContext),
204 ProfileFuncArgs, false);
205
206 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
207 llvm::CallInst *CallSite = Builder.CreateCall(
208 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000209 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000210 "callsite");
211
Chris Lattner8dab6572010-06-23 05:21:28 +0000212 Builder.CreateCall2(F,
213 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
214 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000215}
216
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000217void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000218 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000219 const FunctionArgList &Args,
220 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000221 const Decl *D = GD.getDecl();
222
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000223 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000224 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000225 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000226 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000227 assert(CurFn->isDeclaration() && "Function already has body?");
228
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000229 // Pass inline keyword to optimizer if it appears explicitly on any
230 // declaration.
231 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
232 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
233 RE = FD->redecls_end(); RI != RE; ++RI)
234 if (RI->isInlineSpecified()) {
235 Fn->addFnAttr(llvm::Attribute::InlineHint);
236 break;
237 }
238
Daniel Dunbar55e87422008-11-11 02:29:29 +0000239 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000240
Chris Lattner41110242008-06-17 18:05:57 +0000241 // Create a marker to make it easy to insert allocas into the entryblock
242 // later. Don't create this with the builder, because we don't want it
243 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000244 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
245 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000246 if (Builder.isNamePreserving())
247 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000248
John McCallf1549f62010-07-06 01:34:17 +0000249 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattner41110242008-06-17 18:05:57 +0000251 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Douglas Gregorce056bc2010-02-21 22:15:06 +0000253 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
254 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000255 /*FIXME?*/
256 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000257
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000258 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000259 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000260 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000261 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000262 }
263
Chris Lattner7255a2d2010-06-22 00:03:40 +0000264 EmitFunctionInstrumentation("__cyg_profile_func_enter");
265
Daniel Dunbar88b53962009-02-02 22:03:45 +0000266 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000267 // CC info is ignored, hopefully?
268 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000269 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000270
271 if (RetTy->isVoidType()) {
272 // Void type; nothing to return.
273 ReturnValue = 0;
274 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
275 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
276 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000277 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000278 ReturnValue = CurFn->arg_begin();
279 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000280 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000281 }
282
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000283 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000284 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
John McCall4c40d982010-08-31 07:33:07 +0000286 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
287 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
John McCall25049412010-02-16 22:04:33 +0000288
Anders Carlsson751358f2008-12-20 21:28:43 +0000289 // If any of the arguments have a variably modified type, make sure to
290 // emit the type size.
291 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
292 i != e; ++i) {
293 QualType Ty = i->second;
294
295 if (Ty->isVariablyModifiedType())
296 EmitVLASize(Ty);
297 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000298}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000299
John McCall9fc6a772010-02-19 09:25:03 +0000300void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
301 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000302 assert(FD->getBody());
303 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000304}
305
John McCall39dad532010-08-03 22:46:07 +0000306/// Tries to mark the given function nounwind based on the
307/// non-existence of any throwing calls within it. We believe this is
308/// lightweight enough to do at -O0.
309static void TryMarkNoThrow(llvm::Function *F) {
John McCallb3a29f12010-08-11 22:38:33 +0000310 // LLVM treats 'nounwind' on a function as part of the type, so we
311 // can't do this on functions that can be overwritten.
312 if (F->mayBeOverridden()) return;
313
John McCall39dad532010-08-03 22:46:07 +0000314 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
315 for (llvm::BasicBlock::iterator
316 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
317 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
318 if (!Call->doesNotThrow())
319 return;
320 F->setDoesNotThrow(true);
321}
322
Anders Carlssonc997d422010-01-02 01:01:18 +0000323void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000324 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
325
Anders Carlssone896d982009-02-13 08:11:52 +0000326 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000327 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000328 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Daniel Dunbar7c086512008-09-09 23:14:03 +0000330 FunctionArgList Args;
John McCall4c40d982010-08-31 07:33:07 +0000331 QualType ResTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000333 CurGD = GD;
John McCall4c40d982010-08-31 07:33:07 +0000334 if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
335 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000337 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000338 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000339 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000340
341 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000342 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000343 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000344 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000345
John McCalla355e072010-02-18 03:17:58 +0000346 SourceRange BodyRange;
347 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000348
John McCalla355e072010-02-18 03:17:58 +0000349 // Emit the standard function prologue.
John McCall4c40d982010-08-31 07:33:07 +0000350 StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000351
John McCalla355e072010-02-18 03:17:58 +0000352 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000353 if (isa<CXXDestructorDecl>(FD))
354 EmitDestructorBody(Args);
355 else if (isa<CXXConstructorDecl>(FD))
356 EmitConstructorBody(Args);
357 else
358 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000359
John McCalla355e072010-02-18 03:17:58 +0000360 // Emit the standard function epilogue.
361 FinishFunction(BodyRange.getEnd());
John McCall39dad532010-08-03 22:46:07 +0000362
363 // If we haven't marked the function nothrow through other means, do
364 // a quick pass now to see if we can.
365 if (!CurFn->doesNotThrow())
366 TryMarkNoThrow(CurFn);
Chris Lattner41110242008-06-17 18:05:57 +0000367}
368
Chris Lattner0946ccd2008-11-11 07:41:27 +0000369/// ContainsLabel - Return true if the statement contains a label in it. If
370/// this statement is not executed normally, it not containing a label means
371/// that we can just remove the code.
372bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
373 // Null statement, not a label!
374 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner0946ccd2008-11-11 07:41:27 +0000376 // If this is a label, we have to emit the code, consider something like:
377 // if (0) { ... foo: bar(); } goto foo;
378 if (isa<LabelStmt>(S))
379 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattner0946ccd2008-11-11 07:41:27 +0000381 // If this is a case/default statement, and we haven't seen a switch, we have
382 // to emit the code.
383 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
384 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattner0946ccd2008-11-11 07:41:27 +0000386 // If this is a switch statement, we want to ignore cases below it.
387 if (isa<SwitchStmt>(S))
388 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattner0946ccd2008-11-11 07:41:27 +0000390 // Scan subexpressions for verboten labels.
391 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
392 I != E; ++I)
393 if (ContainsLabel(*I, IgnoreCaseStmts))
394 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner0946ccd2008-11-11 07:41:27 +0000396 return false;
397}
398
Chris Lattner31a09842008-11-12 08:04:58 +0000399
400/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
401/// a constant, or if it does but contains a label, return 0. If it constant
402/// folds to 'true' and does not contain a label, return 1, if it constant folds
403/// to 'false' and does not contain a label, return -1.
404int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000405 // FIXME: Rename and handle conversion of other evaluatable things
406 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000407 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000409 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000410 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Chris Lattner31a09842008-11-12 08:04:58 +0000412 if (CodeGenFunction::ContainsLabel(Cond))
413 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Anders Carlsson64712f12008-12-01 02:46:24 +0000415 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000416}
417
418
419/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
420/// statement) to the specified blocks. Based on the condition, this might try
421/// to simplify the codegen of the conditional based on the branch.
422///
423void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
424 llvm::BasicBlock *TrueBlock,
425 llvm::BasicBlock *FalseBlock) {
426 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
427 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Chris Lattner31a09842008-11-12 08:04:58 +0000429 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
430 // Handle X && Y in a condition.
John McCall2de56d12010-08-25 11:45:40 +0000431 if (CondBOp->getOpcode() == BO_LAnd) {
Chris Lattner31a09842008-11-12 08:04:58 +0000432 // If we have "1 && X", simplify the code. "0 && X" would have constant
433 // folded if the case was simple enough.
434 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
435 // br(1 && X) -> br(X).
436 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner31a09842008-11-12 08:04:58 +0000439 // If we have "X && 1", simplify the code to use an uncond branch.
440 // "X && 0" would have been constant folded to 0.
441 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
442 // br(X && 1) -> br(X).
443 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner31a09842008-11-12 08:04:58 +0000446 // Emit the LHS as a conditional. If the LHS conditional is false, we
447 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000448 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000449 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
450 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Anders Carlsson08e9e452010-01-24 00:20:05 +0000452 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000453 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000454 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000455 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000456
Chris Lattner31a09842008-11-12 08:04:58 +0000457 return;
John McCall2de56d12010-08-25 11:45:40 +0000458 } else if (CondBOp->getOpcode() == BO_LOr) {
Chris Lattner31a09842008-11-12 08:04:58 +0000459 // If we have "0 || X", simplify the code. "1 || X" would have constant
460 // folded if the case was simple enough.
461 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
462 // br(0 || X) -> br(X).
463 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner31a09842008-11-12 08:04:58 +0000466 // If we have "X || 0", simplify the code to use an uncond branch.
467 // "X || 1" would have been constant folded to 1.
468 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
469 // br(X || 0) -> br(X).
470 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner31a09842008-11-12 08:04:58 +0000473 // Emit the LHS as a conditional. If the LHS conditional is true, we
474 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000475 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000476 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
477 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Anders Carlsson08e9e452010-01-24 00:20:05 +0000479 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000480 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000481 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000482 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000483
Chris Lattner31a09842008-11-12 08:04:58 +0000484 return;
485 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattner552f4c42008-11-12 08:13:36 +0000488 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
489 // br(!x, t, f) -> br(x, f, t)
John McCall2de56d12010-08-25 11:45:40 +0000490 if (CondUOp->getOpcode() == UO_LNot)
Chris Lattner552f4c42008-11-12 08:13:36 +0000491 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000492 }
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Daniel Dunbar09b14892008-11-12 10:30:32 +0000494 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
495 // Handle ?: operator.
496
497 // Just ignore GNU ?: extension.
498 if (CondOp->getLHS()) {
499 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
500 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
501 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
502 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
503 EmitBlock(LHSBlock);
504 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
505 EmitBlock(RHSBlock);
506 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
507 return;
508 }
509 }
510
Chris Lattner31a09842008-11-12 08:04:58 +0000511 // Emit the code with the fully general case.
512 llvm::Value *CondV = EvaluateExprAsBool(Cond);
513 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
514}
515
Daniel Dunbar488e9932008-08-16 00:56:44 +0000516/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000517/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000518void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
519 bool OmitOnError) {
520 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000521}
522
Anders Carlsson1884eb02010-05-22 17:35:42 +0000523void
524CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000525 // Ignore empty classes in C++.
526 if (getContext().getLangOptions().CPlusPlus) {
527 if (const RecordType *RT = Ty->getAs<RecordType>()) {
528 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
529 return;
530 }
531 }
John McCall90217182010-08-07 08:21:30 +0000532
533 // Cast the dest ptr to the appropriate i8 pointer type.
534 unsigned DestAS =
535 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
536 const llvm::Type *BP =
537 llvm::Type::getInt8PtrTy(VMContext, DestAS);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000538 if (DestPtr->getType() != BP)
539 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
540
541 // Get size and alignment info for this aggregate.
542 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
John McCall90217182010-08-07 08:21:30 +0000543 uint64_t Size = TypeInfo.first;
544 unsigned Align = TypeInfo.second;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000545
Chris Lattner88207c92009-04-21 17:59:23 +0000546 // Don't bother emitting a zero-byte memset.
John McCall90217182010-08-07 08:21:30 +0000547 if (Size == 0)
Chris Lattner88207c92009-04-21 17:59:23 +0000548 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
John McCall90217182010-08-07 08:21:30 +0000550 llvm::ConstantInt *SizeVal = llvm::ConstantInt::get(IntPtrTy, Size / 8);
551 llvm::ConstantInt *AlignVal = Builder.getInt32(Align / 8);
552
553 // If the type contains a pointer to data member we can't memset it to zero.
554 // Instead, create a null constant and copy it to the destination.
John McCallf16aa102010-08-22 21:01:12 +0000555 if (!CGM.getTypes().isZeroInitializable(Ty)) {
John McCall90217182010-08-07 08:21:30 +0000556 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
557
558 llvm::GlobalVariable *NullVariable =
559 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
560 /*isConstant=*/true,
561 llvm::GlobalVariable::PrivateLinkage,
562 NullConstant, llvm::Twine());
563 llvm::Value *SrcPtr =
564 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
565
566 // FIXME: variable-size types?
567
568 // Get and call the appropriate llvm.memcpy overload.
569 llvm::Constant *Memcpy =
570 CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), IntPtrTy);
571 Builder.CreateCall5(Memcpy, DestPtr, SrcPtr, SizeVal, AlignVal,
572 /*volatile*/ Builder.getFalse());
573 return;
574 }
575
576 // Otherwise, just memset the whole thing to zero. This is legal
577 // because in LLVM, all default initializers (other than the ones we just
578 // handled above) are guaranteed to have a bit pattern of all zeros.
579
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000580 // FIXME: Handle variable sized types.
Chris Lattner77b89b82010-06-27 07:15:29 +0000581 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
John McCall90217182010-08-07 08:21:30 +0000582 Builder.getInt8(0),
583 SizeVal, AlignVal, /*volatile*/ Builder.getFalse());
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000584}
585
Chris Lattnerd9becd12009-10-28 23:59:40 +0000586llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
587 // Make sure that there is a block for the indirect goto.
588 if (IndirectBranch == 0)
589 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000590
John McCallff8e1152010-07-23 21:56:41 +0000591 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000592
Chris Lattnerd9becd12009-10-28 23:59:40 +0000593 // Make sure the indirect branch includes all of the address-taken blocks.
594 IndirectBranch->addDestination(BB);
595 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000596}
597
598llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000599 // If we already made the indirect branch for indirect goto, return its block.
600 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000601
Chris Lattnerd9becd12009-10-28 23:59:40 +0000602 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000603
Chris Lattnerd9becd12009-10-28 23:59:40 +0000604 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000605
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000606 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000607 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000608
Chris Lattnerd9becd12009-10-28 23:59:40 +0000609 // Create the indirect branch instruction.
610 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
611 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000612}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000613
Daniel Dunbard286f052009-07-19 06:58:07 +0000614llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000615 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Anders Carlssonf666b772008-12-20 20:27:15 +0000617 assert(SizeEntry && "Did not emit size for type");
618 return SizeEntry;
619}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000620
Daniel Dunbard286f052009-07-19 06:58:07 +0000621llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000622 assert(Ty->isVariablyModifiedType() &&
623 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Daniel Dunbard286f052009-07-19 06:58:07 +0000625 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Anders Carlsson60d35412008-12-20 20:46:34 +0000627 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000628 // unknown size indication requires no size computation.
629 if (!VAT->getSizeExpr())
630 return 0;
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000631 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000633 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000634 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000636 // Get the element size;
637 QualType ElemTy = VAT->getElementType();
638 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000639 if (ElemTy->isVariableArrayType())
640 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000641 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000642 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000643 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000645 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000646 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000648 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000649 }
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Anders Carlsson60d35412008-12-20 20:46:34 +0000651 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000652 }
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000654 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
655 EmitVLASize(AT->getElementType());
656 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000657 }
658
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000659 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
660 EmitVLASize(PT->getInnerType());
661 return 0;
662 }
663
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000664 const PointerType *PT = Ty->getAs<PointerType>();
665 assert(PT && "unknown VM type!");
666 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000667 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000668}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000669
670llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Dan Gohmanbc07a552010-10-29 22:47:07 +0000671 if (getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000672 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000673 return EmitLValue(E).getAddress();
674}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000675
John McCallf1549f62010-07-06 01:34:17 +0000676/// Pops cleanup blocks until the given savepoint is reached.
677void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
678 assert(Old.isValid());
679
John McCallff8e1152010-07-23 21:56:41 +0000680 while (EHStack.stable_begin() != Old) {
681 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
682
683 // As long as Old strictly encloses the scope's enclosing normal
684 // cleanup, we're going to emit another normal cleanup which
685 // fallthrough can propagate through.
686 bool FallThroughIsBranchThrough =
687 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
688
689 PopCleanupBlock(FallThroughIsBranchThrough);
690 }
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000691}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000692
John McCallff8e1152010-07-23 21:56:41 +0000693static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
694 EHCleanupScope &Scope) {
695 assert(Scope.isNormalCleanup());
696 llvm::BasicBlock *Entry = Scope.getNormalBlock();
697 if (!Entry) {
698 Entry = CGF.createBasicBlock("cleanup");
699 Scope.setNormalBlock(Entry);
Mike Stump99533832009-12-02 07:41:41 +0000700 }
John McCallff8e1152010-07-23 21:56:41 +0000701 return Entry;
702}
Mike Stump99533832009-12-02 07:41:41 +0000703
John McCallff8e1152010-07-23 21:56:41 +0000704static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF,
705 EHCleanupScope &Scope) {
706 assert(Scope.isEHCleanup());
707 llvm::BasicBlock *Entry = Scope.getEHBlock();
708 if (!Entry) {
709 Entry = CGF.createBasicBlock("eh.cleanup");
710 Scope.setEHBlock(Entry);
711 }
712 return Entry;
713}
Devang Patelcd9199e2010-04-13 00:08:43 +0000714
John McCallff8e1152010-07-23 21:56:41 +0000715/// Transitions the terminator of the given exit-block of a cleanup to
716/// be a cleanup switch.
717static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
718 llvm::BasicBlock *Block) {
719 // If it's a branch, turn it into a switch whose default
720 // destination is its original target.
721 llvm::TerminatorInst *Term = Block->getTerminator();
722 assert(Term && "can't transition block without terminator");
723
724 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
725 assert(Br->isUnconditional());
726 llvm::LoadInst *Load =
727 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
728 llvm::SwitchInst *Switch =
729 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
730 Br->eraseFromParent();
731 return Switch;
732 } else {
733 return cast<llvm::SwitchInst>(Term);
734 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000735}
736
John McCallf1549f62010-07-06 01:34:17 +0000737/// Attempts to reduce a cleanup's entry block to a fallthrough. This
738/// is basically llvm::MergeBlockIntoPredecessor, except
John McCallff8e1152010-07-23 21:56:41 +0000739/// simplified/optimized for the tighter constraints on cleanup blocks.
740///
741/// Returns the new block, whatever it is.
742static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
743 llvm::BasicBlock *Entry) {
John McCallf1549f62010-07-06 01:34:17 +0000744 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
John McCallff8e1152010-07-23 21:56:41 +0000745 if (!Pred) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000746
John McCallf1549f62010-07-06 01:34:17 +0000747 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
John McCallff8e1152010-07-23 21:56:41 +0000748 if (!Br || Br->isConditional()) return Entry;
John McCallf1549f62010-07-06 01:34:17 +0000749 assert(Br->getSuccessor(0) == Entry);
750
751 // If we were previously inserting at the end of the cleanup entry
752 // block, we'll need to continue inserting at the end of the
753 // predecessor.
754 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
755 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
756
757 // Kill the branch.
758 Br->eraseFromParent();
759
760 // Merge the blocks.
761 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
762
763 // Kill the entry block.
764 Entry->eraseFromParent();
765
766 if (WasInsertBlock)
767 CGF.Builder.SetInsertPoint(Pred);
Anders Carlsson87eaf172009-02-08 00:50:42 +0000768
John McCallff8e1152010-07-23 21:56:41 +0000769 return Pred;
John McCallf1549f62010-07-06 01:34:17 +0000770}
771
John McCall1f0fca52010-07-21 07:22:38 +0000772static void EmitCleanup(CodeGenFunction &CGF,
773 EHScopeStack::Cleanup *Fn,
John McCall7d8647f2010-09-14 07:57:04 +0000774 bool ForEH,
775 llvm::Value *ActiveFlag) {
776 // EH cleanups always occur within a terminate scope.
John McCallda65ea82010-07-13 20:32:21 +0000777 if (ForEH) CGF.EHStack.pushTerminate();
John McCall7d8647f2010-09-14 07:57:04 +0000778
779 // If there's an active flag, load it and skip the cleanup if it's
780 // false.
781 llvm::BasicBlock *ContBB = 0;
782 if (ActiveFlag) {
783 ContBB = CGF.createBasicBlock("cleanup.done");
784 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
785 llvm::Value *IsActive
786 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
787 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
788 CGF.EmitBlock(CleanupBB);
789 }
790
791 // Ask the cleanup to emit itself.
John McCallda65ea82010-07-13 20:32:21 +0000792 Fn->Emit(CGF, ForEH);
John McCallda65ea82010-07-13 20:32:21 +0000793 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
John McCall7d8647f2010-09-14 07:57:04 +0000794
795 // Emit the continuation block if there was an active flag.
796 if (ActiveFlag)
797 CGF.EmitBlock(ContBB);
798
799 // Leave the terminate scope.
800 if (ForEH) CGF.EHStack.popTerminate();
801}
802
803static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
804 llvm::BasicBlock *From,
805 llvm::BasicBlock *To) {
806 // Exit is the exit block of a cleanup, so it always terminates in
807 // an unconditional branch or a switch.
808 llvm::TerminatorInst *Term = Exit->getTerminator();
809
810 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
811 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
812 Br->setSuccessor(0, To);
813 } else {
814 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
815 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
816 if (Switch->getSuccessor(I) == From)
817 Switch->setSuccessor(I, To);
818 }
John McCallda65ea82010-07-13 20:32:21 +0000819}
820
John McCall1f0fca52010-07-21 07:22:38 +0000821/// Pops a cleanup block. If the block includes a normal cleanup, the
822/// current insertion point is threaded through the cleanup, as are
823/// any branch fixups on the cleanup.
John McCallff8e1152010-07-23 21:56:41 +0000824void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCall1f0fca52010-07-21 07:22:38 +0000825 assert(!EHStack.empty() && "cleanup stack is empty!");
826 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
827 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
828 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
John McCall7d8647f2010-09-14 07:57:04 +0000829
830 // Remember activation information.
831 bool IsActive = Scope.isActive();
832 llvm::Value *NormalActiveFlag =
833 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : 0;
834 llvm::Value *EHActiveFlag =
835 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : 0;
John McCallda65ea82010-07-13 20:32:21 +0000836
837 // Check whether we need an EH cleanup. This is only true if we've
838 // generated a lazy EH cleanup block.
John McCallff8e1152010-07-23 21:56:41 +0000839 bool RequiresEHCleanup = Scope.hasEHBranches();
John McCallda65ea82010-07-13 20:32:21 +0000840
841 // Check the three conditions which might require a normal cleanup:
842
843 // - whether there are branch fix-ups through this cleanup
844 unsigned FixupDepth = Scope.getFixupDepth();
John McCall1f0fca52010-07-21 07:22:38 +0000845 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
John McCallda65ea82010-07-13 20:32:21 +0000846
John McCallff8e1152010-07-23 21:56:41 +0000847 // - whether there are branch-throughs or branch-afters
848 bool HasExistingBranches = Scope.hasBranches();
John McCallda65ea82010-07-13 20:32:21 +0000849
850 // - whether there's a fallthrough
John McCall1f0fca52010-07-21 07:22:38 +0000851 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
John McCall7d8647f2010-09-14 07:57:04 +0000852 bool HasFallthrough = (FallthroughSource != 0 && IsActive);
853
John McCalle71d60d2010-10-05 20:48:15 +0000854 // Branch-through fall-throughs leave the insertion point set to the
855 // end of the last cleanup, which points to the current scope. The
856 // rest of IR gen doesn't need to worry about this; it only happens
857 // during the execution of PopCleanupBlocks().
John McCall7d8647f2010-09-14 07:57:04 +0000858 bool HasPrebranchedFallthrough =
859 (FallthroughSource && FallthroughSource->getTerminator());
John McCallda65ea82010-07-13 20:32:21 +0000860
John McCalle71d60d2010-10-05 20:48:15 +0000861 // If this is a normal cleanup, then having a prebranched
862 // fallthrough implies that the fallthrough source unconditionally
863 // jumps here.
864 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
865 (Scope.getNormalBlock() &&
866 FallthroughSource->getTerminator()->getSuccessor(0)
867 == Scope.getNormalBlock()));
868
John McCallda65ea82010-07-13 20:32:21 +0000869 bool RequiresNormalCleanup = false;
870 if (Scope.isNormalCleanup() &&
871 (HasFixups || HasExistingBranches || HasFallthrough)) {
872 RequiresNormalCleanup = true;
873 }
874
John McCall7d8647f2010-09-14 07:57:04 +0000875 // Even if we don't need the normal cleanup, we might still have
876 // prebranched fallthrough to worry about.
John McCalle71d60d2010-10-05 20:48:15 +0000877 if (Scope.isNormalCleanup() && !RequiresNormalCleanup &&
878 HasPrebranchedFallthrough) {
John McCall7d8647f2010-09-14 07:57:04 +0000879 assert(!IsActive);
880
881 llvm::BasicBlock *NormalEntry = Scope.getNormalBlock();
882
883 // If we're branching through this cleanup, just forward the
884 // prebranched fallthrough to the next cleanup, leaving the insert
885 // point in the old block.
886 if (FallthroughIsBranchThrough) {
887 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
888 llvm::BasicBlock *EnclosingEntry =
889 CreateNormalEntry(*this, cast<EHCleanupScope>(S));
890
891 ForwardPrebranchedFallthrough(FallthroughSource,
892 NormalEntry, EnclosingEntry);
893 assert(NormalEntry->use_empty() &&
894 "uses of entry remain after forwarding?");
895 delete NormalEntry;
896
897 // Otherwise, we're branching out; just emit the next block.
898 } else {
899 EmitBlock(NormalEntry);
900 SimplifyCleanupEntry(*this, NormalEntry);
901 }
902 }
903
John McCallda65ea82010-07-13 20:32:21 +0000904 // If we don't need the cleanup at all, we're done.
905 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallff8e1152010-07-23 21:56:41 +0000906 EHStack.popCleanup(); // safe because there are no fixups
John McCall1f0fca52010-07-21 07:22:38 +0000907 assert(EHStack.getNumBranchFixups() == 0 ||
908 EHStack.hasNormalCleanups());
John McCallda65ea82010-07-13 20:32:21 +0000909 return;
910 }
911
912 // Copy the cleanup emission data out. Note that SmallVector
913 // guarantees maximal alignment for its buffer regardless of its
914 // type parameter.
915 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
916 CleanupBuffer.reserve(Scope.getCleanupSize());
917 memcpy(CleanupBuffer.data(),
918 Scope.getCleanupBuffer(), Scope.getCleanupSize());
919 CleanupBuffer.set_size(Scope.getCleanupSize());
John McCall1f0fca52010-07-21 07:22:38 +0000920 EHScopeStack::Cleanup *Fn =
921 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
John McCallda65ea82010-07-13 20:32:21 +0000922
John McCallff8e1152010-07-23 21:56:41 +0000923 // We want to emit the EH cleanup after the normal cleanup, but go
924 // ahead and do the setup for the EH cleanup while the scope is still
925 // alive.
926 llvm::BasicBlock *EHEntry = 0;
927 llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend;
928 if (RequiresEHCleanup) {
929 EHEntry = CreateEHEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000930
John McCallff8e1152010-07-23 21:56:41 +0000931 // Figure out the branch-through dest if necessary.
932 llvm::BasicBlock *EHBranchThroughDest = 0;
933 if (Scope.hasEHBranchThroughs()) {
934 assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end());
935 EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup());
936 EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S));
937 }
938
939 // If we have exactly one branch-after and no branch-throughs, we
940 // can dispatch it without a switch.
John McCall7cd4b062010-07-26 22:44:58 +0000941 if (!Scope.hasEHBranchThroughs() &&
John McCallff8e1152010-07-23 21:56:41 +0000942 Scope.getNumEHBranchAfters() == 1) {
943 assert(!EHBranchThroughDest);
944
945 // TODO: remove the spurious eh.cleanup.dest stores if this edge
946 // never went through any switches.
947 llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0);
948 EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest));
949
950 // Otherwise, if we have any branch-afters, we need a switch.
951 } else if (Scope.getNumEHBranchAfters()) {
952 // The default of the switch belongs to the branch-throughs if
953 // they exist.
954 llvm::BasicBlock *Default =
955 (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock());
956
957 const unsigned SwitchCapacity = Scope.getNumEHBranchAfters();
958
959 llvm::LoadInst *Load =
960 new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest");
961 llvm::SwitchInst *Switch =
962 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
963
964 EHInstsToAppend.push_back(Load);
965 EHInstsToAppend.push_back(Switch);
966
967 for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I)
968 Switch->addCase(Scope.getEHBranchAfterIndex(I),
969 Scope.getEHBranchAfterBlock(I));
970
971 // Otherwise, we have only branch-throughs; jump to the next EH
972 // cleanup.
973 } else {
974 assert(EHBranchThroughDest);
975 EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest));
976 }
977 }
978
979 if (!RequiresNormalCleanup) {
980 EHStack.popCleanup();
981 } else {
John McCallda65ea82010-07-13 20:32:21 +0000982 // If we have a fallthrough and no other need for the cleanup,
983 // emit it directly.
John McCallff8e1152010-07-23 21:56:41 +0000984 if (HasFallthrough && !HasPrebranchedFallthrough &&
985 !HasFixups && !HasExistingBranches) {
986
987 // Fixups can cause us to optimistically create a normal block,
988 // only to later have no real uses for it. Just delete it in
989 // this case.
990 // TODO: we can potentially simplify all the uses after this.
991 if (Scope.getNormalBlock()) {
992 Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock());
993 delete Scope.getNormalBlock();
994 }
995
996 EHStack.popCleanup();
997
John McCall7d8647f2010-09-14 07:57:04 +0000998 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag);
John McCallda65ea82010-07-13 20:32:21 +0000999
1000 // Otherwise, the best approach is to thread everything through
1001 // the cleanup block and then try to clean up after ourselves.
1002 } else {
1003 // Force the entry block to exist.
John McCallff8e1152010-07-23 21:56:41 +00001004 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +00001005
John McCall7d8647f2010-09-14 07:57:04 +00001006 // I. Set up the fallthrough edge in.
1007
John McCallff8e1152010-07-23 21:56:41 +00001008 // If there's a fallthrough, we need to store the cleanup
1009 // destination index. For fall-throughs this is always zero.
John McCall7d8647f2010-09-14 07:57:04 +00001010 if (HasFallthrough) {
1011 if (!HasPrebranchedFallthrough)
1012 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
John McCallff8e1152010-07-23 21:56:41 +00001013
John McCall7d8647f2010-09-14 07:57:04 +00001014 // Otherwise, clear the IP if we don't have fallthrough because
1015 // the cleanup is inactive. We don't need to save it because
1016 // it's still just FallthroughSource.
1017 } else if (FallthroughSource) {
1018 assert(!IsActive && "source without fallthrough for active cleanup");
1019 Builder.ClearInsertionPoint();
1020 }
1021
1022 // II. Emit the entry block. This implicitly branches to it if
1023 // we have fallthrough. All the fixups and existing branches
1024 // should already be branched to it.
John McCall1f0fca52010-07-21 07:22:38 +00001025 EmitBlock(NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001026
John McCall7d8647f2010-09-14 07:57:04 +00001027 // III. Figure out where we're going and build the cleanup
1028 // epilogue.
1029
John McCallff8e1152010-07-23 21:56:41 +00001030 bool HasEnclosingCleanups =
1031 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
John McCallda65ea82010-07-13 20:32:21 +00001032
John McCallff8e1152010-07-23 21:56:41 +00001033 // Compute the branch-through dest if we need it:
1034 // - if there are branch-throughs threaded through the scope
1035 // - if fall-through is a branch-through
1036 // - if there are fixups that will be optimistically forwarded
1037 // to the enclosing cleanup
1038 llvm::BasicBlock *BranchThroughDest = 0;
1039 if (Scope.hasBranchThroughs() ||
John McCall7d8647f2010-09-14 07:57:04 +00001040 (FallthroughSource && FallthroughIsBranchThrough) ||
John McCallff8e1152010-07-23 21:56:41 +00001041 (HasFixups && HasEnclosingCleanups)) {
1042 assert(HasEnclosingCleanups);
1043 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
1044 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
John McCallda65ea82010-07-13 20:32:21 +00001045 }
1046
John McCallff8e1152010-07-23 21:56:41 +00001047 llvm::BasicBlock *FallthroughDest = 0;
1048 llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend;
1049
1050 // If there's exactly one branch-after and no other threads,
1051 // we can route it without a switch.
1052 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
1053 Scope.getNumBranchAfters() == 1) {
John McCall7d8647f2010-09-14 07:57:04 +00001054 assert(!BranchThroughDest || !IsActive);
John McCallff8e1152010-07-23 21:56:41 +00001055
1056 // TODO: clean up the possibly dead stores to the cleanup dest slot.
1057 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
1058 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
1059
1060 // Build a switch-out if we need it:
1061 // - if there are branch-afters threaded through the scope
1062 // - if fall-through is a branch-after
1063 // - if there are fixups that have nowhere left to go and
1064 // so must be immediately resolved
1065 } else if (Scope.getNumBranchAfters() ||
1066 (HasFallthrough && !FallthroughIsBranchThrough) ||
1067 (HasFixups && !HasEnclosingCleanups)) {
1068
1069 llvm::BasicBlock *Default =
1070 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
1071
1072 // TODO: base this on the number of branch-afters and fixups
1073 const unsigned SwitchCapacity = 10;
1074
1075 llvm::LoadInst *Load =
1076 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
1077 llvm::SwitchInst *Switch =
1078 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
1079
1080 InstsToAppend.push_back(Load);
1081 InstsToAppend.push_back(Switch);
1082
1083 // Branch-after fallthrough.
John McCall7d8647f2010-09-14 07:57:04 +00001084 if (FallthroughSource && !FallthroughIsBranchThrough) {
John McCallff8e1152010-07-23 21:56:41 +00001085 FallthroughDest = createBasicBlock("cleanup.cont");
John McCall7d8647f2010-09-14 07:57:04 +00001086 if (HasFallthrough)
1087 Switch->addCase(Builder.getInt32(0), FallthroughDest);
John McCallff8e1152010-07-23 21:56:41 +00001088 }
1089
1090 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
1091 Switch->addCase(Scope.getBranchAfterIndex(I),
1092 Scope.getBranchAfterBlock(I));
1093 }
1094
John McCall8abdbd82010-09-18 02:24:39 +00001095 // If there aren't any enclosing cleanups, we can resolve all
1096 // the fixups now.
John McCallff8e1152010-07-23 21:56:41 +00001097 if (HasFixups && !HasEnclosingCleanups)
John McCall8abdbd82010-09-18 02:24:39 +00001098 ResolveAllBranchFixups(*this, Switch, NormalEntry);
John McCallff8e1152010-07-23 21:56:41 +00001099 } else {
1100 // We should always have a branch-through destination in this case.
1101 assert(BranchThroughDest);
1102 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
1103 }
1104
John McCall7d8647f2010-09-14 07:57:04 +00001105 // IV. Pop the cleanup and emit it.
John McCallff8e1152010-07-23 21:56:41 +00001106 EHStack.popCleanup();
1107 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
1108
John McCall7d8647f2010-09-14 07:57:04 +00001109 EmitCleanup(*this, Fn, /*ForEH*/ false, NormalActiveFlag);
John McCallff8e1152010-07-23 21:56:41 +00001110
1111 // Append the prepared cleanup prologue from above.
1112 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
1113 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
1114 NormalExit->getInstList().push_back(InstsToAppend[I]);
1115
1116 // Optimistically hope that any fixups will continue falling through.
John McCall1f0fca52010-07-21 07:22:38 +00001117 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
John McCallff8e1152010-07-23 21:56:41 +00001118 I < E; ++I) {
1119 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
1120 if (!Fixup.Destination) continue;
1121 if (!Fixup.OptimisticBranchBlock) {
1122 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
1123 getNormalCleanupDestSlot(),
1124 Fixup.InitialBranch);
1125 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
1126 }
1127 Fixup.OptimisticBranchBlock = NormalExit;
1128 }
John McCall7d8647f2010-09-14 07:57:04 +00001129
1130 // V. Set up the fallthrough edge out.
John McCallff8e1152010-07-23 21:56:41 +00001131
John McCall7d8647f2010-09-14 07:57:04 +00001132 // Case 1: a fallthrough source exists but shouldn't branch to
1133 // the cleanup because the cleanup is inactive.
1134 if (!HasFallthrough && FallthroughSource) {
1135 assert(!IsActive);
1136
1137 // If we have a prebranched fallthrough, that needs to be
1138 // forwarded to the right block.
1139 if (HasPrebranchedFallthrough) {
1140 llvm::BasicBlock *Next;
1141 if (FallthroughIsBranchThrough) {
1142 Next = BranchThroughDest;
1143 assert(!FallthroughDest);
1144 } else {
1145 Next = FallthroughDest;
1146 }
1147
1148 ForwardPrebranchedFallthrough(FallthroughSource, NormalEntry, Next);
1149 }
1150 Builder.SetInsertPoint(FallthroughSource);
1151
1152 // Case 2: a fallthrough source exists and should branch to the
1153 // cleanup, but we're not supposed to branch through to the next
1154 // cleanup.
1155 } else if (HasFallthrough && FallthroughDest) {
1156 assert(!FallthroughIsBranchThrough);
John McCallff8e1152010-07-23 21:56:41 +00001157 EmitBlock(FallthroughDest);
John McCall7d8647f2010-09-14 07:57:04 +00001158
1159 // Case 3: a fallthrough source exists and should branch to the
1160 // cleanup and then through to the next.
1161 } else if (HasFallthrough) {
1162 // Everything is already set up for this.
1163
1164 // Case 4: no fallthrough source exists.
1165 } else {
John McCallff8e1152010-07-23 21:56:41 +00001166 Builder.ClearInsertionPoint();
John McCall7d8647f2010-09-14 07:57:04 +00001167 }
1168
1169 // VI. Assorted cleaning.
John McCallda65ea82010-07-13 20:32:21 +00001170
John McCallff8e1152010-07-23 21:56:41 +00001171 // Check whether we can merge NormalEntry into a single predecessor.
1172 // This might invalidate (non-IR) pointers to NormalEntry.
1173 llvm::BasicBlock *NewNormalEntry =
1174 SimplifyCleanupEntry(*this, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001175
John McCallff8e1152010-07-23 21:56:41 +00001176 // If it did invalidate those pointers, and NormalEntry was the same
1177 // as NormalExit, go back and patch up the fixups.
1178 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1179 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1180 I < E; ++I)
1181 CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCallda65ea82010-07-13 20:32:21 +00001182 }
1183 }
1184
John McCallff8e1152010-07-23 21:56:41 +00001185 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1186
John McCallda65ea82010-07-13 20:32:21 +00001187 // Emit the EH cleanup if required.
1188 if (RequiresEHCleanup) {
John McCall1f0fca52010-07-21 07:22:38 +00001189 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallff8e1152010-07-23 21:56:41 +00001190
John McCall1f0fca52010-07-21 07:22:38 +00001191 EmitBlock(EHEntry);
John McCall7d8647f2010-09-14 07:57:04 +00001192 EmitCleanup(*this, Fn, /*ForEH*/ true, EHActiveFlag);
John McCallff8e1152010-07-23 21:56:41 +00001193
1194 // Append the prepared cleanup prologue from above.
1195 llvm::BasicBlock *EHExit = Builder.GetInsertBlock();
1196 for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I)
1197 EHExit->getInstList().push_back(EHInstsToAppend[I]);
1198
John McCall1f0fca52010-07-21 07:22:38 +00001199 Builder.restoreIP(SavedIP);
John McCallff8e1152010-07-23 21:56:41 +00001200
1201 SimplifyCleanupEntry(*this, EHEntry);
John McCallda65ea82010-07-13 20:32:21 +00001202 }
1203}
1204
John McCallff8e1152010-07-23 21:56:41 +00001205/// Terminate the current block by emitting a branch which might leave
1206/// the current cleanup-protected scope. The target scope may not yet
1207/// be known, in which case this will require a fixup.
1208///
1209/// As a side-effect, this method clears the insertion point.
John McCallf1549f62010-07-06 01:34:17 +00001210void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall413e6772010-07-28 01:07:35 +00001211 assert(Dest.getScopeDepth().encloses(EHStack.getInnermostNormalCleanup())
1212 && "stale jump destination");
1213
Anders Carlsson46831a92009-02-08 22:13:37 +00001214 if (!HaveInsertPoint())
1215 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
John McCallf1549f62010-07-06 01:34:17 +00001217 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001218 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001219
John McCall838d7962010-08-14 07:46:19 +00001220 // Calculate the innermost active normal cleanup.
1221 EHScopeStack::stable_iterator
1222 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1223
1224 // If we're not in an active normal cleanup scope, or if the
1225 // destination scope is within the innermost active normal cleanup
1226 // scope, we don't need to worry about fixups.
1227 if (TopCleanup == EHStack.stable_end() ||
1228 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
John McCallf1549f62010-07-06 01:34:17 +00001229 Builder.ClearInsertionPoint();
1230 return;
1231 }
1232
John McCallf1549f62010-07-06 01:34:17 +00001233 // If we can't resolve the destination cleanup scope, just add this
John McCallff8e1152010-07-23 21:56:41 +00001234 // to the current cleanup scope as a branch fixup.
1235 if (!Dest.getScopeDepth().isValid()) {
1236 BranchFixup &Fixup = EHStack.addBranchFixup();
1237 Fixup.Destination = Dest.getBlock();
1238 Fixup.DestinationIndex = Dest.getDestIndex();
1239 Fixup.InitialBranch = BI;
1240 Fixup.OptimisticBranchBlock = 0;
1241
John McCallf1549f62010-07-06 01:34:17 +00001242 Builder.ClearInsertionPoint();
1243 return;
1244 }
1245
John McCallff8e1152010-07-23 21:56:41 +00001246 // Otherwise, thread through all the normal cleanups in scope.
1247
1248 // Store the index at the start.
1249 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1250 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
1251
1252 // Adjust BI to point to the first cleanup block.
1253 {
1254 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001255 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001256 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1257 }
1258
1259 // Add this destination to all the scopes involved.
John McCall838d7962010-08-14 07:46:19 +00001260 EHScopeStack::stable_iterator I = TopCleanup;
John McCallff8e1152010-07-23 21:56:41 +00001261 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1262 if (E.strictlyEncloses(I)) {
1263 while (true) {
1264 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1265 assert(Scope.isNormalCleanup());
1266 I = Scope.getEnclosingNormalCleanup();
1267
1268 // If this is the last cleanup we're propagating through, tell it
1269 // that there's a resolved jump moving through it.
1270 if (!E.strictlyEncloses(I)) {
1271 Scope.addBranchAfter(Index, Dest.getBlock());
1272 break;
John McCallda65ea82010-07-13 20:32:21 +00001273 }
John McCallff8e1152010-07-23 21:56:41 +00001274
1275 // Otherwise, tell the scope that there's a jump propoagating
1276 // through it. If this isn't new information, all the rest of
1277 // the work has been done before.
1278 if (!Scope.addBranchThrough(Dest.getBlock()))
1279 break;
John McCallf1549f62010-07-06 01:34:17 +00001280 }
1281 }
1282
Anders Carlsson46831a92009-02-08 22:13:37 +00001283 Builder.ClearInsertionPoint();
John McCallf1549f62010-07-06 01:34:17 +00001284}
Mike Stump1eb44332009-09-09 15:08:12 +00001285
John McCallff8e1152010-07-23 21:56:41 +00001286void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) {
1287 // We should never get invalid scope depths for an UnwindDest; that
1288 // implies that the destination wasn't set up correctly.
1289 assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?");
1290
John McCallf1549f62010-07-06 01:34:17 +00001291 if (!HaveInsertPoint())
Anders Carlsson87eaf172009-02-08 00:50:42 +00001292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCallf1549f62010-07-06 01:34:17 +00001294 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001295 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001296
John McCall838d7962010-08-14 07:46:19 +00001297 // Calculate the innermost active cleanup.
1298 EHScopeStack::stable_iterator
1299 InnermostCleanup = EHStack.getInnermostActiveEHCleanup();
1300
John McCallff8e1152010-07-23 21:56:41 +00001301 // If the destination is in the same EH cleanup scope as us, we
1302 // don't need to thread through anything.
John McCall838d7962010-08-14 07:46:19 +00001303 if (InnermostCleanup.encloses(Dest.getScopeDepth())) {
John McCallf1549f62010-07-06 01:34:17 +00001304 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001305 return;
1306 }
John McCall838d7962010-08-14 07:46:19 +00001307 assert(InnermostCleanup != EHStack.stable_end());
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCallff8e1152010-07-23 21:56:41 +00001309 // Store the index at the start.
1310 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1311 new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI);
John McCallf1549f62010-07-06 01:34:17 +00001312
John McCallff8e1152010-07-23 21:56:41 +00001313 // Adjust BI to point to the first cleanup block.
1314 {
1315 EHCleanupScope &Scope =
John McCall838d7962010-08-14 07:46:19 +00001316 cast<EHCleanupScope>(*EHStack.find(InnermostCleanup));
John McCallff8e1152010-07-23 21:56:41 +00001317 BI->setSuccessor(0, CreateEHEntry(*this, Scope));
1318 }
1319
1320 // Add this destination to all the scopes involved.
1321 for (EHScopeStack::stable_iterator
John McCall838d7962010-08-14 07:46:19 +00001322 I = InnermostCleanup, E = Dest.getScopeDepth(); ; ) {
John McCallff8e1152010-07-23 21:56:41 +00001323 assert(E.strictlyEncloses(I));
1324 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1325 assert(Scope.isEHCleanup());
1326 I = Scope.getEnclosingEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +00001327
John McCallff8e1152010-07-23 21:56:41 +00001328 // If this is the last cleanup we're propagating through, add this
1329 // as a branch-after.
1330 if (I == E) {
1331 Scope.addEHBranchAfter(Index, Dest.getBlock());
1332 break;
John McCallf1549f62010-07-06 01:34:17 +00001333 }
John McCallff8e1152010-07-23 21:56:41 +00001334
1335 // Otherwise, add it as a branch-through. If this isn't new
1336 // information, all the rest of the work has been done before.
1337 if (!Scope.addEHBranchThrough(Dest.getBlock()))
1338 break;
Anders Carlsson87eaf172009-02-08 00:50:42 +00001339 }
John McCallf1549f62010-07-06 01:34:17 +00001340
1341 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001342}
John McCallff8e1152010-07-23 21:56:41 +00001343
1344/// All the branch fixups on the EH stack have propagated out past the
1345/// outermost normal cleanup; resolve them all by adding cases to the
1346/// given switch instruction.
John McCall8abdbd82010-09-18 02:24:39 +00001347static void ResolveAllBranchFixups(CodeGenFunction &CGF,
1348 llvm::SwitchInst *Switch,
1349 llvm::BasicBlock *CleanupEntry) {
John McCallff8e1152010-07-23 21:56:41 +00001350 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
1351
John McCall8abdbd82010-09-18 02:24:39 +00001352 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
John McCall0680e972010-10-05 02:33:56 +00001353 // Skip this fixup if its destination isn't set.
John McCall8abdbd82010-09-18 02:24:39 +00001354 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
John McCallff8e1152010-07-23 21:56:41 +00001355 if (Fixup.Destination == 0) continue;
John McCallff8e1152010-07-23 21:56:41 +00001356
John McCall8abdbd82010-09-18 02:24:39 +00001357 // If there isn't an OptimisticBranchBlock, then InitialBranch is
1358 // still pointing directly to its destination; forward it to the
1359 // appropriate cleanup entry. This is required in the specific
1360 // case of
1361 // { std::string s; goto lbl; }
1362 // lbl:
1363 // i.e. where there's an unresolved fixup inside a single cleanup
1364 // entry which we're currently popping.
1365 if (Fixup.OptimisticBranchBlock == 0) {
1366 new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex),
1367 CGF.getNormalCleanupDestSlot(),
1368 Fixup.InitialBranch);
1369 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
1370 }
1371
John McCall0680e972010-10-05 02:33:56 +00001372 // Don't add this case to the switch statement twice.
1373 if (!CasesAdded.insert(Fixup.Destination)) continue;
1374
John McCall8abdbd82010-09-18 02:24:39 +00001375 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
John McCallff8e1152010-07-23 21:56:41 +00001376 Fixup.Destination);
1377 }
1378
John McCall8abdbd82010-09-18 02:24:39 +00001379 CGF.EHStack.clearFixups();
John McCallff8e1152010-07-23 21:56:41 +00001380}
1381
1382void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
1383 assert(Block && "resolving a null target block");
1384 if (!EHStack.getNumBranchFixups()) return;
1385
1386 assert(EHStack.hasNormalCleanups() &&
1387 "branch fixups exist with no normal cleanups on stack");
1388
1389 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
1390 bool ResolvedAny = false;
1391
1392 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1393 // Skip this fixup if its destination doesn't match.
1394 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1395 if (Fixup.Destination != Block) continue;
1396
1397 Fixup.Destination = 0;
1398 ResolvedAny = true;
1399
1400 // If it doesn't have an optimistic branch block, LatestBranch is
1401 // already pointing to the right place.
1402 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
1403 if (!BranchBB)
1404 continue;
1405
1406 // Don't process the same optimistic branch block twice.
1407 if (!ModifiedOptimisticBlocks.insert(BranchBB))
1408 continue;
1409
1410 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
1411
1412 // Add a case to the switch.
1413 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
1414 }
1415
1416 if (ResolvedAny)
1417 EHStack.popNullFixups();
1418}
1419
John McCall7d8647f2010-09-14 07:57:04 +00001420static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1421 EHScopeStack::stable_iterator C) {
1422 // If we needed a normal block for any reason, that counts.
1423 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1424 return true;
1425
1426 // Check whether any enclosed cleanups were needed.
1427 for (EHScopeStack::stable_iterator
1428 I = EHStack.getInnermostNormalCleanup();
1429 I != C; ) {
1430 assert(C.strictlyEncloses(I));
1431 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1432 if (S.getNormalBlock()) return true;
1433 I = S.getEnclosingNormalCleanup();
1434 }
1435
1436 return false;
1437}
1438
1439static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1440 EHScopeStack::stable_iterator C) {
1441 // If we needed an EH block for any reason, that counts.
1442 if (cast<EHCleanupScope>(*EHStack.find(C)).getEHBlock())
1443 return true;
1444
1445 // Check whether any enclosed cleanups were needed.
1446 for (EHScopeStack::stable_iterator
1447 I = EHStack.getInnermostEHCleanup(); I != C; ) {
1448 assert(C.strictlyEncloses(I));
1449 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1450 if (S.getEHBlock()) return true;
1451 I = S.getEnclosingEHCleanup();
1452 }
1453
1454 return false;
1455}
1456
1457enum ForActivation_t {
1458 ForActivation,
1459 ForDeactivation
1460};
1461
1462/// The given cleanup block is changing activation state. Configure a
1463/// cleanup variable if necessary.
1464///
1465/// It would be good if we had some way of determining if there were
1466/// extra uses *after* the change-over point.
1467static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1468 EHScopeStack::stable_iterator C,
1469 ForActivation_t Kind) {
1470 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
John McCall7d8647f2010-09-14 07:57:04 +00001471
John McCall3019c442010-09-17 00:50:28 +00001472 // We always need the flag if we're activating the cleanup, because
1473 // we have to assume that the current location doesn't necessarily
1474 // dominate all future uses of the cleanup.
1475 bool NeedFlag = (Kind == ForActivation);
John McCall7d8647f2010-09-14 07:57:04 +00001476
1477 // Calculate whether the cleanup was used:
1478
1479 // - as a normal cleanup
1480 if (Scope.isNormalCleanup() && IsUsedAsNormalCleanup(CGF.EHStack, C)) {
1481 Scope.setTestFlagInNormalCleanup();
1482 NeedFlag = true;
1483 }
1484
1485 // - as an EH cleanup
1486 if (Scope.isEHCleanup() && IsUsedAsEHCleanup(CGF.EHStack, C)) {
1487 Scope.setTestFlagInEHCleanup();
1488 NeedFlag = true;
1489 }
1490
1491 // If it hasn't yet been used as either, we're done.
1492 if (!NeedFlag) return;
1493
John McCall3019c442010-09-17 00:50:28 +00001494 llvm::AllocaInst *Var = Scope.getActiveFlag();
1495 if (!Var) {
1496 Var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive");
1497 Scope.setActiveFlag(Var);
John McCall7d8647f2010-09-14 07:57:04 +00001498
John McCall3019c442010-09-17 00:50:28 +00001499 // Initialize to true or false depending on whether it was
1500 // active up to this point.
1501 CGF.InitTempAlloca(Var, CGF.Builder.getInt1(Kind == ForDeactivation));
John McCall7d8647f2010-09-14 07:57:04 +00001502 }
John McCall3019c442010-09-17 00:50:28 +00001503
1504 CGF.Builder.CreateStore(CGF.Builder.getInt1(Kind == ForActivation), Var);
John McCall7d8647f2010-09-14 07:57:04 +00001505}
1506
John McCallcd2d2b72010-08-13 21:20:51 +00001507/// Activate a cleanup that was created in an inactivated state.
John McCall7d8647f2010-09-14 07:57:04 +00001508void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C) {
John McCallcd2d2b72010-08-13 21:20:51 +00001509 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1510 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1511 assert(!Scope.isActive() && "double activation");
1512
John McCall7d8647f2010-09-14 07:57:04 +00001513 SetupCleanupBlockActivation(*this, C, ForActivation);
John McCallcd2d2b72010-08-13 21:20:51 +00001514
John McCall7d8647f2010-09-14 07:57:04 +00001515 Scope.setActive(true);
1516}
John McCallcd2d2b72010-08-13 21:20:51 +00001517
John McCall7d8647f2010-09-14 07:57:04 +00001518/// Deactive a cleanup that was created in an active state.
1519void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C) {
1520 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1521 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
John McCall3019c442010-09-17 00:50:28 +00001522 assert(Scope.isActive() && "double deactivation");
John McCall7d8647f2010-09-14 07:57:04 +00001523
1524 // If it's the top of the stack, just pop it.
1525 if (C == EHStack.stable_begin()) {
1526 // If it's a normal cleanup, we need to pretend that the
1527 // fallthrough is unreachable.
1528 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1529 PopCleanupBlock();
1530 Builder.restoreIP(SavedIP);
1531 return;
John McCallcd2d2b72010-08-13 21:20:51 +00001532 }
1533
John McCall7d8647f2010-09-14 07:57:04 +00001534 // Otherwise, follow the general case.
1535 SetupCleanupBlockActivation(*this, C, ForDeactivation);
John McCallcd2d2b72010-08-13 21:20:51 +00001536
John McCall7d8647f2010-09-14 07:57:04 +00001537 Scope.setActive(false);
John McCallcd2d2b72010-08-13 21:20:51 +00001538}
1539
John McCallff8e1152010-07-23 21:56:41 +00001540llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1541 if (!NormalCleanupDest)
1542 NormalCleanupDest =
1543 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1544 return NormalCleanupDest;
1545}
1546
1547llvm::Value *CodeGenFunction::getEHCleanupDestSlot() {
1548 if (!EHCleanupDest)
1549 EHCleanupDest =
1550 CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot");
1551 return EHCleanupDest;
1552}
Devang Patel8d308382010-08-10 07:24:25 +00001553
1554void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
John McCall189d6ef2010-10-09 01:34:31 +00001555 llvm::Constant *Init) {
Devang Patel25c2c8f2010-08-10 17:53:33 +00001556 assert (Init && "Invalid DeclRefExpr initializer!");
1557 if (CGDebugInfo *Dbg = getDebugInfo())
Devang Pateld2829b72010-10-06 15:58:57 +00001558 Dbg->EmitGlobalVariable(E->getDecl(), Init);
Devang Patel8d308382010-08-10 07:24:25 +00001559}