blob: a4cbf449efcfbd84de81cf9790b07638723aa410 [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 Stumpcb2fbcb2009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000023using namespace clang;
24using namespace CodeGen;
25
Mike Stump11289f42009-09-09 15:08:12 +000026CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stump0c743272009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Owen Andersonc9673d52009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
Chris Lattner6c4d2552009-10-28 23:59:40 +000030 DebugInfo(0), IndirectBranch(0),
Chris Lattner2bb5cb42009-10-13 06:55:33 +000031 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson0a66c262009-11-20 17:27:56 +000032 CXXThisDecl(0),
33 ConditionalBranchLevel(0) {
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000034 LLVMIntTy = ConvertType(getContext().IntTy);
35 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner5696e7b2008-06-17 18:05:57 +000036}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000037
Chris Lattner6db1fb82007-06-02 22:49:07 +000038ASTContext &CodeGenFunction::getContext() const {
39 return CGM.getContext();
40}
41
Chris Lattnerd1af2d22007-05-29 23:17:50 +000042
Chris Lattnerac248202007-05-30 00:13:02 +000043llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
Chris Lattner23b7eb62007-06-15 23:05:46 +000044 llvm::BasicBlock *&BB = LabelMap[S];
Chris Lattnerac248202007-05-30 00:13:02 +000045 if (BB) return BB;
Mike Stump11289f42009-09-09 15:08:12 +000046
Chris Lattnerac248202007-05-30 00:13:02 +000047 // Create, but don't insert, the new block.
Daniel Dunbar75283ff2008-11-11 02:29:29 +000048 return BB = createBasicBlock(S->getName());
Chris Lattnerac248202007-05-30 00:13:02 +000049}
50
Daniel Dunbar22a87f92009-02-25 19:24:29 +000051llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
52 llvm::Value *Res = LocalDeclMap[VD];
53 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
54 return Res;
Lauro Ramos Venancio01a72ff2008-02-26 21:41:45 +000055}
Chris Lattnerac248202007-05-30 00:13:02 +000056
Daniel Dunbar22a87f92009-02-25 19:24:29 +000057llvm::Constant *
58CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
59 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson9396a892008-09-11 09:15:33 +000060}
61
Daniel Dunbaree3da872009-02-03 23:03:55 +000062const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
63 return CGM.getTypes().ConvertTypeForMem(T);
64}
65
Chris Lattnerf033c142007-06-22 19:05:19 +000066const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
67 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +000068}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000069
Chris Lattner54fb19e2007-06-22 22:02:34 +000070bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssonb05a3e52009-09-29 02:09:01 +000071 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
72 T->isMemberFunctionPointerType();
Chris Lattner54fb19e2007-06-22 22:02:34 +000073}
74
Daniel Dunbarfd346a32009-01-26 23:27:52 +000075void CodeGenFunction::EmitReturnBlock() {
76 // For cleanliness, we try to avoid emitting the return block for
77 // simple cases.
78 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
79
80 if (CurBB) {
81 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
82
Daniel Dunbarea3060a2009-07-19 08:24:34 +000083 // We have a valid insert point, reuse it if it is empty or there are no
84 // explicit jumps to the return block.
85 if (CurBB->empty() || ReturnBlock->use_empty()) {
86 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbarfd346a32009-01-26 23:27:52 +000087 delete ReturnBlock;
Daniel Dunbarea3060a2009-07-19 08:24:34 +000088 } else
Daniel Dunbarfd346a32009-01-26 23:27:52 +000089 EmitBlock(ReturnBlock);
90 return;
91 }
92
93 // Otherwise, if the return block is the target of a single direct
94 // branch then we can just put the code in that block instead. This
95 // cleans up functions which started with a unified return block.
96 if (ReturnBlock->hasOneUse()) {
Mike Stump11289f42009-09-09 15:08:12 +000097 llvm::BranchInst *BI =
Daniel Dunbarfd346a32009-01-26 23:27:52 +000098 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
99 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
100 // Reset insertion point and delete the branch.
101 Builder.SetInsertPoint(BI->getParent());
102 BI->eraseFromParent();
103 delete ReturnBlock;
104 return;
105 }
106 }
107
Mike Stump18bb9282009-05-16 07:57:57 +0000108 // FIXME: We are at an unreachable point, there is no reason to emit the block
109 // unless it has uses. However, we still need a place to put the debug
110 // region.end for now.
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000111
112 EmitBlock(ReturnBlock);
113}
114
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000115void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000116 assert(BreakContinueStack.empty() &&
117 "mismatched push/pop in break/continue stack!");
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000118 assert(BlockScopes.empty() &&
119 "did not remove all blocks from block scope map!");
120 assert(CleanupEntries.empty() &&
121 "mismatched push/pop in cleanup stack!");
Mike Stump11289f42009-09-09 15:08:12 +0000122
123 // Emit function epilog (to return).
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000124 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000125
126 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000127 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000128 DI->setLocation(EndLoc);
129 DI->EmitRegionEnd(CurFn, Builder);
130 }
131
Daniel Dunbard931a872009-02-02 22:03:45 +0000132 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000133
Chris Lattner6c4d2552009-10-28 23:59:40 +0000134 // If someone did an indirect goto, emit the indirect goto block at the end of
135 // the function.
136 if (IndirectBranch) {
137 EmitBlock(IndirectBranch->getParent());
138 Builder.ClearInsertionPoint();
139 }
140
Chris Lattnerc48023b2007-12-02 06:32:24 +0000141 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000142 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerc48023b2007-12-02 06:32:24 +0000143 AllocaInsertPt = 0;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000144 Ptr->eraseFromParent();
Chris Lattner6c4d2552009-10-28 23:59:40 +0000145
146 // If someone took the address of a label but never did an indirect goto, we
147 // made a zero entry PHI node, which is illegal, zap it now.
148 if (IndirectBranch) {
149 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
150 if (PN->getNumIncomingValues() == 0) {
151 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
152 PN->eraseFromParent();
153 }
154 }
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000155}
Chris Lattner308f4312007-05-29 23:50:05 +0000156
Anders Carlsson73fcc952009-09-11 00:07:24 +0000157void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000158 llvm::Function *Fn,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000159 const FunctionArgList &Args,
160 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000161 const Decl *D = GD.getDecl();
162
Anders Carlssonf4478e92009-02-09 20:20:56 +0000163 DidCallStackSave = false;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000164 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000165 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000166 CurFn = Fn;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000167 assert(CurFn->isDeclaration() && "Function already has body?");
168
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000169 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000170
Chris Lattner5696e7b2008-06-17 18:05:57 +0000171 // Create a marker to make it easy to insert allocas into the entryblock
172 // later. Don't create this with the builder, because we don't want it
173 // folded.
Owen Anderson41a75022009-08-13 21:57:51 +0000174 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stump1dbb8f72009-09-25 18:11:00 +0000175 AllocaInsertPt = new llvm::BitCastInst(Undef,
176 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner5696e7b2008-06-17 18:05:57 +0000177 EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000178 if (Builder.isNamePreserving())
179 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000180
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000181 ReturnBlock = createBasicBlock("return");
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000182 ReturnValue = 0;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000183 if (!RetTy->isVoidType())
184 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattner5696e7b2008-06-17 18:05:57 +0000186 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000187
Mike Stumpae2559a2009-10-23 01:52:13 +0000188 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
189
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000190 // Emit subprogram debug descriptor.
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000191 // FIXME: The cast here is a huge hack.
Anders Carlsson63784f42009-02-13 08:11:52 +0000192 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar354d2782008-10-18 18:22:23 +0000193 DI->setLocation(StartLoc);
Anders Carlssonfd384d82009-09-11 00:11:35 +0000194 if (isa<FunctionDecl>(D)) {
Mike Stumpae2559a2009-10-23 01:52:13 +0000195 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar354d2782008-10-18 18:22:23 +0000196 } else {
197 // Just use LLVM function name.
Mike Stump11289f42009-09-09 15:08:12 +0000198
Daniel Dunbar7c02cf62009-07-23 05:30:36 +0000199 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump11289f42009-09-09 15:08:12 +0000200 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stumpae2559a2009-10-23 01:52:13 +0000201 FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000202 }
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000203 }
204
Daniel Dunbard931a872009-02-02 22:03:45 +0000205 // FIXME: Leaked.
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000206 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbard931a872009-02-02 22:03:45 +0000207 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000208
Anders Carlssonc20879a2008-12-20 21:28:43 +0000209 // If any of the arguments have a variably modified type, make sure to
210 // emit the type size.
211 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
212 i != e; ++i) {
213 QualType Ty = i->second;
214
215 if (Ty->isVariablyModifiedType())
216 EmitVLASize(Ty);
217 }
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000218}
Eli Friedman3d421e12008-08-25 21:31:01 +0000219
Anders Carlsson73fcc952009-09-11 00:07:24 +0000220void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000221 llvm::Function *Fn) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000222 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
223
Anders Carlsson63784f42009-02-13 08:11:52 +0000224 // Check if we should generate debug info for this function.
Mike Stump3722f582009-08-26 22:31:08 +0000225 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlsson63784f42009-02-13 08:11:52 +0000226 DebugInfo = CGM.getDebugInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000227
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000228 FunctionArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000229
Anders Carlsson468fa632009-04-04 20:47:02 +0000230 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
231 if (MD->isInstance()) {
232 // Create the implicit 'this' decl.
233 // FIXME: I'm not entirely sure I like using a fake decl just for code
234 // generation. Maybe we can come up with a better way?
235 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +0000236 &getContext().Idents.get("this"),
Anders Carlsson468fa632009-04-04 20:47:02 +0000237 MD->getThisType(getContext()));
238 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
239 }
240 }
Mike Stump11289f42009-09-09 15:08:12 +0000241
Eli Friedman3d421e12008-08-25 21:31:01 +0000242 if (FD->getNumParams()) {
John McCall9dd450b2009-09-21 23:43:11 +0000243 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedman3d421e12008-08-25 21:31:01 +0000244 assert(FProto && "Function def must have prototype!");
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000245
246 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump11289f42009-09-09 15:08:12 +0000247 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000248 FProto->getArgType(i)));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000249 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000250
Sebastian Redla7b98a72009-04-26 20:35:05 +0000251 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000252 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000253 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson438cf922009-11-06 02:55:43 +0000254
255 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonddf57d32009-09-14 05:32:02 +0000256 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson438cf922009-11-06 02:55:43 +0000257 EmitStmt(S);
Anders Carlsson421a5c92009-11-06 04:19:02 +0000258
259 // If any of the member initializers are temporaries bound to references
260 // make sure to emit their destructors.
261 EmitCleanupBlocks(0);
262
Anders Carlsson438cf922009-11-06 02:55:43 +0000263 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
264 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
265 PushCleanupBlock(DtorEpilogue);
266
267 EmitStmt(S);
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000268
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000269 CleanupBlockInfo Info = PopCleanupBlock();
270
271 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
272 EmitBlock(DtorEpilogue);
Anders Carlssonddf57d32009-09-14 05:32:02 +0000273 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000274
275 if (Info.SwitchBlock)
276 EmitBlock(Info.SwitchBlock);
277 if (Info.EndBlock)
278 EmitBlock(Info.EndBlock);
Anders Carlsson438cf922009-11-06 02:55:43 +0000279 } else {
280 // Just a regular function, emit its body.
281 EmitStmt(S);
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000282 }
Anders Carlsson438cf922009-11-06 02:55:43 +0000283
Sebastian Redla7b98a72009-04-26 20:35:05 +0000284 FinishFunction(S->getRBracLoc());
Douglas Gregor369acf92009-10-01 20:44:19 +0000285 } else if (FD->isImplicit()) {
286 const CXXRecordDecl *ClassDecl =
287 cast<CXXRecordDecl>(FD->getDeclContext());
288 (void) ClassDecl;
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000289 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor369acf92009-10-01 20:44:19 +0000290 // FIXME: For C++0x, we want to look for implicit *definitions* of
291 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000292 if (CD->isCopyConstructor(getContext())) {
293 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000294 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000295 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000296 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000297 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000298 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000299 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000300 } else {
301 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000302 }
Douglas Gregor369acf92009-10-01 20:44:19 +0000303 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
304 assert(!ClassDecl->hasUserDeclaredDestructor() &&
305 "Cannot synthesize a non-implicit destructor");
306 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
307 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
308 assert(MD->isCopyAssignment() &&
309 !ClassDecl->hasUserDeclaredCopyAssignment() &&
310 "Cannot synthesize a method that is not an implicit-defined "
311 "copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000312 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000313 } else {
314 assert(false && "Cannot synthesize unknown implicit function");
315 }
Anders Carlsson73fcc952009-09-11 00:07:24 +0000316 }
Mike Stump11289f42009-09-09 15:08:12 +0000317
Anders Carlsson468fa632009-04-04 20:47:02 +0000318 // Destroy the 'this' declaration.
319 if (CXXThisDecl)
320 CXXThisDecl->Destroy(getContext());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000321}
322
Chris Lattner5b1964b2008-11-11 07:41:27 +0000323/// ContainsLabel - Return true if the statement contains a label in it. If
324/// this statement is not executed normally, it not containing a label means
325/// that we can just remove the code.
326bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
327 // Null statement, not a label!
328 if (S == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattner5b1964b2008-11-11 07:41:27 +0000330 // If this is a label, we have to emit the code, consider something like:
331 // if (0) { ... foo: bar(); } goto foo;
332 if (isa<LabelStmt>(S))
333 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000334
Chris Lattner5b1964b2008-11-11 07:41:27 +0000335 // If this is a case/default statement, and we haven't seen a switch, we have
336 // to emit the code.
337 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
338 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Chris Lattner5b1964b2008-11-11 07:41:27 +0000340 // If this is a switch statement, we want to ignore cases below it.
341 if (isa<SwitchStmt>(S))
342 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner5b1964b2008-11-11 07:41:27 +0000344 // Scan subexpressions for verboten labels.
345 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
346 I != E; ++I)
347 if (ContainsLabel(*I, IgnoreCaseStmts))
348 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000349
Chris Lattner5b1964b2008-11-11 07:41:27 +0000350 return false;
351}
352
Chris Lattnercd439292008-11-12 08:04:58 +0000353
354/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
355/// a constant, or if it does but contains a label, return 0. If it constant
356/// folds to 'true' and does not contain a label, return 1, if it constant folds
357/// to 'false' and does not contain a label, return -1.
358int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000359 // FIXME: Rename and handle conversion of other evaluatable things
360 // to bool.
Anders Carlsson86286452008-12-01 02:46:24 +0000361 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +0000362 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson86286452008-12-01 02:46:24 +0000363 Result.HasSideEffects)
Anders Carlsson4046e652008-11-22 22:32:07 +0000364 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump11289f42009-09-09 15:08:12 +0000365
Chris Lattnercd439292008-11-12 08:04:58 +0000366 if (CodeGenFunction::ContainsLabel(Cond))
367 return 0; // Contains a label.
Mike Stump11289f42009-09-09 15:08:12 +0000368
Anders Carlsson86286452008-12-01 02:46:24 +0000369 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattnercd439292008-11-12 08:04:58 +0000370}
371
372
373/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
374/// statement) to the specified blocks. Based on the condition, this might try
375/// to simplify the codegen of the conditional based on the branch.
376///
377void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
378 llvm::BasicBlock *TrueBlock,
379 llvm::BasicBlock *FalseBlock) {
380 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
381 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattnercd439292008-11-12 08:04:58 +0000383 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
384 // Handle X && Y in a condition.
385 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
386 // If we have "1 && X", simplify the code. "0 && X" would have constant
387 // folded if the case was simple enough.
388 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
389 // br(1 && X) -> br(X).
390 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
391 }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Chris Lattnercd439292008-11-12 08:04:58 +0000393 // If we have "X && 1", simplify the code to use an uncond branch.
394 // "X && 0" would have been constant folded to 0.
395 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
396 // br(X && 1) -> br(X).
397 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
398 }
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattnercd439292008-11-12 08:04:58 +0000400 // Emit the LHS as a conditional. If the LHS conditional is false, we
401 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000402 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattnercd439292008-11-12 08:04:58 +0000403 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
404 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattnercd439292008-11-12 08:04:58 +0000406 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
407 return;
408 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
409 // If we have "0 || X", simplify the code. "1 || X" would have constant
410 // folded if the case was simple enough.
411 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
412 // br(0 || X) -> br(X).
413 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
414 }
Mike Stump11289f42009-09-09 15:08:12 +0000415
Chris Lattnercd439292008-11-12 08:04:58 +0000416 // If we have "X || 0", simplify the code to use an uncond branch.
417 // "X || 1" would have been constant folded to 1.
418 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
419 // br(X || 0) -> br(X).
420 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
421 }
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattnercd439292008-11-12 08:04:58 +0000423 // Emit the LHS as a conditional. If the LHS conditional is true, we
424 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000425 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattnercd439292008-11-12 08:04:58 +0000426 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
427 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattnercd439292008-11-12 08:04:58 +0000429 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
430 return;
431 }
Chris Lattnerd9537732008-11-12 08:13:36 +0000432 }
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattnerd9537732008-11-12 08:13:36 +0000434 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
435 // br(!x, t, f) -> br(x, f, t)
436 if (CondUOp->getOpcode() == UnaryOperator::LNot)
437 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattnercd439292008-11-12 08:04:58 +0000438 }
Mike Stump11289f42009-09-09 15:08:12 +0000439
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +0000440 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
441 // Handle ?: operator.
442
443 // Just ignore GNU ?: extension.
444 if (CondOp->getLHS()) {
445 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
446 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
447 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
448 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
449 EmitBlock(LHSBlock);
450 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
451 EmitBlock(RHSBlock);
452 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
453 return;
454 }
455 }
456
Chris Lattnercd439292008-11-12 08:04:58 +0000457 // Emit the code with the fully general case.
458 llvm::Value *CondV = EvaluateExprAsBool(Cond);
459 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
460}
461
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000462/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +0000463/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000464void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
465 bool OmitOnError) {
466 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerfc944342007-12-02 01:43:38 +0000467}
468
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000469void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattnerdd7eaad2009-10-13 06:02:42 +0000470 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000471 if (DestPtr->getType() != BP)
472 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
473
474 // Get size and alignment info for this aggregate.
475 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
476
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000477 // Don't bother emitting a zero-byte memset.
478 if (TypeInfo.first == 0)
479 return;
Mike Stump11289f42009-09-09 15:08:12 +0000480
Anders Carlsson2e744e82008-08-30 19:51:14 +0000481 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +0000482 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000483 LLVMPointerWidth);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000484
485 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson41a75022009-08-13 21:57:51 +0000486 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000487 // TypeInfo.first describes size in bits.
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000488 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump11289f42009-09-09 15:08:12 +0000489 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000490 TypeInfo.second/8));
491}
492
Chris Lattner6c4d2552009-10-28 23:59:40 +0000493llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
494 // Make sure that there is a block for the indirect goto.
495 if (IndirectBranch == 0)
496 GetIndirectGotoBlock();
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000497
Chris Lattner6c4d2552009-10-28 23:59:40 +0000498 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000499
Chris Lattner6c4d2552009-10-28 23:59:40 +0000500 // Make sure the indirect branch includes all of the address-taken blocks.
501 IndirectBranch->addDestination(BB);
502 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000503}
504
505llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000506 // If we already made the indirect branch for indirect goto, return its block.
507 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000508
Chris Lattner6c4d2552009-10-28 23:59:40 +0000509 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000510
Chris Lattner6c4d2552009-10-28 23:59:40 +0000511 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattnera0c0d882009-10-28 20:36:47 +0000512
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000513 // Create the PHI node that indirect gotos will add entries to.
Chris Lattner6c4d2552009-10-28 23:59:40 +0000514 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000515
Chris Lattner6c4d2552009-10-28 23:59:40 +0000516 // Create the indirect branch instruction.
517 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
518 return IndirectBranch->getParent();
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000519}
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000520
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000521llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000522 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000523
Anders Carlssone388a5b2008-12-20 20:27:15 +0000524 assert(SizeEntry && "Did not emit size for type");
525 return SizeEntry;
526}
Anders Carlssonccbe9202008-12-12 07:19:02 +0000527
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000528llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson8a01b792008-12-20 20:46:34 +0000529 assert(Ty->isVariablyModifiedType() &&
530 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +0000531
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000532 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000533
Anders Carlsson8a01b792008-12-20 20:46:34 +0000534 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000535 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000536
Anders Carlsson5d985f52008-12-20 21:51:53 +0000537 if (!SizeEntry) {
Anders Carlsson31f86492009-02-05 19:43:10 +0000538 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000539
Chris Lattner8dc76262009-08-15 00:03:43 +0000540 // Get the element size;
541 QualType ElemTy = VAT->getElementType();
542 llvm::Value *ElemSize;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000543 if (ElemTy->isVariableArrayType())
544 ElemSize = EmitVLASize(ElemTy);
Chris Lattner8dc76262009-08-15 00:03:43 +0000545 else
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000546 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlsson5d985f52008-12-20 21:51:53 +0000547 getContext().getTypeSize(ElemTy) / 8);
Mike Stump11289f42009-09-09 15:08:12 +0000548
Anders Carlsson5d985f52008-12-20 21:51:53 +0000549 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson31f86492009-02-05 19:43:10 +0000550 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000551
Anders Carlsson5d985f52008-12-20 21:51:53 +0000552 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson8a01b792008-12-20 20:46:34 +0000553 }
Mike Stump11289f42009-09-09 15:08:12 +0000554
Anders Carlsson8a01b792008-12-20 20:46:34 +0000555 return SizeEntry;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000556 }
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattner8dc76262009-08-15 00:03:43 +0000558 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
559 EmitVLASize(AT->getElementType());
560 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000561 }
562
Chris Lattner8dc76262009-08-15 00:03:43 +0000563 const PointerType *PT = Ty->getAs<PointerType>();
564 assert(PT && "unknown VM type!");
565 EmitVLASize(PT->getPointeeType());
Anders Carlsson8a01b792008-12-20 20:46:34 +0000566 return 0;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000567}
Eli Friedmanddea0ad2009-01-20 17:46:04 +0000568
569llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
570 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
571 return EmitScalarExpr(E);
572 }
573 return EmitLValue(E).getAddress();
574}
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000575
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000576void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
577 llvm::BasicBlock *CleanupExitBlock) {
578 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock));
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000579}
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000580
Mike Stump11289f42009-09-09 15:08:12 +0000581void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
582 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000583 "Cleanup stack mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000584
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000585 while (CleanupEntries.size() > OldCleanupStackSize)
586 EmitCleanupBlock();
587}
588
Mike Stump11289f42009-09-09 15:08:12 +0000589CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000590 CleanupEntry &CE = CleanupEntries.back();
Mike Stump11289f42009-09-09 15:08:12 +0000591
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000592 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Anders Carlsson66c384a2009-02-08 07:46:24 +0000594 std::vector<llvm::BasicBlock *> Blocks;
595 std::swap(Blocks, CE.Blocks);
Mike Stump11289f42009-09-09 15:08:12 +0000596
Anders Carlsson66c384a2009-02-08 07:46:24 +0000597 std::vector<llvm::BranchInst *> BranchFixups;
598 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump11289f42009-09-09 15:08:12 +0000599
Anders Carlsson66c384a2009-02-08 07:46:24 +0000600 CleanupEntries.pop_back();
601
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000602 // Check if any branch fixups pointed to the scope we just popped. If so,
603 // we can remove them.
604 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
605 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
606 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000607
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000608 if (I == BlockScopes.end())
609 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000610
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000611 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump11289f42009-09-09 15:08:12 +0000612
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000613 if (I->second == CleanupEntries.size()) {
614 // We don't need to do this branch fixup.
615 BranchFixups[i] = BranchFixups.back();
616 BranchFixups.pop_back();
617 i--;
618 e--;
619 continue;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000620 }
621 }
Mike Stump11289f42009-09-09 15:08:12 +0000622
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000623 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlsson66c384a2009-02-08 07:46:24 +0000624 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000625 if (!BranchFixups.empty()) {
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000626 if (!SwitchBlock)
627 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlsson66c384a2009-02-08 07:46:24 +0000628 EndBlock = createBasicBlock("cleanup.end");
Mike Stump11289f42009-09-09 15:08:12 +0000629
Anders Carlsson66c384a2009-02-08 07:46:24 +0000630 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000631
Anders Carlsson66c384a2009-02-08 07:46:24 +0000632 Builder.SetInsertPoint(SwitchBlock);
633
Mike Stump11289f42009-09-09 15:08:12 +0000634 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000635 "cleanup.dst");
636 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000637
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000638 // Create a switch instruction to determine where to jump next.
Mike Stump11289f42009-09-09 15:08:12 +0000639 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000640 BranchFixups.size());
Anders Carlsson66c384a2009-02-08 07:46:24 +0000641
Anders Carlsson76180ea2009-02-08 22:13:37 +0000642 // Restore the current basic block (if any)
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000643 if (CurBB) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000644 Builder.SetInsertPoint(CurBB);
Mike Stump11289f42009-09-09 15:08:12 +0000645
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000646 // If we had a current basic block, we also need to emit an instruction
647 // to initialize the cleanup destination.
Owen Anderson41a75022009-08-13 21:57:51 +0000648 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000649 DestCodePtr);
650 } else
Anders Carlsson76180ea2009-02-08 22:13:37 +0000651 Builder.ClearInsertionPoint();
Anders Carlsson66c384a2009-02-08 07:46:24 +0000652
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000653 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
654 llvm::BranchInst *BI = BranchFixups[i];
655 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump11289f42009-09-09 15:08:12 +0000656
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000657 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000658 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000659
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000660 if (CleanupEntries.empty()) {
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000661 llvm::ConstantInt *ID;
Mike Stump11289f42009-09-09 15:08:12 +0000662
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000663 // Check if we already have a destination for this block.
664 if (Dest == SI->getDefaultDest())
Owen Anderson41a75022009-08-13 21:57:51 +0000665 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000666 else {
667 ID = SI->findCaseDest(Dest);
668 if (!ID) {
669 // No code found, get a new unique one by using the number of
670 // switch successors.
Mike Stump11289f42009-09-09 15:08:12 +0000671 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000672 SI->getNumSuccessors());
673 SI->addCase(ID, Dest);
674 }
675 }
Mike Stump11289f42009-09-09 15:08:12 +0000676
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000677 // Store the jump destination before the branch instruction.
678 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000679 } else {
680 // We need to jump through another cleanup block. Create a pad block
681 // with a branch instruction that jumps to the final destination and
682 // add it as a branch fixup to the current cleanup scope.
Mike Stump11289f42009-09-09 15:08:12 +0000683
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000684 // Create the pad block.
685 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000686
687 // Create a unique case ID.
Mike Stump11289f42009-09-09 15:08:12 +0000688 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000689 SI->getNumSuccessors());
690
691 // Store the jump destination before the branch instruction.
692 new llvm::StoreInst(ID, DestCodePtr, BI);
693
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000694 // Add it as the destination.
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000695 SI->addCase(ID, CleanupPad);
Mike Stump11289f42009-09-09 15:08:12 +0000696
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000697 // Create the branch to the final destination.
698 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
699 CleanupPad->getInstList().push_back(BI);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000701 // And add it as a branch fixup.
702 CleanupEntries.back().BranchFixups.push_back(BI);
703 }
704 }
705 }
Mike Stump11289f42009-09-09 15:08:12 +0000706
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000707 // Remove all blocks from the block scope map.
708 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
709 assert(BlockScopes.count(Blocks[i]) &&
710 "Did not find block in scope map!");
Mike Stump11289f42009-09-09 15:08:12 +0000711
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000712 BlockScopes.erase(Blocks[i]);
713 }
Mike Stump11289f42009-09-09 15:08:12 +0000714
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000715 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000716}
717
Mike Stump11289f42009-09-09 15:08:12 +0000718void CodeGenFunction::EmitCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000719 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000720
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000721 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000722 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000723 Info.CleanupBlock->getNumUses() == 0) {
724 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
725 delete Info.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000726 } else
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000727 EmitBlock(Info.CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000728
Anders Carlsson66c384a2009-02-08 07:46:24 +0000729 if (Info.SwitchBlock)
730 EmitBlock(Info.SwitchBlock);
731 if (Info.EndBlock)
732 EmitBlock(Info.EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000733}
734
Mike Stump11289f42009-09-09 15:08:12 +0000735void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
736 assert(!CleanupEntries.empty() &&
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000737 "Trying to add branch fixup without cleanup block!");
Mike Stump11289f42009-09-09 15:08:12 +0000738
Mike Stump18bb9282009-05-16 07:57:57 +0000739 // FIXME: We could be more clever here and check if there's already a branch
740 // fixup for this destination and recycle it.
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000741 CleanupEntries.back().BranchFixups.push_back(BI);
742}
743
Mike Stump11289f42009-09-09 15:08:12 +0000744void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000745 if (!HaveInsertPoint())
746 return;
Mike Stump11289f42009-09-09 15:08:12 +0000747
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000748 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000749
Anders Carlsson76180ea2009-02-08 22:13:37 +0000750 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000751
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000752 // The stack is empty, no need to do any cleanup.
753 if (CleanupEntries.empty())
754 return;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000756 if (!Dest->getParent()) {
757 // We are trying to branch to a block that hasn't been inserted yet.
758 AddBranchFixup(BI);
759 return;
760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000762 BlockScopeMap::iterator I = BlockScopes.find(Dest);
763 if (I == BlockScopes.end()) {
764 // We are trying to jump to a block that is outside of any cleanup scope.
765 AddBranchFixup(BI);
766 return;
767 }
Mike Stump11289f42009-09-09 15:08:12 +0000768
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000769 assert(I->second < CleanupEntries.size() &&
770 "Trying to branch into cleanup region");
Mike Stump11289f42009-09-09 15:08:12 +0000771
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000772 if (I->second == CleanupEntries.size() - 1) {
773 // We have a branch to a block in the same scope.
774 return;
775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000777 AddBranchFixup(BI);
778}