blob: 5206f447f8d0da54239553fdc6b9571214000c06 [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 Lattner3d00fdc2009-10-13 06:55:33 +000030 DebugInfo(0), IndirectGotoSwitch(0),
31 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson2b77ba82009-04-04 20:47:02 +000032 CXXThisDecl(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000033 LLVMIntTy = ConvertType(getContext().IntTy);
34 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000035}
Reid Spencer5f016e22007-07-11 17:01:13 +000036
37ASTContext &CodeGenFunction::getContext() const {
38 return CGM.getContext();
39}
40
41
42llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
43 llvm::BasicBlock *&BB = LabelMap[S];
44 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000045
Reid Spencer5f016e22007-07-11 17:01:13 +000046 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000047 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Daniel Dunbar0096acf2009-02-25 19:24:29 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
51 llvm::Value *Res = LocalDeclMap[VD];
52 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
53 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000054}
Reid Spencer5f016e22007-07-11 17:01:13 +000055
Daniel Dunbar0096acf2009-02-25 19:24:29 +000056llvm::Constant *
57CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
58 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000059}
60
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000061const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
62 return CGM.getTypes().ConvertTypeForMem(T);
63}
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
66 return CGM.getTypes().ConvertType(T);
67}
68
69bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000070 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
71 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000072}
73
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000074void CodeGenFunction::EmitReturnBlock() {
75 // For cleanliness, we try to avoid emitting the return block for
76 // simple cases.
77 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
78
79 if (CurBB) {
80 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
81
Daniel Dunbar96e18b02009-07-19 08:24:34 +000082 // We have a valid insert point, reuse it if it is empty or there are no
83 // explicit jumps to the return block.
84 if (CurBB->empty() || ReturnBlock->use_empty()) {
85 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000086 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000087 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000088 EmitBlock(ReturnBlock);
89 return;
90 }
91
92 // Otherwise, if the return block is the target of a single direct
93 // branch then we can just put the code in that block instead. This
94 // cleans up functions which started with a unified return block.
95 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000096 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000097 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
98 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
99 // Reset insertion point and delete the branch.
100 Builder.SetInsertPoint(BI->getParent());
101 BI->eraseFromParent();
102 delete ReturnBlock;
103 return;
104 }
105 }
106
Mike Stumpf5408fe2009-05-16 07:57:57 +0000107 // FIXME: We are at an unreachable point, there is no reason to emit the block
108 // unless it has uses. However, we still need a place to put the debug
109 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000110
111 EmitBlock(ReturnBlock);
112}
113
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000114void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000115 assert(BreakContinueStack.empty() &&
116 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000117 assert(BlockScopes.empty() &&
118 "did not remove all blocks from block scope map!");
119 assert(CleanupEntries.empty() &&
120 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000121
122 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000123 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000124
125 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000126 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000127 DI->setLocation(EndLoc);
128 DI->EmitRegionEnd(CurFn, Builder);
129 }
130
Daniel Dunbar88b53962009-02-02 22:03:45 +0000131 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000132
Chris Lattner5a2fa142007-12-02 06:32:24 +0000133 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000134 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000135 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000136 Ptr->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000137}
138
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000139void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000140 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000141 const FunctionArgList &Args,
142 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000143 const Decl *D = GD.getDecl();
144
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000145 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000146 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000147 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000148 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000149 assert(CurFn->isDeclaration() && "Function already has body?");
150
Daniel Dunbar55e87422008-11-11 02:29:29 +0000151 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000152
Chris Lattner41110242008-06-17 18:05:57 +0000153 // Create a marker to make it easy to insert allocas into the entryblock
154 // later. Don't create this with the builder, because we don't want it
155 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000156 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000157 AllocaInsertPt = new llvm::BitCastInst(Undef,
158 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000159 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000160 if (Builder.isNamePreserving())
161 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Daniel Dunbar55e87422008-11-11 02:29:29 +0000163 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000164 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000165 if (!RetTy->isVoidType())
166 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattner41110242008-06-17 18:05:57 +0000168 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000170 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000171 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000172 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000173 DI->setLocation(StartLoc);
Anders Carlsson1860a312009-09-11 00:11:35 +0000174 if (isa<FunctionDecl>(D)) {
175 DI->EmitFunctionStart(CGM.getMangledName(GD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000176 } else {
177 // Just use LLVM function name.
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000179 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump1eb44332009-09-09 15:08:12 +0000180 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000181 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000182 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000183 }
184
Daniel Dunbar88b53962009-02-02 22:03:45 +0000185 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000186 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000187 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Anders Carlsson751358f2008-12-20 21:28:43 +0000189 // If any of the arguments have a variably modified type, make sure to
190 // emit the type size.
191 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
192 i != e; ++i) {
193 QualType Ty = i->second;
194
195 if (Ty->isVariablyModifiedType())
196 EmitVLASize(Ty);
197 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000198}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000199
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000200void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000201 llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000202 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
203
Anders Carlssone896d982009-02-13 08:11:52 +0000204 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000205 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000206 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Daniel Dunbar7c086512008-09-09 23:14:03 +0000208 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000210 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
211 if (MD->isInstance()) {
212 // Create the implicit 'this' decl.
213 // FIXME: I'm not entirely sure I like using a fake decl just for code
214 // generation. Maybe we can come up with a better way?
215 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000216 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000217 MD->getThisType(getContext()));
218 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
219 }
220 }
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000222 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000223 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000224 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000225
226 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000227 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000228 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000229 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000230
Sebastian Redld3a413d2009-04-26 20:35:05 +0000231 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000232 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000233 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000234 const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD);
235 llvm::BasicBlock *DtorEpilogue = 0;
236 if (DD) {
237 DtorEpilogue = createBasicBlock("dtor.epilogue");
238
239 PushCleanupBlock(DtorEpilogue);
240 }
241
Fariborz Jahanianab3c0a22009-07-20 22:35:22 +0000242 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000243 EmitCtorPrologue(CD, GD.getCtorType());
Sebastian Redld3a413d2009-04-26 20:35:05 +0000244 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000245
246 if (DD) {
247 CleanupBlockInfo Info = PopCleanupBlock();
248
249 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
250 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000251 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000252
253 if (Info.SwitchBlock)
254 EmitBlock(Info.SwitchBlock);
255 if (Info.EndBlock)
256 EmitBlock(Info.EndBlock);
257 }
Sebastian Redld3a413d2009-04-26 20:35:05 +0000258 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000259 } else if (FD->isImplicit()) {
260 const CXXRecordDecl *ClassDecl =
261 cast<CXXRecordDecl>(FD->getDeclContext());
262 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000263 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000264 // FIXME: For C++0x, we want to look for implicit *definitions* of
265 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian98896522009-08-06 23:38:16 +0000266 if (CD->isCopyConstructor(getContext())) {
267 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000268 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000269 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000270 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000271 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000272 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000273 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000274 } else {
275 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000276 }
Douglas Gregor45132722009-10-01 20:44:19 +0000277 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
278 assert(!ClassDecl->hasUserDeclaredDestructor() &&
279 "Cannot synthesize a non-implicit destructor");
280 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
281 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
282 assert(MD->isCopyAssignment() &&
283 !ClassDecl->hasUserDeclaredCopyAssignment() &&
284 "Cannot synthesize a method that is not an implicit-defined "
285 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000286 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000287 } else {
288 assert(false && "Cannot synthesize unknown implicit function");
289 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000290 }
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000292 // Destroy the 'this' declaration.
293 if (CXXThisDecl)
294 CXXThisDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000295}
296
Chris Lattner0946ccd2008-11-11 07:41:27 +0000297/// ContainsLabel - Return true if the statement contains a label in it. If
298/// this statement is not executed normally, it not containing a label means
299/// that we can just remove the code.
300bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
301 // Null statement, not a label!
302 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner0946ccd2008-11-11 07:41:27 +0000304 // If this is a label, we have to emit the code, consider something like:
305 // if (0) { ... foo: bar(); } goto foo;
306 if (isa<LabelStmt>(S))
307 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner0946ccd2008-11-11 07:41:27 +0000309 // If this is a case/default statement, and we haven't seen a switch, we have
310 // to emit the code.
311 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
312 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner0946ccd2008-11-11 07:41:27 +0000314 // If this is a switch statement, we want to ignore cases below it.
315 if (isa<SwitchStmt>(S))
316 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Chris Lattner0946ccd2008-11-11 07:41:27 +0000318 // Scan subexpressions for verboten labels.
319 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
320 I != E; ++I)
321 if (ContainsLabel(*I, IgnoreCaseStmts))
322 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattner0946ccd2008-11-11 07:41:27 +0000324 return false;
325}
326
Chris Lattner31a09842008-11-12 08:04:58 +0000327
328/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
329/// a constant, or if it does but contains a label, return 0. If it constant
330/// folds to 'true' and does not contain a label, return 1, if it constant folds
331/// to 'false' and does not contain a label, return -1.
332int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000333 // FIXME: Rename and handle conversion of other evaluatable things
334 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000335 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000336 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000337 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000338 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattner31a09842008-11-12 08:04:58 +0000340 if (CodeGenFunction::ContainsLabel(Cond))
341 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Anders Carlsson64712f12008-12-01 02:46:24 +0000343 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000344}
345
346
347/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
348/// statement) to the specified blocks. Based on the condition, this might try
349/// to simplify the codegen of the conditional based on the branch.
350///
351void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
352 llvm::BasicBlock *TrueBlock,
353 llvm::BasicBlock *FalseBlock) {
354 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
355 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner31a09842008-11-12 08:04:58 +0000357 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
358 // Handle X && Y in a condition.
359 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
360 // If we have "1 && X", simplify the code. "0 && X" would have constant
361 // folded if the case was simple enough.
362 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
363 // br(1 && X) -> br(X).
364 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
365 }
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Chris Lattner31a09842008-11-12 08:04:58 +0000367 // If we have "X && 1", simplify the code to use an uncond branch.
368 // "X && 0" would have been constant folded to 0.
369 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
370 // br(X && 1) -> br(X).
371 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
372 }
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Chris Lattner31a09842008-11-12 08:04:58 +0000374 // Emit the LHS as a conditional. If the LHS conditional is false, we
375 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000376 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000377 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
378 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattner31a09842008-11-12 08:04:58 +0000380 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
381 return;
382 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
383 // If we have "0 || X", simplify the code. "1 || X" would have constant
384 // folded if the case was simple enough.
385 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
386 // br(0 || X) -> br(X).
387 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
388 }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattner31a09842008-11-12 08:04:58 +0000390 // If we have "X || 0", simplify the code to use an uncond branch.
391 // "X || 1" would have been constant folded to 1.
392 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
393 // br(X || 0) -> br(X).
394 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner31a09842008-11-12 08:04:58 +0000397 // Emit the LHS as a conditional. If the LHS conditional is true, we
398 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000399 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000400 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
401 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner31a09842008-11-12 08:04:58 +0000403 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
404 return;
405 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner552f4c42008-11-12 08:13:36 +0000408 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
409 // br(!x, t, f) -> br(x, f, t)
410 if (CondUOp->getOpcode() == UnaryOperator::LNot)
411 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Daniel Dunbar09b14892008-11-12 10:30:32 +0000414 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
415 // Handle ?: operator.
416
417 // Just ignore GNU ?: extension.
418 if (CondOp->getLHS()) {
419 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
420 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
421 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
422 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
423 EmitBlock(LHSBlock);
424 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
425 EmitBlock(RHSBlock);
426 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
427 return;
428 }
429 }
430
Chris Lattner31a09842008-11-12 08:04:58 +0000431 // Emit the code with the fully general case.
432 llvm::Value *CondV = EvaluateExprAsBool(Cond);
433 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
434}
435
Daniel Dunbar488e9932008-08-16 00:56:44 +0000436/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000437/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000438void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
439 bool OmitOnError) {
440 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000441}
442
Chris Lattner88207c92009-04-21 17:59:23 +0000443void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattner36afd382009-10-13 06:02:42 +0000444 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000445 if (DestPtr->getType() != BP)
446 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
447
448 // Get size and alignment info for this aggregate.
449 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
450
Chris Lattner88207c92009-04-21 17:59:23 +0000451 // Don't bother emitting a zero-byte memset.
452 if (TypeInfo.first == 0)
453 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000455 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000456 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000457 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000458
459 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000460 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000461 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000462 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000463 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000464 TypeInfo.second/8));
465}
466
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000467unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
468 // Use LabelIDs.size()+1 as the new ID if one hasn't been assigned.
469 unsigned &Entry = LabelIDs[L];
470 if (Entry) return Entry;
471
472 Entry = LabelIDs.size();
473
474 // If this is the first "address taken" of a label and the indirect goto has
475 // already been seen, add this to it.
476 if (IndirectGotoSwitch) {
477 // If this is the first address-taken label, set it as the default dest.
478 if (Entry == 1)
479 IndirectGotoSwitch->setSuccessor(0, getBasicBlockForLabel(L));
480 else {
481 // Otherwise add it to the switch as a new dest.
482 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
483 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, Entry),
484 getBasicBlockForLabel(L));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486 }
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000487
488 return Entry;
489}
490
491llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
492 // If we already made the switch stmt for indirect goto, return its block.
493 if (IndirectGotoSwitch) return IndirectGotoSwitch->getParent();
494
495 EmitBlock(createBasicBlock("indirectgoto"));
496
497 // Create the PHI node that indirect gotos will add entries to.
498 llvm::Value *DestVal =
499 Builder.CreatePHI(llvm::Type::getInt32Ty(VMContext), "indirect.goto.dest");
500
501 // Create the switch instruction. For now, set the insert block to this block
502 // which will be fixed as labels are added.
503 IndirectGotoSwitch = Builder.CreateSwitch(DestVal, Builder.GetInsertBlock());
504
505 // Clear the insertion point to indicate we are in unreachable code.
506 Builder.ClearInsertionPoint();
507
508 // If we already have labels created, add them.
509 if (!LabelIDs.empty()) {
510 // Invert LabelID's so that the order is determinstic.
511 std::vector<const LabelStmt*> AddrTakenLabelsByID;
512 AddrTakenLabelsByID.resize(LabelIDs.size());
513
514 for (std::map<const LabelStmt*,unsigned>::iterator
515 LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) {
516 assert(LI->second-1 < AddrTakenLabelsByID.size() &&
517 "Numbering inconsistent");
518 AddrTakenLabelsByID[LI->second-1] = LI->first;
519 }
520
521 // Set the default entry as the first block.
522 IndirectGotoSwitch->setSuccessor(0,
523 getBasicBlockForLabel(AddrTakenLabelsByID[0]));
524
525 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
526
527 // FIXME: The iteration order of this is nondeterminstic!
528 for (unsigned i = 1, e = AddrTakenLabelsByID.size(); i != e; ++i)
529 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, i+1),
530 getBasicBlockForLabel(AddrTakenLabelsByID[i]));
531 } else {
532 // Otherwise, create a dead block and set it as the default dest. This will
533 // be removed by the optimizers after the indirect goto is set up.
534 llvm::BasicBlock *Dummy = createBasicBlock("indgoto.dummy");
535 EmitBlock(Dummy);
536 IndirectGotoSwitch->setSuccessor(0, Dummy);
537 Builder.CreateUnreachable();
538 Builder.ClearInsertionPoint();
539 }
540
541 return IndirectGotoSwitch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000542}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000543
Daniel Dunbard286f052009-07-19 06:58:07 +0000544llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000545 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Anders Carlssonf666b772008-12-20 20:27:15 +0000547 assert(SizeEntry && "Did not emit size for type");
548 return SizeEntry;
549}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000550
Daniel Dunbard286f052009-07-19 06:58:07 +0000551llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000552 assert(Ty->isVariablyModifiedType() &&
553 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Daniel Dunbard286f052009-07-19 06:58:07 +0000555 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Anders Carlsson60d35412008-12-20 20:46:34 +0000557 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000558 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000560 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000561 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000563 // Get the element size;
564 QualType ElemTy = VAT->getElementType();
565 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000566 if (ElemTy->isVariableArrayType())
567 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000568 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000569 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000570 getContext().getTypeSize(ElemTy) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000572 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000573 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000575 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000576 }
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Anders Carlsson60d35412008-12-20 20:46:34 +0000578 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000579 }
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000581 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
582 EmitVLASize(AT->getElementType());
583 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000584 }
585
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000586 const PointerType *PT = Ty->getAs<PointerType>();
587 assert(PT && "unknown VM type!");
588 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000589 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000590}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000591
592llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
593 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
594 return EmitScalarExpr(E);
595 }
596 return EmitLValue(E).getAddress();
597}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000598
Mike Stump1eb44332009-09-09 15:08:12 +0000599void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) {
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000600 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000601}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000602
Mike Stump1eb44332009-09-09 15:08:12 +0000603void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
604 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000605 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Anders Carlssonc71c8452009-02-07 23:50:39 +0000607 while (CleanupEntries.size() > OldCleanupStackSize)
608 EmitCleanupBlock();
609}
610
Mike Stump1eb44332009-09-09 15:08:12 +0000611CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000612 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000614 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000616 std::vector<llvm::BasicBlock *> Blocks;
617 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000619 std::vector<llvm::BranchInst *> BranchFixups;
620 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000622 CleanupEntries.pop_back();
623
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000624 // Check if any branch fixups pointed to the scope we just popped. If so,
625 // we can remove them.
626 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
627 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
628 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000630 if (I == BlockScopes.end())
631 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000633 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000635 if (I->second == CleanupEntries.size()) {
636 // We don't need to do this branch fixup.
637 BranchFixups[i] = BranchFixups.back();
638 BranchFixups.pop_back();
639 i--;
640 e--;
641 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000642 }
643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000645 llvm::BasicBlock *SwitchBlock = 0;
646 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000647 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000648 SwitchBlock = createBasicBlock("cleanup.switch");
649 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000651 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000653 Builder.SetInsertPoint(SwitchBlock);
654
Mike Stump1eb44332009-09-09 15:08:12 +0000655 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000656 "cleanup.dst");
657 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000659 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000660 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000661 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000662
Anders Carlsson46831a92009-02-08 22:13:37 +0000663 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000664 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000665 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000667 // If we had a current basic block, we also need to emit an instruction
668 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000669 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000670 DestCodePtr);
671 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000672 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000673
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000674 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
675 llvm::BranchInst *BI = BranchFixups[i];
676 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000678 // Fixup the branch instruction to point to the cleanup block.
679 BI->setSuccessor(0, CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000681 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000682 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Anders Carlssoncc899202009-02-08 22:46:50 +0000684 // Check if we already have a destination for this block.
685 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000686 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000687 else {
688 ID = SI->findCaseDest(Dest);
689 if (!ID) {
690 // No code found, get a new unique one by using the number of
691 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000692 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000693 SI->getNumSuccessors());
694 SI->addCase(ID, Dest);
695 }
696 }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Anders Carlssoncc899202009-02-08 22:46:50 +0000698 // Store the jump destination before the branch instruction.
699 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000700 } else {
701 // We need to jump through another cleanup block. Create a pad block
702 // with a branch instruction that jumps to the final destination and
703 // add it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000705 // Create the pad block.
706 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000707
708 // Create a unique case ID.
Mike Stump1eb44332009-09-09 15:08:12 +0000709 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000710 SI->getNumSuccessors());
711
712 // Store the jump destination before the branch instruction.
713 new llvm::StoreInst(ID, DestCodePtr, BI);
714
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000715 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000716 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000718 // Create the branch to the final destination.
719 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
720 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000722 // And add it as a branch fixup.
723 CleanupEntries.back().BranchFixups.push_back(BI);
724 }
725 }
726 }
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000728 // Remove all blocks from the block scope map.
729 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
730 assert(BlockScopes.count(Blocks[i]) &&
731 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000733 BlockScopes.erase(Blocks[i]);
734 }
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000736 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000737}
738
Mike Stump1eb44332009-09-09 15:08:12 +0000739void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000740 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000742 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000743 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000744 Info.CleanupBlock->getNumUses() == 0) {
745 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
746 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000747 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000748 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000750 if (Info.SwitchBlock)
751 EmitBlock(Info.SwitchBlock);
752 if (Info.EndBlock)
753 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000754}
755
Mike Stump1eb44332009-09-09 15:08:12 +0000756void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
757 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000758 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Mike Stumpf5408fe2009-05-16 07:57:57 +0000760 // FIXME: We could be more clever here and check if there's already a branch
761 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000762 CleanupEntries.back().BranchFixups.push_back(BI);
763}
764
Mike Stump1eb44332009-09-09 15:08:12 +0000765void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000766 if (!HaveInsertPoint())
767 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Anders Carlsson87eaf172009-02-08 00:50:42 +0000769 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Anders Carlsson46831a92009-02-08 22:13:37 +0000771 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Anders Carlsson87eaf172009-02-08 00:50:42 +0000773 // The stack is empty, no need to do any cleanup.
774 if (CleanupEntries.empty())
775 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Anders Carlsson87eaf172009-02-08 00:50:42 +0000777 if (!Dest->getParent()) {
778 // We are trying to branch to a block that hasn't been inserted yet.
779 AddBranchFixup(BI);
780 return;
781 }
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Anders Carlsson87eaf172009-02-08 00:50:42 +0000783 BlockScopeMap::iterator I = BlockScopes.find(Dest);
784 if (I == BlockScopes.end()) {
785 // We are trying to jump to a block that is outside of any cleanup scope.
786 AddBranchFixup(BI);
787 return;
788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Anders Carlsson87eaf172009-02-08 00:50:42 +0000790 assert(I->second < CleanupEntries.size() &&
791 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Anders Carlsson87eaf172009-02-08 00:50:42 +0000793 if (I->second == CleanupEntries.size() - 1) {
794 // We have a branch to a block in the same scope.
795 return;
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Anders Carlsson87eaf172009-02-08 00:50:42 +0000798 AddBranchFixup(BI);
799}