blob: 9cd44fda95482c3d296f0c65c3e46b2ce939fb51 [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 Stump4e7a1f72009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
Mike Stump1eb44332009-09-09 15:08:12 +000026CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
Chris Lattnerd9becd12009-10-28 23:59:40 +000030#ifndef USEINDIRECTBRANCH
Chris Lattner3d00fdc2009-10-13 06:55:33 +000031 DebugInfo(0), IndirectGotoSwitch(0),
Chris Lattnerd9becd12009-10-28 23:59:40 +000032#else
33 DebugInfo(0), IndirectBranch(0),
34#endif
Chris Lattner3d00fdc2009-10-13 06:55:33 +000035 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson2b77ba82009-04-04 20:47:02 +000036 CXXThisDecl(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000037 LLVMIntTy = ConvertType(getContext().IntTy);
38 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000039}
Reid Spencer5f016e22007-07-11 17:01:13 +000040
41ASTContext &CodeGenFunction::getContext() const {
42 return CGM.getContext();
43}
44
45
46llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
47 llvm::BasicBlock *&BB = LabelMap[S];
48 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000049
Reid Spencer5f016e22007-07-11 17:01:13 +000050 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000051 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000052}
53
Daniel Dunbar0096acf2009-02-25 19:24:29 +000054llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
55 llvm::Value *Res = LocalDeclMap[VD];
56 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
57 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000058}
Reid Spencer5f016e22007-07-11 17:01:13 +000059
Daniel Dunbar0096acf2009-02-25 19:24:29 +000060llvm::Constant *
61CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
62 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000063}
64
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000065const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
66 return CGM.getTypes().ConvertTypeForMem(T);
67}
68
Reid Spencer5f016e22007-07-11 17:01:13 +000069const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
70 return CGM.getTypes().ConvertType(T);
71}
72
73bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000074 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
75 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000076}
77
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000078void CodeGenFunction::EmitReturnBlock() {
79 // For cleanliness, we try to avoid emitting the return block for
80 // simple cases.
81 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
82
83 if (CurBB) {
84 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
85
Daniel Dunbar96e18b02009-07-19 08:24:34 +000086 // We have a valid insert point, reuse it if it is empty or there are no
87 // explicit jumps to the return block.
88 if (CurBB->empty() || ReturnBlock->use_empty()) {
89 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000090 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000091 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000092 EmitBlock(ReturnBlock);
93 return;
94 }
95
96 // Otherwise, if the return block is the target of a single direct
97 // branch then we can just put the code in that block instead. This
98 // cleans up functions which started with a unified return block.
99 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000100 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000101 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
102 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
103 // Reset insertion point and delete the branch.
104 Builder.SetInsertPoint(BI->getParent());
105 BI->eraseFromParent();
106 delete ReturnBlock;
107 return;
108 }
109 }
110
Mike Stumpf5408fe2009-05-16 07:57:57 +0000111 // FIXME: We are at an unreachable point, there is no reason to emit the block
112 // unless it has uses. However, we still need a place to put the debug
113 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000114
115 EmitBlock(ReturnBlock);
116}
117
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000118void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000119 assert(BreakContinueStack.empty() &&
120 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000121 assert(BlockScopes.empty() &&
122 "did not remove all blocks from block scope map!");
123 assert(CleanupEntries.empty() &&
124 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000125
126 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000127 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000128
129 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000130 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000131 DI->setLocation(EndLoc);
132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Daniel Dunbar88b53962009-02-02 22:03:45 +0000135 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000136
Chris Lattnerd9becd12009-10-28 23:59:40 +0000137#ifdef USEINDIRECTBRANCH
138 // If someone did an indirect goto, emit the indirect goto block at the end of
139 // the function.
140 if (IndirectBranch) {
141 EmitBlock(IndirectBranch->getParent());
142 Builder.ClearInsertionPoint();
143 }
144
145
146#endif
Chris Lattner5a2fa142007-12-02 06:32:24 +0000147 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000148 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000149 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000150 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000151#ifdef USEINDIRECTBRANCH
152
153 // If someone took the address of a label but never did an indirect goto, we
154 // made a zero entry PHI node, which is illegal, zap it now.
155 if (IndirectBranch) {
156 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
157 if (PN->getNumIncomingValues() == 0) {
158 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
159 PN->eraseFromParent();
160 }
161 }
162
163#endif
Reid Spencer5f016e22007-07-11 17:01:13 +0000164}
165
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000166void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000167 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000168 const FunctionArgList &Args,
169 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000170 const Decl *D = GD.getDecl();
171
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000172 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000173 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000174 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000175 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000176 assert(CurFn->isDeclaration() && "Function already has body?");
177
Daniel Dunbar55e87422008-11-11 02:29:29 +0000178 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000179
Chris Lattner41110242008-06-17 18:05:57 +0000180 // Create a marker to make it easy to insert allocas into the entryblock
181 // later. Don't create this with the builder, because we don't want it
182 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000183 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000184 AllocaInsertPt = new llvm::BitCastInst(Undef,
185 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000186 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000187 if (Builder.isNamePreserving())
188 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Daniel Dunbar55e87422008-11-11 02:29:29 +0000190 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000191 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000192 if (!RetTy->isVoidType())
193 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattner41110242008-06-17 18:05:57 +0000195 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Mike Stump91cc8152009-10-23 01:52:13 +0000197 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
198
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000199 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000200 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000201 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000202 DI->setLocation(StartLoc);
Anders Carlsson1860a312009-09-11 00:11:35 +0000203 if (isa<FunctionDecl>(D)) {
Mike Stump91cc8152009-10-23 01:52:13 +0000204 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000205 } else {
206 // Just use LLVM function name.
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000208 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump1eb44332009-09-09 15:08:12 +0000209 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stump91cc8152009-10-23 01:52:13 +0000210 FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000211 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000212 }
213
Daniel Dunbar88b53962009-02-02 22:03:45 +0000214 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000215 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000216 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Anders Carlsson751358f2008-12-20 21:28:43 +0000218 // If any of the arguments have a variably modified type, make sure to
219 // emit the type size.
220 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
221 i != e; ++i) {
222 QualType Ty = i->second;
223
224 if (Ty->isVariablyModifiedType())
225 EmitVLASize(Ty);
226 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000227}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000228
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000229void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000230 llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000231 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
232
Anders Carlssone896d982009-02-13 08:11:52 +0000233 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000234 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000235 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Daniel Dunbar7c086512008-09-09 23:14:03 +0000237 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000239 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
240 if (MD->isInstance()) {
241 // Create the implicit 'this' decl.
242 // FIXME: I'm not entirely sure I like using a fake decl just for code
243 // generation. Maybe we can come up with a better way?
244 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000245 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000246 MD->getThisType(getContext()));
247 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
248 }
249 }
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000251 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000252 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000253 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000254
255 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000256 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000257 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000258 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000259
Sebastian Redld3a413d2009-04-26 20:35:05 +0000260 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000261 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000262 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000263
264 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000265 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000266 EmitStmt(S);
Anders Carlsson5e1b9182009-11-06 04:19:02 +0000267
268 // If any of the member initializers are temporaries bound to references
269 // make sure to emit their destructors.
270 EmitCleanupBlocks(0);
271
Anders Carlsson4365bba2009-11-06 02:55:43 +0000272 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
273 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
274 PushCleanupBlock(DtorEpilogue);
275
276 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000277
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000278 CleanupBlockInfo Info = PopCleanupBlock();
279
280 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
281 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000282 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000283
284 if (Info.SwitchBlock)
285 EmitBlock(Info.SwitchBlock);
286 if (Info.EndBlock)
287 EmitBlock(Info.EndBlock);
Anders Carlsson4365bba2009-11-06 02:55:43 +0000288 } else {
289 // Just a regular function, emit its body.
290 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000291 }
Anders Carlsson4365bba2009-11-06 02:55:43 +0000292
Sebastian Redld3a413d2009-04-26 20:35:05 +0000293 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000294 } else if (FD->isImplicit()) {
295 const CXXRecordDecl *ClassDecl =
296 cast<CXXRecordDecl>(FD->getDeclContext());
297 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000298 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000299 // FIXME: For C++0x, we want to look for implicit *definitions* of
300 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian98896522009-08-06 23:38:16 +0000301 if (CD->isCopyConstructor(getContext())) {
302 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000303 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000304 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000305 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000306 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000307 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000308 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000309 } else {
310 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000311 }
Douglas Gregor45132722009-10-01 20:44:19 +0000312 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
313 assert(!ClassDecl->hasUserDeclaredDestructor() &&
314 "Cannot synthesize a non-implicit destructor");
315 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
316 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
317 assert(MD->isCopyAssignment() &&
318 !ClassDecl->hasUserDeclaredCopyAssignment() &&
319 "Cannot synthesize a method that is not an implicit-defined "
320 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000321 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000322 } else {
323 assert(false && "Cannot synthesize unknown implicit function");
324 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000325 }
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000327 // Destroy the 'this' declaration.
328 if (CXXThisDecl)
329 CXXThisDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000330}
331
Chris Lattner0946ccd2008-11-11 07:41:27 +0000332/// ContainsLabel - Return true if the statement contains a label in it. If
333/// this statement is not executed normally, it not containing a label means
334/// that we can just remove the code.
335bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
336 // Null statement, not a label!
337 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner0946ccd2008-11-11 07:41:27 +0000339 // If this is a label, we have to emit the code, consider something like:
340 // if (0) { ... foo: bar(); } goto foo;
341 if (isa<LabelStmt>(S))
342 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Chris Lattner0946ccd2008-11-11 07:41:27 +0000344 // If this is a case/default statement, and we haven't seen a switch, we have
345 // to emit the code.
346 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
347 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattner0946ccd2008-11-11 07:41:27 +0000349 // If this is a switch statement, we want to ignore cases below it.
350 if (isa<SwitchStmt>(S))
351 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Chris Lattner0946ccd2008-11-11 07:41:27 +0000353 // Scan subexpressions for verboten labels.
354 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
355 I != E; ++I)
356 if (ContainsLabel(*I, IgnoreCaseStmts))
357 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattner0946ccd2008-11-11 07:41:27 +0000359 return false;
360}
361
Chris Lattner31a09842008-11-12 08:04:58 +0000362
363/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
364/// a constant, or if it does but contains a label, return 0. If it constant
365/// folds to 'true' and does not contain a label, return 1, if it constant folds
366/// to 'false' and does not contain a label, return -1.
367int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000368 // FIXME: Rename and handle conversion of other evaluatable things
369 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000370 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000371 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000372 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000373 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner31a09842008-11-12 08:04:58 +0000375 if (CodeGenFunction::ContainsLabel(Cond))
376 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Anders Carlsson64712f12008-12-01 02:46:24 +0000378 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000379}
380
381
382/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
383/// statement) to the specified blocks. Based on the condition, this might try
384/// to simplify the codegen of the conditional based on the branch.
385///
386void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
387 llvm::BasicBlock *TrueBlock,
388 llvm::BasicBlock *FalseBlock) {
389 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
390 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner31a09842008-11-12 08:04:58 +0000392 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
393 // Handle X && Y in a condition.
394 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
395 // If we have "1 && X", simplify the code. "0 && X" would have constant
396 // folded if the case was simple enough.
397 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
398 // br(1 && X) -> br(X).
399 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
400 }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattner31a09842008-11-12 08:04:58 +0000402 // If we have "X && 1", simplify the code to use an uncond branch.
403 // "X && 0" would have been constant folded to 0.
404 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
405 // br(X && 1) -> br(X).
406 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner31a09842008-11-12 08:04:58 +0000409 // Emit the LHS as a conditional. If the LHS conditional is false, we
410 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000411 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000412 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
413 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner31a09842008-11-12 08:04:58 +0000415 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
416 return;
417 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
418 // If we have "0 || X", simplify the code. "1 || X" would have constant
419 // folded if the case was simple enough.
420 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
421 // br(0 || X) -> br(X).
422 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner31a09842008-11-12 08:04:58 +0000425 // If we have "X || 0", simplify the code to use an uncond branch.
426 // "X || 1" would have been constant folded to 1.
427 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
428 // br(X || 0) -> br(X).
429 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Chris Lattner31a09842008-11-12 08:04:58 +0000432 // Emit the LHS as a conditional. If the LHS conditional is true, we
433 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000434 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000435 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
436 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner31a09842008-11-12 08:04:58 +0000438 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
439 return;
440 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Chris Lattner552f4c42008-11-12 08:13:36 +0000443 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
444 // br(!x, t, f) -> br(x, f, t)
445 if (CondUOp->getOpcode() == UnaryOperator::LNot)
446 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000447 }
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Daniel Dunbar09b14892008-11-12 10:30:32 +0000449 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
450 // Handle ?: operator.
451
452 // Just ignore GNU ?: extension.
453 if (CondOp->getLHS()) {
454 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
455 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
456 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
457 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
458 EmitBlock(LHSBlock);
459 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
460 EmitBlock(RHSBlock);
461 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
462 return;
463 }
464 }
465
Chris Lattner31a09842008-11-12 08:04:58 +0000466 // Emit the code with the fully general case.
467 llvm::Value *CondV = EvaluateExprAsBool(Cond);
468 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
469}
470
Daniel Dunbar488e9932008-08-16 00:56:44 +0000471/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000472/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000473void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
474 bool OmitOnError) {
475 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000476}
477
Chris Lattner88207c92009-04-21 17:59:23 +0000478void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000479 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000480 if (DestPtr->getType() != BP)
481 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
482
483 // Get size and alignment info for this aggregate.
484 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
485
Chris Lattner88207c92009-04-21 17:59:23 +0000486 // Don't bother emitting a zero-byte memset.
487 if (TypeInfo.first == 0)
488 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000490 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000491 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000492 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000493
494 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000495 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000496 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000497 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000498 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000499 TypeInfo.second/8));
500}
501
Chris Lattnerd9becd12009-10-28 23:59:40 +0000502#ifndef USEINDIRECTBRANCH
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000503unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
504 // Use LabelIDs.size()+1 as the new ID if one hasn't been assigned.
505 unsigned &Entry = LabelIDs[L];
506 if (Entry) return Entry;
Chris Lattnerd9becd12009-10-28 23:59:40 +0000507#else
508
509llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
510 // Make sure that there is a block for the indirect goto.
511 if (IndirectBranch == 0)
512 GetIndirectGotoBlock();
513#endif
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000514
Chris Lattnerd9becd12009-10-28 23:59:40 +0000515#ifndef USEINDIRECTBRANCH
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000516 Entry = LabelIDs.size();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000517#else
518 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
519#endif
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000520
Chris Lattnerd9becd12009-10-28 23:59:40 +0000521#ifndef USEINDIRECTBRANCH
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000522 // If this is the first "address taken" of a label and the indirect goto has
523 // already been seen, add this to it.
524 if (IndirectGotoSwitch) {
525 // If this is the first address-taken label, set it as the default dest.
526 if (Entry == 1)
527 IndirectGotoSwitch->setSuccessor(0, getBasicBlockForLabel(L));
528 else {
529 // Otherwise add it to the switch as a new dest.
530 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
531 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, Entry),
532 getBasicBlockForLabel(L));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000533 }
Mike Stump1eb44332009-09-09 15:08:12 +0000534 }
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000535
536 return Entry;
Chris Lattnerd9becd12009-10-28 23:59:40 +0000537#else
538 // Make sure the indirect branch includes all of the address-taken blocks.
539 IndirectBranch->addDestination(BB);
540 return llvm::BlockAddress::get(CurFn, BB);
541#endif
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000542}
543
544llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000545#ifndef USEINDIRECTBRANCH
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000546 // If we already made the switch stmt for indirect goto, return its block.
547 if (IndirectGotoSwitch) return IndirectGotoSwitch->getParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000548#else
549 // If we already made the indirect branch for indirect goto, return its block.
550 if (IndirectBranch) return IndirectBranch->getParent();
551#endif
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000552
Chris Lattnerd9becd12009-10-28 23:59:40 +0000553#ifndef USEINDIRECTBRANCH
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000554 EmitBlock(createBasicBlock("indirectgoto"));
Chris Lattnerd9becd12009-10-28 23:59:40 +0000555#else
556 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
557#endif
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000558
Chris Lattnerd9becd12009-10-28 23:59:40 +0000559#ifndef USEINDIRECTBRANCH
Chris Lattner85e74ac2009-10-28 20:36:47 +0000560 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000561#else
562 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
563#endif
Chris Lattner85e74ac2009-10-28 20:36:47 +0000564
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000565 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000566#ifndef USEINDIRECTBRANCH
Chris Lattner85e74ac2009-10-28 20:36:47 +0000567 llvm::Value *DestVal = Builder.CreatePHI(Int32Ty, "indirect.goto.dest");
Chris Lattnerd9becd12009-10-28 23:59:40 +0000568#else
569 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
570#endif
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000571
Chris Lattnerd9becd12009-10-28 23:59:40 +0000572#ifndef USEINDIRECTBRANCH
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000573 // Create the switch instruction. For now, set the insert block to this block
574 // which will be fixed as labels are added.
575 IndirectGotoSwitch = Builder.CreateSwitch(DestVal, Builder.GetInsertBlock());
576
577 // Clear the insertion point to indicate we are in unreachable code.
578 Builder.ClearInsertionPoint();
579
580 // If we already have labels created, add them.
581 if (!LabelIDs.empty()) {
582 // Invert LabelID's so that the order is determinstic.
583 std::vector<const LabelStmt*> AddrTakenLabelsByID;
584 AddrTakenLabelsByID.resize(LabelIDs.size());
585
586 for (std::map<const LabelStmt*,unsigned>::iterator
587 LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) {
588 assert(LI->second-1 < AddrTakenLabelsByID.size() &&
589 "Numbering inconsistent");
590 AddrTakenLabelsByID[LI->second-1] = LI->first;
591 }
592
593 // Set the default entry as the first block.
594 IndirectGotoSwitch->setSuccessor(0,
595 getBasicBlockForLabel(AddrTakenLabelsByID[0]));
596
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000597 // FIXME: The iteration order of this is nondeterminstic!
598 for (unsigned i = 1, e = AddrTakenLabelsByID.size(); i != e; ++i)
599 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, i+1),
600 getBasicBlockForLabel(AddrTakenLabelsByID[i]));
601 } else {
602 // Otherwise, create a dead block and set it as the default dest. This will
603 // be removed by the optimizers after the indirect goto is set up.
604 llvm::BasicBlock *Dummy = createBasicBlock("indgoto.dummy");
605 EmitBlock(Dummy);
606 IndirectGotoSwitch->setSuccessor(0, Dummy);
607 Builder.CreateUnreachable();
608 Builder.ClearInsertionPoint();
609 }
610
611 return IndirectGotoSwitch->getParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000612#else
613 // Create the indirect branch instruction.
614 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
615 return IndirectBranch->getParent();
616#endif
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000617}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000618
Daniel Dunbard286f052009-07-19 06:58:07 +0000619llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000620 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Anders Carlssonf666b772008-12-20 20:27:15 +0000622 assert(SizeEntry && "Did not emit size for type");
623 return SizeEntry;
624}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000625
Daniel Dunbard286f052009-07-19 06:58:07 +0000626llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000627 assert(Ty->isVariablyModifiedType() &&
628 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Daniel Dunbard286f052009-07-19 06:58:07 +0000630 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Anders Carlsson60d35412008-12-20 20:46:34 +0000632 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000633 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000635 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000636 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000638 // Get the element size;
639 QualType ElemTy = VAT->getElementType();
640 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000641 if (ElemTy->isVariableArrayType())
642 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000643 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000644 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000645 getContext().getTypeSize(ElemTy) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000647 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000648 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000650 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000651 }
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Anders Carlsson60d35412008-12-20 20:46:34 +0000653 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000654 }
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000656 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
657 EmitVLASize(AT->getElementType());
658 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000659 }
660
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000661 const PointerType *PT = Ty->getAs<PointerType>();
662 assert(PT && "unknown VM type!");
663 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000664 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000665}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000666
667llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
668 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
669 return EmitScalarExpr(E);
670 }
671 return EmitLValue(E).getAddress();
672}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000673
Fariborz Jahanian77996212009-11-04 17:57:40 +0000674void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
675 llvm::BasicBlock *CleanupExitBlock) {
676 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000677}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000678
Mike Stump1eb44332009-09-09 15:08:12 +0000679void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
680 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000681 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Anders Carlssonc71c8452009-02-07 23:50:39 +0000683 while (CleanupEntries.size() > OldCleanupStackSize)
684 EmitCleanupBlock();
685}
686
Mike Stump1eb44332009-09-09 15:08:12 +0000687CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000688 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Fariborz Jahanian77996212009-11-04 17:57:40 +0000690 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000692 std::vector<llvm::BasicBlock *> Blocks;
693 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000695 std::vector<llvm::BranchInst *> BranchFixups;
696 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000698 CleanupEntries.pop_back();
699
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000700 // Check if any branch fixups pointed to the scope we just popped. If so,
701 // we can remove them.
702 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
703 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
704 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000706 if (I == BlockScopes.end())
707 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000709 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000711 if (I->second == CleanupEntries.size()) {
712 // We don't need to do this branch fixup.
713 BranchFixups[i] = BranchFixups.back();
714 BranchFixups.pop_back();
715 i--;
716 e--;
717 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000718 }
719 }
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Fariborz Jahanian77996212009-11-04 17:57:40 +0000721 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000722 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000723 if (!BranchFixups.empty()) {
Fariborz Jahanian77996212009-11-04 17:57:40 +0000724 if (!SwitchBlock)
725 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000726 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000728 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000730 Builder.SetInsertPoint(SwitchBlock);
731
Mike Stump1eb44332009-09-09 15:08:12 +0000732 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000733 "cleanup.dst");
734 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000736 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000737 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000738 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000739
Anders Carlsson46831a92009-02-08 22:13:37 +0000740 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000741 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000742 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000744 // If we had a current basic block, we also need to emit an instruction
745 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000746 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000747 DestCodePtr);
748 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000749 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000750
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000751 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
752 llvm::BranchInst *BI = BranchFixups[i];
753 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000755 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian77996212009-11-04 17:57:40 +0000756 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000758 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000759 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Anders Carlssoncc899202009-02-08 22:46:50 +0000761 // Check if we already have a destination for this block.
762 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000763 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000764 else {
765 ID = SI->findCaseDest(Dest);
766 if (!ID) {
767 // No code found, get a new unique one by using the number of
768 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000769 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000770 SI->getNumSuccessors());
771 SI->addCase(ID, Dest);
772 }
773 }
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Anders Carlssoncc899202009-02-08 22:46:50 +0000775 // Store the jump destination before the branch instruction.
776 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000777 } else {
778 // We need to jump through another cleanup block. Create a pad block
779 // with a branch instruction that jumps to the final destination and
780 // add it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000782 // Create the pad block.
783 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000784
785 // Create a unique case ID.
Mike Stump1eb44332009-09-09 15:08:12 +0000786 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000787 SI->getNumSuccessors());
788
789 // Store the jump destination before the branch instruction.
790 new llvm::StoreInst(ID, DestCodePtr, BI);
791
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000792 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000793 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000795 // Create the branch to the final destination.
796 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
797 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000799 // And add it as a branch fixup.
800 CleanupEntries.back().BranchFixups.push_back(BI);
801 }
802 }
803 }
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000805 // Remove all blocks from the block scope map.
806 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
807 assert(BlockScopes.count(Blocks[i]) &&
808 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000810 BlockScopes.erase(Blocks[i]);
811 }
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Fariborz Jahanian77996212009-11-04 17:57:40 +0000813 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000814}
815
Mike Stump1eb44332009-09-09 15:08:12 +0000816void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000817 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000819 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000820 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000821 Info.CleanupBlock->getNumUses() == 0) {
822 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
823 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000824 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000825 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000827 if (Info.SwitchBlock)
828 EmitBlock(Info.SwitchBlock);
829 if (Info.EndBlock)
830 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000831}
832
Mike Stump1eb44332009-09-09 15:08:12 +0000833void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
834 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000835 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Mike Stumpf5408fe2009-05-16 07:57:57 +0000837 // FIXME: We could be more clever here and check if there's already a branch
838 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000839 CleanupEntries.back().BranchFixups.push_back(BI);
840}
841
Mike Stump1eb44332009-09-09 15:08:12 +0000842void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000843 if (!HaveInsertPoint())
844 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Anders Carlsson87eaf172009-02-08 00:50:42 +0000846 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Anders Carlsson46831a92009-02-08 22:13:37 +0000848 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Anders Carlsson87eaf172009-02-08 00:50:42 +0000850 // The stack is empty, no need to do any cleanup.
851 if (CleanupEntries.empty())
852 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Anders Carlsson87eaf172009-02-08 00:50:42 +0000854 if (!Dest->getParent()) {
855 // We are trying to branch to a block that hasn't been inserted yet.
856 AddBranchFixup(BI);
857 return;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Anders Carlsson87eaf172009-02-08 00:50:42 +0000860 BlockScopeMap::iterator I = BlockScopes.find(Dest);
861 if (I == BlockScopes.end()) {
862 // We are trying to jump to a block that is outside of any cleanup scope.
863 AddBranchFixup(BI);
864 return;
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Anders Carlsson87eaf172009-02-08 00:50:42 +0000867 assert(I->second < CleanupEntries.size() &&
868 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Anders Carlsson87eaf172009-02-08 00:50:42 +0000870 if (I->second == CleanupEntries.size() - 1) {
871 // We have a branch to a block in the same scope.
872 return;
873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Anders Carlsson87eaf172009-02-08 00:50:42 +0000875 AddBranchFixup(BI);
876}