blob: e5cfa624b2cc2e5c6fe836b23b682ca69a6e7ed1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000017#include "CGException.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000019#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/Decl.h"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000022#include "clang/AST/DeclCXX.h"
Mike Stump6a1e0eb2009-12-04 23:26:17 +000023#include "clang/AST/StmtCXX.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000024#include "clang/Frontend/CodeGenOptions.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000025#include "llvm/Target/TargetData.h"
Chris Lattner7255a2d2010-06-22 00:03:40 +000026#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace CodeGen;
29
Mike Stump1eb44332009-09-09 15:08:12 +000030CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000031 : BlockFunction(cgm, *this, Builder), CGM(cgm),
32 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000033 Builder(cgm.getModule().getContext()),
John McCallff8e1152010-07-23 21:56:41 +000034 NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
John McCallf1549f62010-07-06 01:34:17 +000035 ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
John McCallff8e1152010-07-23 21:56:41 +000036 SwitchInsn(0), CaseRangeBlock(0),
John McCallf1549f62010-07-06 01:34:17 +000037 DidCallStackSave(false), UnreachableBlock(0),
John McCall25049412010-02-16 22:04:33 +000038 CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
John McCallf1549f62010-07-06 01:34:17 +000039 ConditionalBranchLevel(0), TerminateLandingPad(0), TerminateHandler(0),
Chris Lattner83252dc2010-07-20 21:07:09 +000040 TrapBB(0) {
Chris Lattner77b89b82010-06-27 07:15:29 +000041
42 // Get some frequently used types.
Mike Stump4e7a1f72009-02-21 20:00:35 +000043 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner77b89b82010-06-27 07:15:29 +000044 llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
45 IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
46 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
47 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
48
Mike Stumpd88ea562009-12-09 03:35:49 +000049 Exceptions = getContext().getLangOptions().Exceptions;
Mike Stump9c276ae2009-12-12 01:27:46 +000050 CatchUndefined = getContext().getLangOptions().CatchUndefined;
Douglas Gregor35415f52010-05-25 17:04:15 +000051 CGM.getMangleContext().startNewFunction();
Chris Lattner41110242008-06-17 18:05:57 +000052}
Reid Spencer5f016e22007-07-11 17:01:13 +000053
54ASTContext &CodeGenFunction::getContext() const {
55 return CGM.getContext();
56}
57
58
Daniel Dunbar0096acf2009-02-25 19:24:29 +000059llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
60 llvm::Value *Res = LocalDeclMap[VD];
61 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
62 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000063}
Reid Spencer5f016e22007-07-11 17:01:13 +000064
Daniel Dunbar0096acf2009-02-25 19:24:29 +000065llvm::Constant *
66CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
67 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000068}
69
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000070const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
71 return CGM.getTypes().ConvertTypeForMem(T);
72}
73
Reid Spencer5f016e22007-07-11 17:01:13 +000074const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
75 return CGM.getTypes().ConvertType(T);
76}
77
78bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Anders Carlssone9d34dc2009-09-29 02:09:01 +000079 return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
Fariborz Jahanianfaa34492010-08-11 17:37:35 +000080 T->isMemberFunctionPointerType() || T->isObjCObjectType();
Reid Spencer5f016e22007-07-11 17:01:13 +000081}
82
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000083void CodeGenFunction::EmitReturnBlock() {
84 // For cleanliness, we try to avoid emitting the return block for
85 // simple cases.
86 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
87
88 if (CurBB) {
89 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
90
Daniel Dunbar96e18b02009-07-19 08:24:34 +000091 // We have a valid insert point, reuse it if it is empty or there are no
92 // explicit jumps to the return block.
John McCallff8e1152010-07-23 21:56:41 +000093 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
94 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
95 delete ReturnBlock.getBlock();
Daniel Dunbar96e18b02009-07-19 08:24:34 +000096 } else
John McCallff8e1152010-07-23 21:56:41 +000097 EmitBlock(ReturnBlock.getBlock());
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000098 return;
99 }
100
101 // Otherwise, if the return block is the target of a single direct
102 // branch then we can just put the code in that block instead. This
103 // cleans up functions which started with a unified return block.
John McCallff8e1152010-07-23 21:56:41 +0000104 if (ReturnBlock.getBlock()->hasOneUse()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000105 llvm::BranchInst *BI =
John McCallff8e1152010-07-23 21:56:41 +0000106 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
John McCallf1549f62010-07-06 01:34:17 +0000107 if (BI && BI->isUnconditional() &&
John McCallff8e1152010-07-23 21:56:41 +0000108 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000109 // Reset insertion point and delete the branch.
110 Builder.SetInsertPoint(BI->getParent());
111 BI->eraseFromParent();
John McCallff8e1152010-07-23 21:56:41 +0000112 delete ReturnBlock.getBlock();
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000113 return;
114 }
115 }
116
Mike Stumpf5408fe2009-05-16 07:57:57 +0000117 // FIXME: We are at an unreachable point, there is no reason to emit the block
118 // unless it has uses. However, we still need a place to put the debug
119 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000120
John McCallff8e1152010-07-23 21:56:41 +0000121 EmitBlock(ReturnBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000122}
123
124static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
125 if (!BB) return;
126 if (!BB->use_empty())
127 return CGF.CurFn->getBasicBlockList().push_back(BB);
128 delete BB;
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000129}
130
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000131void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Chris Lattnerda138702007-07-16 21:28:45 +0000132 assert(BreakContinueStack.empty() &&
133 "mismatched push/pop in break/continue stack!");
Mike Stump1eb44332009-09-09 15:08:12 +0000134
135 // Emit function epilog (to return).
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000136 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000137
Chris Lattner7255a2d2010-06-22 00:03:40 +0000138 EmitFunctionInstrumentation("__cyg_profile_func_exit");
139
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000140 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000141 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000142 DI->setLocation(EndLoc);
Devang Patel5a6fbcf2010-07-22 22:29:16 +0000143 DI->EmitFunctionEnd(Builder);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000144 }
145
Chris Lattner35b21b82010-06-27 01:06:27 +0000146 EmitFunctionEpilog(*CurFnInfo);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000147 EmitEndEHSpec(CurCodeDecl);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000148
John McCallf1549f62010-07-06 01:34:17 +0000149 assert(EHStack.empty() &&
150 "did not remove all scopes from cleanup stack!");
151
Chris Lattnerd9becd12009-10-28 23:59:40 +0000152 // If someone did an indirect goto, emit the indirect goto block at the end of
153 // the function.
154 if (IndirectBranch) {
155 EmitBlock(IndirectBranch->getParent());
156 Builder.ClearInsertionPoint();
157 }
158
Chris Lattner5a2fa142007-12-02 06:32:24 +0000159 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000160 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000161 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000162 Ptr->eraseFromParent();
Chris Lattnerd9becd12009-10-28 23:59:40 +0000163
164 // If someone took the address of a label but never did an indirect goto, we
165 // made a zero entry PHI node, which is illegal, zap it now.
166 if (IndirectBranch) {
167 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
168 if (PN->getNumIncomingValues() == 0) {
169 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
170 PN->eraseFromParent();
171 }
172 }
John McCallf1549f62010-07-06 01:34:17 +0000173
John McCallff8e1152010-07-23 21:56:41 +0000174 EmitIfUsed(*this, RethrowBlock.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000175 EmitIfUsed(*this, TerminateLandingPad);
176 EmitIfUsed(*this, TerminateHandler);
177 EmitIfUsed(*this, UnreachableBlock);
John McCall744016d2010-07-06 23:57:41 +0000178
179 if (CGM.getCodeGenOpts().EmitDeclMetadata)
180 EmitDeclMetadata();
Reid Spencer5f016e22007-07-11 17:01:13 +0000181}
182
Chris Lattner7255a2d2010-06-22 00:03:40 +0000183/// ShouldInstrumentFunction - Return true if the current function should be
184/// instrumented with __cyg_profile_func_* calls
185bool CodeGenFunction::ShouldInstrumentFunction() {
186 if (!CGM.getCodeGenOpts().InstrumentFunctions)
187 return false;
188 if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
189 return false;
190 return true;
191}
192
193/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
194/// instrumentation function with the current function and the call site, if
195/// function instrumentation is enabled.
196void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
197 if (!ShouldInstrumentFunction())
198 return;
199
Chris Lattner8dab6572010-06-23 05:21:28 +0000200 const llvm::PointerType *PointerTy;
Chris Lattner7255a2d2010-06-22 00:03:40 +0000201 const llvm::FunctionType *FunctionTy;
202 std::vector<const llvm::Type*> ProfileFuncArgs;
203
Chris Lattner8dab6572010-06-23 05:21:28 +0000204 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
205 PointerTy = llvm::Type::getInt8PtrTy(VMContext);
206 ProfileFuncArgs.push_back(PointerTy);
207 ProfileFuncArgs.push_back(PointerTy);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000208 FunctionTy = llvm::FunctionType::get(
209 llvm::Type::getVoidTy(VMContext),
210 ProfileFuncArgs, false);
211
212 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
213 llvm::CallInst *CallSite = Builder.CreateCall(
214 CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
Chris Lattner77b89b82010-06-27 07:15:29 +0000215 llvm::ConstantInt::get(Int32Ty, 0),
Chris Lattner7255a2d2010-06-22 00:03:40 +0000216 "callsite");
217
Chris Lattner8dab6572010-06-23 05:21:28 +0000218 Builder.CreateCall2(F,
219 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
220 CallSite);
Chris Lattner7255a2d2010-06-22 00:03:40 +0000221}
222
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000223void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
Daniel Dunbar7c086512008-09-09 23:14:03 +0000224 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000225 const FunctionArgList &Args,
226 SourceLocation StartLoc) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000227 const Decl *D = GD.getDecl();
228
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000229 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000230 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000231 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000232 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000233 assert(CurFn->isDeclaration() && "Function already has body?");
234
Jakob Stoklund Olesena3fe2842010-02-09 00:10:00 +0000235 // Pass inline keyword to optimizer if it appears explicitly on any
236 // declaration.
237 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
238 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
239 RE = FD->redecls_end(); RI != RE; ++RI)
240 if (RI->isInlineSpecified()) {
241 Fn->addFnAttr(llvm::Attribute::InlineHint);
242 break;
243 }
244
Daniel Dunbar55e87422008-11-11 02:29:29 +0000245 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000246
Chris Lattner41110242008-06-17 18:05:57 +0000247 // Create a marker to make it easy to insert allocas into the entryblock
248 // later. Don't create this with the builder, because we don't want it
249 // folded.
Chris Lattner77b89b82010-06-27 07:15:29 +0000250 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
251 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000252 if (Builder.isNamePreserving())
253 AllocaInsertPt->setName("allocapt");
Mike Stump1eb44332009-09-09 15:08:12 +0000254
John McCallf1549f62010-07-06 01:34:17 +0000255 ReturnBlock = getJumpDestInCurrentScope("return");
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattner41110242008-06-17 18:05:57 +0000257 Builder.SetInsertPoint(EntryBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Douglas Gregorce056bc2010-02-21 22:15:06 +0000259 QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
260 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +0000261 /*FIXME?*/
262 FunctionType::ExtInfo());
Mike Stump91cc8152009-10-23 01:52:13 +0000263
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000264 // Emit subprogram debug descriptor.
Anders Carlssone896d982009-02-13 08:11:52 +0000265 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000266 DI->setLocation(StartLoc);
Devang Patel9c6c3a02010-01-14 00:36:21 +0000267 DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000268 }
269
Chris Lattner7255a2d2010-06-22 00:03:40 +0000270 EmitFunctionInstrumentation("__cyg_profile_func_enter");
271
Daniel Dunbar88b53962009-02-02 22:03:45 +0000272 // FIXME: Leaked.
John McCall04a67a62010-02-05 21:31:56 +0000273 // CC info is ignored, hopefully?
274 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000275 FunctionType::ExtInfo());
Eli Friedmanb17daf92009-12-04 02:43:40 +0000276
277 if (RetTy->isVoidType()) {
278 // Void type; nothing to return.
279 ReturnValue = 0;
280 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
281 hasAggregateLLVMType(CurFnInfo->getReturnType())) {
282 // Indirect aggregate return; emit returned value directly into sret slot.
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000283 // This reduces code size, and affects correctness in C++.
Eli Friedmanb17daf92009-12-04 02:43:40 +0000284 ReturnValue = CurFn->arg_begin();
285 } else {
Daniel Dunbar647a1ec2010-02-16 19:45:20 +0000286 ReturnValue = CreateIRTemp(RetTy, "retval");
Eli Friedmanb17daf92009-12-04 02:43:40 +0000287 }
288
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000289 EmitStartEHSpec(CurCodeDecl);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000290 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000291
John McCall25049412010-02-16 22:04:33 +0000292 if (CXXThisDecl)
293 CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
294 if (CXXVTTDecl)
295 CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
296
Anders Carlsson751358f2008-12-20 21:28:43 +0000297 // If any of the arguments have a variably modified type, make sure to
298 // emit the type size.
299 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
300 i != e; ++i) {
301 QualType Ty = i->second;
302
303 if (Ty->isVariablyModifiedType())
304 EmitVLASize(Ty);
305 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000306}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000307
John McCall9fc6a772010-02-19 09:25:03 +0000308void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
309 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
Douglas Gregor06a9f362010-05-01 20:49:11 +0000310 assert(FD->getBody());
311 EmitStmt(FD->getBody());
John McCalla355e072010-02-18 03:17:58 +0000312}
313
John McCall39dad532010-08-03 22:46:07 +0000314/// Tries to mark the given function nounwind based on the
315/// non-existence of any throwing calls within it. We believe this is
316/// lightweight enough to do at -O0.
317static void TryMarkNoThrow(llvm::Function *F) {
John McCallb3a29f12010-08-11 22:38:33 +0000318 // LLVM treats 'nounwind' on a function as part of the type, so we
319 // can't do this on functions that can be overwritten.
320 if (F->mayBeOverridden()) return;
321
John McCall39dad532010-08-03 22:46:07 +0000322 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
323 for (llvm::BasicBlock::iterator
324 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
325 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
326 if (!Call->doesNotThrow())
327 return;
328 F->setDoesNotThrow(true);
329}
330
Anders Carlssonc997d422010-01-02 01:01:18 +0000331void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
Anders Carlsson0ff8baf2009-09-11 00:07:24 +0000332 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
333
Anders Carlssone896d982009-02-13 08:11:52 +0000334 // Check if we should generate debug info for this function.
Mike Stump1feade82009-08-26 22:31:08 +0000335 if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000336 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Daniel Dunbar7c086512008-09-09 23:14:03 +0000338 FunctionArgList Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Mike Stump6a1e0eb2009-12-04 23:26:17 +0000340 CurGD = GD;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000341 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
342 if (MD->isInstance()) {
343 // Create the implicit 'this' decl.
344 // FIXME: I'm not entirely sure I like using a fake decl just for code
345 // generation. Maybe we can come up with a better way?
John McCall25049412010-02-16 22:04:33 +0000346 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
347 FD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000348 &getContext().Idents.get("this"),
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000349 MD->getThisType(getContext()));
350 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000351
352 // Check if we need a VTT parameter as well.
Anders Carlssonaf440352010-03-23 04:11:45 +0000353 if (CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000354 // FIXME: The comment about using a fake decl above applies here too.
355 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
356 CXXVTTDecl =
John McCall25049412010-02-16 22:04:33 +0000357 ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000358 &getContext().Idents.get("vtt"), T);
359 Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
360 }
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000361 }
362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000364 if (FD->getNumParams()) {
John McCall183700f2009-09-21 23:43:11 +0000365 const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000366 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000367
368 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
Mike Stump1eb44332009-09-09 15:08:12 +0000369 Args.push_back(std::make_pair(FD->getParamDecl(i),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000370 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000371 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000372
John McCalla355e072010-02-18 03:17:58 +0000373 SourceRange BodyRange;
374 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
Anders Carlsson4365bba2009-11-06 02:55:43 +0000375
John McCalla355e072010-02-18 03:17:58 +0000376 // Emit the standard function prologue.
377 StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
Anders Carlsson4365bba2009-11-06 02:55:43 +0000378
John McCalla355e072010-02-18 03:17:58 +0000379 // Generate the body of the function.
John McCall9fc6a772010-02-19 09:25:03 +0000380 if (isa<CXXDestructorDecl>(FD))
381 EmitDestructorBody(Args);
382 else if (isa<CXXConstructorDecl>(FD))
383 EmitConstructorBody(Args);
384 else
385 EmitFunctionBody(Args);
Anders Carlsson1851a122010-02-07 19:45:40 +0000386
John McCalla355e072010-02-18 03:17:58 +0000387 // Emit the standard function epilogue.
388 FinishFunction(BodyRange.getEnd());
John McCall39dad532010-08-03 22:46:07 +0000389
390 // If we haven't marked the function nothrow through other means, do
391 // a quick pass now to see if we can.
392 if (!CurFn->doesNotThrow())
393 TryMarkNoThrow(CurFn);
Chris Lattner41110242008-06-17 18:05:57 +0000394}
395
Chris Lattner0946ccd2008-11-11 07:41:27 +0000396/// ContainsLabel - Return true if the statement contains a label in it. If
397/// this statement is not executed normally, it not containing a label means
398/// that we can just remove the code.
399bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
400 // Null statement, not a label!
401 if (S == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner0946ccd2008-11-11 07:41:27 +0000403 // If this is a label, we have to emit the code, consider something like:
404 // if (0) { ... foo: bar(); } goto foo;
405 if (isa<LabelStmt>(S))
406 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner0946ccd2008-11-11 07:41:27 +0000408 // If this is a case/default statement, and we haven't seen a switch, we have
409 // to emit the code.
410 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
411 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattner0946ccd2008-11-11 07:41:27 +0000413 // If this is a switch statement, we want to ignore cases below it.
414 if (isa<SwitchStmt>(S))
415 IgnoreCaseStmts = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner0946ccd2008-11-11 07:41:27 +0000417 // Scan subexpressions for verboten labels.
418 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
419 I != E; ++I)
420 if (ContainsLabel(*I, IgnoreCaseStmts))
421 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner0946ccd2008-11-11 07:41:27 +0000423 return false;
424}
425
Chris Lattner31a09842008-11-12 08:04:58 +0000426
427/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
428/// a constant, or if it does but contains a label, return 0. If it constant
429/// folds to 'true' and does not contain a label, return 1, if it constant folds
430/// to 'false' and does not contain a label, return -1.
431int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000432 // FIXME: Rename and handle conversion of other evaluatable things
433 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000434 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000435 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
Anders Carlsson64712f12008-12-01 02:46:24 +0000436 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000437 return 0; // Not foldable, not integer or not fully evaluatable.
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner31a09842008-11-12 08:04:58 +0000439 if (CodeGenFunction::ContainsLabel(Cond))
440 return 0; // Contains a label.
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Anders Carlsson64712f12008-12-01 02:46:24 +0000442 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000443}
444
445
446/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
447/// statement) to the specified blocks. Based on the condition, this might try
448/// to simplify the codegen of the conditional based on the branch.
449///
450void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
451 llvm::BasicBlock *TrueBlock,
452 llvm::BasicBlock *FalseBlock) {
453 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
454 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Chris Lattner31a09842008-11-12 08:04:58 +0000456 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
457 // Handle X && Y in a condition.
458 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
459 // If we have "1 && X", simplify the code. "0 && X" would have constant
460 // folded if the case was simple enough.
461 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
462 // br(1 && X) -> br(X).
463 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner31a09842008-11-12 08:04:58 +0000466 // If we have "X && 1", simplify the code to use an uncond branch.
467 // "X && 0" would have been constant folded to 0.
468 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
469 // br(X && 1) -> br(X).
470 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner31a09842008-11-12 08:04:58 +0000473 // Emit the LHS as a conditional. If the LHS conditional is false, we
474 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000475 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000476 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
477 EmitBlock(LHSTrue);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Anders Carlsson08e9e452010-01-24 00:20:05 +0000479 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000480 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000481 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000482 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000483
Chris Lattner31a09842008-11-12 08:04:58 +0000484 return;
485 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
486 // If we have "0 || X", simplify the code. "1 || X" would have constant
487 // folded if the case was simple enough.
488 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
489 // br(0 || X) -> br(X).
490 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Chris Lattner31a09842008-11-12 08:04:58 +0000493 // If we have "X || 0", simplify the code to use an uncond branch.
494 // "X || 1" would have been constant folded to 1.
495 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
496 // br(X || 0) -> br(X).
497 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattner31a09842008-11-12 08:04:58 +0000500 // Emit the LHS as a conditional. If the LHS conditional is true, we
501 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000502 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000503 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
504 EmitBlock(LHSFalse);
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Anders Carlsson08e9e452010-01-24 00:20:05 +0000506 // Any temporaries created here are conditional.
Anders Carlsson72119a82010-02-04 17:18:07 +0000507 BeginConditionalBranch();
Chris Lattner31a09842008-11-12 08:04:58 +0000508 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
Anders Carlsson72119a82010-02-04 17:18:07 +0000509 EndConditionalBranch();
Anders Carlsson08e9e452010-01-24 00:20:05 +0000510
Chris Lattner31a09842008-11-12 08:04:58 +0000511 return;
512 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Chris Lattner552f4c42008-11-12 08:13:36 +0000515 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
516 // br(!x, t, f) -> br(x, f, t)
517 if (CondUOp->getOpcode() == UnaryOperator::LNot)
518 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Daniel Dunbar09b14892008-11-12 10:30:32 +0000521 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
522 // Handle ?: operator.
523
524 // Just ignore GNU ?: extension.
525 if (CondOp->getLHS()) {
526 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
527 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
528 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
529 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
530 EmitBlock(LHSBlock);
531 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
532 EmitBlock(RHSBlock);
533 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
534 return;
535 }
536 }
537
Chris Lattner31a09842008-11-12 08:04:58 +0000538 // Emit the code with the fully general case.
539 llvm::Value *CondV = EvaluateExprAsBool(Cond);
540 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
541}
542
Daniel Dunbar488e9932008-08-16 00:56:44 +0000543/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000544/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000545void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
546 bool OmitOnError) {
547 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000548}
549
Anders Carlsson1884eb02010-05-22 17:35:42 +0000550void
551CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson0d7c5832010-05-03 01:20:20 +0000552 // Ignore empty classes in C++.
553 if (getContext().getLangOptions().CPlusPlus) {
554 if (const RecordType *RT = Ty->getAs<RecordType>()) {
555 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
556 return;
557 }
558 }
John McCall90217182010-08-07 08:21:30 +0000559
560 // Cast the dest ptr to the appropriate i8 pointer type.
561 unsigned DestAS =
562 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
563 const llvm::Type *BP =
564 llvm::Type::getInt8PtrTy(VMContext, DestAS);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000565 if (DestPtr->getType() != BP)
566 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
567
568 // Get size and alignment info for this aggregate.
569 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
John McCall90217182010-08-07 08:21:30 +0000570 uint64_t Size = TypeInfo.first;
571 unsigned Align = TypeInfo.second;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000572
Chris Lattner88207c92009-04-21 17:59:23 +0000573 // Don't bother emitting a zero-byte memset.
John McCall90217182010-08-07 08:21:30 +0000574 if (Size == 0)
Chris Lattner88207c92009-04-21 17:59:23 +0000575 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCall90217182010-08-07 08:21:30 +0000577 llvm::ConstantInt *SizeVal = llvm::ConstantInt::get(IntPtrTy, Size / 8);
578 llvm::ConstantInt *AlignVal = Builder.getInt32(Align / 8);
579
580 // If the type contains a pointer to data member we can't memset it to zero.
581 // Instead, create a null constant and copy it to the destination.
582 if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
583 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
584
585 llvm::GlobalVariable *NullVariable =
586 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
587 /*isConstant=*/true,
588 llvm::GlobalVariable::PrivateLinkage,
589 NullConstant, llvm::Twine());
590 llvm::Value *SrcPtr =
591 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
592
593 // FIXME: variable-size types?
594
595 // Get and call the appropriate llvm.memcpy overload.
596 llvm::Constant *Memcpy =
597 CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), IntPtrTy);
598 Builder.CreateCall5(Memcpy, DestPtr, SrcPtr, SizeVal, AlignVal,
599 /*volatile*/ Builder.getFalse());
600 return;
601 }
602
603 // Otherwise, just memset the whole thing to zero. This is legal
604 // because in LLVM, all default initializers (other than the ones we just
605 // handled above) are guaranteed to have a bit pattern of all zeros.
606
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000607 // FIXME: Handle variable sized types.
Chris Lattner77b89b82010-06-27 07:15:29 +0000608 Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtrTy), DestPtr,
John McCall90217182010-08-07 08:21:30 +0000609 Builder.getInt8(0),
610 SizeVal, AlignVal, /*volatile*/ Builder.getFalse());
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000611}
612
Chris Lattnerd9becd12009-10-28 23:59:40 +0000613llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
614 // Make sure that there is a block for the indirect goto.
615 if (IndirectBranch == 0)
616 GetIndirectGotoBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000617
John McCallff8e1152010-07-23 21:56:41 +0000618 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000619
Chris Lattnerd9becd12009-10-28 23:59:40 +0000620 // Make sure the indirect branch includes all of the address-taken blocks.
621 IndirectBranch->addDestination(BB);
622 return llvm::BlockAddress::get(CurFn, BB);
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000623}
624
625llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000626 // If we already made the indirect branch for indirect goto, return its block.
627 if (IndirectBranch) return IndirectBranch->getParent();
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000628
Chris Lattnerd9becd12009-10-28 23:59:40 +0000629 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000630
Chris Lattnerd9becd12009-10-28 23:59:40 +0000631 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner85e74ac2009-10-28 20:36:47 +0000632
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000633 // Create the PHI node that indirect gotos will add entries to.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000634 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000635
Chris Lattnerd9becd12009-10-28 23:59:40 +0000636 // Create the indirect branch instruction.
637 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
638 return IndirectBranch->getParent();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000639}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000640
Daniel Dunbard286f052009-07-19 06:58:07 +0000641llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000642 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Anders Carlssonf666b772008-12-20 20:27:15 +0000644 assert(SizeEntry && "Did not emit size for type");
645 return SizeEntry;
646}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000647
Daniel Dunbard286f052009-07-19 06:58:07 +0000648llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000649 assert(Ty->isVariablyModifiedType() &&
650 "Must pass variably modified type to EmitVLASizes!");
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Daniel Dunbard286f052009-07-19 06:58:07 +0000652 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Anders Carlsson60d35412008-12-20 20:46:34 +0000654 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
Eli Friedmanbbed6b92009-08-15 02:50:32 +0000655 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000657 if (!SizeEntry) {
Anders Carlsson96f21472009-02-05 19:43:10 +0000658 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000660 // Get the element size;
661 QualType ElemTy = VAT->getElementType();
662 llvm::Value *ElemSize;
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000663 if (ElemTy->isVariableArrayType())
664 ElemSize = EmitVLASize(ElemTy);
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000665 else
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000666 ElemSize = llvm::ConstantInt::get(SizeTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000667 getContext().getTypeSizeInChars(ElemTy).getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000669 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000670 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000672 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000673 }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Anders Carlsson60d35412008-12-20 20:46:34 +0000675 return SizeEntry;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000678 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
679 EmitVLASize(AT->getElementType());
680 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000681 }
682
Chris Lattnerec18ddd2009-08-15 00:03:43 +0000683 const PointerType *PT = Ty->getAs<PointerType>();
684 assert(PT && "unknown VM type!");
685 EmitVLASize(PT->getPointeeType());
Anders Carlsson60d35412008-12-20 20:46:34 +0000686 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000687}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000688
689llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
Chris Lattnerfbe02ff2010-06-27 07:40:06 +0000690 if (CGM.getContext().getBuiltinVaListType()->isArrayType())
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000691 return EmitScalarExpr(E);
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000692 return EmitLValue(E).getAddress();
693}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000694
John McCallf1549f62010-07-06 01:34:17 +0000695/// Pops cleanup blocks until the given savepoint is reached.
696void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
697 assert(Old.isValid());
698
John McCallff8e1152010-07-23 21:56:41 +0000699 while (EHStack.stable_begin() != Old) {
700 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
701
702 // As long as Old strictly encloses the scope's enclosing normal
703 // cleanup, we're going to emit another normal cleanup which
704 // fallthrough can propagate through.
705 bool FallThroughIsBranchThrough =
706 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
707
708 PopCleanupBlock(FallThroughIsBranchThrough);
709 }
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000710}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000711
John McCallff8e1152010-07-23 21:56:41 +0000712static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
713 EHCleanupScope &Scope) {
714 assert(Scope.isNormalCleanup());
715 llvm::BasicBlock *Entry = Scope.getNormalBlock();
716 if (!Entry) {
717 Entry = CGF.createBasicBlock("cleanup");
718 Scope.setNormalBlock(Entry);
Mike Stump99533832009-12-02 07:41:41 +0000719 }
John McCallff8e1152010-07-23 21:56:41 +0000720 return Entry;
721}
Mike Stump99533832009-12-02 07:41:41 +0000722
John McCallff8e1152010-07-23 21:56:41 +0000723static llvm::BasicBlock *CreateEHEntry(CodeGenFunction &CGF,
724 EHCleanupScope &Scope) {
725 assert(Scope.isEHCleanup());
726 llvm::BasicBlock *Entry = Scope.getEHBlock();
727 if (!Entry) {
728 Entry = CGF.createBasicBlock("eh.cleanup");
729 Scope.setEHBlock(Entry);
730 }
731 return Entry;
732}
Devang Patelcd9199e2010-04-13 00:08:43 +0000733
John McCallff8e1152010-07-23 21:56:41 +0000734/// Transitions the terminator of the given exit-block of a cleanup to
735/// be a cleanup switch.
736static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
737 llvm::BasicBlock *Block) {
738 // If it's a branch, turn it into a switch whose default
739 // destination is its original target.
740 llvm::TerminatorInst *Term = Block->getTerminator();
741 assert(Term && "can't transition block without terminator");
742
743 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
744 assert(Br->isUnconditional());
745 llvm::LoadInst *Load =
746 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
747 llvm::SwitchInst *Switch =
748 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
749 Br->eraseFromParent();
750 return Switch;
751 } else {
752 return cast<llvm::SwitchInst>(Term);
753 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000754}
755
John McCallf1549f62010-07-06 01:34:17 +0000756/// Attempts to reduce a cleanup's entry block to a fallthrough. This
757/// is basically llvm::MergeBlockIntoPredecessor, except
John McCallff8e1152010-07-23 21:56:41 +0000758/// simplified/optimized for the tighter constraints on cleanup blocks.
759///
760/// Returns the new block, whatever it is.
761static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
762 llvm::BasicBlock *Entry) {
John McCallf1549f62010-07-06 01:34:17 +0000763 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
John McCallff8e1152010-07-23 21:56:41 +0000764 if (!Pred) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000765
John McCallf1549f62010-07-06 01:34:17 +0000766 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
John McCallff8e1152010-07-23 21:56:41 +0000767 if (!Br || Br->isConditional()) return Entry;
John McCallf1549f62010-07-06 01:34:17 +0000768 assert(Br->getSuccessor(0) == Entry);
769
770 // If we were previously inserting at the end of the cleanup entry
771 // block, we'll need to continue inserting at the end of the
772 // predecessor.
773 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
774 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
775
776 // Kill the branch.
777 Br->eraseFromParent();
778
779 // Merge the blocks.
780 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
781
782 // Kill the entry block.
783 Entry->eraseFromParent();
784
785 if (WasInsertBlock)
786 CGF.Builder.SetInsertPoint(Pred);
Anders Carlsson87eaf172009-02-08 00:50:42 +0000787
John McCallff8e1152010-07-23 21:56:41 +0000788 return Pred;
John McCallf1549f62010-07-06 01:34:17 +0000789}
790
John McCall1f0fca52010-07-21 07:22:38 +0000791static void EmitCleanup(CodeGenFunction &CGF,
792 EHScopeStack::Cleanup *Fn,
793 bool ForEH) {
John McCallda65ea82010-07-13 20:32:21 +0000794 if (ForEH) CGF.EHStack.pushTerminate();
795 Fn->Emit(CGF, ForEH);
796 if (ForEH) CGF.EHStack.popTerminate();
797 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
798}
799
John McCall1f0fca52010-07-21 07:22:38 +0000800/// Pops a cleanup block. If the block includes a normal cleanup, the
801/// current insertion point is threaded through the cleanup, as are
802/// any branch fixups on the cleanup.
John McCallff8e1152010-07-23 21:56:41 +0000803void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCall1f0fca52010-07-21 07:22:38 +0000804 assert(!EHStack.empty() && "cleanup stack is empty!");
805 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
806 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
807 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
John McCallda65ea82010-07-13 20:32:21 +0000808
809 // Check whether we need an EH cleanup. This is only true if we've
810 // generated a lazy EH cleanup block.
John McCallff8e1152010-07-23 21:56:41 +0000811 bool RequiresEHCleanup = Scope.hasEHBranches();
John McCallda65ea82010-07-13 20:32:21 +0000812
813 // Check the three conditions which might require a normal cleanup:
814
815 // - whether there are branch fix-ups through this cleanup
816 unsigned FixupDepth = Scope.getFixupDepth();
John McCall1f0fca52010-07-21 07:22:38 +0000817 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
John McCallda65ea82010-07-13 20:32:21 +0000818
John McCallff8e1152010-07-23 21:56:41 +0000819 // - whether there are branch-throughs or branch-afters
820 bool HasExistingBranches = Scope.hasBranches();
John McCallda65ea82010-07-13 20:32:21 +0000821
822 // - whether there's a fallthrough
John McCall1f0fca52010-07-21 07:22:38 +0000823 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
John McCallda65ea82010-07-13 20:32:21 +0000824 bool HasFallthrough = (FallthroughSource != 0);
825
826 bool RequiresNormalCleanup = false;
827 if (Scope.isNormalCleanup() &&
828 (HasFixups || HasExistingBranches || HasFallthrough)) {
829 RequiresNormalCleanup = true;
830 }
831
832 // If we don't need the cleanup at all, we're done.
833 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallff8e1152010-07-23 21:56:41 +0000834 EHStack.popCleanup(); // safe because there are no fixups
John McCall1f0fca52010-07-21 07:22:38 +0000835 assert(EHStack.getNumBranchFixups() == 0 ||
836 EHStack.hasNormalCleanups());
John McCallda65ea82010-07-13 20:32:21 +0000837 return;
838 }
839
840 // Copy the cleanup emission data out. Note that SmallVector
841 // guarantees maximal alignment for its buffer regardless of its
842 // type parameter.
843 llvm::SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
844 CleanupBuffer.reserve(Scope.getCleanupSize());
845 memcpy(CleanupBuffer.data(),
846 Scope.getCleanupBuffer(), Scope.getCleanupSize());
847 CleanupBuffer.set_size(Scope.getCleanupSize());
John McCall1f0fca52010-07-21 07:22:38 +0000848 EHScopeStack::Cleanup *Fn =
849 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
John McCallda65ea82010-07-13 20:32:21 +0000850
John McCallff8e1152010-07-23 21:56:41 +0000851 // We want to emit the EH cleanup after the normal cleanup, but go
852 // ahead and do the setup for the EH cleanup while the scope is still
853 // alive.
854 llvm::BasicBlock *EHEntry = 0;
855 llvm::SmallVector<llvm::Instruction*, 2> EHInstsToAppend;
856 if (RequiresEHCleanup) {
857 EHEntry = CreateEHEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000858
John McCallff8e1152010-07-23 21:56:41 +0000859 // Figure out the branch-through dest if necessary.
860 llvm::BasicBlock *EHBranchThroughDest = 0;
861 if (Scope.hasEHBranchThroughs()) {
862 assert(Scope.getEnclosingEHCleanup() != EHStack.stable_end());
863 EHScope &S = *EHStack.find(Scope.getEnclosingEHCleanup());
864 EHBranchThroughDest = CreateEHEntry(*this, cast<EHCleanupScope>(S));
865 }
866
867 // If we have exactly one branch-after and no branch-throughs, we
868 // can dispatch it without a switch.
John McCall7cd4b062010-07-26 22:44:58 +0000869 if (!Scope.hasEHBranchThroughs() &&
John McCallff8e1152010-07-23 21:56:41 +0000870 Scope.getNumEHBranchAfters() == 1) {
871 assert(!EHBranchThroughDest);
872
873 // TODO: remove the spurious eh.cleanup.dest stores if this edge
874 // never went through any switches.
875 llvm::BasicBlock *BranchAfterDest = Scope.getEHBranchAfterBlock(0);
876 EHInstsToAppend.push_back(llvm::BranchInst::Create(BranchAfterDest));
877
878 // Otherwise, if we have any branch-afters, we need a switch.
879 } else if (Scope.getNumEHBranchAfters()) {
880 // The default of the switch belongs to the branch-throughs if
881 // they exist.
882 llvm::BasicBlock *Default =
883 (EHBranchThroughDest ? EHBranchThroughDest : getUnreachableBlock());
884
885 const unsigned SwitchCapacity = Scope.getNumEHBranchAfters();
886
887 llvm::LoadInst *Load =
888 new llvm::LoadInst(getEHCleanupDestSlot(), "cleanup.dest");
889 llvm::SwitchInst *Switch =
890 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
891
892 EHInstsToAppend.push_back(Load);
893 EHInstsToAppend.push_back(Switch);
894
895 for (unsigned I = 0, E = Scope.getNumEHBranchAfters(); I != E; ++I)
896 Switch->addCase(Scope.getEHBranchAfterIndex(I),
897 Scope.getEHBranchAfterBlock(I));
898
899 // Otherwise, we have only branch-throughs; jump to the next EH
900 // cleanup.
901 } else {
902 assert(EHBranchThroughDest);
903 EHInstsToAppend.push_back(llvm::BranchInst::Create(EHBranchThroughDest));
904 }
905 }
906
907 if (!RequiresNormalCleanup) {
908 EHStack.popCleanup();
909 } else {
910 // As a kindof crazy internal case, branch-through fall-throughs
911 // leave the insertion point set to the end of the last cleanup.
912 bool HasPrebranchedFallthrough =
913 (HasFallthrough && FallthroughSource->getTerminator());
914 assert(!HasPrebranchedFallthrough ||
915 FallthroughSource->getTerminator()->getSuccessor(0)
916 == Scope.getNormalBlock());
917
John McCallda65ea82010-07-13 20:32:21 +0000918 // If we have a fallthrough and no other need for the cleanup,
919 // emit it directly.
John McCallff8e1152010-07-23 21:56:41 +0000920 if (HasFallthrough && !HasPrebranchedFallthrough &&
921 !HasFixups && !HasExistingBranches) {
922
923 // Fixups can cause us to optimistically create a normal block,
924 // only to later have no real uses for it. Just delete it in
925 // this case.
926 // TODO: we can potentially simplify all the uses after this.
927 if (Scope.getNormalBlock()) {
928 Scope.getNormalBlock()->replaceAllUsesWith(getUnreachableBlock());
929 delete Scope.getNormalBlock();
930 }
931
932 EHStack.popCleanup();
933
John McCall1f0fca52010-07-21 07:22:38 +0000934 EmitCleanup(*this, Fn, /*ForEH*/ false);
John McCallda65ea82010-07-13 20:32:21 +0000935
936 // Otherwise, the best approach is to thread everything through
937 // the cleanup block and then try to clean up after ourselves.
938 } else {
939 // Force the entry block to exist.
John McCallff8e1152010-07-23 21:56:41 +0000940 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
John McCallda65ea82010-07-13 20:32:21 +0000941
John McCallff8e1152010-07-23 21:56:41 +0000942 // If there's a fallthrough, we need to store the cleanup
943 // destination index. For fall-throughs this is always zero.
944 if (HasFallthrough && !HasPrebranchedFallthrough)
945 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
946
947 // Emit the entry block. This implicitly branches to it if we
948 // have fallthrough. All the fixups and existing branches should
949 // already be branched to it.
John McCall1f0fca52010-07-21 07:22:38 +0000950 EmitBlock(NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +0000951
John McCallff8e1152010-07-23 21:56:41 +0000952 bool HasEnclosingCleanups =
953 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
John McCallda65ea82010-07-13 20:32:21 +0000954
John McCallff8e1152010-07-23 21:56:41 +0000955 // Compute the branch-through dest if we need it:
956 // - if there are branch-throughs threaded through the scope
957 // - if fall-through is a branch-through
958 // - if there are fixups that will be optimistically forwarded
959 // to the enclosing cleanup
960 llvm::BasicBlock *BranchThroughDest = 0;
961 if (Scope.hasBranchThroughs() ||
962 (HasFallthrough && FallthroughIsBranchThrough) ||
963 (HasFixups && HasEnclosingCleanups)) {
964 assert(HasEnclosingCleanups);
965 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
966 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
John McCallda65ea82010-07-13 20:32:21 +0000967 }
968
John McCallff8e1152010-07-23 21:56:41 +0000969 llvm::BasicBlock *FallthroughDest = 0;
970 llvm::SmallVector<llvm::Instruction*, 2> InstsToAppend;
971
972 // If there's exactly one branch-after and no other threads,
973 // we can route it without a switch.
974 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
975 Scope.getNumBranchAfters() == 1) {
976 assert(!BranchThroughDest);
977
978 // TODO: clean up the possibly dead stores to the cleanup dest slot.
979 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
980 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
981
982 // Build a switch-out if we need it:
983 // - if there are branch-afters threaded through the scope
984 // - if fall-through is a branch-after
985 // - if there are fixups that have nowhere left to go and
986 // so must be immediately resolved
987 } else if (Scope.getNumBranchAfters() ||
988 (HasFallthrough && !FallthroughIsBranchThrough) ||
989 (HasFixups && !HasEnclosingCleanups)) {
990
991 llvm::BasicBlock *Default =
992 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
993
994 // TODO: base this on the number of branch-afters and fixups
995 const unsigned SwitchCapacity = 10;
996
997 llvm::LoadInst *Load =
998 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
999 llvm::SwitchInst *Switch =
1000 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
1001
1002 InstsToAppend.push_back(Load);
1003 InstsToAppend.push_back(Switch);
1004
1005 // Branch-after fallthrough.
1006 if (HasFallthrough && !FallthroughIsBranchThrough) {
1007 FallthroughDest = createBasicBlock("cleanup.cont");
1008 Switch->addCase(Builder.getInt32(0), FallthroughDest);
1009 }
1010
1011 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
1012 Switch->addCase(Scope.getBranchAfterIndex(I),
1013 Scope.getBranchAfterBlock(I));
1014 }
1015
1016 if (HasFixups && !HasEnclosingCleanups)
1017 ResolveAllBranchFixups(Switch);
1018 } else {
1019 // We should always have a branch-through destination in this case.
1020 assert(BranchThroughDest);
1021 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
1022 }
1023
1024 // We're finally ready to pop the cleanup.
1025 EHStack.popCleanup();
1026 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
1027
1028 EmitCleanup(*this, Fn, /*ForEH*/ false);
1029
1030 // Append the prepared cleanup prologue from above.
1031 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
1032 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
1033 NormalExit->getInstList().push_back(InstsToAppend[I]);
1034
1035 // Optimistically hope that any fixups will continue falling through.
John McCall1f0fca52010-07-21 07:22:38 +00001036 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
John McCallff8e1152010-07-23 21:56:41 +00001037 I < E; ++I) {
1038 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
1039 if (!Fixup.Destination) continue;
1040 if (!Fixup.OptimisticBranchBlock) {
1041 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
1042 getNormalCleanupDestSlot(),
1043 Fixup.InitialBranch);
1044 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
1045 }
1046 Fixup.OptimisticBranchBlock = NormalExit;
1047 }
1048
1049 if (FallthroughDest)
1050 EmitBlock(FallthroughDest);
1051 else if (!HasFallthrough)
1052 Builder.ClearInsertionPoint();
John McCallda65ea82010-07-13 20:32:21 +00001053
John McCallff8e1152010-07-23 21:56:41 +00001054 // Check whether we can merge NormalEntry into a single predecessor.
1055 // This might invalidate (non-IR) pointers to NormalEntry.
1056 llvm::BasicBlock *NewNormalEntry =
1057 SimplifyCleanupEntry(*this, NormalEntry);
John McCallda65ea82010-07-13 20:32:21 +00001058
John McCallff8e1152010-07-23 21:56:41 +00001059 // If it did invalidate those pointers, and NormalEntry was the same
1060 // as NormalExit, go back and patch up the fixups.
1061 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1062 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1063 I < E; ++I)
1064 CGF.EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCallda65ea82010-07-13 20:32:21 +00001065 }
1066 }
1067
John McCallff8e1152010-07-23 21:56:41 +00001068 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1069
John McCallda65ea82010-07-13 20:32:21 +00001070 // Emit the EH cleanup if required.
1071 if (RequiresEHCleanup) {
John McCall1f0fca52010-07-21 07:22:38 +00001072 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallff8e1152010-07-23 21:56:41 +00001073
John McCall1f0fca52010-07-21 07:22:38 +00001074 EmitBlock(EHEntry);
John McCallff8e1152010-07-23 21:56:41 +00001075 EmitCleanup(*this, Fn, /*ForEH*/ true);
1076
1077 // Append the prepared cleanup prologue from above.
1078 llvm::BasicBlock *EHExit = Builder.GetInsertBlock();
1079 for (unsigned I = 0, E = EHInstsToAppend.size(); I != E; ++I)
1080 EHExit->getInstList().push_back(EHInstsToAppend[I]);
1081
John McCall1f0fca52010-07-21 07:22:38 +00001082 Builder.restoreIP(SavedIP);
John McCallff8e1152010-07-23 21:56:41 +00001083
1084 SimplifyCleanupEntry(*this, EHEntry);
John McCallda65ea82010-07-13 20:32:21 +00001085 }
1086}
1087
John McCallff8e1152010-07-23 21:56:41 +00001088/// Terminate the current block by emitting a branch which might leave
1089/// the current cleanup-protected scope. The target scope may not yet
1090/// be known, in which case this will require a fixup.
1091///
1092/// As a side-effect, this method clears the insertion point.
John McCallf1549f62010-07-06 01:34:17 +00001093void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall413e6772010-07-28 01:07:35 +00001094 assert(Dest.getScopeDepth().encloses(EHStack.getInnermostNormalCleanup())
1095 && "stale jump destination");
1096
Anders Carlsson46831a92009-02-08 22:13:37 +00001097 if (!HaveInsertPoint())
1098 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001099
John McCallf1549f62010-07-06 01:34:17 +00001100 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001101 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001102
John McCallff8e1152010-07-23 21:56:41 +00001103 // If we're not in a cleanup scope, or if the destination scope is
1104 // the current normal-cleanup scope, we don't need to worry about
John McCallf1549f62010-07-06 01:34:17 +00001105 // fixups.
John McCallff8e1152010-07-23 21:56:41 +00001106 if (!EHStack.hasNormalCleanups() ||
1107 Dest.getScopeDepth() == EHStack.getInnermostNormalCleanup()) {
John McCallf1549f62010-07-06 01:34:17 +00001108 Builder.ClearInsertionPoint();
1109 return;
1110 }
1111
John McCallf1549f62010-07-06 01:34:17 +00001112 // If we can't resolve the destination cleanup scope, just add this
John McCallff8e1152010-07-23 21:56:41 +00001113 // to the current cleanup scope as a branch fixup.
1114 if (!Dest.getScopeDepth().isValid()) {
1115 BranchFixup &Fixup = EHStack.addBranchFixup();
1116 Fixup.Destination = Dest.getBlock();
1117 Fixup.DestinationIndex = Dest.getDestIndex();
1118 Fixup.InitialBranch = BI;
1119 Fixup.OptimisticBranchBlock = 0;
1120
John McCallf1549f62010-07-06 01:34:17 +00001121 Builder.ClearInsertionPoint();
1122 return;
1123 }
1124
John McCallff8e1152010-07-23 21:56:41 +00001125 // Otherwise, thread through all the normal cleanups in scope.
1126
1127 // Store the index at the start.
1128 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1129 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
1130
1131 // Adjust BI to point to the first cleanup block.
1132 {
1133 EHCleanupScope &Scope =
1134 cast<EHCleanupScope>(*EHStack.find(EHStack.getInnermostNormalCleanup()));
1135 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1136 }
1137
1138 // Add this destination to all the scopes involved.
1139 EHScopeStack::stable_iterator I = EHStack.getInnermostNormalCleanup();
1140 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1141 if (E.strictlyEncloses(I)) {
1142 while (true) {
1143 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1144 assert(Scope.isNormalCleanup());
1145 I = Scope.getEnclosingNormalCleanup();
1146
1147 // If this is the last cleanup we're propagating through, tell it
1148 // that there's a resolved jump moving through it.
1149 if (!E.strictlyEncloses(I)) {
1150 Scope.addBranchAfter(Index, Dest.getBlock());
1151 break;
John McCallda65ea82010-07-13 20:32:21 +00001152 }
John McCallff8e1152010-07-23 21:56:41 +00001153
1154 // Otherwise, tell the scope that there's a jump propoagating
1155 // through it. If this isn't new information, all the rest of
1156 // the work has been done before.
1157 if (!Scope.addBranchThrough(Dest.getBlock()))
1158 break;
John McCallf1549f62010-07-06 01:34:17 +00001159 }
1160 }
1161
Anders Carlsson46831a92009-02-08 22:13:37 +00001162 Builder.ClearInsertionPoint();
John McCallf1549f62010-07-06 01:34:17 +00001163}
Mike Stump1eb44332009-09-09 15:08:12 +00001164
John McCallff8e1152010-07-23 21:56:41 +00001165void CodeGenFunction::EmitBranchThroughEHCleanup(UnwindDest Dest) {
1166 // We should never get invalid scope depths for an UnwindDest; that
1167 // implies that the destination wasn't set up correctly.
1168 assert(Dest.getScopeDepth().isValid() && "invalid scope depth on EH dest?");
1169
John McCallf1549f62010-07-06 01:34:17 +00001170 if (!HaveInsertPoint())
Anders Carlsson87eaf172009-02-08 00:50:42 +00001171 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001172
John McCallf1549f62010-07-06 01:34:17 +00001173 // Create the branch.
John McCallff8e1152010-07-23 21:56:41 +00001174 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001175
John McCallff8e1152010-07-23 21:56:41 +00001176 // If the destination is in the same EH cleanup scope as us, we
1177 // don't need to thread through anything.
1178 if (Dest.getScopeDepth() == EHStack.getInnermostEHCleanup()) {
John McCallf1549f62010-07-06 01:34:17 +00001179 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001180 return;
1181 }
John McCallff8e1152010-07-23 21:56:41 +00001182 assert(EHStack.hasEHCleanups());
Mike Stump1eb44332009-09-09 15:08:12 +00001183
John McCallff8e1152010-07-23 21:56:41 +00001184 // Store the index at the start.
1185 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1186 new llvm::StoreInst(Index, getEHCleanupDestSlot(), BI);
John McCallf1549f62010-07-06 01:34:17 +00001187
John McCallff8e1152010-07-23 21:56:41 +00001188 // Adjust BI to point to the first cleanup block.
1189 {
1190 EHCleanupScope &Scope =
1191 cast<EHCleanupScope>(*EHStack.find(EHStack.getInnermostEHCleanup()));
1192 BI->setSuccessor(0, CreateEHEntry(*this, Scope));
1193 }
1194
1195 // Add this destination to all the scopes involved.
1196 for (EHScopeStack::stable_iterator
1197 I = EHStack.getInnermostEHCleanup(),
1198 E = Dest.getScopeDepth(); ; ) {
1199 assert(E.strictlyEncloses(I));
1200 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1201 assert(Scope.isEHCleanup());
1202 I = Scope.getEnclosingEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +00001203
John McCallff8e1152010-07-23 21:56:41 +00001204 // If this is the last cleanup we're propagating through, add this
1205 // as a branch-after.
1206 if (I == E) {
1207 Scope.addEHBranchAfter(Index, Dest.getBlock());
1208 break;
John McCallf1549f62010-07-06 01:34:17 +00001209 }
John McCallff8e1152010-07-23 21:56:41 +00001210
1211 // Otherwise, add it as a branch-through. If this isn't new
1212 // information, all the rest of the work has been done before.
1213 if (!Scope.addEHBranchThrough(Dest.getBlock()))
1214 break;
Anders Carlsson87eaf172009-02-08 00:50:42 +00001215 }
John McCallf1549f62010-07-06 01:34:17 +00001216
1217 Builder.ClearInsertionPoint();
Anders Carlsson87eaf172009-02-08 00:50:42 +00001218}
John McCallff8e1152010-07-23 21:56:41 +00001219
1220/// All the branch fixups on the EH stack have propagated out past the
1221/// outermost normal cleanup; resolve them all by adding cases to the
1222/// given switch instruction.
1223void CodeGenFunction::ResolveAllBranchFixups(llvm::SwitchInst *Switch) {
1224 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
1225
1226 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1227 // Skip this fixup if its destination isn't set or if we've
1228 // already treated it.
1229 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1230 if (Fixup.Destination == 0) continue;
1231 if (!CasesAdded.insert(Fixup.Destination)) continue;
1232
1233 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex),
1234 Fixup.Destination);
1235 }
1236
1237 EHStack.clearFixups();
1238}
1239
1240void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
1241 assert(Block && "resolving a null target block");
1242 if (!EHStack.getNumBranchFixups()) return;
1243
1244 assert(EHStack.hasNormalCleanups() &&
1245 "branch fixups exist with no normal cleanups on stack");
1246
1247 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
1248 bool ResolvedAny = false;
1249
1250 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
1251 // Skip this fixup if its destination doesn't match.
1252 BranchFixup &Fixup = EHStack.getBranchFixup(I);
1253 if (Fixup.Destination != Block) continue;
1254
1255 Fixup.Destination = 0;
1256 ResolvedAny = true;
1257
1258 // If it doesn't have an optimistic branch block, LatestBranch is
1259 // already pointing to the right place.
1260 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
1261 if (!BranchBB)
1262 continue;
1263
1264 // Don't process the same optimistic branch block twice.
1265 if (!ModifiedOptimisticBlocks.insert(BranchBB))
1266 continue;
1267
1268 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
1269
1270 // Add a case to the switch.
1271 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
1272 }
1273
1274 if (ResolvedAny)
1275 EHStack.popNullFixups();
1276}
1277
1278llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1279 if (!NormalCleanupDest)
1280 NormalCleanupDest =
1281 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1282 return NormalCleanupDest;
1283}
1284
1285llvm::Value *CodeGenFunction::getEHCleanupDestSlot() {
1286 if (!EHCleanupDest)
1287 EHCleanupDest =
1288 CreateTempAlloca(Builder.getInt32Ty(), "eh.cleanup.dest.slot");
1289 return EHCleanupDest;
1290}
Devang Patel8d308382010-08-10 07:24:25 +00001291
1292void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
Devang Patel25c2c8f2010-08-10 17:53:33 +00001293 llvm::ConstantInt *Init) {
1294 assert (Init && "Invalid DeclRefExpr initializer!");
1295 if (CGDebugInfo *Dbg = getDebugInfo())
1296 Dbg->EmitGlobalVariable(E->getDecl(), Init, Builder);
Devang Patel8d308382010-08-10 07:24:25 +00001297}