blob: f9e54b75708f6fda4d92ae502f7bd6a5d50bd5ea [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()),
Mike Stump11289f42009-09-09 15:08:12 +000030 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson468fa632009-04-04 20:47:02 +000031 CXXThisDecl(0) {
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000032 LLVMIntTy = ConvertType(getContext().IntTy);
33 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner5696e7b2008-06-17 18:05:57 +000034}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000035
Chris Lattner6db1fb82007-06-02 22:49:07 +000036ASTContext &CodeGenFunction::getContext() const {
37 return CGM.getContext();
38}
39
Chris Lattnerd1af2d22007-05-29 23:17:50 +000040
Chris Lattnerac248202007-05-30 00:13:02 +000041llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
Chris Lattner23b7eb62007-06-15 23:05:46 +000042 llvm::BasicBlock *&BB = LabelMap[S];
Chris Lattnerac248202007-05-30 00:13:02 +000043 if (BB) return BB;
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerac248202007-05-30 00:13:02 +000045 // Create, but don't insert, the new block.
Daniel Dunbar75283ff2008-11-11 02:29:29 +000046 return BB = createBasicBlock(S->getName());
Chris Lattnerac248202007-05-30 00:13:02 +000047}
48
Daniel Dunbar22a87f92009-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 Venancio01a72ff2008-02-26 21:41:45 +000053}
Chris Lattnerac248202007-05-30 00:13:02 +000054
Daniel Dunbar22a87f92009-02-25 19:24:29 +000055llvm::Constant *
56CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
57 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson9396a892008-09-11 09:15:33 +000058}
59
Daniel Dunbaree3da872009-02-03 23:03:55 +000060const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61 return CGM.getTypes().ConvertTypeForMem(T);
62}
63
Chris Lattnerf033c142007-06-22 19:05:19 +000064const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +000066}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000067
Chris Lattner54fb19e2007-06-22 22:02:34 +000068bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssonb05a3e52009-09-29 02:09:01 +000069 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
70 T->isMemberFunctionPointerType();
Chris Lattner54fb19e2007-06-22 22:02:34 +000071}
72
Daniel Dunbarfd346a32009-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 Dunbarea3060a2009-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 Dunbarfd346a32009-01-26 23:27:52 +000085 delete ReturnBlock;
Daniel Dunbarea3060a2009-07-19 08:24:34 +000086 } else
Daniel Dunbarfd346a32009-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 Stump11289f42009-09-09 15:08:12 +000095 llvm::BranchInst *BI =
Daniel Dunbarfd346a32009-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 Stump18bb9282009-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 Dunbarfd346a32009-01-26 23:27:52 +0000109
110 EmitBlock(ReturnBlock);
111}
112
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000113void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000114 // Finish emission of indirect switches.
115 EmitIndirectSwitches();
116
Chris Lattnere73e4322007-07-16 21:28:45 +0000117 assert(BreakContinueStack.empty() &&
118 "mismatched push/pop in break/continue stack!");
Anders Carlssonfbfb5e62009-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 Stump11289f42009-09-09 15:08:12 +0000123
124 // Emit function epilog (to return).
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000125 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000126
127 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000128 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000129 DI->setLocation(EndLoc);
130 DI->EmitRegionEnd(CurFn, Builder);
131 }
132
Daniel Dunbard931a872009-02-02 22:03:45 +0000133 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000134
Chris Lattnerc48023b2007-12-02 06:32:24 +0000135 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000136 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerc48023b2007-12-02 06:32:24 +0000137 AllocaInsertPt = 0;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000138 Ptr->eraseFromParent();
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000139}
Chris Lattner308f4312007-05-29 23:50:05 +0000140
Anders Carlsson73fcc952009-09-11 00:07:24 +0000141void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000142 llvm::Function *Fn,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000143 const FunctionArgList &Args,
144 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000145 const Decl *D = GD.getDecl();
146
Anders Carlssonf4478e92009-02-09 20:20:56 +0000147 DidCallStackSave = false;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000148 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000149 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000150 CurFn = Fn;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000151 assert(CurFn->isDeclaration() && "Function already has body?");
152
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000153 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000154
Chris Lattner5696e7b2008-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 Anderson41a75022009-08-13 21:57:51 +0000158 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stump1dbb8f72009-09-25 18:11:00 +0000159 AllocaInsertPt = new llvm::BitCastInst(Undef,
160 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner5696e7b2008-06-17 18:05:57 +0000161 EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000162 if (Builder.isNamePreserving())
163 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000164
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000165 ReturnBlock = createBasicBlock("return");
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000166 ReturnValue = 0;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000167 if (!RetTy->isVoidType())
168 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattner5696e7b2008-06-17 18:05:57 +0000170 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000171
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000172 // Emit subprogram debug descriptor.
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000173 // FIXME: The cast here is a huge hack.
Anders Carlsson63784f42009-02-13 08:11:52 +0000174 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar354d2782008-10-18 18:22:23 +0000175 DI->setLocation(StartLoc);
Anders Carlssonfd384d82009-09-11 00:11:35 +0000176 if (isa<FunctionDecl>(D)) {
177 DI->EmitFunctionStart(CGM.getMangledName(GD), RetTy, CurFn, Builder);
Daniel Dunbar354d2782008-10-18 18:22:23 +0000178 } else {
179 // Just use LLVM function name.
Mike Stump11289f42009-09-09 15:08:12 +0000180
Daniel Dunbar7c02cf62009-07-23 05:30:36 +0000181 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump11289f42009-09-09 15:08:12 +0000182 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Daniel Dunbar354d2782008-10-18 18:22:23 +0000183 RetTy, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000184 }
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000185 }
186
Daniel Dunbard931a872009-02-02 22:03:45 +0000187 // FIXME: Leaked.
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000188 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbard931a872009-02-02 22:03:45 +0000189 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000190
Anders Carlssonc20879a2008-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 Dunbarbc915f42008-09-09 23:14:03 +0000200}
Eli Friedman3d421e12008-08-25 21:31:01 +0000201
Anders Carlsson73fcc952009-09-11 00:07:24 +0000202void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000203 llvm::Function *Fn) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000204 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
205
Anders Carlsson63784f42009-02-13 08:11:52 +0000206 // Check if we should generate debug info for this function.
Mike Stump3722f582009-08-26 22:31:08 +0000207 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlsson63784f42009-02-13 08:11:52 +0000208 DebugInfo = CGM.getDebugInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000210 FunctionArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000211
Anders Carlsson468fa632009-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 Stump11289f42009-09-09 15:08:12 +0000218 &getContext().Idents.get("this"),
Anders Carlsson468fa632009-04-04 20:47:02 +0000219 MD->getThisType(getContext()));
220 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
221 }
222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223
Eli Friedman3d421e12008-08-25 21:31:01 +0000224 if (FD->getNumParams()) {
John McCall9dd450b2009-09-21 23:43:11 +0000225 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedman3d421e12008-08-25 21:31:01 +0000226 assert(FProto && "Function def must have prototype!");
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000227
228 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump11289f42009-09-09 15:08:12 +0000229 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000230 FProto->getArgType(i)));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000231 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000232
Sebastian Redla7b98a72009-04-26 20:35:05 +0000233 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000234 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000235 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Fariborz Jahanian127059c2009-07-20 22:35:22 +0000236 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Anders Carlssonddf57d32009-09-14 05:32:02 +0000237 EmitCtorPrologue(CD, GD.getCtorType());
Sebastian Redla7b98a72009-04-26 20:35:05 +0000238 EmitStmt(S);
Fariborz Jahanianaa01d2a2009-07-30 17:49:11 +0000239 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Anders Carlssonddf57d32009-09-14 05:32:02 +0000240 EmitDtorEpilogue(DD, GD.getDtorType());
Sebastian Redla7b98a72009-04-26 20:35:05 +0000241 FinishFunction(S->getRBracLoc());
Douglas Gregor369acf92009-10-01 20:44:19 +0000242 } else if (FD->isImplicit()) {
243 const CXXRecordDecl *ClassDecl =
244 cast<CXXRecordDecl>(FD->getDeclContext());
245 (void) ClassDecl;
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000246 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor369acf92009-10-01 20:44:19 +0000247 // FIXME: For C++0x, we want to look for implicit *definitions* of
248 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000249 if (CD->isCopyConstructor(getContext())) {
250 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000251 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000252 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000253 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000254 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000255 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000256 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000257 } else {
258 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000259 }
Douglas Gregor369acf92009-10-01 20:44:19 +0000260 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
261 assert(!ClassDecl->hasUserDeclaredDestructor() &&
262 "Cannot synthesize a non-implicit destructor");
263 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
264 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
265 assert(MD->isCopyAssignment() &&
266 !ClassDecl->hasUserDeclaredCopyAssignment() &&
267 "Cannot synthesize a method that is not an implicit-defined "
268 "copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000269 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000270 } else {
271 assert(false && "Cannot synthesize unknown implicit function");
272 }
Anders Carlsson73fcc952009-09-11 00:07:24 +0000273 }
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlsson468fa632009-04-04 20:47:02 +0000275 // Destroy the 'this' declaration.
276 if (CXXThisDecl)
277 CXXThisDecl->Destroy(getContext());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000278}
279
Chris Lattner5b1964b2008-11-11 07:41:27 +0000280/// ContainsLabel - Return true if the statement contains a label in it. If
281/// this statement is not executed normally, it not containing a label means
282/// that we can just remove the code.
283bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
284 // Null statement, not a label!
285 if (S == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattner5b1964b2008-11-11 07:41:27 +0000287 // If this is a label, we have to emit the code, consider something like:
288 // if (0) { ... foo: bar(); } goto foo;
289 if (isa<LabelStmt>(S))
290 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner5b1964b2008-11-11 07:41:27 +0000292 // If this is a case/default statement, and we haven't seen a switch, we have
293 // to emit the code.
294 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
295 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattner5b1964b2008-11-11 07:41:27 +0000297 // If this is a switch statement, we want to ignore cases below it.
298 if (isa<SwitchStmt>(S))
299 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattner5b1964b2008-11-11 07:41:27 +0000301 // Scan subexpressions for verboten labels.
302 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
303 I != E; ++I)
304 if (ContainsLabel(*I, IgnoreCaseStmts))
305 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000306
Chris Lattner5b1964b2008-11-11 07:41:27 +0000307 return false;
308}
309
Chris Lattnercd439292008-11-12 08:04:58 +0000310
311/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
312/// a constant, or if it does but contains a label, return 0. If it constant
313/// folds to 'true' and does not contain a label, return 1, if it constant folds
314/// to 'false' and does not contain a label, return -1.
315int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000316 // FIXME: Rename and handle conversion of other evaluatable things
317 // to bool.
Anders Carlsson86286452008-12-01 02:46:24 +0000318 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +0000319 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson86286452008-12-01 02:46:24 +0000320 Result.HasSideEffects)
Anders Carlsson4046e652008-11-22 22:32:07 +0000321 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattnercd439292008-11-12 08:04:58 +0000323 if (CodeGenFunction::ContainsLabel(Cond))
324 return 0; // Contains a label.
Mike Stump11289f42009-09-09 15:08:12 +0000325
Anders Carlsson86286452008-12-01 02:46:24 +0000326 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattnercd439292008-11-12 08:04:58 +0000327}
328
329
330/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
331/// statement) to the specified blocks. Based on the condition, this might try
332/// to simplify the codegen of the conditional based on the branch.
333///
334void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
335 llvm::BasicBlock *TrueBlock,
336 llvm::BasicBlock *FalseBlock) {
337 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
338 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000339
Chris Lattnercd439292008-11-12 08:04:58 +0000340 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
341 // Handle X && Y in a condition.
342 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
343 // If we have "1 && X", simplify the code. "0 && X" would have constant
344 // folded if the case was simple enough.
345 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
346 // br(1 && X) -> br(X).
347 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
348 }
Mike Stump11289f42009-09-09 15:08:12 +0000349
Chris Lattnercd439292008-11-12 08:04:58 +0000350 // If we have "X && 1", simplify the code to use an uncond branch.
351 // "X && 0" would have been constant folded to 0.
352 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
353 // br(X && 1) -> br(X).
354 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
355 }
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattnercd439292008-11-12 08:04:58 +0000357 // Emit the LHS as a conditional. If the LHS conditional is false, we
358 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000359 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattnercd439292008-11-12 08:04:58 +0000360 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
361 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattnercd439292008-11-12 08:04:58 +0000363 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
364 return;
365 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
366 // If we have "0 || X", simplify the code. "1 || X" would have constant
367 // folded if the case was simple enough.
368 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
369 // br(0 || X) -> br(X).
370 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
371 }
Mike Stump11289f42009-09-09 15:08:12 +0000372
Chris Lattnercd439292008-11-12 08:04:58 +0000373 // If we have "X || 0", simplify the code to use an uncond branch.
374 // "X || 1" would have been constant folded to 1.
375 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
376 // br(X || 0) -> br(X).
377 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
378 }
Mike Stump11289f42009-09-09 15:08:12 +0000379
Chris Lattnercd439292008-11-12 08:04:58 +0000380 // Emit the LHS as a conditional. If the LHS conditional is true, we
381 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000382 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattnercd439292008-11-12 08:04:58 +0000383 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
384 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnercd439292008-11-12 08:04:58 +0000386 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
387 return;
388 }
Chris Lattnerd9537732008-11-12 08:13:36 +0000389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerd9537732008-11-12 08:13:36 +0000391 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
392 // br(!x, t, f) -> br(x, f, t)
393 if (CondUOp->getOpcode() == UnaryOperator::LNot)
394 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattnercd439292008-11-12 08:04:58 +0000395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +0000397 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
398 // Handle ?: operator.
399
400 // Just ignore GNU ?: extension.
401 if (CondOp->getLHS()) {
402 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
403 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
404 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
405 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
406 EmitBlock(LHSBlock);
407 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
408 EmitBlock(RHSBlock);
409 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
410 return;
411 }
412 }
413
Chris Lattnercd439292008-11-12 08:04:58 +0000414 // Emit the code with the fully general case.
415 llvm::Value *CondV = EvaluateExprAsBool(Cond);
416 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
417}
418
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000419/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +0000420/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000421void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
422 bool OmitOnError) {
423 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerfc944342007-12-02 01:43:38 +0000424}
425
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000426unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
427 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
428 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
429}
430
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000431void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Owen Anderson41a75022009-08-13 21:57:51 +0000432 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlsson2e744e82008-08-30 19:51:14 +0000433 if (DestPtr->getType() != BP)
434 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
435
436 // Get size and alignment info for this aggregate.
437 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
438
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000439 // Don't bother emitting a zero-byte memset.
440 if (TypeInfo.first == 0)
441 return;
Mike Stump11289f42009-09-09 15:08:12 +0000442
Anders Carlsson2e744e82008-08-30 19:51:14 +0000443 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +0000444 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000445 LLVMPointerWidth);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000446
447 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson41a75022009-08-13 21:57:51 +0000448 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000449 // TypeInfo.first describes size in bits.
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000450 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump11289f42009-09-09 15:08:12 +0000451 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000452 TypeInfo.second/8));
453}
454
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000455void CodeGenFunction::EmitIndirectSwitches() {
456 llvm::BasicBlock *Default;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Daniel Dunbard27262f2008-08-04 17:24:44 +0000458 if (IndirectSwitches.empty())
459 return;
Mike Stump11289f42009-09-09 15:08:12 +0000460
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000461 if (!LabelIDs.empty()) {
462 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
463 } else {
464 // No possible targets for indirect goto, just emit an infinite
465 // loop.
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000466 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000467 llvm::BranchInst::Create(Default, Default);
468 }
469
470 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
471 e = IndirectSwitches.end(); i != e; ++i) {
472 llvm::SwitchInst *I = *i;
Mike Stump11289f42009-09-09 15:08:12 +0000473
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000474 I->setSuccessor(0, Default);
Mike Stump11289f42009-09-09 15:08:12 +0000475 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000476 LE = LabelIDs.end(); LI != LE; ++LI) {
Owen Anderson41a75022009-08-13 21:57:51 +0000477 I->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Mike Stump11289f42009-09-09 15:08:12 +0000478 LI->second),
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000479 getBasicBlockForLabel(LI->first));
480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481 }
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000482}
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000483
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000484llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000485 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000486
Anders Carlssone388a5b2008-12-20 20:27:15 +0000487 assert(SizeEntry && "Did not emit size for type");
488 return SizeEntry;
489}
Anders Carlssonccbe9202008-12-12 07:19:02 +0000490
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000491llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson8a01b792008-12-20 20:46:34 +0000492 assert(Ty->isVariablyModifiedType() &&
493 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +0000494
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000495 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000496
Anders Carlsson8a01b792008-12-20 20:46:34 +0000497 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000498 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000499
Anders Carlsson5d985f52008-12-20 21:51:53 +0000500 if (!SizeEntry) {
Anders Carlsson31f86492009-02-05 19:43:10 +0000501 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chris Lattner8dc76262009-08-15 00:03:43 +0000503 // Get the element size;
504 QualType ElemTy = VAT->getElementType();
505 llvm::Value *ElemSize;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000506 if (ElemTy->isVariableArrayType())
507 ElemSize = EmitVLASize(ElemTy);
Chris Lattner8dc76262009-08-15 00:03:43 +0000508 else
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000509 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlsson5d985f52008-12-20 21:51:53 +0000510 getContext().getTypeSize(ElemTy) / 8);
Mike Stump11289f42009-09-09 15:08:12 +0000511
Anders Carlsson5d985f52008-12-20 21:51:53 +0000512 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson31f86492009-02-05 19:43:10 +0000513 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000514
Anders Carlsson5d985f52008-12-20 21:51:53 +0000515 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson8a01b792008-12-20 20:46:34 +0000516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Anders Carlsson8a01b792008-12-20 20:46:34 +0000518 return SizeEntry;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattner8dc76262009-08-15 00:03:43 +0000521 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
522 EmitVLASize(AT->getElementType());
523 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000524 }
525
Chris Lattner8dc76262009-08-15 00:03:43 +0000526 const PointerType *PT = Ty->getAs<PointerType>();
527 assert(PT && "unknown VM type!");
528 EmitVLASize(PT->getPointeeType());
Anders Carlsson8a01b792008-12-20 20:46:34 +0000529 return 0;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000530}
Eli Friedmanddea0ad2009-01-20 17:46:04 +0000531
532llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
533 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
534 return EmitScalarExpr(E);
535 }
536 return EmitLValue(E).getAddress();
537}
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000538
Mike Stump11289f42009-09-09 15:08:12 +0000539void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) {
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000540 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000541}
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000542
Mike Stump11289f42009-09-09 15:08:12 +0000543void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
544 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000545 "Cleanup stack mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000546
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000547 while (CleanupEntries.size() > OldCleanupStackSize)
548 EmitCleanupBlock();
549}
550
Mike Stump11289f42009-09-09 15:08:12 +0000551CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000552 CleanupEntry &CE = CleanupEntries.back();
Mike Stump11289f42009-09-09 15:08:12 +0000553
Anders Carlsson66c384a2009-02-08 07:46:24 +0000554 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000555
Anders Carlsson66c384a2009-02-08 07:46:24 +0000556 std::vector<llvm::BasicBlock *> Blocks;
557 std::swap(Blocks, CE.Blocks);
Mike Stump11289f42009-09-09 15:08:12 +0000558
Anders Carlsson66c384a2009-02-08 07:46:24 +0000559 std::vector<llvm::BranchInst *> BranchFixups;
560 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump11289f42009-09-09 15:08:12 +0000561
Anders Carlsson66c384a2009-02-08 07:46:24 +0000562 CleanupEntries.pop_back();
563
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000564 // Check if any branch fixups pointed to the scope we just popped. If so,
565 // we can remove them.
566 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
567 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
568 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000569
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000570 if (I == BlockScopes.end())
571 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000572
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000573 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump11289f42009-09-09 15:08:12 +0000574
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000575 if (I->second == CleanupEntries.size()) {
576 // We don't need to do this branch fixup.
577 BranchFixups[i] = BranchFixups.back();
578 BranchFixups.pop_back();
579 i--;
580 e--;
581 continue;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000582 }
583 }
Mike Stump11289f42009-09-09 15:08:12 +0000584
Anders Carlsson66c384a2009-02-08 07:46:24 +0000585 llvm::BasicBlock *SwitchBlock = 0;
586 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000587 if (!BranchFixups.empty()) {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000588 SwitchBlock = createBasicBlock("cleanup.switch");
589 EndBlock = createBasicBlock("cleanup.end");
Mike Stump11289f42009-09-09 15:08:12 +0000590
Anders Carlsson66c384a2009-02-08 07:46:24 +0000591 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000592
Anders Carlsson66c384a2009-02-08 07:46:24 +0000593 Builder.SetInsertPoint(SwitchBlock);
594
Mike Stump11289f42009-09-09 15:08:12 +0000595 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000596 "cleanup.dst");
597 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000598
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000599 // Create a switch instruction to determine where to jump next.
Mike Stump11289f42009-09-09 15:08:12 +0000600 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000601 BranchFixups.size());
Anders Carlsson66c384a2009-02-08 07:46:24 +0000602
Anders Carlsson76180ea2009-02-08 22:13:37 +0000603 // Restore the current basic block (if any)
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000604 if (CurBB) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000605 Builder.SetInsertPoint(CurBB);
Mike Stump11289f42009-09-09 15:08:12 +0000606
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000607 // If we had a current basic block, we also need to emit an instruction
608 // to initialize the cleanup destination.
Owen Anderson41a75022009-08-13 21:57:51 +0000609 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000610 DestCodePtr);
611 } else
Anders Carlsson76180ea2009-02-08 22:13:37 +0000612 Builder.ClearInsertionPoint();
Anders Carlsson66c384a2009-02-08 07:46:24 +0000613
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000614 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
615 llvm::BranchInst *BI = BranchFixups[i];
616 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump11289f42009-09-09 15:08:12 +0000617
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000618 // Fixup the branch instruction to point to the cleanup block.
619 BI->setSuccessor(0, CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000620
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000621 if (CleanupEntries.empty()) {
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000622 llvm::ConstantInt *ID;
Mike Stump11289f42009-09-09 15:08:12 +0000623
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000624 // Check if we already have a destination for this block.
625 if (Dest == SI->getDefaultDest())
Owen Anderson41a75022009-08-13 21:57:51 +0000626 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000627 else {
628 ID = SI->findCaseDest(Dest);
629 if (!ID) {
630 // No code found, get a new unique one by using the number of
631 // switch successors.
Mike Stump11289f42009-09-09 15:08:12 +0000632 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000633 SI->getNumSuccessors());
634 SI->addCase(ID, Dest);
635 }
636 }
Mike Stump11289f42009-09-09 15:08:12 +0000637
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000638 // Store the jump destination before the branch instruction.
639 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000640 } else {
641 // We need to jump through another cleanup block. Create a pad block
642 // with a branch instruction that jumps to the final destination and
643 // add it as a branch fixup to the current cleanup scope.
Mike Stump11289f42009-09-09 15:08:12 +0000644
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000645 // Create the pad block.
646 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000647
648 // Create a unique case ID.
Mike Stump11289f42009-09-09 15:08:12 +0000649 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000650 SI->getNumSuccessors());
651
652 // Store the jump destination before the branch instruction.
653 new llvm::StoreInst(ID, DestCodePtr, BI);
654
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000655 // Add it as the destination.
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000656 SI->addCase(ID, CleanupPad);
Mike Stump11289f42009-09-09 15:08:12 +0000657
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000658 // Create the branch to the final destination.
659 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
660 CleanupPad->getInstList().push_back(BI);
Mike Stump11289f42009-09-09 15:08:12 +0000661
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000662 // And add it as a branch fixup.
663 CleanupEntries.back().BranchFixups.push_back(BI);
664 }
665 }
666 }
Mike Stump11289f42009-09-09 15:08:12 +0000667
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000668 // Remove all blocks from the block scope map.
669 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
670 assert(BlockScopes.count(Blocks[i]) &&
671 "Did not find block in scope map!");
Mike Stump11289f42009-09-09 15:08:12 +0000672
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000673 BlockScopes.erase(Blocks[i]);
674 }
Mike Stump11289f42009-09-09 15:08:12 +0000675
Anders Carlsson66c384a2009-02-08 07:46:24 +0000676 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000677}
678
Mike Stump11289f42009-09-09 15:08:12 +0000679void CodeGenFunction::EmitCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000680 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000681
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000682 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000683 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000684 Info.CleanupBlock->getNumUses() == 0) {
685 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
686 delete Info.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000687 } else
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000688 EmitBlock(Info.CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000689
Anders Carlsson66c384a2009-02-08 07:46:24 +0000690 if (Info.SwitchBlock)
691 EmitBlock(Info.SwitchBlock);
692 if (Info.EndBlock)
693 EmitBlock(Info.EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000694}
695
Mike Stump11289f42009-09-09 15:08:12 +0000696void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
697 assert(!CleanupEntries.empty() &&
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000698 "Trying to add branch fixup without cleanup block!");
Mike Stump11289f42009-09-09 15:08:12 +0000699
Mike Stump18bb9282009-05-16 07:57:57 +0000700 // FIXME: We could be more clever here and check if there's already a branch
701 // fixup for this destination and recycle it.
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000702 CleanupEntries.back().BranchFixups.push_back(BI);
703}
704
Mike Stump11289f42009-09-09 15:08:12 +0000705void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000706 if (!HaveInsertPoint())
707 return;
Mike Stump11289f42009-09-09 15:08:12 +0000708
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000709 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000710
Anders Carlsson76180ea2009-02-08 22:13:37 +0000711 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000712
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000713 // The stack is empty, no need to do any cleanup.
714 if (CleanupEntries.empty())
715 return;
Mike Stump11289f42009-09-09 15:08:12 +0000716
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000717 if (!Dest->getParent()) {
718 // We are trying to branch to a block that hasn't been inserted yet.
719 AddBranchFixup(BI);
720 return;
721 }
Mike Stump11289f42009-09-09 15:08:12 +0000722
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000723 BlockScopeMap::iterator I = BlockScopes.find(Dest);
724 if (I == BlockScopes.end()) {
725 // We are trying to jump to a block that is outside of any cleanup scope.
726 AddBranchFixup(BI);
727 return;
728 }
Mike Stump11289f42009-09-09 15:08:12 +0000729
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000730 assert(I->second < CleanupEntries.size() &&
731 "Trying to branch into cleanup region");
Mike Stump11289f42009-09-09 15:08:12 +0000732
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000733 if (I->second == CleanupEntries.size() - 1) {
734 // We have a branch to a block in the same scope.
735 return;
736 }
Mike Stump11289f42009-09-09 15:08:12 +0000737
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000738 AddBranchFixup(BI);
739}