blob: 8a0b41a7cad2ddd5c39388170447558fa4644f49 [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) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000037 LLVMIntTy = ConvertType(getContext().IntTy);
38 LLVMPointerWidth = Target.getPointerWidth(0);
Mike Stumpd88ea562009-12-09 03:35:49 +000039 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000040 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Douglas Gregor35415f52010-05-25 17:04:15 +000041 CGM.getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000042}
Reid Spencer5f016e22007-07-11 17:01:13 +000043
44ASTContext &CodeGenFunction::getContext() const {
45 return CGM.getContext();
46}
47
48
49llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
50 llvm::BasicBlock *&BB = LabelMap[S];
51 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000052
Reid Spencer5f016e22007-07-11 17:01:13 +000053 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000054 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Daniel Dunbar0096acf2009-02-25 19:24:29 +000057llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
58 llvm::Value *Res = LocalDeclMap[VD];
59 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
60 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000061}
Reid Spencer5f016e22007-07-11 17:01:13 +000062
Daniel Dunbar0096acf2009-02-25 19:24:29 +000063llvm::Constant *
64CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
65 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000066}
67
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000068const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
69 return CGM.getTypes().ConvertTypeForMem(T);
70}
71
Reid Spencer5f016e22007-07-11 17:01:13 +000072const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
73 return CGM.getTypes().ConvertType(T);
74}
75
76bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000077 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
78 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000079}
80
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000081void CodeGenFunction::EmitReturnBlock() {
82 // For cleanliness, we try to avoid emitting the return block for
83 // simple cases.
84 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
85
86 if (CurBB) {
87 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
88
Daniel Dunbar96e18b02009-07-19 08:24:34 +000089 // We have a valid insert point, reuse it if it is empty or there are no
90 // explicit jumps to the return block.
91 if (CurBB->empty() || ReturnBlock->use_empty()) {
92 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000093 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000094 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000095 EmitBlock(ReturnBlock);
96 return;
97 }
98
99 // Otherwise, if the return block is the target of a single direct
100 // branch then we can just put the code in that block instead. This
101 // cleans up functions which started with a unified return block.
102 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000103 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000104 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
105 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
106 // Reset insertion point and delete the branch.
107 Builder.SetInsertPoint(BI->getParent());
108 BI->eraseFromParent();
109 delete ReturnBlock;
110 return;
111 }
112 }
113
Mike Stumpf5408fe2009-05-16 07:57:57 +0000114 // FIXME: We are at an unreachable point, there is no reason to emit the block
115 // unless it has uses. However, we still need a place to put the debug
116 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000117
118 EmitBlock(ReturnBlock);
119}
120
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000121void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000122 assert(BreakContinueStack.empty() &&
123 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000124 assert(BlockScopes.empty() &&
125 "did not remove all blocks from block scope map!");
126 assert(CleanupEntries.empty() &&
127 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000128
129 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000130 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000131
Chris Lattner7255a2d2010-06-22 00:03:40 +0000132 EmitFunctionInstrumentation("__cyg_profile_func_exit");
133
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000134 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000135 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000136 DI->setLocation(EndLoc);
137 DI->EmitRegionEnd(CurFn, Builder);
138 }
139
Daniel Dunbar88b53962009-02-02 22:03:45 +0000140 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000141 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000142
Chris Lattnerd9becd12009-10-28 23:59:40 +0000143 // If someone did an indirect goto, emit the indirect goto block at the end of
144 // the function.
145 if (IndirectBranch) {
146 EmitBlock(IndirectBranch->getParent());
147 Builder.ClearInsertionPoint();
148 }
149
Chris Lattner5a2fa142007-12-02 06:32:24 +0000150 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000151 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000152 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000153 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000154
155 // If someone took the address of a label but never did an indirect goto, we
156 // made a zero entry PHI node, which is illegal, zap it now.
157 if (IndirectBranch) {
158 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
159 if (PN->getNumIncomingValues() == 0) {
160 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
161 PN->eraseFromParent();
162 }
163 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000164}
165
Chris Lattner7255a2d2010-06-22 00:03:40 +0000166/// ShouldInstrumentFunction - Return true if the current function should be
167/// instrumented with __cyg_profile_func_* calls
168bool CodeGenFunction::ShouldInstrumentFunction() {
169 if (!CGM.getCodeGenOpts().InstrumentFunctions)
170 return false;
171 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
172 return false;
173 return true;
174}
175
176/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
177/// instrumentation function with the current function and the call site, if
178/// function instrumentation is enabled.
179void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
180 if (!ShouldInstrumentFunction())
181 return;
182
183 const llvm::FunctionType *FunctionTy;
184 std::vector<const llvm::Type*> ProfileFuncArgs;
185
186 ProfileFuncArgs.push_back(CurFn->getType());
187 ProfileFuncArgs.push_back(llvm::Type::getInt8PtrTy(VMContext));
188 FunctionTy = llvm::FunctionType::get(
189 llvm::Type::getVoidTy(VMContext),
190 ProfileFuncArgs, false);
191
192 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
193 llvm::CallInst *CallSite = Builder.CreateCall(
194 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
195 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0),
196 "callsite");
197
198 Builder.CreateCall2(F, CurFn, CallSite);
199}
200
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000201void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000202 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000203 const FunctionArgList &Args,
204 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000205 const Decl *D = GD.getDecl();
206
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000207 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000208 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000209 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000210 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000211 assert(CurFn->isDeclaration() && "Function already has body?");
212
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000213 // Pass inline keyword to optimizer if it appears explicitly on any
214 // declaration.
215 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
216 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
217 RE = FD->redecls_end(); RI != RE; ++RI)
218 if (RI->isInlineSpecified()) {
219 Fn->addFnAttr(llvm::Attribute::InlineHint);
220 break;
221 }
222
Daniel Dunbar55e87422008-11-11 02:29:29 +0000223 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000224
Chris Lattner41110242008-06-17 18:05:57 +0000225 // Create a marker to make it easy to insert allocas into the entryblock
226 // later. Don't create this with the builder, because we don't want it
227 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000228 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000229 AllocaInsertPt = new llvm::BitCastInst(Undef,
230 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000231 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000232 if (Builder.isNamePreserving())
233 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Daniel Dunbar55e87422008-11-11 02:29:29 +0000235 ReturnBlock = createBasicBlock("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattner41110242008-06-17 18:05:57 +0000237 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Douglas Gregorce056bc2010-02-21 22:15:06 +0000239 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
240 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000241 /*FIXME?*/
242 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000243
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000244 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000245 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000246 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000247 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000248 }
249
Chris Lattner7255a2d2010-06-22 00:03:40 +0000250 EmitFunctionInstrumentation("__cyg_profile_func_enter");
251
Daniel Dunbar88b53962009-02-02 22:03:45 +0000252 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000253 // CC info is ignored, hopefully?
254 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000255 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000256
257 if (RetTy->isVoidType()) {
258 // Void type; nothing to return.
259 ReturnValue = 0;
260 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
261 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
262 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000263 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000264 ReturnValue = CurFn->arg_begin();
265 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000266 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000267 }
268
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000269 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000270 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000271
John McCall25049412010-02-16 22:04:33 +0000272 if (CXXThisDecl)
273 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
274 if (CXXVTTDecl)
275 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
276
Anders Carlsson751358f2008-12-20 21:28:43 +0000277 // If any of the arguments have a variably modified type, make sure to
278 // emit the type size.
279 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
280 i != e; ++i) {
281 QualType Ty = i->second;
282
283 if (Ty->isVariablyModifiedType())
284 EmitVLASize(Ty);
285 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000286}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000287
John McCall9fc6a772010-02-19 09:25:03 +0000288void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
289 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000290 assert(FD->getBody());
291 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000292}
293
Anders Carlssonc997d422010-01-02 01:01:18 +0000294void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000295 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
296
Anders Carlssone896d982009-02-13 08:11:52 +0000297 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000298 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000299 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Daniel Dunbar7c086512008-09-09 23:14:03 +0000301 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000303 CurGD = GD;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000304 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
305 if (MD->isInstance()) {
306 // Create the implicit 'this' decl.
307 // FIXME: I'm not entirely sure I like using a fake decl just for code
308 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000309 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
310 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000311 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000312 MD->getThisType(getContext()));
313 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000314
315 // Check if we need a VTT parameter as well.
Anders Carlssonaf440352010-03-23 04:11:45 +0000316 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000317 // FIXME: The comment about using a fake decl above applies here too.
318 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
319 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000320 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000321 &getContext().Idents.get("vtt"), T);
322 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
323 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000324 }
325 }
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000327 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000328 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000329 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000330
331 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000332 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000333 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000334 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000335
John McCalla355e072010-02-18 03:17:58 +0000336 SourceRange BodyRange;
337 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000338
John McCalla355e072010-02-18 03:17:58 +0000339 // Emit the standard function prologue.
340 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000341
John McCalla355e072010-02-18 03:17:58 +0000342 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000343 if (isa<CXXDestructorDecl>(FD))
344 EmitDestructorBody(Args);
345 else if (isa<CXXConstructorDecl>(FD))
346 EmitConstructorBody(Args);
347 else
348 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000349
John McCalla355e072010-02-18 03:17:58 +0000350 // Emit the standard function epilogue.
351 FinishFunction(BodyRange.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000353 // Destroy the 'this' declaration.
354 if (CXXThisDecl)
355 CXXThisDecl->Destroy(getContext());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000356
357 // Destroy the VTT declaration.
358 if (CXXVTTDecl)
359 CXXVTTDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000360}
361
Chris Lattner0946ccd2008-11-11 07:41:27 +0000362/// ContainsLabel - Return true if the statement contains a label in it. If
363/// this statement is not executed normally, it not containing a label means
364/// that we can just remove the code.
365bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
366 // Null statement, not a label!
367 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Chris Lattner0946ccd2008-11-11 07:41:27 +0000369 // If this is a label, we have to emit the code, consider something like:
370 // if (0) { ... foo: bar(); } goto foo;
371 if (isa<LabelStmt>(S))
372 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Chris Lattner0946ccd2008-11-11 07:41:27 +0000374 // If this is a case/default statement, and we haven't seen a switch, we have
375 // to emit the code.
376 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
377 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner0946ccd2008-11-11 07:41:27 +0000379 // If this is a switch statement, we want to ignore cases below it.
380 if (isa<SwitchStmt>(S))
381 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Chris Lattner0946ccd2008-11-11 07:41:27 +0000383 // Scan subexpressions for verboten labels.
384 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
385 I != E; ++I)
386 if (ContainsLabel(*I, IgnoreCaseStmts))
387 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattner0946ccd2008-11-11 07:41:27 +0000389 return false;
390}
391
Chris Lattner31a09842008-11-12 08:04:58 +0000392
393/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
394/// a constant, or if it does but contains a label, return 0. If it constant
395/// folds to 'true' and does not contain a label, return 1, if it constant folds
396/// to 'false' and does not contain a label, return -1.
397int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000398 // FIXME: Rename and handle conversion of other evaluatable things
399 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000400 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000401 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000402 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000403 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner31a09842008-11-12 08:04:58 +0000405 if (CodeGenFunction::ContainsLabel(Cond))
406 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Anders Carlsson64712f12008-12-01 02:46:24 +0000408 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000409}
410
411
412/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
413/// statement) to the specified blocks. Based on the condition, this might try
414/// to simplify the codegen of the conditional based on the branch.
415///
416void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
417 llvm::BasicBlock *TrueBlock,
418 llvm::BasicBlock *FalseBlock) {
419 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
420 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner31a09842008-11-12 08:04:58 +0000422 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
423 // Handle X && Y in a condition.
424 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
425 // If we have "1 && X", simplify the code. "0 && X" would have constant
426 // folded if the case was simple enough.
427 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
428 // br(1 && X) -> br(X).
429 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Chris Lattner31a09842008-11-12 08:04:58 +0000432 // If we have "X && 1", simplify the code to use an uncond branch.
433 // "X && 0" would have been constant folded to 0.
434 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
435 // br(X && 1) -> br(X).
436 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner31a09842008-11-12 08:04:58 +0000439 // Emit the LHS as a conditional. If the LHS conditional is false, we
440 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000441 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000442 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
443 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Anders Carlsson08e9e452010-01-24 00:20:05 +0000445 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000446 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000447 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000448 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000449
Chris Lattner31a09842008-11-12 08:04:58 +0000450 return;
451 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
452 // If we have "0 || X", simplify the code. "1 || X" would have constant
453 // folded if the case was simple enough.
454 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
455 // br(0 || X) -> br(X).
456 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattner31a09842008-11-12 08:04:58 +0000459 // If we have "X || 0", simplify the code to use an uncond branch.
460 // "X || 1" would have been constant folded to 1.
461 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
462 // br(X || 0) -> br(X).
463 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner31a09842008-11-12 08:04:58 +0000466 // Emit the LHS as a conditional. If the LHS conditional is true, we
467 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000468 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000469 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
470 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlsson08e9e452010-01-24 00:20:05 +0000472 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000473 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000474 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000475 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000476
Chris Lattner31a09842008-11-12 08:04:58 +0000477 return;
478 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattner552f4c42008-11-12 08:13:36 +0000481 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
482 // br(!x, t, f) -> br(x, f, t)
483 if (CondUOp->getOpcode() == UnaryOperator::LNot)
484 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Daniel Dunbar09b14892008-11-12 10:30:32 +0000487 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
488 // Handle ?: operator.
489
490 // Just ignore GNU ?: extension.
491 if (CondOp->getLHS()) {
492 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
493 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
494 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
495 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
496 EmitBlock(LHSBlock);
497 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
498 EmitBlock(RHSBlock);
499 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
500 return;
501 }
502 }
503
Chris Lattner31a09842008-11-12 08:04:58 +0000504 // Emit the code with the fully general case.
505 llvm::Value *CondV = EvaluateExprAsBool(Cond);
506 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
507}
508
Daniel Dunbar488e9932008-08-16 00:56:44 +0000509/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000510/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000511void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
512 bool OmitOnError) {
513 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000514}
515
Anders Carlsson1884eb02010-05-22 17:35:42 +0000516void
517CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
518 // If the type contains a pointer to data member we can't memset it to zero.
519 // Instead, create a null constant and copy it to the destination.
520 if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
521 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
522
523 llvm::GlobalVariable *NullVariable =
524 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
525 /*isConstant=*/true,
526 llvm::GlobalVariable::PrivateLinkage,
527 NullConstant, llvm::Twine());
528 EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
529 return;
530 }
531
532
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000533 // Ignore empty classes in C++.
534 if (getContext().getLangOptions().CPlusPlus) {
535 if (const RecordType *RT = Ty->getAs<RecordType>()) {
536 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
537 return;
538 }
539 }
540
Anders Carlsson1884eb02010-05-22 17:35:42 +0000541 // Otherwise, just memset the whole thing to zero. This is legal
542 // because in LLVM, all default initializers (other than the ones we just
543 // handled above) are guaranteed to have a bit pattern of all zeros.
Chris Lattner36afd382009-10-13 06:02:42 +0000544 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000545 if (DestPtr->getType() != BP)
546 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
547
548 // Get size and alignment info for this aggregate.
549 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
550
Chris Lattner88207c92009-04-21 17:59:23 +0000551 // Don't bother emitting a zero-byte memset.
552 if (TypeInfo.first == 0)
553 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000555 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000556 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000557 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000558
Mon P Wang3ecd7852010-04-04 03:10:52 +0000559 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000560 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000561 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000562 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000563 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Mon P Wang3ecd7852010-04-04 03:10:52 +0000564 TypeInfo.second/8),
565 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
566 0));
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000567}
568
Chris Lattnerd9becd12009-10-28 23:59:40 +0000569llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
570 // Make sure that there is a block for the indirect goto.
571 if (IndirectBranch == 0)
572 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000573
Chris Lattnerd9becd12009-10-28 23:59:40 +0000574 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000575
Chris Lattnerd9becd12009-10-28 23:59:40 +0000576 // Make sure the indirect branch includes all of the address-taken blocks.
577 IndirectBranch->addDestination(BB);
578 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000579}
580
581llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000582 // If we already made the indirect branch for indirect goto, return its block.
583 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000584
Chris Lattnerd9becd12009-10-28 23:59:40 +0000585 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000586
Chris Lattnerd9becd12009-10-28 23:59:40 +0000587 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000588
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000589 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000590 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000591
Chris Lattnerd9becd12009-10-28 23:59:40 +0000592 // Create the indirect branch instruction.
593 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
594 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000595}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000596
Daniel Dunbard286f052009-07-19 06:58:07 +0000597llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000598 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Anders Carlssonf666b772008-12-20 20:27:15 +0000600 assert(SizeEntry && "Did not emit size for type");
601 return SizeEntry;
602}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000603
Daniel Dunbard286f052009-07-19 06:58:07 +0000604llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000605 assert(Ty->isVariablyModifiedType() &&
606 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Daniel Dunbard286f052009-07-19 06:58:07 +0000608 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Anders Carlsson60d35412008-12-20 20:46:34 +0000610 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000611 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000613 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000614 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000616 // Get the element size;
617 QualType ElemTy = VAT->getElementType();
618 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000619 if (ElemTy->isVariableArrayType())
620 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000621 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000622 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000623 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000625 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000626 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000628 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Anders Carlsson60d35412008-12-20 20:46:34 +0000631 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000632 }
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000634 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
635 EmitVLASize(AT->getElementType());
636 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000637 }
638
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000639 const PointerType *PT = Ty->getAs<PointerType>();
640 assert(PT && "unknown VM type!");
641 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000642 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000643}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000644
645llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
646 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
647 return EmitScalarExpr(E);
648 }
649 return EmitLValue(E).getAddress();
650}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000651
Fariborz Jahanian77996212009-11-04 17:57:40 +0000652void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump99533832009-12-02 07:41:41 +0000653 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000654 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump99533832009-12-02 07:41:41 +0000655 bool EHOnly) {
656 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpd88ea562009-12-09 03:35:49 +0000657 PreviousInvokeDest, EHOnly));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000658}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000659
Mike Stump1eb44332009-09-09 15:08:12 +0000660void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
661 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000662 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Anders Carlssonc71c8452009-02-07 23:50:39 +0000664 while (CleanupEntries.size() > OldCleanupStackSize)
665 EmitCleanupBlock();
666}
667
Mike Stump1eb44332009-09-09 15:08:12 +0000668CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000669 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Fariborz Jahanian77996212009-11-04 17:57:40 +0000671 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000673 std::vector<llvm::BasicBlock *> Blocks;
674 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000676 std::vector<llvm::BranchInst *> BranchFixups;
677 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Mike Stump99533832009-12-02 07:41:41 +0000679 bool EHOnly = CE.EHOnly;
680
Mike Stumpd88ea562009-12-09 03:35:49 +0000681 setInvokeDest(CE.PreviousInvokeDest);
682
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000683 CleanupEntries.pop_back();
684
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000685 // Check if any branch fixups pointed to the scope we just popped. If so,
686 // we can remove them.
687 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
688 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
689 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000691 if (I == BlockScopes.end())
692 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000694 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000696 if (I->second == CleanupEntries.size()) {
697 // We don't need to do this branch fixup.
698 BranchFixups[i] = BranchFixups.back();
699 BranchFixups.pop_back();
700 i--;
701 e--;
702 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000703 }
704 }
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Fariborz Jahanian77996212009-11-04 17:57:40 +0000706 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000707 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000708 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000709 if (!SwitchBlock)
710 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000711 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000713 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000715 Builder.SetInsertPoint(SwitchBlock);
716
Mike Stump99533832009-12-02 07:41:41 +0000717 llvm::Value *DestCodePtr
718 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
719 "cleanup.dst");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000720 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000722 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000723 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000724 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000725
Anders Carlsson46831a92009-02-08 22:13:37 +0000726 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000727 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000728 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000730 // If we had a current basic block, we also need to emit an instruction
731 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000732 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000733 DestCodePtr);
734 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000735 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000736
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000737 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
738 llvm::BranchInst *BI = BranchFixups[i];
739 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000741 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000742 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000744 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000745 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Anders Carlssoncc899202009-02-08 22:46:50 +0000747 // Check if we already have a destination for this block.
748 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000749 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000750 else {
751 ID = SI->findCaseDest(Dest);
752 if (!ID) {
753 // No code found, get a new unique one by using the number of
754 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000755 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000756 SI->getNumSuccessors());
757 SI->addCase(ID, Dest);
758 }
759 }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Anders Carlssoncc899202009-02-08 22:46:50 +0000761 // Store the jump destination before the branch instruction.
762 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000763 } else {
764 // We need to jump through another cleanup block. Create a pad block
Mike Stump99533832009-12-02 07:41:41 +0000765 // with a branch instruction that jumps to the final destination and add
766 // it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000768 // Create the pad block.
769 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000770
771 // Create a unique case ID.
Mike Stump99533832009-12-02 07:41:41 +0000772 llvm::ConstantInt *ID
773 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
774 SI->getNumSuccessors());
Anders Carlssoncc899202009-02-08 22:46:50 +0000775
776 // Store the jump destination before the branch instruction.
777 new llvm::StoreInst(ID, DestCodePtr, BI);
778
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000779 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000780 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000782 // Create the branch to the final destination.
783 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
784 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000786 // And add it as a branch fixup.
787 CleanupEntries.back().BranchFixups.push_back(BI);
788 }
789 }
790 }
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000792 // Remove all blocks from the block scope map.
793 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
794 assert(BlockScopes.count(Blocks[i]) &&
795 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000797 BlockScopes.erase(Blocks[i]);
798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Mike Stump99533832009-12-02 07:41:41 +0000800 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000801}
802
Mike Stump1eb44332009-09-09 15:08:12 +0000803void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000804 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Mike Stump99533832009-12-02 07:41:41 +0000806 if (Info.EHOnly) {
807 // FIXME: Add this to the exceptional edge
808 if (Info.CleanupBlock->getNumUses() == 0)
809 delete Info.CleanupBlock;
810 return;
811 }
812
Devang Patelcd9199e2010-04-13 00:08:43 +0000813 // Scrub debug location info.
814 for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
815 LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
816 Builder.SetInstDebugLocation(LBI);
817
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000818 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000819 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000820 Info.CleanupBlock->getNumUses() == 0) {
821 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
822 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000823 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000824 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000826 if (Info.SwitchBlock)
827 EmitBlock(Info.SwitchBlock);
828 if (Info.EndBlock)
829 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000830}
831
Mike Stump1eb44332009-09-09 15:08:12 +0000832void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
833 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000834 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Mike Stumpf5408fe2009-05-16 07:57:57 +0000836 // FIXME: We could be more clever here and check if there's already a branch
837 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000838 CleanupEntries.back().BranchFixups.push_back(BI);
839}
840
Mike Stump1eb44332009-09-09 15:08:12 +0000841void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000842 if (!HaveInsertPoint())
843 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Anders Carlsson87eaf172009-02-08 00:50:42 +0000845 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Anders Carlsson46831a92009-02-08 22:13:37 +0000847 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Anders Carlsson87eaf172009-02-08 00:50:42 +0000849 // The stack is empty, no need to do any cleanup.
850 if (CleanupEntries.empty())
851 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Anders Carlsson87eaf172009-02-08 00:50:42 +0000853 if (!Dest->getParent()) {
854 // We are trying to branch to a block that hasn't been inserted yet.
855 AddBranchFixup(BI);
856 return;
857 }
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Anders Carlsson87eaf172009-02-08 00:50:42 +0000859 BlockScopeMap::iterator I = BlockScopes.find(Dest);
860 if (I == BlockScopes.end()) {
861 // We are trying to jump to a block that is outside of any cleanup scope.
862 AddBranchFixup(BI);
863 return;
864 }
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Anders Carlsson87eaf172009-02-08 00:50:42 +0000866 assert(I->second < CleanupEntries.size() &&
867 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Anders Carlsson87eaf172009-02-08 00:50:42 +0000869 if (I->second == CleanupEntries.size() - 1) {
870 // We have a branch to a block in the same scope.
871 return;
872 }
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Anders Carlsson87eaf172009-02-08 00:50:42 +0000874 AddBranchFixup(BI);
875}