blob: 9375b77360cc7c1e8b6b1c3f0dc161e16ce60f5a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000017#include "CGException.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000019#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000022#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000023#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000024#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000025#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000026#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace CodeGen;
29
Mike Stump1eb44332009-09-09 15:08:12 +000030CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000031 : BlockFunction(cgm, *this, Builder), CGM(cgm),
32 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000033 Builder(cgm.getModule().getContext()),
John McCallf1549f62010-07-06 01:34:17 +000034 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000035 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
John McCallf1549f62010-07-06 01:34:17 +000036 DidCallStackSave(false), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000037 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCallf1549f62010-07-06 01:34:17 +000038 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
39 TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000040
41 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000042 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000043 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
44 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
45 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
46 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
47
Mike Stumpd88ea562009-12-09 03:35:49 +000048 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000049 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Douglas Gregor35415f52010-05-25 17:04:15 +000050 CGM.getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000051}
Reid Spencer5f016e22007-07-11 17:01:13 +000052
53ASTContext &CodeGenFunction::getContext() const {
54 return CGM.getContext();
55}
56
57
Daniel Dunbar0096acf2009-02-25 19:24:29 +000058llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
59 llvm::Value *Res = LocalDeclMap[VD];
60 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
61 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000062}
Reid Spencer5f016e22007-07-11 17:01:13 +000063
Daniel Dunbar0096acf2009-02-25 19:24:29 +000064llvm::Constant *
65CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
66 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000067}
68
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000069const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
70 return CGM.getTypes().ConvertTypeForMem(T);
71}
72
Reid Spencer5f016e22007-07-11 17:01:13 +000073const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
74 return CGM.getTypes().ConvertType(T);
75}
76
77bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000078 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
79 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000080}
81
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000082void CodeGenFunction::EmitReturnBlock() {
83 // For cleanliness, we try to avoid emitting the return block for
84 // simple cases.
85 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
86
87 if (CurBB) {
88 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
89
Daniel Dunbar96e18b02009-07-19 08:24:34 +000090 // We have a valid insert point, reuse it if it is empty or there are no
91 // explicit jumps to the return block.
John McCallf1549f62010-07-06 01:34:17 +000092 if (CurBB->empty() || ReturnBlock.Block->use_empty()) {
93 ReturnBlock.Block->replaceAllUsesWith(CurBB);
94 delete ReturnBlock.Block;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000095 } else
John McCallf1549f62010-07-06 01:34:17 +000096 EmitBlock(ReturnBlock.Block);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000097 return;
98 }
99
100 // Otherwise, if the return block is the target of a single direct
101 // branch then we can just put the code in that block instead. This
102 // cleans up functions which started with a unified return block.
John McCallf1549f62010-07-06 01:34:17 +0000103 if (ReturnBlock.Block->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000104 llvm::BranchInst *BI =
John McCallf1549f62010-07-06 01:34:17 +0000105 dyn_cast<llvm::BranchInst>(*ReturnBlock.Block->use_begin());
106 if (BI && BI->isUnconditional() &&
107 BI->getSuccessor(0) == ReturnBlock.Block) {
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000108 // Reset insertion point and delete the branch.
109 Builder.SetInsertPoint(BI->getParent());
110 BI->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000111 delete ReturnBlock.Block;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000112 return;
113 }
114 }
115
Mike Stumpf5408fe2009-05-16 07:57:57 +0000116 // FIXME: We are at an unreachable point, there is no reason to emit the block
117 // unless it has uses. However, we still need a place to put the debug
118 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000119
John McCallf1549f62010-07-06 01:34:17 +0000120 EmitBlock(ReturnBlock.Block);
121}
122
123static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
124 if (!BB) return;
125 if (!BB->use_empty())
126 return CGF.CurFn->getBasicBlockList().push_back(BB);
127 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000128}
129
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000130void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000131 assert(BreakContinueStack.empty() &&
132 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000133
134 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000135 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000136
Chris Lattner7255a2d2010-06-22 00:03:40 +0000137 EmitFunctionInstrumentation("__cyg_profile_func_exit");
138
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000139 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000140 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000141 DI->setLocation(EndLoc);
142 DI->EmitRegionEnd(CurFn, Builder);
143 }
144
Chris Lattner35b21b82010-06-27 01:06:27 +0000145 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000146 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000147
John McCallf1549f62010-07-06 01:34:17 +0000148 assert(EHStack.empty() &&
149 "did not remove all scopes from cleanup stack!");
150
Chris Lattnerd9becd12009-10-28 23:59:40 +0000151 // If someone did an indirect goto, emit the indirect goto block at the end of
152 // the function.
153 if (IndirectBranch) {
154 EmitBlock(IndirectBranch->getParent());
155 Builder.ClearInsertionPoint();
156 }
157
Chris Lattner5a2fa142007-12-02 06:32:24 +0000158 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000159 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000160 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000161 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000162
163 // If someone took the address of a label but never did an indirect goto, we
164 // made a zero entry PHI node, which is illegal, zap it now.
165 if (IndirectBranch) {
166 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
167 if (PN->getNumIncomingValues() == 0) {
168 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
169 PN->eraseFromParent();
170 }
171 }
John McCallf1549f62010-07-06 01:34:17 +0000172
173 EmitIfUsed(*this, TerminateLandingPad);
174 EmitIfUsed(*this, TerminateHandler);
175 EmitIfUsed(*this, UnreachableBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
Chris Lattner7255a2d2010-06-22 00:03:40 +0000178/// ShouldInstrumentFunction - Return true if the current function should be
179/// instrumented with __cyg_profile_func_* calls
180bool CodeGenFunction::ShouldInstrumentFunction() {
181 if (!CGM.getCodeGenOpts().InstrumentFunctions)
182 return false;
183 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
184 return false;
185 return true;
186}
187
188/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
189/// instrumentation function with the current function and the call site, if
190/// function instrumentation is enabled.
191void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
192 if (!ShouldInstrumentFunction())
193 return;
194
Chris Lattner8dab6572010-06-23 05:21:28 +0000195 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000196 const llvm::FunctionType *FunctionTy;
197 std::vector<const llvm::Type*> ProfileFuncArgs;
198
Chris Lattner8dab6572010-06-23 05:21:28 +0000199 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
200 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
201 ProfileFuncArgs.push_back(PointerTy);
202 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000203 FunctionTy = llvm::FunctionType::get(
204 llvm::Type::getVoidTy(VMContext),
205 ProfileFuncArgs, false);
206
207 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
208 llvm::CallInst *CallSite = Builder.CreateCall(
209 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000210 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000211 "callsite");
212
Chris Lattner8dab6572010-06-23 05:21:28 +0000213 Builder.CreateCall2(F,
214 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
215 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000216}
217
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000218void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000219 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000220 const FunctionArgList &Args,
221 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000222 const Decl *D = GD.getDecl();
223
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000224 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000225 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000226 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000227 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000228 assert(CurFn->isDeclaration() && "Function already has body?");
229
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000230 // Pass inline keyword to optimizer if it appears explicitly on any
231 // declaration.
232 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
233 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
234 RE = FD->redecls_end(); RI != RE; ++RI)
235 if (RI->isInlineSpecified()) {
236 Fn->addFnAttr(llvm::Attribute::InlineHint);
237 break;
238 }
239
Daniel Dunbar55e87422008-11-11 02:29:29 +0000240 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000241
Chris Lattner41110242008-06-17 18:05:57 +0000242 // Create a marker to make it easy to insert allocas into the entryblock
243 // later. Don't create this with the builder, because we don't want it
244 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000245 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
246 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000247 if (Builder.isNamePreserving())
248 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000249
John McCallf1549f62010-07-06 01:34:17 +0000250 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattner41110242008-06-17 18:05:57 +0000252 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Douglas Gregorce056bc2010-02-21 22:15:06 +0000254 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
255 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000256 /*FIXME?*/
257 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000258
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000259 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000260 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000261 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000262 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000263 }
264
Chris Lattner7255a2d2010-06-22 00:03:40 +0000265 EmitFunctionInstrumentation("__cyg_profile_func_enter");
266
Daniel Dunbar88b53962009-02-02 22:03:45 +0000267 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000268 // CC info is ignored, hopefully?
269 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000270 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000271
272 if (RetTy->isVoidType()) {
273 // Void type; nothing to return.
274 ReturnValue = 0;
275 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
276 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
277 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000278 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000279 ReturnValue = CurFn->arg_begin();
280 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000281 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000282 }
283
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000284 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000285 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
John McCall25049412010-02-16 22:04:33 +0000287 if (CXXThisDecl)
288 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
289 if (CXXVTTDecl)
290 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
291
Anders Carlsson751358f2008-12-20 21:28:43 +0000292 // If any of the arguments have a variably modified type, make sure to
293 // emit the type size.
294 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
295 i != e; ++i) {
296 QualType Ty = i->second;
297
298 if (Ty->isVariablyModifiedType())
299 EmitVLASize(Ty);
300 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000301}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000302
John McCall9fc6a772010-02-19 09:25:03 +0000303void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
304 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000305 assert(FD->getBody());
306 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000307}
308
Anders Carlssonc997d422010-01-02 01:01:18 +0000309void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000310 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
311
Anders Carlssone896d982009-02-13 08:11:52 +0000312 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000313 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000314 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Daniel Dunbar7c086512008-09-09 23:14:03 +0000316 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000318 CurGD = GD;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000319 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
320 if (MD->isInstance()) {
321 // Create the implicit 'this' decl.
322 // FIXME: I'm not entirely sure I like using a fake decl just for code
323 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000324 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
325 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000326 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000327 MD->getThisType(getContext()));
328 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000329
330 // Check if we need a VTT parameter as well.
Anders Carlssonaf440352010-03-23 04:11:45 +0000331 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000332 // FIXME: The comment about using a fake decl above applies here too.
333 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
334 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000335 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000336 &getContext().Idents.get("vtt"), T);
337 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
338 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000339 }
340 }
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000342 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000343 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000344 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000345
346 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000347 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000348 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000349 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000350
John McCalla355e072010-02-18 03:17:58 +0000351 SourceRange BodyRange;
352 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000353
John McCalla355e072010-02-18 03:17:58 +0000354 // Emit the standard function prologue.
355 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000356
John McCalla355e072010-02-18 03:17:58 +0000357 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000358 if (isa<CXXDestructorDecl>(FD))
359 EmitDestructorBody(Args);
360 else if (isa<CXXConstructorDecl>(FD))
361 EmitConstructorBody(Args);
362 else
363 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000364
John McCalla355e072010-02-18 03:17:58 +0000365 // Emit the standard function epilogue.
366 FinishFunction(BodyRange.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000368 // Destroy the 'this' declaration.
369 if (CXXThisDecl)
370 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000371
372 // Destroy the VTT declaration.
373 if (CXXVTTDecl)
374 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000375}
376
Chris Lattner0946ccd2008-11-11 07:41:27 +0000377/// ContainsLabel - Return true if the statement contains a label in it. If
378/// this statement is not executed normally, it not containing a label means
379/// that we can just remove the code.
380bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
381 // Null statement, not a label!
382 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattner0946ccd2008-11-11 07:41:27 +0000384 // If this is a label, we have to emit the code, consider something like:
385 // if (0) { ... foo: bar(); } goto foo;
386 if (isa<LabelStmt>(S))
387 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattner0946ccd2008-11-11 07:41:27 +0000389 // If this is a case/default statement, and we haven't seen a switch, we have
390 // to emit the code.
391 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
392 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Chris Lattner0946ccd2008-11-11 07:41:27 +0000394 // If this is a switch statement, we want to ignore cases below it.
395 if (isa<SwitchStmt>(S))
396 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner0946ccd2008-11-11 07:41:27 +0000398 // Scan subexpressions for verboten labels.
399 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
400 I != E; ++I)
401 if (ContainsLabel(*I, IgnoreCaseStmts))
402 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner0946ccd2008-11-11 07:41:27 +0000404 return false;
405}
406
Chris Lattner31a09842008-11-12 08:04:58 +0000407
408/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
409/// a constant, or if it does but contains a label, return 0. If it constant
410/// folds to 'true' and does not contain a label, return 1, if it constant folds
411/// to 'false' and does not contain a label, return -1.
412int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000413 // FIXME: Rename and handle conversion of other evaluatable things
414 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000415 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000416 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000417 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000418 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner31a09842008-11-12 08:04:58 +0000420 if (CodeGenFunction::ContainsLabel(Cond))
421 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Anders Carlsson64712f12008-12-01 02:46:24 +0000423 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000424}
425
426
427/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
428/// statement) to the specified blocks. Based on the condition, this might try
429/// to simplify the codegen of the conditional based on the branch.
430///
431void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
432 llvm::BasicBlock *TrueBlock,
433 llvm::BasicBlock *FalseBlock) {
434 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
435 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattner31a09842008-11-12 08:04:58 +0000437 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
438 // Handle X && Y in a condition.
439 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
440 // If we have "1 && X", simplify the code. "0 && X" would have constant
441 // folded if the case was simple enough.
442 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
443 // br(1 && X) -> br(X).
444 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner31a09842008-11-12 08:04:58 +0000447 // If we have "X && 1", simplify the code to use an uncond branch.
448 // "X && 0" would have been constant folded to 0.
449 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
450 // br(X && 1) -> br(X).
451 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
452 }
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Chris Lattner31a09842008-11-12 08:04:58 +0000454 // Emit the LHS as a conditional. If the LHS conditional is false, we
455 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000456 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000457 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
458 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Anders Carlsson08e9e452010-01-24 00:20:05 +0000460 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000461 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000462 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000463 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000464
Chris Lattner31a09842008-11-12 08:04:58 +0000465 return;
466 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
467 // If we have "0 || X", simplify the code. "1 || X" would have constant
468 // folded if the case was simple enough.
469 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
470 // br(0 || X) -> br(X).
471 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner31a09842008-11-12 08:04:58 +0000474 // If we have "X || 0", simplify the code to use an uncond branch.
475 // "X || 1" would have been constant folded to 1.
476 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
477 // br(X || 0) -> br(X).
478 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattner31a09842008-11-12 08:04:58 +0000481 // Emit the LHS as a conditional. If the LHS conditional is true, we
482 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000483 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000484 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
485 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Anders Carlsson08e9e452010-01-24 00:20:05 +0000487 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000488 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000489 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000490 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000491
Chris Lattner31a09842008-11-12 08:04:58 +0000492 return;
493 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner552f4c42008-11-12 08:13:36 +0000496 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
497 // br(!x, t, f) -> br(x, f, t)
498 if (CondUOp->getOpcode() == UnaryOperator::LNot)
499 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000500 }
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Daniel Dunbar09b14892008-11-12 10:30:32 +0000502 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
503 // Handle ?: operator.
504
505 // Just ignore GNU ?: extension.
506 if (CondOp->getLHS()) {
507 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
508 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
509 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
510 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
511 EmitBlock(LHSBlock);
512 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
513 EmitBlock(RHSBlock);
514 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
515 return;
516 }
517 }
518
Chris Lattner31a09842008-11-12 08:04:58 +0000519 // Emit the code with the fully general case.
520 llvm::Value *CondV = EvaluateExprAsBool(Cond);
521 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
522}
523
Daniel Dunbar488e9932008-08-16 00:56:44 +0000524/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000525/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000526void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
527 bool OmitOnError) {
528 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000529}
530
Anders Carlsson1884eb02010-05-22 17:35:42 +0000531void
532CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
533 // If the type contains a pointer to data member we can't memset it to zero.
534 // Instead, create a null constant and copy it to the destination.
535 if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
536 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
537
538 llvm::GlobalVariable *NullVariable =
539 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
540 /*isConstant=*/true,
541 llvm::GlobalVariable::PrivateLinkage,
542 NullConstant, llvm::Twine());
543 EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
544 return;
545 }
546
547
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000548 // Ignore empty classes in C++.
549 if (getContext().getLangOptions().CPlusPlus) {
550 if (const RecordType *RT = Ty->getAs<RecordType>()) {
551 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
552 return;
553 }
554 }
555
Anders Carlsson1884eb02010-05-22 17:35:42 +0000556 // Otherwise, just memset the whole thing to zero. This is legal
557 // because in LLVM, all default initializers (other than the ones we just
558 // handled above) are guaranteed to have a bit pattern of all zeros.
Chris Lattner36afd382009-10-13 06:02:42 +0000559 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000560 if (DestPtr->getType() != BP)
561 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
562
563 // Get size and alignment info for this aggregate.
564 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
565
Chris Lattner88207c92009-04-21 17:59:23 +0000566 // Don't bother emitting a zero-byte memset.
567 if (TypeInfo.first == 0)
568 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000570 // FIXME: Handle variable sized types.
Chris Lattner77b89b82010-06-27 07:15:29 +0000571 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000572 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000573 // TypeInfo.first describes size in bits.
Chris Lattner77b89b82010-06-27 07:15:29 +0000574 llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
575 llvm::ConstantInt::get(Int32Ty, TypeInfo.second/8),
Mon P Wang3ecd7852010-04-04 03:10:52 +0000576 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
577 0));
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000578}
579
Chris Lattnerd9becd12009-10-28 23:59:40 +0000580llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
581 // Make sure that there is a block for the indirect goto.
582 if (IndirectBranch == 0)
583 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000584
John McCallf1549f62010-07-06 01:34:17 +0000585 llvm::BasicBlock *BB = getJumpDestForLabel(L).Block;
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000586
Chris Lattnerd9becd12009-10-28 23:59:40 +0000587 // Make sure the indirect branch includes all of the address-taken blocks.
588 IndirectBranch->addDestination(BB);
589 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000590}
591
592llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000593 // If we already made the indirect branch for indirect goto, return its block.
594 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000595
Chris Lattnerd9becd12009-10-28 23:59:40 +0000596 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000597
Chris Lattnerd9becd12009-10-28 23:59:40 +0000598 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000599
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000600 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000601 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000602
Chris Lattnerd9becd12009-10-28 23:59:40 +0000603 // Create the indirect branch instruction.
604 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
605 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000606}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000607
Daniel Dunbard286f052009-07-19 06:58:07 +0000608llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000609 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Anders Carlssonf666b772008-12-20 20:27:15 +0000611 assert(SizeEntry && "Did not emit size for type");
612 return SizeEntry;
613}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000614
Daniel Dunbard286f052009-07-19 06:58:07 +0000615llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000616 assert(Ty->isVariablyModifiedType() &&
617 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Daniel Dunbard286f052009-07-19 06:58:07 +0000619 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Anders Carlsson60d35412008-12-20 20:46:34 +0000621 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000622 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000624 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000625 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000627 // Get the element size;
628 QualType ElemTy = VAT->getElementType();
629 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000630 if (ElemTy->isVariableArrayType())
631 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000632 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000633 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000634 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000636 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000637 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000639 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000640 }
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Anders Carlsson60d35412008-12-20 20:46:34 +0000642 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000645 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
646 EmitVLASize(AT->getElementType());
647 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000648 }
649
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000650 const PointerType *PT = Ty->getAs<PointerType>();
651 assert(PT && "unknown VM type!");
652 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000653 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000654}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000655
656llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Chris Lattnerfbe02ff2010-06-27 07:40:06 +0000657 if (CGM.getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000658 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000659 return EmitLValue(E).getAddress();
660}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000661
John McCallf1549f62010-07-06 01:34:17 +0000662/// Pops cleanup blocks until the given savepoint is reached.
663void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
664 assert(Old.isValid());
665
666 EHScopeStack::iterator E = EHStack.find(Old);
667 while (EHStack.begin() != E)
668 PopCleanupBlock();
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000669}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000670
John McCallf1549f62010-07-06 01:34:17 +0000671/// Destroys a cleanup if it was unused.
672static void DestroyCleanup(CodeGenFunction &CGF,
673 llvm::BasicBlock *Entry,
674 llvm::BasicBlock *Exit) {
675 assert(Entry->use_empty() && "destroying cleanup with uses!");
676 assert(Exit->getTerminator() == 0 &&
677 "exit has terminator but entry has no predecessors!");
Mike Stump1eb44332009-09-09 15:08:12 +0000678
John McCallf1549f62010-07-06 01:34:17 +0000679 // This doesn't always remove the entire cleanup, but it's much
680 // safer as long as we don't know what blocks belong to the cleanup.
681 // A *much* better approach if we care about this inefficiency would
682 // be to lazily emit the cleanup.
683
684 // If the exit block is distinct from the entry, give it a branch to
685 // an unreachable destination. This preserves the well-formedness
686 // of the IR.
687 if (Entry != Exit)
688 llvm::BranchInst::Create(CGF.getUnreachableBlock(), Exit);
689
690 assert(!Entry->getParent() && "cleanup entry already positioned?");
John McCall66d80a92010-07-06 17:35:03 +0000691 // We can't just delete the entry; we have to kill any references to
692 // its instructions in other blocks.
693 for (llvm::BasicBlock::iterator I = Entry->begin(), E = Entry->end();
694 I != E; ++I)
695 if (!I->use_empty())
696 I->replaceAllUsesWith(llvm::UndefValue::get(I->getType()));
John McCallf1549f62010-07-06 01:34:17 +0000697 delete Entry;
Anders Carlssonc71c8452009-02-07 23:50:39 +0000698}
699
John McCallf1549f62010-07-06 01:34:17 +0000700/// Creates a switch instruction to thread branches out of the given
701/// block (which is the exit block of a cleanup).
702static void CreateCleanupSwitch(CodeGenFunction &CGF,
703 llvm::BasicBlock *Block) {
704 if (Block->getTerminator()) {
705 assert(isa<llvm::SwitchInst>(Block->getTerminator()) &&
706 "cleanup block already has a terminator, but it isn't a switch");
Mike Stump99533832009-12-02 07:41:41 +0000707 return;
708 }
709
John McCallf1549f62010-07-06 01:34:17 +0000710 llvm::Value *DestCodePtr
711 = CGF.CreateTempAlloca(CGF.Builder.getInt32Ty(), "cleanup.dst");
712 CGBuilderTy Builder(Block);
713 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Devang Patelcd9199e2010-04-13 00:08:43 +0000714
John McCallf1549f62010-07-06 01:34:17 +0000715 // Create a switch instruction to determine where to jump next.
716 Builder.CreateSwitch(DestCode, CGF.getUnreachableBlock());
Anders Carlssond66a9f92009-02-08 03:55:35 +0000717}
718
John McCallf1549f62010-07-06 01:34:17 +0000719/// Attempts to reduce a cleanup's entry block to a fallthrough. This
720/// is basically llvm::MergeBlockIntoPredecessor, except
721/// simplified/optimized for the tighter constraints on cleanup
722/// blocks.
723static void SimplifyCleanupEntry(CodeGenFunction &CGF,
724 llvm::BasicBlock *Entry) {
725 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
726 if (!Pred) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000727
John McCallf1549f62010-07-06 01:34:17 +0000728 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
729 if (!Br || Br->isConditional()) return;
730 assert(Br->getSuccessor(0) == Entry);
731
732 // If we were previously inserting at the end of the cleanup entry
733 // block, we'll need to continue inserting at the end of the
734 // predecessor.
735 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
736 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
737
738 // Kill the branch.
739 Br->eraseFromParent();
740
741 // Merge the blocks.
742 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
743
744 // Kill the entry block.
745 Entry->eraseFromParent();
746
747 if (WasInsertBlock)
748 CGF.Builder.SetInsertPoint(Pred);
Anders Carlsson87eaf172009-02-08 00:50:42 +0000749}
750
John McCallf1549f62010-07-06 01:34:17 +0000751/// Attempts to reduce an cleanup's exit switch to an unconditional
752/// branch.
753static void SimplifyCleanupExit(llvm::BasicBlock *Exit) {
754 llvm::TerminatorInst *Terminator = Exit->getTerminator();
755 assert(Terminator && "completed cleanup exit has no terminator");
756
757 llvm::SwitchInst *Switch = dyn_cast<llvm::SwitchInst>(Terminator);
758 if (!Switch) return;
759 if (Switch->getNumCases() != 2) return; // default + 1
760
761 llvm::LoadInst *Cond = cast<llvm::LoadInst>(Switch->getCondition());
762 llvm::AllocaInst *CondVar = cast<llvm::AllocaInst>(Cond->getPointerOperand());
763
764 // Replace the switch instruction with an unconditional branch.
765 llvm::BasicBlock *Dest = Switch->getSuccessor(1); // default is 0
766 Switch->eraseFromParent();
767 llvm::BranchInst::Create(Dest, Exit);
768
769 // Delete all uses of the condition variable.
770 Cond->eraseFromParent();
771 while (!CondVar->use_empty())
772 cast<llvm::StoreInst>(*CondVar->use_begin())->eraseFromParent();
773
774 // Delete the condition variable itself.
775 CondVar->eraseFromParent();
776}
777
778/// Threads a branch fixup through a cleanup block.
779static void ThreadFixupThroughCleanup(CodeGenFunction &CGF,
780 BranchFixup &Fixup,
781 llvm::BasicBlock *Entry,
782 llvm::BasicBlock *Exit) {
783 if (!Exit->getTerminator())
784 CreateCleanupSwitch(CGF, Exit);
785
786 // Find the switch and its destination index alloca.
787 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Exit->getTerminator());
788 llvm::Value *DestCodePtr =
789 cast<llvm::LoadInst>(Switch->getCondition())->getPointerOperand();
790
791 // Compute the index of the new case we're adding to the switch.
792 unsigned Index = Switch->getNumCases();
793
794 const llvm::IntegerType *i32 = llvm::Type::getInt32Ty(CGF.getLLVMContext());
795 llvm::ConstantInt *IndexV = llvm::ConstantInt::get(i32, Index);
796
797 // Set the index in the origin block.
798 new llvm::StoreInst(IndexV, DestCodePtr, Fixup.Origin);
799
800 // Add a case to the switch.
801 Switch->addCase(IndexV, Fixup.Destination);
802
803 // Change the last branch to point to the cleanup entry block.
804 Fixup.LatestBranch->setSuccessor(Fixup.LatestBranchIndex, Entry);
805
806 // And finally, update the fixup.
807 Fixup.LatestBranch = Switch;
808 Fixup.LatestBranchIndex = Index;
809}
810
811/// Try to simplify both the entry and exit edges of a cleanup.
812static void SimplifyCleanupEdges(CodeGenFunction &CGF,
813 llvm::BasicBlock *Entry,
814 llvm::BasicBlock *Exit) {
815
816 // Given their current implementations, it's important to run these
817 // in this order: SimplifyCleanupEntry will delete Entry if it can
818 // be merged into its predecessor, which will then break
819 // SimplifyCleanupExit if (as is common) Entry == Exit.
820
821 SimplifyCleanupExit(Exit);
822 SimplifyCleanupEntry(CGF, Entry);
823}
824
825/// Pops a cleanup block. If the block includes a normal cleanup, the
826/// current insertion point is threaded through the cleanup, as are
827/// any branch fixups on the cleanup.
828void CodeGenFunction::PopCleanupBlock() {
829 assert(!EHStack.empty() && "cleanup stack is empty!");
830 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
831 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
832 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
833
834 // Handle the EH cleanup if (1) there is one and (2) it's different
835 // from the normal cleanup.
836 if (Scope.isEHCleanup() &&
837 Scope.getEHEntry() != Scope.getNormalEntry()) {
838 llvm::BasicBlock *EHEntry = Scope.getEHEntry();
839 llvm::BasicBlock *EHExit = Scope.getEHExit();
840
841 if (EHEntry->use_empty()) {
842 DestroyCleanup(*this, EHEntry, EHExit);
843 } else {
844 // TODO: this isn't really the ideal location to put this EH
845 // cleanup, but lazy emission is a better solution than trying
846 // to pick a better spot.
847 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
848 EmitBlock(EHEntry);
849 Builder.restoreIP(SavedIP);
850
851 SimplifyCleanupEdges(*this, EHEntry, EHExit);
852 }
853 }
854
855 // If we only have an EH cleanup, we don't really need to do much
856 // here. Branch fixups just naturally drop down to the enclosing
857 // cleanup scope.
858 if (!Scope.isNormalCleanup()) {
859 EHStack.popCleanup();
860 assert(EHStack.getNumBranchFixups() == 0 || EHStack.hasNormalCleanups());
861 return;
862 }
863
864 // Check whether the scope has any fixups that need to be threaded.
865 unsigned FixupDepth = Scope.getFixupDepth();
866 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
867
868 // Grab the entry and exit blocks.
869 llvm::BasicBlock *Entry = Scope.getNormalEntry();
870 llvm::BasicBlock *Exit = Scope.getNormalExit();
871
872 // Check whether anything's been threaded through the cleanup already.
873 assert((Exit->getTerminator() == 0) == Entry->use_empty() &&
874 "cleanup entry/exit mismatch");
875 bool HasExistingBranches = !Entry->use_empty();
876
877 // Check whether we need to emit a "fallthrough" branch through the
878 // cleanup for the current insertion point.
879 llvm::BasicBlock *FallThrough = Builder.GetInsertBlock();
880 if (FallThrough && FallThrough->getTerminator())
881 FallThrough = 0;
882
883 // If *nothing* is using the cleanup, kill it.
884 if (!FallThrough && !HasFixups && !HasExistingBranches) {
885 EHStack.popCleanup();
886 DestroyCleanup(*this, Entry, Exit);
887 return;
888 }
889
890 // Otherwise, add the block to the function.
891 EmitBlock(Entry);
892
893 if (FallThrough)
894 Builder.SetInsertPoint(Exit);
895 else
896 Builder.ClearInsertionPoint();
897
898 // Fast case: if we don't have to add any fixups, and either
899 // we don't have a fallthrough or the cleanup wasn't previously
900 // used, then the setup above is sufficient.
901 if (!HasFixups) {
902 if (!FallThrough) {
903 assert(HasExistingBranches && "no reason for cleanup but didn't kill before");
904 EHStack.popCleanup();
905 SimplifyCleanupEdges(*this, Entry, Exit);
906 return;
907 } else if (!HasExistingBranches) {
908 assert(FallThrough && "no reason for cleanup but didn't kill before");
909 // We can't simplify the exit edge in this case because we're
910 // already inserting at the end of the exit block.
911 EHStack.popCleanup();
912 SimplifyCleanupEntry(*this, Entry);
913 return;
914 }
915 }
916
917 // Otherwise we're going to have to thread things through the cleanup.
918 llvm::SmallVector<BranchFixup*, 8> Fixups;
919
920 // Synthesize a fixup for the current insertion point.
921 BranchFixup Cur;
922 if (FallThrough) {
923 Cur.Destination = createBasicBlock("cleanup.cont");
924 Cur.LatestBranch = FallThrough->getTerminator();
925 Cur.LatestBranchIndex = 0;
926 Cur.Origin = Cur.LatestBranch;
927
928 // Restore fixup invariant. EmitBlock added a branch to the cleanup
929 // which we need to redirect to the destination.
930 cast<llvm::BranchInst>(Cur.LatestBranch)->setSuccessor(0, Cur.Destination);
931
932 Fixups.push_back(&Cur);
933 } else {
934 Cur.Destination = 0;
935 }
936
937 // Collect any "real" fixups we need to thread.
938 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
939 I != E; ++I)
940 if (EHStack.getBranchFixup(I).Destination)
941 Fixups.push_back(&EHStack.getBranchFixup(I));
942
943 assert(!Fixups.empty() && "no fixups, invariants broken!");
944
945 // If there's only a single fixup to thread through, do so with
946 // unconditional branches. This only happens if there's a single
947 // branch and no fallthrough.
948 if (Fixups.size() == 1 && !HasExistingBranches) {
949 Fixups[0]->LatestBranch->setSuccessor(Fixups[0]->LatestBranchIndex, Entry);
950 llvm::BranchInst *Br =
951 llvm::BranchInst::Create(Fixups[0]->Destination, Exit);
952 Fixups[0]->LatestBranch = Br;
953 Fixups[0]->LatestBranchIndex = 0;
954
955 // Otherwise, force a switch statement and thread everything through
956 // the switch.
957 } else {
958 CreateCleanupSwitch(*this, Exit);
959 for (unsigned I = 0, E = Fixups.size(); I != E; ++I)
960 ThreadFixupThroughCleanup(*this, *Fixups[I], Entry, Exit);
961 }
962
963 // Emit the fallthrough destination block if necessary.
964 if (Cur.Destination)
965 EmitBlock(Cur.Destination);
966
967 // We're finally done with the cleanup.
968 EHStack.popCleanup();
969}
970
971void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000972 if (!HaveInsertPoint())
973 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000974
John McCallf1549f62010-07-06 01:34:17 +0000975 // Create the branch.
976 llvm::BranchInst *BI = Builder.CreateBr(Dest.Block);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
John McCallf1549f62010-07-06 01:34:17 +0000978 // If we're not in a cleanup scope, we don't need to worry about
979 // fixups.
980 if (!EHStack.hasNormalCleanups()) {
981 Builder.ClearInsertionPoint();
982 return;
983 }
984
985 // Initialize a fixup.
986 BranchFixup Fixup;
987 Fixup.Destination = Dest.Block;
988 Fixup.Origin = BI;
989 Fixup.LatestBranch = BI;
990 Fixup.LatestBranchIndex = 0;
991
992 // If we can't resolve the destination cleanup scope, just add this
993 // to the current cleanup scope.
994 if (!Dest.ScopeDepth.isValid()) {
995 EHStack.addBranchFixup() = Fixup;
996 Builder.ClearInsertionPoint();
997 return;
998 }
999
1000 for (EHScopeStack::iterator I = EHStack.begin(),
1001 E = EHStack.find(Dest.ScopeDepth); I != E; ++I) {
1002 if (isa<EHCleanupScope>(*I)) {
1003 EHCleanupScope &Scope = cast<EHCleanupScope>(*I);
1004 if (Scope.isNormalCleanup())
1005 ThreadFixupThroughCleanup(*this, Fixup, Scope.getNormalEntry(),
1006 Scope.getNormalExit());
1007 }
1008 }
1009
Anders Carlsson46831a92009-02-08 22:13:37 +00001010 Builder.ClearInsertionPoint();
John McCallf1549f62010-07-06 01:34:17 +00001011}
Mike Stump1eb44332009-09-09 15:08:12 +00001012
John McCallf1549f62010-07-06 01:34:17 +00001013void CodeGenFunction::EmitBranchThroughEHCleanup(JumpDest Dest) {
1014 if (!HaveInsertPoint())
Anders Carlsson87eaf172009-02-08 00:50:42 +00001015 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001016
John McCallf1549f62010-07-06 01:34:17 +00001017 // Create the branch.
1018 llvm::BranchInst *BI = Builder.CreateBr(Dest.Block);
1019
1020 // If we're not in a cleanup scope, we don't need to worry about
1021 // fixups.
1022 if (!EHStack.hasEHCleanups()) {
1023 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001024 return;
1025 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
John McCallf1549f62010-07-06 01:34:17 +00001027 // Initialize a fixup.
1028 BranchFixup Fixup;
1029 Fixup.Destination = Dest.Block;
1030 Fixup.Origin = BI;
1031 Fixup.LatestBranch = BI;
1032 Fixup.LatestBranchIndex = 0;
1033
1034 // We should never get invalid scope depths for these: invalid scope
1035 // depths only arise for as-yet-unemitted labels, and we can't do an
1036 // EH-unwind to one of those.
1037 assert(Dest.ScopeDepth.isValid() && "invalid scope depth on EH dest?");
1038
1039 for (EHScopeStack::iterator I = EHStack.begin(),
1040 E = EHStack.find(Dest.ScopeDepth); I != E; ++I) {
1041 if (isa<EHCleanupScope>(*I)) {
1042 EHCleanupScope &Scope = cast<EHCleanupScope>(*I);
1043 if (Scope.isEHCleanup())
1044 ThreadFixupThroughCleanup(*this, Fixup, Scope.getEHEntry(),
1045 Scope.getEHExit());
1046 }
Anders Carlsson87eaf172009-02-08 00:50:42 +00001047 }
John McCallf1549f62010-07-06 01:34:17 +00001048
1049 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001050}