blob: 319144e89dd68dfb3c69c8265ecfa5eee57a5c2a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000022#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000023#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000024#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000025#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27using namespace CodeGen;
28
Mike Stump1eb44332009-09-09 15:08:12 +000029CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000030 : BlockFunction(cgm, *this, Builder), CGM(cgm),
31 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000032 Builder(cgm.getModule().getContext()),
Chris Lattnerd9becd12009-10-28 23:59:40 +000033 DebugInfo(0), IndirectBranch(0),
Chris Lattner3d00fdc2009-10-13 06:55:33 +000034 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
John McCall25049412010-02-16 22:04:33 +000035 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
Anders Carlsson5687a5c2010-06-08 22:30:17 +000036 ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000037
38 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000039 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000040 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
41 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
42 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
43 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
44
Mike Stumpd88ea562009-12-09 03:35:49 +000045 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000046 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Douglas Gregor35415f52010-05-25 17:04:15 +000047 CGM.getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000048}
Reid Spencer5f016e22007-07-11 17:01:13 +000049
50ASTContext &CodeGenFunction::getContext() const {
51 return CGM.getContext();
52}
53
54
55llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
56 llvm::BasicBlock *&BB = LabelMap[S];
57 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000058
Reid Spencer5f016e22007-07-11 17:01:13 +000059 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000060 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000061}
62
Daniel Dunbar0096acf2009-02-25 19:24:29 +000063llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
64 llvm::Value *Res = LocalDeclMap[VD];
65 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
66 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000067}
Reid Spencer5f016e22007-07-11 17:01:13 +000068
Daniel Dunbar0096acf2009-02-25 19:24:29 +000069llvm::Constant *
70CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
71 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000072}
73
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000074const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
75 return CGM.getTypes().ConvertTypeForMem(T);
76}
77
Reid Spencer5f016e22007-07-11 17:01:13 +000078const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
79 return CGM.getTypes().ConvertType(T);
80}
81
82bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000083 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
84 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000085}
86
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000087void CodeGenFunction::EmitReturnBlock() {
88 // For cleanliness, we try to avoid emitting the return block for
89 // simple cases.
90 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
91
92 if (CurBB) {
93 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
94
Daniel Dunbar96e18b02009-07-19 08:24:34 +000095 // We have a valid insert point, reuse it if it is empty or there are no
96 // explicit jumps to the return block.
97 if (CurBB->empty() || ReturnBlock->use_empty()) {
98 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000099 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +0000100 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000101 EmitBlock(ReturnBlock);
102 return;
103 }
104
105 // Otherwise, if the return block is the target of a single direct
106 // branch then we can just put the code in that block instead. This
107 // cleans up functions which started with a unified return block.
108 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000110 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
111 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
112 // Reset insertion point and delete the branch.
113 Builder.SetInsertPoint(BI->getParent());
114 BI->eraseFromParent();
115 delete ReturnBlock;
116 return;
117 }
118 }
119
Mike Stumpf5408fe2009-05-16 07:57:57 +0000120 // FIXME: We are at an unreachable point, there is no reason to emit the block
121 // unless it has uses. However, we still need a place to put the debug
122 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000123
124 EmitBlock(ReturnBlock);
125}
126
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000127void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000128 assert(BreakContinueStack.empty() &&
129 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000130 assert(BlockScopes.empty() &&
131 "did not remove all blocks from block scope map!");
132 assert(CleanupEntries.empty() &&
133 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000134
135 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000136 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000137
Chris Lattner7255a2d2010-06-22 00:03:40 +0000138 EmitFunctionInstrumentation("__cyg_profile_func_exit");
139
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000140 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000141 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000142 DI->setLocation(EndLoc);
143 DI->EmitRegionEnd(CurFn, Builder);
144 }
145
Chris Lattner35b21b82010-06-27 01:06:27 +0000146 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000147 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000148
Chris Lattnerd9becd12009-10-28 23:59:40 +0000149 // If someone did an indirect goto, emit the indirect goto block at the end of
150 // the function.
151 if (IndirectBranch) {
152 EmitBlock(IndirectBranch->getParent());
153 Builder.ClearInsertionPoint();
154 }
155
Chris Lattner5a2fa142007-12-02 06:32:24 +0000156 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000157 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000158 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000159 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000160
161 // If someone took the address of a label but never did an indirect goto, we
162 // made a zero entry PHI node, which is illegal, zap it now.
163 if (IndirectBranch) {
164 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
165 if (PN->getNumIncomingValues() == 0) {
166 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
167 PN->eraseFromParent();
168 }
169 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000170}
171
Chris Lattner7255a2d2010-06-22 00:03:40 +0000172/// ShouldInstrumentFunction - Return true if the current function should be
173/// instrumented with __cyg_profile_func_* calls
174bool CodeGenFunction::ShouldInstrumentFunction() {
175 if (!CGM.getCodeGenOpts().InstrumentFunctions)
176 return false;
177 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
178 return false;
179 return true;
180}
181
182/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
183/// instrumentation function with the current function and the call site, if
184/// function instrumentation is enabled.
185void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
186 if (!ShouldInstrumentFunction())
187 return;
188
Chris Lattner8dab6572010-06-23 05:21:28 +0000189 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000190 const llvm::FunctionType *FunctionTy;
191 std::vector<const llvm::Type*> ProfileFuncArgs;
192
Chris Lattner8dab6572010-06-23 05:21:28 +0000193 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
194 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
195 ProfileFuncArgs.push_back(PointerTy);
196 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000197 FunctionTy = llvm::FunctionType::get(
198 llvm::Type::getVoidTy(VMContext),
199 ProfileFuncArgs, false);
200
201 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
202 llvm::CallInst *CallSite = Builder.CreateCall(
203 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000204 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000205 "callsite");
206
Chris Lattner8dab6572010-06-23 05:21:28 +0000207 Builder.CreateCall2(F,
208 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
209 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000210}
211
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000212void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000213 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000214 const FunctionArgList &Args,
215 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000216 const Decl *D = GD.getDecl();
217
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000218 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000219 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000220 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000221 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000222 assert(CurFn->isDeclaration() && "Function already has body?");
223
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000224 // Pass inline keyword to optimizer if it appears explicitly on any
225 // declaration.
226 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
227 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
228 RE = FD->redecls_end(); RI != RE; ++RI)
229 if (RI->isInlineSpecified()) {
230 Fn->addFnAttr(llvm::Attribute::InlineHint);
231 break;
232 }
233
Daniel Dunbar55e87422008-11-11 02:29:29 +0000234 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000235
Chris Lattner41110242008-06-17 18:05:57 +0000236 // Create a marker to make it easy to insert allocas into the entryblock
237 // later. Don't create this with the builder, because we don't want it
238 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000239 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
240 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000241 if (Builder.isNamePreserving())
242 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Daniel Dunbar55e87422008-11-11 02:29:29 +0000244 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner41110242008-06-17 18:05:57 +0000246 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregorce056bc2010-02-21 22:15:06 +0000248 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
249 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000250 /*FIXME?*/
251 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000252
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000253 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000254 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000255 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000256 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000257 }
258
Chris Lattner7255a2d2010-06-22 00:03:40 +0000259 EmitFunctionInstrumentation("__cyg_profile_func_enter");
260
Daniel Dunbar88b53962009-02-02 22:03:45 +0000261 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000262 // CC info is ignored, hopefully?
263 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000264 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000265
266 if (RetTy->isVoidType()) {
267 // Void type; nothing to return.
268 ReturnValue = 0;
269 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
270 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
271 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000272 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000273 ReturnValue = CurFn->arg_begin();
274 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000275 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000276 }
277
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000278 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000279 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
John McCall25049412010-02-16 22:04:33 +0000281 if (CXXThisDecl)
282 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
283 if (CXXVTTDecl)
284 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
285
Anders Carlsson751358f2008-12-20 21:28:43 +0000286 // If any of the arguments have a variably modified type, make sure to
287 // emit the type size.
288 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
289 i != e; ++i) {
290 QualType Ty = i->second;
291
292 if (Ty->isVariablyModifiedType())
293 EmitVLASize(Ty);
294 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000295}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000296
John McCall9fc6a772010-02-19 09:25:03 +0000297void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
298 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000299 assert(FD->getBody());
300 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000301}
302
Anders Carlssonc997d422010-01-02 01:01:18 +0000303void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000304 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
305
Anders Carlssone896d982009-02-13 08:11:52 +0000306 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000307 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000308 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Daniel Dunbar7c086512008-09-09 23:14:03 +0000310 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000312 CurGD = GD;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000313 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
314 if (MD->isInstance()) {
315 // Create the implicit 'this' decl.
316 // FIXME: I'm not entirely sure I like using a fake decl just for code
317 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000318 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
319 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000320 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000321 MD->getThisType(getContext()));
322 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000323
324 // Check if we need a VTT parameter as well.
Anders Carlssonaf440352010-03-23 04:11:45 +0000325 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000326 // FIXME: The comment about using a fake decl above applies here too.
327 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
328 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000329 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000330 &getContext().Idents.get("vtt"), T);
331 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
332 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000333 }
334 }
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000336 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000337 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000338 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000339
340 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000341 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000342 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000343 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000344
John McCalla355e072010-02-18 03:17:58 +0000345 SourceRange BodyRange;
346 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000347
John McCalla355e072010-02-18 03:17:58 +0000348 // Emit the standard function prologue.
349 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000350
John McCalla355e072010-02-18 03:17:58 +0000351 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000352 if (isa<CXXDestructorDecl>(FD))
353 EmitDestructorBody(Args);
354 else if (isa<CXXConstructorDecl>(FD))
355 EmitConstructorBody(Args);
356 else
357 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000358
John McCalla355e072010-02-18 03:17:58 +0000359 // Emit the standard function epilogue.
360 FinishFunction(BodyRange.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000362 // Destroy the 'this' declaration.
363 if (CXXThisDecl)
364 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000365
366 // Destroy the VTT declaration.
367 if (CXXVTTDecl)
368 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000369}
370
Chris Lattner0946ccd2008-11-11 07:41:27 +0000371/// ContainsLabel - Return true if the statement contains a label in it. If
372/// this statement is not executed normally, it not containing a label means
373/// that we can just remove the code.
374bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
375 // Null statement, not a label!
376 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Chris Lattner0946ccd2008-11-11 07:41:27 +0000378 // If this is a label, we have to emit the code, consider something like:
379 // if (0) { ... foo: bar(); } goto foo;
380 if (isa<LabelStmt>(S))
381 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Chris Lattner0946ccd2008-11-11 07:41:27 +0000383 // If this is a case/default statement, and we haven't seen a switch, we have
384 // to emit the code.
385 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
386 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Chris Lattner0946ccd2008-11-11 07:41:27 +0000388 // If this is a switch statement, we want to ignore cases below it.
389 if (isa<SwitchStmt>(S))
390 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner0946ccd2008-11-11 07:41:27 +0000392 // Scan subexpressions for verboten labels.
393 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
394 I != E; ++I)
395 if (ContainsLabel(*I, IgnoreCaseStmts))
396 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner0946ccd2008-11-11 07:41:27 +0000398 return false;
399}
400
Chris Lattner31a09842008-11-12 08:04:58 +0000401
402/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
403/// a constant, or if it does but contains a label, return 0. If it constant
404/// folds to 'true' and does not contain a label, return 1, if it constant folds
405/// to 'false' and does not contain a label, return -1.
406int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000407 // FIXME: Rename and handle conversion of other evaluatable things
408 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000409 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000410 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000411 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000412 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner31a09842008-11-12 08:04:58 +0000414 if (CodeGenFunction::ContainsLabel(Cond))
415 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Anders Carlsson64712f12008-12-01 02:46:24 +0000417 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000418}
419
420
421/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
422/// statement) to the specified blocks. Based on the condition, this might try
423/// to simplify the codegen of the conditional based on the branch.
424///
425void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
426 llvm::BasicBlock *TrueBlock,
427 llvm::BasicBlock *FalseBlock) {
428 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
429 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner31a09842008-11-12 08:04:58 +0000431 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
432 // Handle X && Y in a condition.
433 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
434 // If we have "1 && X", simplify the code. "0 && X" would have constant
435 // folded if the case was simple enough.
436 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
437 // br(1 && X) -> br(X).
438 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner31a09842008-11-12 08:04:58 +0000441 // If we have "X && 1", simplify the code to use an uncond branch.
442 // "X && 0" would have been constant folded to 0.
443 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
444 // br(X && 1) -> br(X).
445 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
446 }
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner31a09842008-11-12 08:04:58 +0000448 // Emit the LHS as a conditional. If the LHS conditional is false, we
449 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000450 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000451 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
452 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Anders Carlsson08e9e452010-01-24 00:20:05 +0000454 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000455 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000456 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000457 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000458
Chris Lattner31a09842008-11-12 08:04:58 +0000459 return;
460 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
461 // If we have "0 || X", simplify the code. "1 || X" would have constant
462 // folded if the case was simple enough.
463 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
464 // br(0 || X) -> br(X).
465 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
466 }
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattner31a09842008-11-12 08:04:58 +0000468 // If we have "X || 0", simplify the code to use an uncond branch.
469 // "X || 1" would have been constant folded to 1.
470 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
471 // br(X || 0) -> br(X).
472 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Chris Lattner31a09842008-11-12 08:04:58 +0000475 // Emit the LHS as a conditional. If the LHS conditional is true, we
476 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000477 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000478 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
479 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Anders Carlsson08e9e452010-01-24 00:20:05 +0000481 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000482 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000483 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000484 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000485
Chris Lattner31a09842008-11-12 08:04:58 +0000486 return;
487 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattner552f4c42008-11-12 08:13:36 +0000490 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
491 // br(!x, t, f) -> br(x, f, t)
492 if (CondUOp->getOpcode() == UnaryOperator::LNot)
493 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Daniel Dunbar09b14892008-11-12 10:30:32 +0000496 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
497 // Handle ?: operator.
498
499 // Just ignore GNU ?: extension.
500 if (CondOp->getLHS()) {
501 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
502 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
503 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
504 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
505 EmitBlock(LHSBlock);
506 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
507 EmitBlock(RHSBlock);
508 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
509 return;
510 }
511 }
512
Chris Lattner31a09842008-11-12 08:04:58 +0000513 // Emit the code with the fully general case.
514 llvm::Value *CondV = EvaluateExprAsBool(Cond);
515 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
516}
517
Daniel Dunbar488e9932008-08-16 00:56:44 +0000518/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000519/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000520void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
521 bool OmitOnError) {
522 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000523}
524
Anders Carlsson1884eb02010-05-22 17:35:42 +0000525void
526CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
527 // If the type contains a pointer to data member we can't memset it to zero.
528 // Instead, create a null constant and copy it to the destination.
529 if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
530 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
531
532 llvm::GlobalVariable *NullVariable =
533 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
534 /*isConstant=*/true,
535 llvm::GlobalVariable::PrivateLinkage,
536 NullConstant, llvm::Twine());
537 EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
538 return;
539 }
540
541
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000542 // Ignore empty classes in C++.
543 if (getContext().getLangOptions().CPlusPlus) {
544 if (const RecordType *RT = Ty->getAs<RecordType>()) {
545 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
546 return;
547 }
548 }
549
Anders Carlsson1884eb02010-05-22 17:35:42 +0000550 // Otherwise, just memset the whole thing to zero. This is legal
551 // because in LLVM, all default initializers (other than the ones we just
552 // handled above) are guaranteed to have a bit pattern of all zeros.
Chris Lattner36afd382009-10-13 06:02:42 +0000553 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000554 if (DestPtr->getType() != BP)
555 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
556
557 // Get size and alignment info for this aggregate.
558 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
559
Chris Lattner88207c92009-04-21 17:59:23 +0000560 // Don't bother emitting a zero-byte memset.
561 if (TypeInfo.first == 0)
562 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000564 // FIXME: Handle variable sized types.
Chris Lattner77b89b82010-06-27 07:15:29 +0000565 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000566 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000567 // TypeInfo.first describes size in bits.
Chris Lattner77b89b82010-06-27 07:15:29 +0000568 llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
569 llvm::ConstantInt::get(Int32Ty, TypeInfo.second/8),
Mon P Wang3ecd7852010-04-04 03:10:52 +0000570 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
571 0));
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000572}
573
Chris Lattnerd9becd12009-10-28 23:59:40 +0000574llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
575 // Make sure that there is a block for the indirect goto.
576 if (IndirectBranch == 0)
577 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000578
Chris Lattnerd9becd12009-10-28 23:59:40 +0000579 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000580
Chris Lattnerd9becd12009-10-28 23:59:40 +0000581 // Make sure the indirect branch includes all of the address-taken blocks.
582 IndirectBranch->addDestination(BB);
583 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000584}
585
586llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000587 // If we already made the indirect branch for indirect goto, return its block.
588 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000589
Chris Lattnerd9becd12009-10-28 23:59:40 +0000590 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000591
Chris Lattnerd9becd12009-10-28 23:59:40 +0000592 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000593
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000594 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000595 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000596
Chris Lattnerd9becd12009-10-28 23:59:40 +0000597 // Create the indirect branch instruction.
598 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
599 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000600}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000601
Daniel Dunbard286f052009-07-19 06:58:07 +0000602llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000603 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Anders Carlssonf666b772008-12-20 20:27:15 +0000605 assert(SizeEntry && "Did not emit size for type");
606 return SizeEntry;
607}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000608
Daniel Dunbard286f052009-07-19 06:58:07 +0000609llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000610 assert(Ty->isVariablyModifiedType() &&
611 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Daniel Dunbard286f052009-07-19 06:58:07 +0000613 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Anders Carlsson60d35412008-12-20 20:46:34 +0000615 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000616 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000618 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000619 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000621 // Get the element size;
622 QualType ElemTy = VAT->getElementType();
623 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000624 if (ElemTy->isVariableArrayType())
625 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000626 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000627 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000628 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000630 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000631 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000633 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000634 }
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Anders Carlsson60d35412008-12-20 20:46:34 +0000636 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000637 }
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000639 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
640 EmitVLASize(AT->getElementType());
641 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000642 }
643
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000644 const PointerType *PT = Ty->getAs<PointerType>();
645 assert(PT && "unknown VM type!");
646 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000647 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000648}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000649
650llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
651 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
652 return EmitScalarExpr(E);
653 }
654 return EmitLValue(E).getAddress();
655}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000656
Fariborz Jahanian77996212009-11-04 17:57:40 +0000657void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000658 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000659 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump99533832009-12-02 07:41:41 +0000660 bool EHOnly) {
661 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000662 PreviousInvokeDest, EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000663}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000664
Mike Stump1eb44332009-09-09 15:08:12 +0000665void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
666 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000667 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Anders Carlssonc71c8452009-02-07 23:50:39 +0000669 while (CleanupEntries.size() > OldCleanupStackSize)
670 EmitCleanupBlock();
671}
672
Mike Stump1eb44332009-09-09 15:08:12 +0000673CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000674 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Fariborz Jahanian77996212009-11-04 17:57:40 +0000676 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000678 std::vector<llvm::BasicBlock *> Blocks;
679 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000681 std::vector<llvm::BranchInst *> BranchFixups;
682 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Mike Stump99533832009-12-02 07:41:41 +0000684 bool EHOnly = CE.EHOnly;
685
Mike Stumpd88ea562009-12-09 03:35:49 +0000686 setInvokeDest(CE.PreviousInvokeDest);
687
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000688 CleanupEntries.pop_back();
689
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000690 // Check if any branch fixups pointed to the scope we just popped. If so,
691 // we can remove them.
692 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
693 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
694 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000696 if (I == BlockScopes.end())
697 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000699 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000701 if (I->second == CleanupEntries.size()) {
702 // We don't need to do this branch fixup.
703 BranchFixups[i] = BranchFixups.back();
704 BranchFixups.pop_back();
705 i--;
706 e--;
707 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000708 }
709 }
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Fariborz Jahanian77996212009-11-04 17:57:40 +0000711 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000712 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000713 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000714 if (!SwitchBlock)
715 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000716 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000718 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000720 Builder.SetInsertPoint(SwitchBlock);
721
Chris Lattner77b89b82010-06-27 07:15:29 +0000722 llvm::Value *DestCodePtr = CreateTempAlloca(Int32Ty, "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000723 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000725 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000726 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000727 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000728
Anders Carlsson46831a92009-02-08 22:13:37 +0000729 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000730 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000731 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000733 // If we had a current basic block, we also need to emit an instruction
734 // to initialize the cleanup destination.
Chris Lattner77b89b82010-06-27 07:15:29 +0000735 Builder.CreateStore(llvm::Constant::getNullValue(Int32Ty),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000736 DestCodePtr);
737 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000738 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000739
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000740 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
741 llvm::BranchInst *BI = BranchFixups[i];
742 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000744 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000745 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000747 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000748 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Anders Carlssoncc899202009-02-08 22:46:50 +0000750 // Check if we already have a destination for this block.
751 if (Dest == SI->getDefaultDest())
Chris Lattner77b89b82010-06-27 07:15:29 +0000752 ID = llvm::ConstantInt::get(Int32Ty, 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000753 else {
754 ID = SI->findCaseDest(Dest);
755 if (!ID) {
756 // No code found, get a new unique one by using the number of
757 // switch successors.
Chris Lattner77b89b82010-06-27 07:15:29 +0000758 ID = llvm::ConstantInt::get(Int32Ty, SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000759 SI->addCase(ID, Dest);
760 }
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Anders Carlssoncc899202009-02-08 22:46:50 +0000763 // Store the jump destination before the branch instruction.
764 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000765 } else {
766 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000767 // with a branch instruction that jumps to the final destination and add
768 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000770 // Create the pad block.
771 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000772
773 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000774 llvm::ConstantInt *ID
Chris Lattner77b89b82010-06-27 07:15:29 +0000775 = llvm::ConstantInt::get(Int32Ty, SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000776
777 // Store the jump destination before the branch instruction.
778 new llvm::StoreInst(ID, DestCodePtr, BI);
779
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000780 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000781 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000783 // Create the branch to the final destination.
784 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
785 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000787 // And add it as a branch fixup.
788 CleanupEntries.back().BranchFixups.push_back(BI);
789 }
790 }
791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000793 // Remove all blocks from the block scope map.
794 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
795 assert(BlockScopes.count(Blocks[i]) &&
796 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000798 BlockScopes.erase(Blocks[i]);
799 }
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Mike Stump99533832009-12-02 07:41:41 +0000801 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000802}
803
Mike Stump1eb44332009-09-09 15:08:12 +0000804void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000805 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Mike Stump99533832009-12-02 07:41:41 +0000807 if (Info.EHOnly) {
808 // FIXME: Add this to the exceptional edge
809 if (Info.CleanupBlock->getNumUses() == 0)
810 delete Info.CleanupBlock;
811 return;
812 }
813
Devang Patelcd9199e2010-04-13 00:08:43 +0000814 // Scrub debug location info.
815 for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
816 LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
817 Builder.SetInstDebugLocation(LBI);
818
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000819 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000820 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000821 Info.CleanupBlock->getNumUses() == 0) {
822 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
823 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000824 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000825 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000827 if (Info.SwitchBlock)
828 EmitBlock(Info.SwitchBlock);
829 if (Info.EndBlock)
830 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000831}
832
Mike Stump1eb44332009-09-09 15:08:12 +0000833void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
834 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000835 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Mike Stumpf5408fe2009-05-16 07:57:57 +0000837 // FIXME: We could be more clever here and check if there's already a branch
838 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000839 CleanupEntries.back().BranchFixups.push_back(BI);
840}
841
Mike Stump1eb44332009-09-09 15:08:12 +0000842void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000843 if (!HaveInsertPoint())
844 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Anders Carlsson87eaf172009-02-08 00:50:42 +0000846 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Anders Carlsson46831a92009-02-08 22:13:37 +0000848 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Anders Carlsson87eaf172009-02-08 00:50:42 +0000850 // The stack is empty, no need to do any cleanup.
851 if (CleanupEntries.empty())
852 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Anders Carlsson87eaf172009-02-08 00:50:42 +0000854 if (!Dest->getParent()) {
855 // We are trying to branch to a block that hasn't been inserted yet.
856 AddBranchFixup(BI);
857 return;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Anders Carlsson87eaf172009-02-08 00:50:42 +0000860 BlockScopeMap::iterator I = BlockScopes.find(Dest);
861 if (I == BlockScopes.end()) {
862 // We are trying to jump to a block that is outside of any cleanup scope.
863 AddBranchFixup(BI);
864 return;
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Anders Carlsson87eaf172009-02-08 00:50:42 +0000867 assert(I->second < CleanupEntries.size() &&
868 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Anders Carlsson87eaf172009-02-08 00:50:42 +0000870 if (I->second == CleanupEntries.size() - 1) {
871 // We have a branch to a block in the same scope.
872 return;
873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Anders Carlsson87eaf172009-02-08 00:50:42 +0000875 AddBranchFixup(BI);
876}