blob: 696c8f516570462b137024b61ff6a7c8973b9ee4 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +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 Friedman17630752008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattnerd1af2d22007-05-29 23:17:50 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattnercd439292008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson468fa632009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stumpbee78dd2009-12-04 23:26:17 +000022#include "clang/AST/StmtCXX.h"
Chris Lattner3c77a352010-06-22 00:03:40 +000023#include "clang/Frontend/CodeGenOptions.h"
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000024#include "llvm/Target/TargetData.h"
Chris Lattner3c77a352010-06-22 00:03:40 +000025#include "llvm/Intrinsics.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000026using namespace clang;
27using namespace CodeGen;
28
Mike Stump11289f42009-09-09 15:08:12 +000029CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stump0c743272009-03-06 01:33:24 +000030 : BlockFunction(cgm, *this, Builder), CGM(cgm),
31 Target(CGM.getContext().Target),
Owen Andersonc9673d52009-07-08 20:52:20 +000032 Builder(cgm.getModule().getContext()),
Chris Lattner6c4d2552009-10-28 23:59:40 +000033 DebugInfo(0), IndirectBranch(0),
Chris Lattner2bb5cb42009-10-13 06:55:33 +000034 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
John McCall347132b2010-02-16 22:04:33 +000035 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
Anders Carlsson9eb101c2010-06-08 22:30:17 +000036 ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0) {
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000037 LLVMIntTy = ConvertType(getContext().IntTy);
38 LLVMPointerWidth = Target.getPointerWidth(0);
Mike Stumpaff69af2009-12-09 03:35:49 +000039 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stumpd9546382009-12-12 01:27:46 +000040 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Douglas Gregor7e10f362010-05-25 17:04:15 +000041 CGM.getMangleContext().startNewFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +000042}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000043
Chris Lattner6db1fb82007-06-02 22:49:07 +000044ASTContext &CodeGenFunction::getContext() const {
45 return CGM.getContext();
46}
47
Chris Lattnerd1af2d22007-05-29 23:17:50 +000048
Chris Lattnerac248202007-05-30 00:13:02 +000049llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
Chris Lattner23b7eb62007-06-15 23:05:46 +000050 llvm::BasicBlock *&BB = LabelMap[S];
Chris Lattnerac248202007-05-30 00:13:02 +000051 if (BB) return BB;
Mike Stump11289f42009-09-09 15:08:12 +000052
Chris Lattnerac248202007-05-30 00:13:02 +000053 // Create, but don't insert, the new block.
Daniel Dunbar75283ff2008-11-11 02:29:29 +000054 return BB = createBasicBlock(S->getName());
Chris Lattnerac248202007-05-30 00:13:02 +000055}
56
Daniel Dunbar22a87f92009-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 Venancio01a72ff2008-02-26 21:41:45 +000061}
Chris Lattnerac248202007-05-30 00:13:02 +000062
Daniel Dunbar22a87f92009-02-25 19:24:29 +000063llvm::Constant *
64CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
65 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson9396a892008-09-11 09:15:33 +000066}
67
Daniel Dunbaree3da872009-02-03 23:03:55 +000068const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
69 return CGM.getTypes().ConvertTypeForMem(T);
70}
71
Chris Lattnerf033c142007-06-22 19:05:19 +000072const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
73 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +000074}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000075
Chris Lattner54fb19e2007-06-22 22:02:34 +000076bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssonb05a3e52009-09-29 02:09:01 +000077 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
78 T->isMemberFunctionPointerType();
Chris Lattner54fb19e2007-06-22 22:02:34 +000079}
80
Daniel Dunbarfd346a32009-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 Dunbarea3060a2009-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 Dunbarfd346a32009-01-26 23:27:52 +000093 delete ReturnBlock;
Daniel Dunbarea3060a2009-07-19 08:24:34 +000094 } else
Daniel Dunbarfd346a32009-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 Stump11289f42009-09-09 15:08:12 +0000103 llvm::BranchInst *BI =
Daniel Dunbarfd346a32009-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 Stump18bb9282009-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 Dunbarfd346a32009-01-26 23:27:52 +0000117
118 EmitBlock(ReturnBlock);
119}
120
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000121void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000122 assert(BreakContinueStack.empty() &&
123 "mismatched push/pop in break/continue stack!");
Anders Carlssonfbfb5e62009-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 Stump11289f42009-09-09 15:08:12 +0000128
129 // Emit function epilog (to return).
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000130 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000131
Chris Lattner3c77a352010-06-22 00:03:40 +0000132 EmitFunctionInstrumentation("__cyg_profile_func_exit");
133
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000134 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000135 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000136 DI->setLocation(EndLoc);
137 DI->EmitRegionEnd(CurFn, Builder);
138 }
139
Chris Lattner3fcc7902010-06-27 01:06:27 +0000140 EmitFunctionEpilog(*CurFnInfo);
Mike Stump1d849212009-12-07 23:38:24 +0000141 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000142
Chris Lattner6c4d2552009-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 Lattnerc48023b2007-12-02 06:32:24 +0000150 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000151 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerc48023b2007-12-02 06:32:24 +0000152 AllocaInsertPt = 0;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000153 Ptr->eraseFromParent();
Chris Lattner6c4d2552009-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 }
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000164}
Chris Lattner308f4312007-05-29 23:50:05 +0000165
Chris Lattner3c77a352010-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
Chris Lattnerb48a2d52010-06-23 05:21:28 +0000183 const llvm::PointerType *PointerTy;
Chris Lattner3c77a352010-06-22 00:03:40 +0000184 const llvm::FunctionType *FunctionTy;
185 std::vector<const llvm::Type*> ProfileFuncArgs;
186
Chris Lattnerb48a2d52010-06-23 05:21:28 +0000187 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
188 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
189 ProfileFuncArgs.push_back(PointerTy);
190 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner3c77a352010-06-22 00:03:40 +0000191 FunctionTy = llvm::FunctionType::get(
192 llvm::Type::getVoidTy(VMContext),
193 ProfileFuncArgs, false);
194
195 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
196 llvm::CallInst *CallSite = Builder.CreateCall(
197 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
198 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0),
199 "callsite");
200
Chris Lattnerb48a2d52010-06-23 05:21:28 +0000201 Builder.CreateCall2(F,
202 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
203 CallSite);
Chris Lattner3c77a352010-06-22 00:03:40 +0000204}
205
Anders Carlsson73fcc952009-09-11 00:07:24 +0000206void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000207 llvm::Function *Fn,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000208 const FunctionArgList &Args,
209 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000210 const Decl *D = GD.getDecl();
211
Anders Carlssonf4478e92009-02-09 20:20:56 +0000212 DidCallStackSave = false;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000213 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000214 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000215 CurFn = Fn;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000216 assert(CurFn->isDeclaration() && "Function already has body?");
217
Jakob Stoklund Olesen819e54b2010-02-09 00:10:00 +0000218 // Pass inline keyword to optimizer if it appears explicitly on any
219 // declaration.
220 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
221 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
222 RE = FD->redecls_end(); RI != RE; ++RI)
223 if (RI->isInlineSpecified()) {
224 Fn->addFnAttr(llvm::Attribute::InlineHint);
225 break;
226 }
227
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000228 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000229
Chris Lattner5696e7b2008-06-17 18:05:57 +0000230 // Create a marker to make it easy to insert allocas into the entryblock
231 // later. Don't create this with the builder, because we don't want it
232 // folded.
Owen Anderson41a75022009-08-13 21:57:51 +0000233 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stump1dbb8f72009-09-25 18:11:00 +0000234 AllocaInsertPt = new llvm::BitCastInst(Undef,
235 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner5696e7b2008-06-17 18:05:57 +0000236 EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000237 if (Builder.isNamePreserving())
238 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000239
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000240 ReturnBlock = createBasicBlock("return");
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner5696e7b2008-06-17 18:05:57 +0000242 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000243
Douglas Gregor36c569f2010-02-21 22:15:06 +0000244 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
245 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000246 /*FIXME?*/
247 FunctionType::ExtInfo());
Mike Stumpae2559a2009-10-23 01:52:13 +0000248
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000249 // Emit subprogram debug descriptor.
Anders Carlsson63784f42009-02-13 08:11:52 +0000250 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar354d2782008-10-18 18:22:23 +0000251 DI->setLocation(StartLoc);
Devang Patel934661e2010-01-14 00:36:21 +0000252 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000253 }
254
Chris Lattner3c77a352010-06-22 00:03:40 +0000255 EmitFunctionInstrumentation("__cyg_profile_func_enter");
256
Daniel Dunbard931a872009-02-02 22:03:45 +0000257 // FIXME: Leaked.
John McCallab26cfa2010-02-05 21:31:56 +0000258 // CC info is ignored, hopefully?
259 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000260 FunctionType::ExtInfo());
Eli Friedman4b1942c2009-12-04 02:43:40 +0000261
262 if (RetTy->isVoidType()) {
263 // Void type; nothing to return.
264 ReturnValue = 0;
265 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
266 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
267 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000268 // This reduces code size, and affects correctness in C++.
Eli Friedman4b1942c2009-12-04 02:43:40 +0000269 ReturnValue = CurFn->arg_begin();
270 } else {
Daniel Dunbarfd09df72010-02-16 19:45:20 +0000271 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedman4b1942c2009-12-04 02:43:40 +0000272 }
273
Mike Stump1d849212009-12-07 23:38:24 +0000274 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbard931a872009-02-02 22:03:45 +0000275 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000276
John McCall347132b2010-02-16 22:04:33 +0000277 if (CXXThisDecl)
278 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
279 if (CXXVTTDecl)
280 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
281
Anders Carlssonc20879a2008-12-20 21:28:43 +0000282 // If any of the arguments have a variably modified type, make sure to
283 // emit the type size.
284 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
285 i != e; ++i) {
286 QualType Ty = i->second;
287
288 if (Ty->isVariablyModifiedType())
289 EmitVLASize(Ty);
290 }
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000291}
Eli Friedman3d421e12008-08-25 21:31:01 +0000292
John McCallb81884d2010-02-19 09:25:03 +0000293void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
294 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregorb139cd52010-05-01 20:49:11 +0000295 assert(FD->getBody());
296 EmitStmt(FD->getBody());
John McCall89b12b32010-02-18 03:17:58 +0000297}
298
Anders Carlssone36a6b32010-01-02 01:01:18 +0000299void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000300 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
301
Anders Carlsson63784f42009-02-13 08:11:52 +0000302 // Check if we should generate debug info for this function.
Mike Stump3722f582009-08-26 22:31:08 +0000303 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlsson63784f42009-02-13 08:11:52 +0000304 DebugInfo = CGM.getDebugInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000306 FunctionArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000307
Mike Stumpbee78dd2009-12-04 23:26:17 +0000308 CurGD = GD;
Anders Carlsson468fa632009-04-04 20:47:02 +0000309 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
310 if (MD->isInstance()) {
311 // Create the implicit 'this' decl.
312 // FIXME: I'm not entirely sure I like using a fake decl just for code
313 // generation. Maybe we can come up with a better way?
John McCall347132b2010-02-16 22:04:33 +0000314 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
315 FD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +0000316 &getContext().Idents.get("this"),
Anders Carlsson468fa632009-04-04 20:47:02 +0000317 MD->getThisType(getContext()));
318 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000319
320 // Check if we need a VTT parameter as well.
Anders Carlssona864caf2010-03-23 04:11:45 +0000321 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000322 // FIXME: The comment about using a fake decl above applies here too.
323 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
324 CXXVTTDecl =
John McCall347132b2010-02-16 22:04:33 +0000325 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000326 &getContext().Idents.get("vtt"), T);
327 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
328 }
Anders Carlsson468fa632009-04-04 20:47:02 +0000329 }
330 }
Mike Stump11289f42009-09-09 15:08:12 +0000331
Eli Friedman3d421e12008-08-25 21:31:01 +0000332 if (FD->getNumParams()) {
John McCall9dd450b2009-09-21 23:43:11 +0000333 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedman3d421e12008-08-25 21:31:01 +0000334 assert(FProto && "Function def must have prototype!");
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000335
336 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump11289f42009-09-09 15:08:12 +0000337 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000338 FProto->getArgType(i)));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000339 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000340
John McCall89b12b32010-02-18 03:17:58 +0000341 SourceRange BodyRange;
342 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson438cf922009-11-06 02:55:43 +0000343
John McCall89b12b32010-02-18 03:17:58 +0000344 // Emit the standard function prologue.
345 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson438cf922009-11-06 02:55:43 +0000346
John McCall89b12b32010-02-18 03:17:58 +0000347 // Generate the body of the function.
John McCallb81884d2010-02-19 09:25:03 +0000348 if (isa<CXXDestructorDecl>(FD))
349 EmitDestructorBody(Args);
350 else if (isa<CXXConstructorDecl>(FD))
351 EmitConstructorBody(Args);
352 else
353 EmitFunctionBody(Args);
Anders Carlssonff8cce42010-02-07 19:45:40 +0000354
John McCall89b12b32010-02-18 03:17:58 +0000355 // Emit the standard function epilogue.
356 FinishFunction(BodyRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000357
Anders Carlsson468fa632009-04-04 20:47:02 +0000358 // Destroy the 'this' declaration.
359 if (CXXThisDecl)
360 CXXThisDecl->Destroy(getContext());
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000361
362 // Destroy the VTT declaration.
363 if (CXXVTTDecl)
364 CXXVTTDecl->Destroy(getContext());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000365}
366
Chris Lattner5b1964b2008-11-11 07:41:27 +0000367/// ContainsLabel - Return true if the statement contains a label in it. If
368/// this statement is not executed normally, it not containing a label means
369/// that we can just remove the code.
370bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
371 // Null statement, not a label!
372 if (S == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattner5b1964b2008-11-11 07:41:27 +0000374 // If this is a label, we have to emit the code, consider something like:
375 // if (0) { ... foo: bar(); } goto foo;
376 if (isa<LabelStmt>(S))
377 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000378
Chris Lattner5b1964b2008-11-11 07:41:27 +0000379 // If this is a case/default statement, and we haven't seen a switch, we have
380 // to emit the code.
381 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
382 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000383
Chris Lattner5b1964b2008-11-11 07:41:27 +0000384 // If this is a switch statement, we want to ignore cases below it.
385 if (isa<SwitchStmt>(S))
386 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Chris Lattner5b1964b2008-11-11 07:41:27 +0000388 // Scan subexpressions for verboten labels.
389 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
390 I != E; ++I)
391 if (ContainsLabel(*I, IgnoreCaseStmts))
392 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattner5b1964b2008-11-11 07:41:27 +0000394 return false;
395}
396
Chris Lattnercd439292008-11-12 08:04:58 +0000397
398/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
399/// a constant, or if it does but contains a label, return 0. If it constant
400/// folds to 'true' and does not contain a label, return 1, if it constant folds
401/// to 'false' and does not contain a label, return -1.
402int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000403 // FIXME: Rename and handle conversion of other evaluatable things
404 // to bool.
Anders Carlsson86286452008-12-01 02:46:24 +0000405 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +0000406 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson86286452008-12-01 02:46:24 +0000407 Result.HasSideEffects)
Anders Carlsson4046e652008-11-22 22:32:07 +0000408 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump11289f42009-09-09 15:08:12 +0000409
Chris Lattnercd439292008-11-12 08:04:58 +0000410 if (CodeGenFunction::ContainsLabel(Cond))
411 return 0; // Contains a label.
Mike Stump11289f42009-09-09 15:08:12 +0000412
Anders Carlsson86286452008-12-01 02:46:24 +0000413 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattnercd439292008-11-12 08:04:58 +0000414}
415
416
417/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
418/// statement) to the specified blocks. Based on the condition, this might try
419/// to simplify the codegen of the conditional based on the branch.
420///
421void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
422 llvm::BasicBlock *TrueBlock,
423 llvm::BasicBlock *FalseBlock) {
424 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
425 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattnercd439292008-11-12 08:04:58 +0000427 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
428 // Handle X && Y in a condition.
429 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
430 // If we have "1 && X", simplify the code. "0 && X" would have constant
431 // folded if the case was simple enough.
432 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
433 // br(1 && X) -> br(X).
434 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
435 }
Mike Stump11289f42009-09-09 15:08:12 +0000436
Chris Lattnercd439292008-11-12 08:04:58 +0000437 // If we have "X && 1", simplify the code to use an uncond branch.
438 // "X && 0" would have been constant folded to 0.
439 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
440 // br(X && 1) -> br(X).
441 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
442 }
Mike Stump11289f42009-09-09 15:08:12 +0000443
Chris Lattnercd439292008-11-12 08:04:58 +0000444 // Emit the LHS as a conditional. If the LHS conditional is false, we
445 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000446 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattnercd439292008-11-12 08:04:58 +0000447 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
448 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +0000449
Anders Carlsson60ddba62010-01-24 00:20:05 +0000450 // Any temporaries created here are conditional.
Anders Carlssonae612d22010-02-04 17:18:07 +0000451 BeginConditionalBranch();
Chris Lattnercd439292008-11-12 08:04:58 +0000452 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlssonae612d22010-02-04 17:18:07 +0000453 EndConditionalBranch();
Anders Carlsson60ddba62010-01-24 00:20:05 +0000454
Chris Lattnercd439292008-11-12 08:04:58 +0000455 return;
456 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
457 // If we have "0 || X", simplify the code. "1 || X" would have constant
458 // folded if the case was simple enough.
459 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
460 // br(0 || X) -> br(X).
461 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
462 }
Mike Stump11289f42009-09-09 15:08:12 +0000463
Chris Lattnercd439292008-11-12 08:04:58 +0000464 // If we have "X || 0", simplify the code to use an uncond branch.
465 // "X || 1" would have been constant folded to 1.
466 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
467 // br(X || 0) -> br(X).
468 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Chris Lattnercd439292008-11-12 08:04:58 +0000471 // Emit the LHS as a conditional. If the LHS conditional is true, we
472 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000473 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattnercd439292008-11-12 08:04:58 +0000474 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
475 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +0000476
Anders Carlsson60ddba62010-01-24 00:20:05 +0000477 // Any temporaries created here are conditional.
Anders Carlssonae612d22010-02-04 17:18:07 +0000478 BeginConditionalBranch();
Chris Lattnercd439292008-11-12 08:04:58 +0000479 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlssonae612d22010-02-04 17:18:07 +0000480 EndConditionalBranch();
Anders Carlsson60ddba62010-01-24 00:20:05 +0000481
Chris Lattnercd439292008-11-12 08:04:58 +0000482 return;
483 }
Chris Lattnerd9537732008-11-12 08:13:36 +0000484 }
Mike Stump11289f42009-09-09 15:08:12 +0000485
Chris Lattnerd9537732008-11-12 08:13:36 +0000486 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
487 // br(!x, t, f) -> br(x, f, t)
488 if (CondUOp->getOpcode() == UnaryOperator::LNot)
489 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattnercd439292008-11-12 08:04:58 +0000490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +0000492 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
493 // Handle ?: operator.
494
495 // Just ignore GNU ?: extension.
496 if (CondOp->getLHS()) {
497 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
498 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
499 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
500 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
501 EmitBlock(LHSBlock);
502 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
503 EmitBlock(RHSBlock);
504 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
505 return;
506 }
507 }
508
Chris Lattnercd439292008-11-12 08:04:58 +0000509 // Emit the code with the fully general case.
510 llvm::Value *CondV = EvaluateExprAsBool(Cond);
511 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
512}
513
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000514/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +0000515/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000516void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
517 bool OmitOnError) {
518 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerfc944342007-12-02 01:43:38 +0000519}
520
Anders Carlssonc0964b62010-05-22 17:35:42 +0000521void
522CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
523 // If the type contains a pointer to data member we can't memset it to zero.
524 // Instead, create a null constant and copy it to the destination.
525 if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
526 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
527
528 llvm::GlobalVariable *NullVariable =
529 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
530 /*isConstant=*/true,
531 llvm::GlobalVariable::PrivateLinkage,
532 NullConstant, llvm::Twine());
533 EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
534 return;
535 }
536
537
Anders Carlsson16e94af2010-05-03 01:20:20 +0000538 // Ignore empty classes in C++.
539 if (getContext().getLangOptions().CPlusPlus) {
540 if (const RecordType *RT = Ty->getAs<RecordType>()) {
541 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
542 return;
543 }
544 }
545
Anders Carlssonc0964b62010-05-22 17:35:42 +0000546 // Otherwise, just memset the whole thing to zero. This is legal
547 // because in LLVM, all default initializers (other than the ones we just
548 // handled above) are guaranteed to have a bit pattern of all zeros.
Chris Lattnerdd7eaad2009-10-13 06:02:42 +0000549 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000550 if (DestPtr->getType() != BP)
551 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
552
553 // Get size and alignment info for this aggregate.
554 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
555
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000556 // Don't bother emitting a zero-byte memset.
557 if (TypeInfo.first == 0)
558 return;
Mike Stump11289f42009-09-09 15:08:12 +0000559
Anders Carlsson2e744e82008-08-30 19:51:14 +0000560 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +0000561 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000562 LLVMPointerWidth);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000563
Mon P Wangcc2ab0c2010-04-04 03:10:52 +0000564 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
Owen Anderson41a75022009-08-13 21:57:51 +0000565 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000566 // TypeInfo.first describes size in bits.
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000567 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump11289f42009-09-09 15:08:12 +0000568 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Mon P Wangcc2ab0c2010-04-04 03:10:52 +0000569 TypeInfo.second/8),
570 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
571 0));
Anders Carlsson2e744e82008-08-30 19:51:14 +0000572}
573
Chris Lattner6c4d2552009-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 Lattner2bb5cb42009-10-13 06:55:33 +0000578
Chris Lattner6c4d2552009-10-28 23:59:40 +0000579 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000580
Chris Lattner6c4d2552009-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 Lattner2bb5cb42009-10-13 06:55:33 +0000584}
585
586llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattner6c4d2552009-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 Lattner2bb5cb42009-10-13 06:55:33 +0000589
Chris Lattner6c4d2552009-10-28 23:59:40 +0000590 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000591
Chris Lattner6c4d2552009-10-28 23:59:40 +0000592 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattnera0c0d882009-10-28 20:36:47 +0000593
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000594 // Create the PHI node that indirect gotos will add entries to.
Chris Lattner6c4d2552009-10-28 23:59:40 +0000595 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000596
Chris Lattner6c4d2552009-10-28 23:59:40 +0000597 // Create the indirect branch instruction.
598 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
599 return IndirectBranch->getParent();
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000600}
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000601
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000602llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000603 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000604
Anders Carlssone388a5b2008-12-20 20:27:15 +0000605 assert(SizeEntry && "Did not emit size for type");
606 return SizeEntry;
607}
Anders Carlssonccbe9202008-12-12 07:19:02 +0000608
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000609llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson8a01b792008-12-20 20:46:34 +0000610 assert(Ty->isVariablyModifiedType() &&
611 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +0000612
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000613 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000614
Anders Carlsson8a01b792008-12-20 20:46:34 +0000615 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000616 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000617
Anders Carlsson5d985f52008-12-20 21:51:53 +0000618 if (!SizeEntry) {
Anders Carlsson31f86492009-02-05 19:43:10 +0000619 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000620
Chris Lattner8dc76262009-08-15 00:03:43 +0000621 // Get the element size;
622 QualType ElemTy = VAT->getElementType();
623 llvm::Value *ElemSize;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000624 if (ElemTy->isVariableArrayType())
625 ElemSize = EmitVLASize(ElemTy);
Chris Lattner8dc76262009-08-15 00:03:43 +0000626 else
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000627 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck40775002010-01-11 17:06:35 +0000628 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump11289f42009-09-09 15:08:12 +0000629
Anders Carlsson5d985f52008-12-20 21:51:53 +0000630 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson31f86492009-02-05 19:43:10 +0000631 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000632
Anders Carlsson5d985f52008-12-20 21:51:53 +0000633 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson8a01b792008-12-20 20:46:34 +0000634 }
Mike Stump11289f42009-09-09 15:08:12 +0000635
Anders Carlsson8a01b792008-12-20 20:46:34 +0000636 return SizeEntry;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000637 }
Mike Stump11289f42009-09-09 15:08:12 +0000638
Chris Lattner8dc76262009-08-15 00:03:43 +0000639 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
640 EmitVLASize(AT->getElementType());
641 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000642 }
643
Chris Lattner8dc76262009-08-15 00:03:43 +0000644 const PointerType *PT = Ty->getAs<PointerType>();
645 assert(PT && "unknown VM type!");
646 EmitVLASize(PT->getPointeeType());
Anders Carlsson8a01b792008-12-20 20:46:34 +0000647 return 0;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000648}
Eli Friedmanddea0ad2009-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 Carlsson15cb75a2009-02-07 22:53:43 +0000656
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000657void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
Mike Stump33270212009-12-02 07:41:41 +0000658 llvm::BasicBlock *CleanupExitBlock,
Mike Stumpaff69af2009-12-09 03:35:49 +0000659 llvm::BasicBlock *PreviousInvokeDest,
Mike Stump33270212009-12-02 07:41:41 +0000660 bool EHOnly) {
661 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
Mike Stumpaff69af2009-12-09 03:35:49 +0000662 PreviousInvokeDest, EHOnly));
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000663}
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000664
Mike Stump11289f42009-09-09 15:08:12 +0000665void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
666 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000667 "Cleanup stack mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000668
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000669 while (CleanupEntries.size() > OldCleanupStackSize)
670 EmitCleanupBlock();
671}
672
Mike Stump11289f42009-09-09 15:08:12 +0000673CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000674 CleanupEntry &CE = CleanupEntries.back();
Mike Stump11289f42009-09-09 15:08:12 +0000675
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000676 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000677
Anders Carlsson66c384a2009-02-08 07:46:24 +0000678 std::vector<llvm::BasicBlock *> Blocks;
679 std::swap(Blocks, CE.Blocks);
Mike Stump11289f42009-09-09 15:08:12 +0000680
Anders Carlsson66c384a2009-02-08 07:46:24 +0000681 std::vector<llvm::BranchInst *> BranchFixups;
682 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump11289f42009-09-09 15:08:12 +0000683
Mike Stump33270212009-12-02 07:41:41 +0000684 bool EHOnly = CE.EHOnly;
685
Mike Stumpaff69af2009-12-09 03:35:49 +0000686 setInvokeDest(CE.PreviousInvokeDest);
687
Anders Carlsson66c384a2009-02-08 07:46:24 +0000688 CleanupEntries.pop_back();
689
Anders Carlssonf57b9ee2009-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 Stump11289f42009-09-09 15:08:12 +0000695
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000696 if (I == BlockScopes.end())
697 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000698
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000699 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump11289f42009-09-09 15:08:12 +0000700
Anders Carlssonf57b9ee2009-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 Carlsson3c21dd52009-02-08 01:23:05 +0000708 }
709 }
Mike Stump11289f42009-09-09 15:08:12 +0000710
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000711 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlsson66c384a2009-02-08 07:46:24 +0000712 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000713 if (!BranchFixups.empty()) {
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000714 if (!SwitchBlock)
715 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlsson66c384a2009-02-08 07:46:24 +0000716 EndBlock = createBasicBlock("cleanup.end");
Mike Stump11289f42009-09-09 15:08:12 +0000717
Anders Carlsson66c384a2009-02-08 07:46:24 +0000718 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000719
Anders Carlsson66c384a2009-02-08 07:46:24 +0000720 Builder.SetInsertPoint(SwitchBlock);
721
Mike Stump33270212009-12-02 07:41:41 +0000722 llvm::Value *DestCodePtr
723 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
724 "cleanup.dst");
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000725 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000726
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000727 // Create a switch instruction to determine where to jump next.
Mike Stump11289f42009-09-09 15:08:12 +0000728 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000729 BranchFixups.size());
Anders Carlsson66c384a2009-02-08 07:46:24 +0000730
Anders Carlsson76180ea2009-02-08 22:13:37 +0000731 // Restore the current basic block (if any)
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000732 if (CurBB) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000733 Builder.SetInsertPoint(CurBB);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000735 // If we had a current basic block, we also need to emit an instruction
736 // to initialize the cleanup destination.
Owen Anderson41a75022009-08-13 21:57:51 +0000737 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000738 DestCodePtr);
739 } else
Anders Carlsson76180ea2009-02-08 22:13:37 +0000740 Builder.ClearInsertionPoint();
Anders Carlsson66c384a2009-02-08 07:46:24 +0000741
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000742 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
743 llvm::BranchInst *BI = BranchFixups[i];
744 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump11289f42009-09-09 15:08:12 +0000745
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000746 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000747 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000748
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000749 if (CleanupEntries.empty()) {
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000750 llvm::ConstantInt *ID;
Mike Stump11289f42009-09-09 15:08:12 +0000751
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000752 // Check if we already have a destination for this block.
753 if (Dest == SI->getDefaultDest())
Owen Anderson41a75022009-08-13 21:57:51 +0000754 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000755 else {
756 ID = SI->findCaseDest(Dest);
757 if (!ID) {
758 // No code found, get a new unique one by using the number of
759 // switch successors.
Mike Stump11289f42009-09-09 15:08:12 +0000760 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000761 SI->getNumSuccessors());
762 SI->addCase(ID, Dest);
763 }
764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000766 // Store the jump destination before the branch instruction.
767 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000768 } else {
769 // We need to jump through another cleanup block. Create a pad block
Mike Stump33270212009-12-02 07:41:41 +0000770 // with a branch instruction that jumps to the final destination and add
771 // it as a branch fixup to the current cleanup scope.
Mike Stump11289f42009-09-09 15:08:12 +0000772
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000773 // Create the pad block.
774 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000775
776 // Create a unique case ID.
Mike Stump33270212009-12-02 07:41:41 +0000777 llvm::ConstantInt *ID
778 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
779 SI->getNumSuccessors());
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000780
781 // Store the jump destination before the branch instruction.
782 new llvm::StoreInst(ID, DestCodePtr, BI);
783
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000784 // Add it as the destination.
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000785 SI->addCase(ID, CleanupPad);
Mike Stump11289f42009-09-09 15:08:12 +0000786
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000787 // Create the branch to the final destination.
788 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
789 CleanupPad->getInstList().push_back(BI);
Mike Stump11289f42009-09-09 15:08:12 +0000790
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000791 // And add it as a branch fixup.
792 CleanupEntries.back().BranchFixups.push_back(BI);
793 }
794 }
795 }
Mike Stump11289f42009-09-09 15:08:12 +0000796
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000797 // Remove all blocks from the block scope map.
798 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
799 assert(BlockScopes.count(Blocks[i]) &&
800 "Did not find block in scope map!");
Mike Stump11289f42009-09-09 15:08:12 +0000801
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000802 BlockScopes.erase(Blocks[i]);
803 }
Mike Stump11289f42009-09-09 15:08:12 +0000804
Mike Stump33270212009-12-02 07:41:41 +0000805 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000806}
807
Mike Stump11289f42009-09-09 15:08:12 +0000808void CodeGenFunction::EmitCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000809 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000810
Mike Stump33270212009-12-02 07:41:41 +0000811 if (Info.EHOnly) {
812 // FIXME: Add this to the exceptional edge
813 if (Info.CleanupBlock->getNumUses() == 0)
814 delete Info.CleanupBlock;
815 return;
816 }
817
Devang Patel74c10502010-04-13 00:08:43 +0000818 // Scrub debug location info.
819 for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
820 LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
821 Builder.SetInstDebugLocation(LBI);
822
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000823 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000824 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000825 Info.CleanupBlock->getNumUses() == 0) {
826 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
827 delete Info.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000828 } else
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000829 EmitBlock(Info.CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000830
Anders Carlsson66c384a2009-02-08 07:46:24 +0000831 if (Info.SwitchBlock)
832 EmitBlock(Info.SwitchBlock);
833 if (Info.EndBlock)
834 EmitBlock(Info.EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000835}
836
Mike Stump11289f42009-09-09 15:08:12 +0000837void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
838 assert(!CleanupEntries.empty() &&
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000839 "Trying to add branch fixup without cleanup block!");
Mike Stump11289f42009-09-09 15:08:12 +0000840
Mike Stump18bb9282009-05-16 07:57:57 +0000841 // FIXME: We could be more clever here and check if there's already a branch
842 // fixup for this destination and recycle it.
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000843 CleanupEntries.back().BranchFixups.push_back(BI);
844}
845
Mike Stump11289f42009-09-09 15:08:12 +0000846void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000847 if (!HaveInsertPoint())
848 return;
Mike Stump11289f42009-09-09 15:08:12 +0000849
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000850 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000851
Anders Carlsson76180ea2009-02-08 22:13:37 +0000852 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000853
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000854 // The stack is empty, no need to do any cleanup.
855 if (CleanupEntries.empty())
856 return;
Mike Stump11289f42009-09-09 15:08:12 +0000857
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000858 if (!Dest->getParent()) {
859 // We are trying to branch to a block that hasn't been inserted yet.
860 AddBranchFixup(BI);
861 return;
862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000864 BlockScopeMap::iterator I = BlockScopes.find(Dest);
865 if (I == BlockScopes.end()) {
866 // We are trying to jump to a block that is outside of any cleanup scope.
867 AddBranchFixup(BI);
868 return;
869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000871 assert(I->second < CleanupEntries.size() &&
872 "Trying to branch into cleanup region");
Mike Stump11289f42009-09-09 15:08:12 +0000873
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000874 if (I->second == CleanupEntries.size() - 1) {
875 // We have a branch to a block in the same scope.
876 return;
877 }
Mike Stump11289f42009-09-09 15:08:12 +0000878
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000879 AddBranchFixup(BI);
880}