blob: f802068b26d3444066b9aef14e96fa066d76c44b [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()),
Mike Stump1eb44332009-09-09 15:08:12 +000030 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson2b77ba82009-04-04 20:47:02 +000031 CXXThisDecl(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000032 LLVMIntTy = ConvertType(getContext().IntTy);
33 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000034}
Reid Spencer5f016e22007-07-11 17:01:13 +000035
36ASTContext &CodeGenFunction::getContext() const {
37 return CGM.getContext();
38}
39
40
41llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
42 llvm::BasicBlock *&BB = LabelMap[S];
43 if (BB) return BB;
Mike Stump1eb44332009-09-09 15:08:12 +000044
Reid Spencer5f016e22007-07-11 17:01:13 +000045 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000046 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000047}
48
Daniel Dunbar0096acf2009-02-25 19:24:29 +000049llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
50 llvm::Value *Res = LocalDeclMap[VD];
51 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
52 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000053}
Reid Spencer5f016e22007-07-11 17:01:13 +000054
Daniel Dunbar0096acf2009-02-25 19:24:29 +000055llvm::Constant *
56CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
57 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000058}
59
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000060const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61 return CGM.getTypes().ConvertTypeForMem(T);
62}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65 return CGM.getTypes().ConvertType(T);
66}
67
68bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000069 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
70 T->isMemberFunctionPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000071}
72
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000073void CodeGenFunction::EmitReturnBlock() {
74 // For cleanliness, we try to avoid emitting the return block for
75 // simple cases.
76 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
77
78 if (CurBB) {
79 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
80
Daniel Dunbar96e18b02009-07-19 08:24:34 +000081 // We have a valid insert point, reuse it if it is empty or there are no
82 // explicit jumps to the return block.
83 if (CurBB->empty() || ReturnBlock->use_empty()) {
84 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000085 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000086 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000087 EmitBlock(ReturnBlock);
88 return;
89 }
90
91 // Otherwise, if the return block is the target of a single direct
92 // branch then we can just put the code in that block instead. This
93 // cleans up functions which started with a unified return block.
94 if (ReturnBlock->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +000095 llvm::BranchInst *BI =
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000096 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
97 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
98 // Reset insertion point and delete the branch.
99 Builder.SetInsertPoint(BI->getParent());
100 BI->eraseFromParent();
101 delete ReturnBlock;
102 return;
103 }
104 }
105
Mike Stumpf5408fe2009-05-16 07:57:57 +0000106 // FIXME: We are at an unreachable point, there is no reason to emit the block
107 // unless it has uses. However, we still need a place to put the debug
108 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000109
110 EmitBlock(ReturnBlock);
111}
112
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000113void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000114 // Finish emission of indirect switches.
115 EmitIndirectSwitches();
116
Chris Lattnerda138702007-07-16 21:28:45 +0000117 assert(BreakContinueStack.empty() &&
118 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000119 assert(BlockScopes.empty() &&
120 "did not remove all blocks from block scope map!");
121 assert(CleanupEntries.empty() &&
122 "mismatched push/pop in cleanup stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000123
124 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000125 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000126
127 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000128 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000129 DI->setLocation(EndLoc);
130 DI->EmitRegionEnd(CurFn, Builder);
131 }
132
Daniel Dunbar88b53962009-02-02 22:03:45 +0000133 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000134
Chris Lattner5a2fa142007-12-02 06:32:24 +0000135 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000136 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000137 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000138 Ptr->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000139}
140
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000141void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000142 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000143 const FunctionArgList &Args,
144 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000145 const Decl *D = GD.getDecl();
146
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000147 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000148 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000149 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000150 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000151 assert(CurFn->isDeclaration() && "Function already has body?");
152
Daniel Dunbar55e87422008-11-11 02:29:29 +0000153 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000154
Chris Lattner41110242008-06-17 18:05:57 +0000155 // Create a marker to make it easy to insert allocas into the entryblock
156 // later. Don't create this with the builder, because we don't want it
157 // folded.
Owen Anderson0032b272009-08-13 21:57:51 +0000158 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stumpbcdc0f02009-09-25 18:11:00 +0000159 AllocaInsertPt = new llvm::BitCastInst(Undef,
160 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner41110242008-06-17 18:05:57 +0000161 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000162 if (Builder.isNamePreserving())
163 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Daniel Dunbar55e87422008-11-11 02:29:29 +0000165 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000166 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000167 if (!RetTy->isVoidType())
168 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattner41110242008-06-17 18:05:57 +0000170 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000172 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000173 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000174 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000175 DI->setLocation(StartLoc);
Anders Carlsson1860a312009-09-11 00:11:35 +0000176 if (isa<FunctionDecl>(D)) {
177 DI->EmitFunctionStart(CGM.getMangledName(GD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000178 } else {
179 // Just use LLVM function name.
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000181 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump1eb44332009-09-09 15:08:12 +0000182 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000183 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000184 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000185 }
186
Daniel Dunbar88b53962009-02-02 22:03:45 +0000187 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000188 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000189 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Anders Carlsson751358f2008-12-20 21:28:43 +0000191 // If any of the arguments have a variably modified type, make sure to
192 // emit the type size.
193 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
194 i != e; ++i) {
195 QualType Ty = i->second;
196
197 if (Ty->isVariablyModifiedType())
198 EmitVLASize(Ty);
199 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000200}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000201
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000202void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000203 llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000204 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
205
Anders Carlssone896d982009-02-13 08:11:52 +0000206 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000207 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000208 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Daniel Dunbar7c086512008-09-09 23:14:03 +0000210 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000212 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
213 if (MD->isInstance()) {
214 // Create the implicit 'this' decl.
215 // FIXME: I'm not entirely sure I like using a fake decl just for code
216 // generation. Maybe we can come up with a better way?
217 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000218 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000219 MD->getThisType(getContext()));
220 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
221 }
222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000224 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000225 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000226 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000227
228 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000229 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000230 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000231 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000232
Sebastian Redld3a413d2009-04-26 20:35:05 +0000233 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000234 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000235 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000236 const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD);
237 llvm::BasicBlock *DtorEpilogue = 0;
238 if (DD) {
239 DtorEpilogue = createBasicBlock("dtor.epilogue");
240
241 PushCleanupBlock(DtorEpilogue);
242 }
243
Fariborz Jahanianab3c0a22009-07-20 22:35:22 +0000244 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000245 EmitCtorPrologue(CD, GD.getCtorType());
Sebastian Redld3a413d2009-04-26 20:35:05 +0000246 EmitStmt(S);
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000247
248 if (DD) {
249 CleanupBlockInfo Info = PopCleanupBlock();
250
251 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
252 EmitBlock(DtorEpilogue);
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000253 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlssonc33e4ba2009-10-06 18:09:57 +0000254
255 if (Info.SwitchBlock)
256 EmitBlock(Info.SwitchBlock);
257 if (Info.EndBlock)
258 EmitBlock(Info.EndBlock);
259 }
Sebastian Redld3a413d2009-04-26 20:35:05 +0000260 FinishFunction(S->getRBracLoc());
Douglas Gregor45132722009-10-01 20:44:19 +0000261 } else if (FD->isImplicit()) {
262 const CXXRecordDecl *ClassDecl =
263 cast<CXXRecordDecl>(FD->getDeclContext());
264 (void) ClassDecl;
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000265 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor45132722009-10-01 20:44:19 +0000266 // FIXME: For C++0x, we want to look for implicit *definitions* of
267 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian98896522009-08-06 23:38:16 +0000268 if (CD->isCopyConstructor(getContext())) {
269 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000270 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000271 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000272 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian98896522009-08-06 23:38:16 +0000273 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor45132722009-10-01 20:44:19 +0000274 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000275 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000276 } else {
277 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian98896522009-08-06 23:38:16 +0000278 }
Douglas Gregor45132722009-10-01 20:44:19 +0000279 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
280 assert(!ClassDecl->hasUserDeclaredDestructor() &&
281 "Cannot synthesize a non-implicit destructor");
282 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
283 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
284 assert(MD->isCopyAssignment() &&
285 !ClassDecl->hasUserDeclaredCopyAssignment() &&
286 "Cannot synthesize a method that is not an implicit-defined "
287 "copy constructor");
Anders Carlssonde1d26b2009-09-14 05:32:02 +0000288 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor45132722009-10-01 20:44:19 +0000289 } else {
290 assert(false && "Cannot synthesize unknown implicit function");
291 }
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000294 // Destroy the 'this' declaration.
295 if (CXXThisDecl)
296 CXXThisDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000297}
298
Chris Lattner0946ccd2008-11-11 07:41:27 +0000299/// ContainsLabel - Return true if the statement contains a label in it. If
300/// this statement is not executed normally, it not containing a label means
301/// that we can just remove the code.
302bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
303 // Null statement, not a label!
304 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner0946ccd2008-11-11 07:41:27 +0000306 // If this is a label, we have to emit the code, consider something like:
307 // if (0) { ... foo: bar(); } goto foo;
308 if (isa<LabelStmt>(S))
309 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattner0946ccd2008-11-11 07:41:27 +0000311 // If this is a case/default statement, and we haven't seen a switch, we have
312 // to emit the code.
313 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
314 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattner0946ccd2008-11-11 07:41:27 +0000316 // If this is a switch statement, we want to ignore cases below it.
317 if (isa<SwitchStmt>(S))
318 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Chris Lattner0946ccd2008-11-11 07:41:27 +0000320 // Scan subexpressions for verboten labels.
321 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
322 I != E; ++I)
323 if (ContainsLabel(*I, IgnoreCaseStmts))
324 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chris Lattner0946ccd2008-11-11 07:41:27 +0000326 return false;
327}
328
Chris Lattner31a09842008-11-12 08:04:58 +0000329
330/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
331/// a constant, or if it does but contains a label, return 0. If it constant
332/// folds to 'true' and does not contain a label, return 1, if it constant folds
333/// to 'false' and does not contain a label, return -1.
334int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000335 // FIXME: Rename and handle conversion of other evaluatable things
336 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000337 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000338 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000339 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000340 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattner31a09842008-11-12 08:04:58 +0000342 if (CodeGenFunction::ContainsLabel(Cond))
343 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson64712f12008-12-01 02:46:24 +0000345 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000346}
347
348
349/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
350/// statement) to the specified blocks. Based on the condition, this might try
351/// to simplify the codegen of the conditional based on the branch.
352///
353void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
354 llvm::BasicBlock *TrueBlock,
355 llvm::BasicBlock *FalseBlock) {
356 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
357 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattner31a09842008-11-12 08:04:58 +0000359 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
360 // Handle X && Y in a condition.
361 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
362 // If we have "1 && X", simplify the code. "0 && X" would have constant
363 // folded if the case was simple enough.
364 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
365 // br(1 && X) -> br(X).
366 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
367 }
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Chris Lattner31a09842008-11-12 08:04:58 +0000369 // If we have "X && 1", simplify the code to use an uncond branch.
370 // "X && 0" would have been constant folded to 0.
371 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
372 // br(X && 1) -> br(X).
373 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
374 }
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner31a09842008-11-12 08:04:58 +0000376 // Emit the LHS as a conditional. If the LHS conditional is false, we
377 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000378 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000379 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
380 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner31a09842008-11-12 08:04:58 +0000382 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
383 return;
384 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
385 // If we have "0 || X", simplify the code. "1 || X" would have constant
386 // folded if the case was simple enough.
387 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
388 // br(0 || X) -> br(X).
389 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
390 }
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner31a09842008-11-12 08:04:58 +0000392 // If we have "X || 0", simplify the code to use an uncond branch.
393 // "X || 1" would have been constant folded to 1.
394 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
395 // br(X || 0) -> br(X).
396 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner31a09842008-11-12 08:04:58 +0000399 // Emit the LHS as a conditional. If the LHS conditional is true, we
400 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000401 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000402 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
403 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner31a09842008-11-12 08:04:58 +0000405 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
406 return;
407 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000408 }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner552f4c42008-11-12 08:13:36 +0000410 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
411 // br(!x, t, f) -> br(x, f, t)
412 if (CondUOp->getOpcode() == UnaryOperator::LNot)
413 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000414 }
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Daniel Dunbar09b14892008-11-12 10:30:32 +0000416 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
417 // Handle ?: operator.
418
419 // Just ignore GNU ?: extension.
420 if (CondOp->getLHS()) {
421 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
422 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
423 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
424 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
425 EmitBlock(LHSBlock);
426 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
427 EmitBlock(RHSBlock);
428 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
429 return;
430 }
431 }
432
Chris Lattner31a09842008-11-12 08:04:58 +0000433 // Emit the code with the fully general case.
434 llvm::Value *CondV = EvaluateExprAsBool(Cond);
435 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
436}
437
Daniel Dunbar488e9932008-08-16 00:56:44 +0000438/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000439/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000440void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
441 bool OmitOnError) {
442 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000443}
444
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000445unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
446 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
447 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
448}
449
Chris Lattner88207c92009-04-21 17:59:23 +0000450void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Owen Anderson0032b272009-08-13 21:57:51 +0000451 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000452 if (DestPtr->getType() != BP)
453 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
454
455 // Get size and alignment info for this aggregate.
456 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
457
Chris Lattner88207c92009-04-21 17:59:23 +0000458 // Don't bother emitting a zero-byte memset.
459 if (TypeInfo.first == 0)
460 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000462 // FIXME: Handle variable sized types.
Mike Stump1eb44332009-09-09 15:08:12 +0000463 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000464 LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000465
466 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson0032b272009-08-13 21:57:51 +0000467 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000468 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000469 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump1eb44332009-09-09 15:08:12 +0000470 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000471 TypeInfo.second/8));
472}
473
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000474void CodeGenFunction::EmitIndirectSwitches() {
475 llvm::BasicBlock *Default;
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Daniel Dunbar76526a52008-08-04 17:24:44 +0000477 if (IndirectSwitches.empty())
478 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000480 if (!LabelIDs.empty()) {
481 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
482 } else {
483 // No possible targets for indirect goto, just emit an infinite
484 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000485 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000486 llvm::BranchInst::Create(Default, Default);
487 }
488
489 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
490 e = IndirectSwitches.end(); i != e; ++i) {
491 llvm::SwitchInst *I = *i;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000493 I->setSuccessor(0, Default);
Mike Stump1eb44332009-09-09 15:08:12 +0000494 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000495 LE = LabelIDs.end(); LI != LE; ++LI) {
Owen Anderson0032b272009-08-13 21:57:51 +0000496 I->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Mike Stump1eb44332009-09-09 15:08:12 +0000497 LI->second),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000498 getBasicBlockForLabel(LI->first));
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500 }
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000501}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000502
Daniel Dunbard286f052009-07-19 06:58:07 +0000503llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000504 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Anders Carlssonf666b772008-12-20 20:27:15 +0000506 assert(SizeEntry && "Did not emit size for type");
507 return SizeEntry;
508}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000509
Daniel Dunbard286f052009-07-19 06:58:07 +0000510llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000511 assert(Ty->isVariablyModifiedType() &&
512 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Daniel Dunbard286f052009-07-19 06:58:07 +0000514 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Anders Carlsson60d35412008-12-20 20:46:34 +0000516 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000517 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000519 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000520 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000522 // Get the element size;
523 QualType ElemTy = VAT->getElementType();
524 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000525 if (ElemTy->isVariableArrayType())
526 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000527 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000528 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000529 getContext().getTypeSize(ElemTy) / 8);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000531 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000532 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000534 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Anders Carlsson60d35412008-12-20 20:46:34 +0000537 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000540 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
541 EmitVLASize(AT->getElementType());
542 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000543 }
544
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000545 const PointerType *PT = Ty->getAs<PointerType>();
546 assert(PT && "unknown VM type!");
547 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000548 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000549}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000550
551llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
552 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
553 return EmitScalarExpr(E);
554 }
555 return EmitLValue(E).getAddress();
556}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000557
Mike Stump1eb44332009-09-09 15:08:12 +0000558void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) {
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000559 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000560}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000561
Mike Stump1eb44332009-09-09 15:08:12 +0000562void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
563 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonc71c8452009-02-07 23:50:39 +0000564 "Cleanup stack mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Anders Carlssonc71c8452009-02-07 23:50:39 +0000566 while (CleanupEntries.size() > OldCleanupStackSize)
567 EmitCleanupBlock();
568}
569
Mike Stump1eb44332009-09-09 15:08:12 +0000570CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000571 CleanupEntry &CE = CleanupEntries.back();
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000573 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000575 std::vector<llvm::BasicBlock *> Blocks;
576 std::swap(Blocks, CE.Blocks);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000578 std::vector<llvm::BranchInst *> BranchFixups;
579 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000581 CleanupEntries.pop_back();
582
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000583 // Check if any branch fixups pointed to the scope we just popped. If so,
584 // we can remove them.
585 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
586 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
587 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000589 if (I == BlockScopes.end())
590 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000592 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000594 if (I->second == CleanupEntries.size()) {
595 // We don't need to do this branch fixup.
596 BranchFixups[i] = BranchFixups.back();
597 BranchFixups.pop_back();
598 i--;
599 e--;
600 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000601 }
602 }
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000604 llvm::BasicBlock *SwitchBlock = 0;
605 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000606 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000607 SwitchBlock = createBasicBlock("cleanup.switch");
608 EndBlock = createBasicBlock("cleanup.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000610 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000612 Builder.SetInsertPoint(SwitchBlock);
613
Mike Stump1eb44332009-09-09 15:08:12 +0000614 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000615 "cleanup.dst");
616 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000618 // Create a switch instruction to determine where to jump next.
Mike Stump1eb44332009-09-09 15:08:12 +0000619 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000620 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000621
Anders Carlsson46831a92009-02-08 22:13:37 +0000622 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000623 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000624 Builder.SetInsertPoint(CurBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000626 // If we had a current basic block, we also need to emit an instruction
627 // to initialize the cleanup destination.
Owen Anderson0032b272009-08-13 21:57:51 +0000628 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000629 DestCodePtr);
630 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000631 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000632
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000633 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
634 llvm::BranchInst *BI = BranchFixups[i];
635 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000637 // Fixup the branch instruction to point to the cleanup block.
638 BI->setSuccessor(0, CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000640 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000641 llvm::ConstantInt *ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Anders Carlssoncc899202009-02-08 22:46:50 +0000643 // Check if we already have a destination for this block.
644 if (Dest == SI->getDefaultDest())
Owen Anderson0032b272009-08-13 21:57:51 +0000645 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000646 else {
647 ID = SI->findCaseDest(Dest);
648 if (!ID) {
649 // No code found, get a new unique one by using the number of
650 // switch successors.
Mike Stump1eb44332009-09-09 15:08:12 +0000651 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000652 SI->getNumSuccessors());
653 SI->addCase(ID, Dest);
654 }
655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Anders Carlssoncc899202009-02-08 22:46:50 +0000657 // Store the jump destination before the branch instruction.
658 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000659 } else {
660 // We need to jump through another cleanup block. Create a pad block
661 // with a branch instruction that jumps to the final destination and
662 // add it as a branch fixup to the current cleanup scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000664 // Create the pad block.
665 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000666
667 // Create a unique case ID.
Mike Stump1eb44332009-09-09 15:08:12 +0000668 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlssoncc899202009-02-08 22:46:50 +0000669 SI->getNumSuccessors());
670
671 // Store the jump destination before the branch instruction.
672 new llvm::StoreInst(ID, DestCodePtr, BI);
673
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000674 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000675 SI->addCase(ID, CleanupPad);
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000677 // Create the branch to the final destination.
678 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
679 CleanupPad->getInstList().push_back(BI);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000681 // And add it as a branch fixup.
682 CleanupEntries.back().BranchFixups.push_back(BI);
683 }
684 }
685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000687 // Remove all blocks from the block scope map.
688 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
689 assert(BlockScopes.count(Blocks[i]) &&
690 "Did not find block in scope map!");
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000692 BlockScopes.erase(Blocks[i]);
693 }
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000695 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000696}
697
Mike Stump1eb44332009-09-09 15:08:12 +0000698void CodeGenFunction::EmitCleanupBlock() {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000699 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000701 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump1eb44332009-09-09 15:08:12 +0000702 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000703 Info.CleanupBlock->getNumUses() == 0) {
704 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
705 delete Info.CleanupBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000706 } else
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000707 EmitBlock(Info.CleanupBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000709 if (Info.SwitchBlock)
710 EmitBlock(Info.SwitchBlock);
711 if (Info.EndBlock)
712 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000713}
714
Mike Stump1eb44332009-09-09 15:08:12 +0000715void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
716 assert(!CleanupEntries.empty() &&
Anders Carlsson87eaf172009-02-08 00:50:42 +0000717 "Trying to add branch fixup without cleanup block!");
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Mike Stumpf5408fe2009-05-16 07:57:57 +0000719 // FIXME: We could be more clever here and check if there's already a branch
720 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000721 CleanupEntries.back().BranchFixups.push_back(BI);
722}
723
Mike Stump1eb44332009-09-09 15:08:12 +0000724void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000725 if (!HaveInsertPoint())
726 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Anders Carlsson87eaf172009-02-08 00:50:42 +0000728 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Anders Carlsson46831a92009-02-08 22:13:37 +0000730 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Anders Carlsson87eaf172009-02-08 00:50:42 +0000732 // The stack is empty, no need to do any cleanup.
733 if (CleanupEntries.empty())
734 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Anders Carlsson87eaf172009-02-08 00:50:42 +0000736 if (!Dest->getParent()) {
737 // We are trying to branch to a block that hasn't been inserted yet.
738 AddBranchFixup(BI);
739 return;
740 }
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Anders Carlsson87eaf172009-02-08 00:50:42 +0000742 BlockScopeMap::iterator I = BlockScopes.find(Dest);
743 if (I == BlockScopes.end()) {
744 // We are trying to jump to a block that is outside of any cleanup scope.
745 AddBranchFixup(BI);
746 return;
747 }
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Anders Carlsson87eaf172009-02-08 00:50:42 +0000749 assert(I->second < CleanupEntries.size() &&
750 "Trying to branch into cleanup region");
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Anders Carlsson87eaf172009-02-08 00:50:42 +0000752 if (I->second == CleanupEntries.size() - 1) {
753 // We have a branch to a block in the same scope.
754 return;
755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Anders Carlsson87eaf172009-02-08 00:50:42 +0000757 AddBranchFixup(BI);
758}