blob: 281aa604fe3a7222f41cff4ff1ece81c8719aca5 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman17630752008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattnerd1af2d22007-05-29 23:17:50 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattnercd439292008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson468fa632009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000023using namespace clang;
24using namespace CodeGen;
25
Mike Stump11289f42009-09-09 15:08:12 +000026CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stump0c743272009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Owen Andersonc9673d52009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
Chris Lattner6c4d2552009-10-28 23:59:40 +000030#ifndef USEINDIRECTBRANCH
Chris Lattner2bb5cb42009-10-13 06:55:33 +000031 DebugInfo(0), IndirectGotoSwitch(0),
Chris Lattner6c4d2552009-10-28 23:59:40 +000032#else
33 DebugInfo(0), IndirectBranch(0),
34#endif
Chris Lattner2bb5cb42009-10-13 06:55:33 +000035 SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
Anders Carlsson468fa632009-04-04 20:47:02 +000036 CXXThisDecl(0) {
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000037 LLVMIntTy = ConvertType(getContext().IntTy);
38 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner5696e7b2008-06-17 18:05:57 +000039}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000040
Chris Lattner6db1fb82007-06-02 22:49:07 +000041ASTContext &CodeGenFunction::getContext() const {
42 return CGM.getContext();
43}
44
Chris Lattnerd1af2d22007-05-29 23:17:50 +000045
Chris Lattnerac248202007-05-30 00:13:02 +000046llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
Chris Lattner23b7eb62007-06-15 23:05:46 +000047 llvm::BasicBlock *&BB = LabelMap[S];
Chris Lattnerac248202007-05-30 00:13:02 +000048 if (BB) return BB;
Mike Stump11289f42009-09-09 15:08:12 +000049
Chris Lattnerac248202007-05-30 00:13:02 +000050 // Create, but don't insert, the new block.
Daniel Dunbar75283ff2008-11-11 02:29:29 +000051 return BB = createBasicBlock(S->getName());
Chris Lattnerac248202007-05-30 00:13:02 +000052}
53
Daniel Dunbar22a87f92009-02-25 19:24:29 +000054llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
55 llvm::Value *Res = LocalDeclMap[VD];
56 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
57 return Res;
Lauro Ramos Venancio01a72ff2008-02-26 21:41:45 +000058}
Chris Lattnerac248202007-05-30 00:13:02 +000059
Daniel Dunbar22a87f92009-02-25 19:24:29 +000060llvm::Constant *
61CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
62 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson9396a892008-09-11 09:15:33 +000063}
64
Daniel Dunbaree3da872009-02-03 23:03:55 +000065const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
66 return CGM.getTypes().ConvertTypeForMem(T);
67}
68
Chris Lattnerf033c142007-06-22 19:05:19 +000069const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
70 return CGM.getTypes().ConvertType(T);
Chris Lattner45bb9142007-06-09 02:28:57 +000071}
Chris Lattnerd1af2d22007-05-29 23:17:50 +000072
Chris Lattner54fb19e2007-06-22 22:02:34 +000073bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssonb05a3e52009-09-29 02:09:01 +000074 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
75 T->isMemberFunctionPointerType();
Chris Lattner54fb19e2007-06-22 22:02:34 +000076}
77
Daniel Dunbarfd346a32009-01-26 23:27:52 +000078void CodeGenFunction::EmitReturnBlock() {
79 // For cleanliness, we try to avoid emitting the return block for
80 // simple cases.
81 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
82
83 if (CurBB) {
84 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
85
Daniel Dunbarea3060a2009-07-19 08:24:34 +000086 // We have a valid insert point, reuse it if it is empty or there are no
87 // explicit jumps to the return block.
88 if (CurBB->empty() || ReturnBlock->use_empty()) {
89 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbarfd346a32009-01-26 23:27:52 +000090 delete ReturnBlock;
Daniel Dunbarea3060a2009-07-19 08:24:34 +000091 } else
Daniel Dunbarfd346a32009-01-26 23:27:52 +000092 EmitBlock(ReturnBlock);
93 return;
94 }
95
96 // Otherwise, if the return block is the target of a single direct
97 // branch then we can just put the code in that block instead. This
98 // cleans up functions which started with a unified return block.
99 if (ReturnBlock->hasOneUse()) {
Mike Stump11289f42009-09-09 15:08:12 +0000100 llvm::BranchInst *BI =
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000101 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
102 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
103 // Reset insertion point and delete the branch.
104 Builder.SetInsertPoint(BI->getParent());
105 BI->eraseFromParent();
106 delete ReturnBlock;
107 return;
108 }
109 }
110
Mike Stump18bb9282009-05-16 07:57:57 +0000111 // FIXME: We are at an unreachable point, there is no reason to emit the block
112 // unless it has uses. However, we still need a place to put the debug
113 // region.end for now.
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000114
115 EmitBlock(ReturnBlock);
116}
117
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000118void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnere73e4322007-07-16 21:28:45 +0000119 assert(BreakContinueStack.empty() &&
120 "mismatched push/pop in break/continue stack!");
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000121 assert(BlockScopes.empty() &&
122 "did not remove all blocks from block scope map!");
123 assert(CleanupEntries.empty() &&
124 "mismatched push/pop in cleanup stack!");
Mike Stump11289f42009-09-09 15:08:12 +0000125
126 // Emit function epilog (to return).
Daniel Dunbarfd346a32009-01-26 23:27:52 +0000127 EmitReturnBlock();
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000128
129 // Emit debug descriptor for function end.
Anders Carlsson63784f42009-02-13 08:11:52 +0000130 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarfab3f932008-11-11 20:59:54 +0000131 DI->setLocation(EndLoc);
132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Daniel Dunbard931a872009-02-02 22:03:45 +0000135 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000136
Chris Lattner6c4d2552009-10-28 23:59:40 +0000137#ifdef USEINDIRECTBRANCH
138 // If someone did an indirect goto, emit the indirect goto block at the end of
139 // the function.
140 if (IndirectBranch) {
141 EmitBlock(IndirectBranch->getParent());
142 Builder.ClearInsertionPoint();
143 }
144
145
146#endif
Chris Lattnerc48023b2007-12-02 06:32:24 +0000147 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner2739d2b2009-03-31 22:17:44 +0000148 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerc48023b2007-12-02 06:32:24 +0000149 AllocaInsertPt = 0;
Chris Lattner2739d2b2009-03-31 22:17:44 +0000150 Ptr->eraseFromParent();
Chris Lattner6c4d2552009-10-28 23:59:40 +0000151#ifdef USEINDIRECTBRANCH
152
153 // If someone took the address of a label but never did an indirect goto, we
154 // made a zero entry PHI node, which is illegal, zap it now.
155 if (IndirectBranch) {
156 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
157 if (PN->getNumIncomingValues() == 0) {
158 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
159 PN->eraseFromParent();
160 }
161 }
162
163#endif
Chris Lattnerd1af2d22007-05-29 23:17:50 +0000164}
Chris Lattner308f4312007-05-29 23:50:05 +0000165
Anders Carlsson73fcc952009-09-11 00:07:24 +0000166void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000167 llvm::Function *Fn,
Daniel Dunbar354d2782008-10-18 18:22:23 +0000168 const FunctionArgList &Args,
169 SourceLocation StartLoc) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000170 const Decl *D = GD.getDecl();
171
Anders Carlssonf4478e92009-02-09 20:20:56 +0000172 DidCallStackSave = false;
Chris Lattner28ec0cf2009-04-23 05:30:27 +0000173 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000174 FnRetTy = RetTy;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000175 CurFn = Fn;
Chris Lattner5696e7b2008-06-17 18:05:57 +0000176 assert(CurFn->isDeclaration() && "Function already has body?");
177
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000178 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000179
Chris Lattner5696e7b2008-06-17 18:05:57 +0000180 // Create a marker to make it easy to insert allocas into the entryblock
181 // later. Don't create this with the builder, because we don't want it
182 // folded.
Owen Anderson41a75022009-08-13 21:57:51 +0000183 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
Mike Stump1dbb8f72009-09-25 18:11:00 +0000184 AllocaInsertPt = new llvm::BitCastInst(Undef,
185 llvm::Type::getInt32Ty(VMContext), "",
Chris Lattner5696e7b2008-06-17 18:05:57 +0000186 EntryBB);
Chris Lattner47640222009-03-22 00:24:14 +0000187 if (Builder.isNamePreserving())
188 AllocaInsertPt->setName("allocapt");
Mike Stump11289f42009-09-09 15:08:12 +0000189
Daniel Dunbar75283ff2008-11-11 02:29:29 +0000190 ReturnBlock = createBasicBlock("return");
Daniel Dunbar54bb1932008-09-09 21:00:17 +0000191 ReturnValue = 0;
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000192 if (!RetTy->isVoidType())
193 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner5696e7b2008-06-17 18:05:57 +0000195 Builder.SetInsertPoint(EntryBB);
Mike Stump11289f42009-09-09 15:08:12 +0000196
Mike Stumpae2559a2009-10-23 01:52:13 +0000197 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
198
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000199 // Emit subprogram debug descriptor.
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000200 // FIXME: The cast here is a huge hack.
Anders Carlsson63784f42009-02-13 08:11:52 +0000201 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar354d2782008-10-18 18:22:23 +0000202 DI->setLocation(StartLoc);
Anders Carlssonfd384d82009-09-11 00:11:35 +0000203 if (isa<FunctionDecl>(D)) {
Mike Stumpae2559a2009-10-23 01:52:13 +0000204 DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder);
Daniel Dunbar354d2782008-10-18 18:22:23 +0000205 } else {
206 // Just use LLVM function name.
Mike Stump11289f42009-09-09 15:08:12 +0000207
Daniel Dunbar7c02cf62009-07-23 05:30:36 +0000208 // FIXME: Remove unnecessary conversion to std::string when API settles.
Mike Stump11289f42009-09-09 15:08:12 +0000209 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Mike Stumpae2559a2009-10-23 01:52:13 +0000210 FnType, CurFn, Builder);
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000211 }
Sanjiv Gupta1e8b6082008-07-04 11:04:26 +0000212 }
213
Daniel Dunbard931a872009-02-02 22:03:45 +0000214 // FIXME: Leaked.
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000215 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbard931a872009-02-02 22:03:45 +0000216 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000217
Anders Carlssonc20879a2008-12-20 21:28:43 +0000218 // If any of the arguments have a variably modified type, make sure to
219 // emit the type size.
220 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
221 i != e; ++i) {
222 QualType Ty = i->second;
223
224 if (Ty->isVariablyModifiedType())
225 EmitVLASize(Ty);
226 }
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000227}
Eli Friedman3d421e12008-08-25 21:31:01 +0000228
Anders Carlsson73fcc952009-09-11 00:07:24 +0000229void CodeGenFunction::GenerateCode(GlobalDecl GD,
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000230 llvm::Function *Fn) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000231 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
232
Anders Carlsson63784f42009-02-13 08:11:52 +0000233 // Check if we should generate debug info for this function.
Mike Stump3722f582009-08-26 22:31:08 +0000234 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlsson63784f42009-02-13 08:11:52 +0000235 DebugInfo = CGM.getDebugInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000236
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000237 FunctionArgList Args;
Mike Stump11289f42009-09-09 15:08:12 +0000238
Anders Carlsson468fa632009-04-04 20:47:02 +0000239 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
240 if (MD->isInstance()) {
241 // Create the implicit 'this' decl.
242 // FIXME: I'm not entirely sure I like using a fake decl just for code
243 // generation. Maybe we can come up with a better way?
244 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +0000245 &getContext().Idents.get("this"),
Anders Carlsson468fa632009-04-04 20:47:02 +0000246 MD->getThisType(getContext()));
247 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
248 }
249 }
Mike Stump11289f42009-09-09 15:08:12 +0000250
Eli Friedman3d421e12008-08-25 21:31:01 +0000251 if (FD->getNumParams()) {
John McCall9dd450b2009-09-21 23:43:11 +0000252 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedman3d421e12008-08-25 21:31:01 +0000253 assert(FProto && "Function def must have prototype!");
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000254
255 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump11289f42009-09-09 15:08:12 +0000256 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000257 FProto->getArgType(i)));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000258 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000259
Sebastian Redla7b98a72009-04-26 20:35:05 +0000260 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000261 if (const CompoundStmt *S = FD->getCompoundBody()) {
Anders Carlsson73fcc952009-09-11 00:07:24 +0000262 StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Anders Carlsson438cf922009-11-06 02:55:43 +0000263
264 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssonddf57d32009-09-14 05:32:02 +0000265 EmitCtorPrologue(CD, GD.getCtorType());
Anders Carlsson438cf922009-11-06 02:55:43 +0000266 EmitStmt(S);
267 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
268 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
269 PushCleanupBlock(DtorEpilogue);
270
271 EmitStmt(S);
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000272
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000273 CleanupBlockInfo Info = PopCleanupBlock();
274
275 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
276 EmitBlock(DtorEpilogue);
Anders Carlssonddf57d32009-09-14 05:32:02 +0000277 EmitDtorEpilogue(DD, GD.getDtorType());
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000278
279 if (Info.SwitchBlock)
280 EmitBlock(Info.SwitchBlock);
281 if (Info.EndBlock)
282 EmitBlock(Info.EndBlock);
Anders Carlsson438cf922009-11-06 02:55:43 +0000283 } else {
284 // Just a regular function, emit its body.
285 EmitStmt(S);
Anders Carlsson6b7378b2009-10-06 18:09:57 +0000286 }
Anders Carlsson438cf922009-11-06 02:55:43 +0000287
Sebastian Redla7b98a72009-04-26 20:35:05 +0000288 FinishFunction(S->getRBracLoc());
Douglas Gregor369acf92009-10-01 20:44:19 +0000289 } else if (FD->isImplicit()) {
290 const CXXRecordDecl *ClassDecl =
291 cast<CXXRecordDecl>(FD->getDeclContext());
292 (void) ClassDecl;
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000293 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Douglas Gregor369acf92009-10-01 20:44:19 +0000294 // FIXME: For C++0x, we want to look for implicit *definitions* of
295 // these special member functions, rather than implicit *declarations*.
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000296 if (CD->isCopyConstructor(getContext())) {
297 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000298 "Cannot synthesize a non-implicit copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000299 SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000300 } else if (CD->isDefaultConstructor()) {
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000301 assert(!ClassDecl->hasUserDeclaredConstructor() &&
Douglas Gregor369acf92009-10-01 20:44:19 +0000302 "Cannot synthesize a non-implicit default constructor.");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000303 SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000304 } else {
305 assert(false && "Implicit constructor cannot be synthesized");
Fariborz Jahanian9301b242009-08-06 23:38:16 +0000306 }
Douglas Gregor369acf92009-10-01 20:44:19 +0000307 } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) {
308 assert(!ClassDecl->hasUserDeclaredDestructor() &&
309 "Cannot synthesize a non-implicit destructor");
310 SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args);
311 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
312 assert(MD->isCopyAssignment() &&
313 !ClassDecl->hasUserDeclaredCopyAssignment() &&
314 "Cannot synthesize a method that is not an implicit-defined "
315 "copy constructor");
Anders Carlssonddf57d32009-09-14 05:32:02 +0000316 SynthesizeCXXCopyAssignment(MD, Fn, Args);
Douglas Gregor369acf92009-10-01 20:44:19 +0000317 } else {
318 assert(false && "Cannot synthesize unknown implicit function");
319 }
Anders Carlsson73fcc952009-09-11 00:07:24 +0000320 }
Mike Stump11289f42009-09-09 15:08:12 +0000321
Anders Carlsson468fa632009-04-04 20:47:02 +0000322 // Destroy the 'this' declaration.
323 if (CXXThisDecl)
324 CXXThisDecl->Destroy(getContext());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000325}
326
Chris Lattner5b1964b2008-11-11 07:41:27 +0000327/// ContainsLabel - Return true if the statement contains a label in it. If
328/// this statement is not executed normally, it not containing a label means
329/// that we can just remove the code.
330bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
331 // Null statement, not a label!
332 if (S == 0) return false;
Mike Stump11289f42009-09-09 15:08:12 +0000333
Chris Lattner5b1964b2008-11-11 07:41:27 +0000334 // If this is a label, we have to emit the code, consider something like:
335 // if (0) { ... foo: bar(); } goto foo;
336 if (isa<LabelStmt>(S))
337 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattner5b1964b2008-11-11 07:41:27 +0000339 // If this is a case/default statement, and we haven't seen a switch, we have
340 // to emit the code.
341 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
342 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner5b1964b2008-11-11 07:41:27 +0000344 // If this is a switch statement, we want to ignore cases below it.
345 if (isa<SwitchStmt>(S))
346 IgnoreCaseStmts = true;
Mike Stump11289f42009-09-09 15:08:12 +0000347
Chris Lattner5b1964b2008-11-11 07:41:27 +0000348 // Scan subexpressions for verboten labels.
349 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
350 I != E; ++I)
351 if (ContainsLabel(*I, IgnoreCaseStmts))
352 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000353
Chris Lattner5b1964b2008-11-11 07:41:27 +0000354 return false;
355}
356
Chris Lattnercd439292008-11-12 08:04:58 +0000357
358/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
359/// a constant, or if it does but contains a label, return 0. If it constant
360/// folds to 'true' and does not contain a label, return 1, if it constant folds
361/// to 'false' and does not contain a label, return -1.
362int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbarf32443c2008-11-12 22:37:10 +0000363 // FIXME: Rename and handle conversion of other evaluatable things
364 // to bool.
Anders Carlsson86286452008-12-01 02:46:24 +0000365 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +0000366 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson86286452008-12-01 02:46:24 +0000367 Result.HasSideEffects)
Anders Carlsson4046e652008-11-22 22:32:07 +0000368 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump11289f42009-09-09 15:08:12 +0000369
Chris Lattnercd439292008-11-12 08:04:58 +0000370 if (CodeGenFunction::ContainsLabel(Cond))
371 return 0; // Contains a label.
Mike Stump11289f42009-09-09 15:08:12 +0000372
Anders Carlsson86286452008-12-01 02:46:24 +0000373 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattnercd439292008-11-12 08:04:58 +0000374}
375
376
377/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
378/// statement) to the specified blocks. Based on the condition, this might try
379/// to simplify the codegen of the conditional based on the branch.
380///
381void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
382 llvm::BasicBlock *TrueBlock,
383 llvm::BasicBlock *FalseBlock) {
384 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
385 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Chris Lattnercd439292008-11-12 08:04:58 +0000387 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
388 // Handle X && Y in a condition.
389 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
390 // If we have "1 && X", simplify the code. "0 && X" would have constant
391 // folded if the case was simple enough.
392 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
393 // br(1 && X) -> br(X).
394 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattnercd439292008-11-12 08:04:58 +0000397 // If we have "X && 1", simplify the code to use an uncond branch.
398 // "X && 0" would have been constant folded to 0.
399 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
400 // br(X && 1) -> br(X).
401 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
402 }
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattnercd439292008-11-12 08:04:58 +0000404 // Emit the LHS as a conditional. If the LHS conditional is false, we
405 // want to jump to the FalseBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000406 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattnercd439292008-11-12 08:04:58 +0000407 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
408 EmitBlock(LHSTrue);
Mike Stump11289f42009-09-09 15:08:12 +0000409
Chris Lattnercd439292008-11-12 08:04:58 +0000410 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
411 return;
412 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
413 // If we have "0 || X", simplify the code. "1 || X" would have constant
414 // folded if the case was simple enough.
415 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
416 // br(0 || X) -> br(X).
417 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
418 }
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattnercd439292008-11-12 08:04:58 +0000420 // If we have "X || 0", simplify the code to use an uncond branch.
421 // "X || 1" would have been constant folded to 1.
422 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
423 // br(X || 0) -> br(X).
424 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
425 }
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattnercd439292008-11-12 08:04:58 +0000427 // Emit the LHS as a conditional. If the LHS conditional is true, we
428 // want to jump to the TrueBlock.
Daniel Dunbara612e792008-11-13 01:38:36 +0000429 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattnercd439292008-11-12 08:04:58 +0000430 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
431 EmitBlock(LHSFalse);
Mike Stump11289f42009-09-09 15:08:12 +0000432
Chris Lattnercd439292008-11-12 08:04:58 +0000433 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
434 return;
435 }
Chris Lattnerd9537732008-11-12 08:13:36 +0000436 }
Mike Stump11289f42009-09-09 15:08:12 +0000437
Chris Lattnerd9537732008-11-12 08:13:36 +0000438 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
439 // br(!x, t, f) -> br(x, f, t)
440 if (CondUOp->getOpcode() == UnaryOperator::LNot)
441 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattnercd439292008-11-12 08:04:58 +0000442 }
Mike Stump11289f42009-09-09 15:08:12 +0000443
Daniel Dunbarbf3c22e2008-11-12 10:30:32 +0000444 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
445 // Handle ?: operator.
446
447 // Just ignore GNU ?: extension.
448 if (CondOp->getLHS()) {
449 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
450 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
451 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
452 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
453 EmitBlock(LHSBlock);
454 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
455 EmitBlock(RHSBlock);
456 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
457 return;
458 }
459 }
460
Chris Lattnercd439292008-11-12 08:04:58 +0000461 // Emit the code with the fully general case.
462 llvm::Value *CondV = EvaluateExprAsBool(Cond);
463 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
464}
465
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000466/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerfc944342007-12-02 01:43:38 +0000467/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000468void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
469 bool OmitOnError) {
470 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerfc944342007-12-02 01:43:38 +0000471}
472
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000473void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Chris Lattnerdd7eaad2009-10-13 06:02:42 +0000474 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000475 if (DestPtr->getType() != BP)
476 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
477
478 // Get size and alignment info for this aggregate.
479 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
480
Chris Lattnerb534f6a2009-04-21 17:59:23 +0000481 // Don't bother emitting a zero-byte memset.
482 if (TypeInfo.first == 0)
483 return;
Mike Stump11289f42009-09-09 15:08:12 +0000484
Anders Carlsson2e744e82008-08-30 19:51:14 +0000485 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +0000486 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000487 LLVMPointerWidth);
Anders Carlsson2e744e82008-08-30 19:51:14 +0000488
489 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson41a75022009-08-13 21:57:51 +0000490 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000491 // TypeInfo.first describes size in bits.
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000492 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
Mike Stump11289f42009-09-09 15:08:12 +0000493 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson2e744e82008-08-30 19:51:14 +0000494 TypeInfo.second/8));
495}
496
Chris Lattner6c4d2552009-10-28 23:59:40 +0000497#ifndef USEINDIRECTBRANCH
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000498unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
499 // Use LabelIDs.size()+1 as the new ID if one hasn't been assigned.
500 unsigned &Entry = LabelIDs[L];
501 if (Entry) return Entry;
Chris Lattner6c4d2552009-10-28 23:59:40 +0000502#else
503
504llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
505 // Make sure that there is a block for the indirect goto.
506 if (IndirectBranch == 0)
507 GetIndirectGotoBlock();
508#endif
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000509
Chris Lattner6c4d2552009-10-28 23:59:40 +0000510#ifndef USEINDIRECTBRANCH
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000511 Entry = LabelIDs.size();
Chris Lattner6c4d2552009-10-28 23:59:40 +0000512#else
513 llvm::BasicBlock *BB = getBasicBlockForLabel(L);
514#endif
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000515
Chris Lattner6c4d2552009-10-28 23:59:40 +0000516#ifndef USEINDIRECTBRANCH
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000517 // If this is the first "address taken" of a label and the indirect goto has
518 // already been seen, add this to it.
519 if (IndirectGotoSwitch) {
520 // If this is the first address-taken label, set it as the default dest.
521 if (Entry == 1)
522 IndirectGotoSwitch->setSuccessor(0, getBasicBlockForLabel(L));
523 else {
524 // Otherwise add it to the switch as a new dest.
525 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
526 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, Entry),
527 getBasicBlockForLabel(L));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000528 }
Mike Stump11289f42009-09-09 15:08:12 +0000529 }
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000530
531 return Entry;
Chris Lattner6c4d2552009-10-28 23:59:40 +0000532#else
533 // Make sure the indirect branch includes all of the address-taken blocks.
534 IndirectBranch->addDestination(BB);
535 return llvm::BlockAddress::get(CurFn, BB);
536#endif
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000537}
538
539llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000540#ifndef USEINDIRECTBRANCH
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000541 // If we already made the switch stmt for indirect goto, return its block.
542 if (IndirectGotoSwitch) return IndirectGotoSwitch->getParent();
Chris Lattner6c4d2552009-10-28 23:59:40 +0000543#else
544 // If we already made the indirect branch for indirect goto, return its block.
545 if (IndirectBranch) return IndirectBranch->getParent();
546#endif
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000547
Chris Lattner6c4d2552009-10-28 23:59:40 +0000548#ifndef USEINDIRECTBRANCH
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000549 EmitBlock(createBasicBlock("indirectgoto"));
Chris Lattner6c4d2552009-10-28 23:59:40 +0000550#else
551 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
552#endif
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000553
Chris Lattner6c4d2552009-10-28 23:59:40 +0000554#ifndef USEINDIRECTBRANCH
Chris Lattnera0c0d882009-10-28 20:36:47 +0000555 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000556#else
557 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
558#endif
Chris Lattnera0c0d882009-10-28 20:36:47 +0000559
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000560 // Create the PHI node that indirect gotos will add entries to.
Chris Lattner6c4d2552009-10-28 23:59:40 +0000561#ifndef USEINDIRECTBRANCH
Chris Lattnera0c0d882009-10-28 20:36:47 +0000562 llvm::Value *DestVal = Builder.CreatePHI(Int32Ty, "indirect.goto.dest");
Chris Lattner6c4d2552009-10-28 23:59:40 +0000563#else
564 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
565#endif
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000566
Chris Lattner6c4d2552009-10-28 23:59:40 +0000567#ifndef USEINDIRECTBRANCH
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000568 // Create the switch instruction. For now, set the insert block to this block
569 // which will be fixed as labels are added.
570 IndirectGotoSwitch = Builder.CreateSwitch(DestVal, Builder.GetInsertBlock());
571
572 // Clear the insertion point to indicate we are in unreachable code.
573 Builder.ClearInsertionPoint();
574
575 // If we already have labels created, add them.
576 if (!LabelIDs.empty()) {
577 // Invert LabelID's so that the order is determinstic.
578 std::vector<const LabelStmt*> AddrTakenLabelsByID;
579 AddrTakenLabelsByID.resize(LabelIDs.size());
580
581 for (std::map<const LabelStmt*,unsigned>::iterator
582 LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) {
583 assert(LI->second-1 < AddrTakenLabelsByID.size() &&
584 "Numbering inconsistent");
585 AddrTakenLabelsByID[LI->second-1] = LI->first;
586 }
587
588 // Set the default entry as the first block.
589 IndirectGotoSwitch->setSuccessor(0,
590 getBasicBlockForLabel(AddrTakenLabelsByID[0]));
591
Chris Lattner2bb5cb42009-10-13 06:55:33 +0000592 // FIXME: The iteration order of this is nondeterminstic!
593 for (unsigned i = 1, e = AddrTakenLabelsByID.size(); i != e; ++i)
594 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, i+1),
595 getBasicBlockForLabel(AddrTakenLabelsByID[i]));
596 } else {
597 // Otherwise, create a dead block and set it as the default dest. This will
598 // be removed by the optimizers after the indirect goto is set up.
599 llvm::BasicBlock *Dummy = createBasicBlock("indgoto.dummy");
600 EmitBlock(Dummy);
601 IndirectGotoSwitch->setSuccessor(0, Dummy);
602 Builder.CreateUnreachable();
603 Builder.ClearInsertionPoint();
604 }
605
606 return IndirectGotoSwitch->getParent();
Chris Lattner6c4d2552009-10-28 23:59:40 +0000607#else
608 // Create the indirect branch instruction.
609 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
610 return IndirectBranch->getParent();
611#endif
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000612}
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000613
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000614llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000615 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000616
Anders Carlssone388a5b2008-12-20 20:27:15 +0000617 assert(SizeEntry && "Did not emit size for type");
618 return SizeEntry;
619}
Anders Carlssonccbe9202008-12-12 07:19:02 +0000620
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000621llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson8a01b792008-12-20 20:46:34 +0000622 assert(Ty->isVariablyModifiedType() &&
623 "Must pass variably modified type to EmitVLASizes!");
Mike Stump11289f42009-09-09 15:08:12 +0000624
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000625 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000626
Anders Carlsson8a01b792008-12-20 20:46:34 +0000627 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedman04fddf02009-08-15 02:50:32 +0000628 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump11289f42009-09-09 15:08:12 +0000629
Anders Carlsson5d985f52008-12-20 21:51:53 +0000630 if (!SizeEntry) {
Anders Carlsson31f86492009-02-05 19:43:10 +0000631 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattner8dc76262009-08-15 00:03:43 +0000633 // Get the element size;
634 QualType ElemTy = VAT->getElementType();
635 llvm::Value *ElemSize;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000636 if (ElemTy->isVariableArrayType())
637 ElemSize = EmitVLASize(ElemTy);
Chris Lattner8dc76262009-08-15 00:03:43 +0000638 else
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000639 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlsson5d985f52008-12-20 21:51:53 +0000640 getContext().getTypeSize(ElemTy) / 8);
Mike Stump11289f42009-09-09 15:08:12 +0000641
Anders Carlsson5d985f52008-12-20 21:51:53 +0000642 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson31f86492009-02-05 19:43:10 +0000643 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000644
Anders Carlsson5d985f52008-12-20 21:51:53 +0000645 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson8a01b792008-12-20 20:46:34 +0000646 }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Anders Carlsson8a01b792008-12-20 20:46:34 +0000648 return SizeEntry;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000649 }
Mike Stump11289f42009-09-09 15:08:12 +0000650
Chris Lattner8dc76262009-08-15 00:03:43 +0000651 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
652 EmitVLASize(AT->getElementType());
653 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000654 }
655
Chris Lattner8dc76262009-08-15 00:03:43 +0000656 const PointerType *PT = Ty->getAs<PointerType>();
657 assert(PT && "unknown VM type!");
658 EmitVLASize(PT->getPointeeType());
Anders Carlsson8a01b792008-12-20 20:46:34 +0000659 return 0;
Anders Carlssonccbe9202008-12-12 07:19:02 +0000660}
Eli Friedmanddea0ad2009-01-20 17:46:04 +0000661
662llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
663 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
664 return EmitScalarExpr(E);
665 }
666 return EmitLValue(E).getAddress();
667}
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000668
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000669void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
670 llvm::BasicBlock *CleanupExitBlock) {
671 CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock));
Anders Carlsson15cb75a2009-02-07 22:53:43 +0000672}
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000673
Mike Stump11289f42009-09-09 15:08:12 +0000674void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
675 assert(CleanupEntries.size() >= OldCleanupStackSize &&
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000676 "Cleanup stack mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000677
Anders Carlssonbe0f76a2009-02-07 23:50:39 +0000678 while (CleanupEntries.size() > OldCleanupStackSize)
679 EmitCleanupBlock();
680}
681
Mike Stump11289f42009-09-09 15:08:12 +0000682CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000683 CleanupEntry &CE = CleanupEntries.back();
Mike Stump11289f42009-09-09 15:08:12 +0000684
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000685 llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000686
Anders Carlsson66c384a2009-02-08 07:46:24 +0000687 std::vector<llvm::BasicBlock *> Blocks;
688 std::swap(Blocks, CE.Blocks);
Mike Stump11289f42009-09-09 15:08:12 +0000689
Anders Carlsson66c384a2009-02-08 07:46:24 +0000690 std::vector<llvm::BranchInst *> BranchFixups;
691 std::swap(BranchFixups, CE.BranchFixups);
Mike Stump11289f42009-09-09 15:08:12 +0000692
Anders Carlsson66c384a2009-02-08 07:46:24 +0000693 CleanupEntries.pop_back();
694
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000695 // Check if any branch fixups pointed to the scope we just popped. If so,
696 // we can remove them.
697 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
698 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
699 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000701 if (I == BlockScopes.end())
702 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000703
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000704 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Mike Stump11289f42009-09-09 15:08:12 +0000705
Anders Carlssonf57b9ee2009-02-08 22:45:15 +0000706 if (I->second == CleanupEntries.size()) {
707 // We don't need to do this branch fixup.
708 BranchFixups[i] = BranchFixups.back();
709 BranchFixups.pop_back();
710 i--;
711 e--;
712 continue;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000713 }
714 }
Mike Stump11289f42009-09-09 15:08:12 +0000715
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000716 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
Anders Carlsson66c384a2009-02-08 07:46:24 +0000717 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000718 if (!BranchFixups.empty()) {
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000719 if (!SwitchBlock)
720 SwitchBlock = createBasicBlock("cleanup.switch");
Anders Carlsson66c384a2009-02-08 07:46:24 +0000721 EndBlock = createBasicBlock("cleanup.end");
Mike Stump11289f42009-09-09 15:08:12 +0000722
Anders Carlsson66c384a2009-02-08 07:46:24 +0000723 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000724
Anders Carlsson66c384a2009-02-08 07:46:24 +0000725 Builder.SetInsertPoint(SwitchBlock);
726
Mike Stump11289f42009-09-09 15:08:12 +0000727 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000728 "cleanup.dst");
729 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +0000730
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000731 // Create a switch instruction to determine where to jump next.
Mike Stump11289f42009-09-09 15:08:12 +0000732 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000733 BranchFixups.size());
Anders Carlsson66c384a2009-02-08 07:46:24 +0000734
Anders Carlsson76180ea2009-02-08 22:13:37 +0000735 // Restore the current basic block (if any)
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000736 if (CurBB) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000737 Builder.SetInsertPoint(CurBB);
Mike Stump11289f42009-09-09 15:08:12 +0000738
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000739 // If we had a current basic block, we also need to emit an instruction
740 // to initialize the cleanup destination.
Owen Anderson41a75022009-08-13 21:57:51 +0000741 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
Anders Carlssone73e3ec2009-03-17 05:53:35 +0000742 DestCodePtr);
743 } else
Anders Carlsson76180ea2009-02-08 22:13:37 +0000744 Builder.ClearInsertionPoint();
Anders Carlsson66c384a2009-02-08 07:46:24 +0000745
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000746 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
747 llvm::BranchInst *BI = BranchFixups[i];
748 llvm::BasicBlock *Dest = BI->getSuccessor(0);
Mike Stump11289f42009-09-09 15:08:12 +0000749
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000750 // Fixup the branch instruction to point to the cleanup block.
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000751 BI->setSuccessor(0, CleanupEntryBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000752
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000753 if (CleanupEntries.empty()) {
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000754 llvm::ConstantInt *ID;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000756 // Check if we already have a destination for this block.
757 if (Dest == SI->getDefaultDest())
Owen Anderson41a75022009-08-13 21:57:51 +0000758 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000759 else {
760 ID = SI->findCaseDest(Dest);
761 if (!ID) {
762 // No code found, get a new unique one by using the number of
763 // switch successors.
Mike Stump11289f42009-09-09 15:08:12 +0000764 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000765 SI->getNumSuccessors());
766 SI->addCase(ID, Dest);
767 }
768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000770 // Store the jump destination before the branch instruction.
771 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000772 } else {
773 // We need to jump through another cleanup block. Create a pad block
774 // with a branch instruction that jumps to the final destination and
775 // add it as a branch fixup to the current cleanup scope.
Mike Stump11289f42009-09-09 15:08:12 +0000776
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000777 // Create the pad block.
778 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000779
780 // Create a unique case ID.
Mike Stump11289f42009-09-09 15:08:12 +0000781 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000782 SI->getNumSuccessors());
783
784 // Store the jump destination before the branch instruction.
785 new llvm::StoreInst(ID, DestCodePtr, BI);
786
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000787 // Add it as the destination.
Anders Carlsson9c964ac2009-02-08 22:46:50 +0000788 SI->addCase(ID, CleanupPad);
Mike Stump11289f42009-09-09 15:08:12 +0000789
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000790 // Create the branch to the final destination.
791 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
792 CleanupPad->getInstList().push_back(BI);
Mike Stump11289f42009-09-09 15:08:12 +0000793
Anders Carlsson3c21dd52009-02-08 01:23:05 +0000794 // And add it as a branch fixup.
795 CleanupEntries.back().BranchFixups.push_back(BI);
796 }
797 }
798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000800 // Remove all blocks from the block scope map.
801 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
802 assert(BlockScopes.count(Blocks[i]) &&
803 "Did not find block in scope map!");
Mike Stump11289f42009-09-09 15:08:12 +0000804
Anders Carlssonfbfb5e62009-02-08 00:16:35 +0000805 BlockScopes.erase(Blocks[i]);
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000808 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000809}
810
Mike Stump11289f42009-09-09 15:08:12 +0000811void CodeGenFunction::EmitCleanupBlock() {
Anders Carlsson66c384a2009-02-08 07:46:24 +0000812 CleanupBlockInfo Info = PopCleanupBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000813
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000814 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000815 if (CurBB && !CurBB->getTerminator() &&
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000816 Info.CleanupBlock->getNumUses() == 0) {
817 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
818 delete Info.CleanupBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000819 } else
Anders Carlssonf3f91ce2009-05-31 00:33:20 +0000820 EmitBlock(Info.CleanupBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000821
Anders Carlsson66c384a2009-02-08 07:46:24 +0000822 if (Info.SwitchBlock)
823 EmitBlock(Info.SwitchBlock);
824 if (Info.EndBlock)
825 EmitBlock(Info.EndBlock);
Anders Carlssonae91d9b2009-02-08 03:55:35 +0000826}
827
Mike Stump11289f42009-09-09 15:08:12 +0000828void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
829 assert(!CleanupEntries.empty() &&
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000830 "Trying to add branch fixup without cleanup block!");
Mike Stump11289f42009-09-09 15:08:12 +0000831
Mike Stump18bb9282009-05-16 07:57:57 +0000832 // FIXME: We could be more clever here and check if there's already a branch
833 // fixup for this destination and recycle it.
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000834 CleanupEntries.back().BranchFixups.push_back(BI);
835}
836
Mike Stump11289f42009-09-09 15:08:12 +0000837void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
Anders Carlsson76180ea2009-02-08 22:13:37 +0000838 if (!HaveInsertPoint())
839 return;
Mike Stump11289f42009-09-09 15:08:12 +0000840
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000841 llvm::BranchInst* BI = Builder.CreateBr(Dest);
Mike Stump11289f42009-09-09 15:08:12 +0000842
Anders Carlsson76180ea2009-02-08 22:13:37 +0000843 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +0000844
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000845 // The stack is empty, no need to do any cleanup.
846 if (CleanupEntries.empty())
847 return;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000849 if (!Dest->getParent()) {
850 // We are trying to branch to a block that hasn't been inserted yet.
851 AddBranchFixup(BI);
852 return;
853 }
Mike Stump11289f42009-09-09 15:08:12 +0000854
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000855 BlockScopeMap::iterator I = BlockScopes.find(Dest);
856 if (I == BlockScopes.end()) {
857 // We are trying to jump to a block that is outside of any cleanup scope.
858 AddBranchFixup(BI);
859 return;
860 }
Mike Stump11289f42009-09-09 15:08:12 +0000861
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000862 assert(I->second < CleanupEntries.size() &&
863 "Trying to branch into cleanup region");
Mike Stump11289f42009-09-09 15:08:12 +0000864
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000865 if (I->second == CleanupEntries.size() - 1) {
866 // We have a branch to a block in the same scope.
867 return;
868 }
Mike Stump11289f42009-09-09 15:08:12 +0000869
Anders Carlsson7d70fd22009-02-08 00:50:42 +0000870 AddBranchFixup(BI);
871}