blob: d1168770ddb23ae07448fb84b845f64e0c059446 [file] [log] [blame]
Anders Carlsson046c2942010-04-17 20:15:18 +00001//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
Anders Carlssondbd920c2009-10-11 22:13:54 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
Anders Carlssondbd920c2009-10-11 22:13:54 +000014#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Anders Carlssond6b07fb2009-11-27 20:47:55 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssondbd920c2009-10-11 22:13:54 +000018#include "clang/AST/RecordLayout.h"
John McCall7a536902010-08-05 20:39:18 +000019#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000020#include "llvm/ADT/DenseSet.h"
Anders Carlssonb9021e92010-02-27 16:18:19 +000021#include "llvm/ADT/SetVector.h"
Chandler Carruthe087f072010-02-13 10:38:52 +000022#include "llvm/Support/Compiler.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000023#include "llvm/Support/Format.h"
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000024#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson5e454aa2010-03-17 20:06:32 +000025#include <algorithm>
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000026#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000027
28using namespace clang;
29using namespace CodeGen;
30
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000031CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32 : CGM(CGM), VTContext(CGM.getContext()) { }
33
Anders Carlsson19879c92010-03-23 17:17:29 +000034llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlsson84c49e42011-02-06 17:15:43 +000035 const ThunkInfo &Thunk) {
Anders Carlsson19879c92010-03-23 17:17:29 +000036 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
37
38 // Compute the mangled name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000039 SmallString<256> Name;
Rafael Espindolaf0be9792011-02-11 02:52:17 +000040 llvm::raw_svector_ostream Out(Name);
Anders Carlsson19879c92010-03-23 17:17:29 +000041 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall4c40d982010-08-31 07:33:07 +000042 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindolaf0be9792011-02-11 02:52:17 +000043 Thunk.This, Out);
Anders Carlsson19879c92010-03-23 17:17:29 +000044 else
Rafael Espindolaf0be9792011-02-11 02:52:17 +000045 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
46 Out.flush();
47
Chris Lattner2acc6e32011-07-18 04:24:23 +000048 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson84c49e42011-02-06 17:15:43 +000049 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
Anders Carlsson19879c92010-03-23 17:17:29 +000050}
51
Anders Carlsson519c3282010-03-24 00:39:18 +000052static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
53 llvm::Value *Ptr,
54 int64_t NonVirtualAdjustment,
Eli Friedman82bad6b2012-09-14 01:45:09 +000055 int64_t VirtualAdjustment,
56 bool IsReturnAdjustment) {
Anders Carlsson519c3282010-03-24 00:39:18 +000057 if (!NonVirtualAdjustment && !VirtualAdjustment)
58 return Ptr;
59
Chris Lattner8b418682012-02-07 00:39:47 +000060 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Anders Carlsson519c3282010-03-24 00:39:18 +000061 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
62
Eli Friedman82bad6b2012-09-14 01:45:09 +000063 if (NonVirtualAdjustment && !IsReturnAdjustment) {
64 // Perform the non-virtual adjustment for a base-to-derived cast.
Anders Carlsson519c3282010-03-24 00:39:18 +000065 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
66 }
67
68 if (VirtualAdjustment) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000069 llvm::Type *PtrDiffTy =
Anders Carlsson519c3282010-03-24 00:39:18 +000070 CGF.ConvertType(CGF.getContext().getPointerDiffType());
71
Eli Friedman82bad6b2012-09-14 01:45:09 +000072 // Perform the virtual adjustment.
Anders Carlsson519c3282010-03-24 00:39:18 +000073 llvm::Value *VTablePtrPtr =
74 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
75
76 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
77
78 llvm::Value *OffsetPtr =
79 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
80
81 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
82
83 // Load the adjustment offset from the vtable.
84 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
85
86 // Adjust our pointer.
87 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
88 }
89
Eli Friedman82bad6b2012-09-14 01:45:09 +000090 if (NonVirtualAdjustment && IsReturnAdjustment) {
91 // Perform the non-virtual adjustment for a derived-to-base cast.
92 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
93 }
94
Anders Carlsson519c3282010-03-24 00:39:18 +000095 // Cast back to the original type.
96 return CGF.Builder.CreateBitCast(V, Ptr->getType());
97}
98
John McCall65005532010-08-04 23:46:35 +000099static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
100 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000101 CGM.setGlobalVisibility(Fn, MD);
John McCall65005532010-08-04 23:46:35 +0000102
John McCall279b5eb2010-08-12 23:36:15 +0000103 if (!CGM.getCodeGenOpts().HiddenWeakVTables)
104 return;
105
John McCall65005532010-08-04 23:46:35 +0000106 // If the thunk has weak/linkonce linkage, but the function must be
107 // emitted in every translation unit that references it, then we can
108 // emit its thunks with hidden visibility, since its thunks must be
109 // emitted when the function is.
110
John McCall7a536902010-08-05 20:39:18 +0000111 // This follows CodeGenModule::setTypeVisibility; see the comments
112 // there for explanation.
John McCall65005532010-08-04 23:46:35 +0000113
114 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
115 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
116 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
117 return;
118
John McCalld4c3d662013-02-20 01:54:26 +0000119 if (MD->getExplicitVisibility(ValueDecl::VisibilityForValue))
John McCall65005532010-08-04 23:46:35 +0000120 return;
121
122 switch (MD->getTemplateSpecializationKind()) {
John McCall65005532010-08-04 23:46:35 +0000123 case TSK_ExplicitInstantiationDefinition:
124 case TSK_ExplicitInstantiationDeclaration:
125 return;
126
John McCall65005532010-08-04 23:46:35 +0000127 case TSK_Undeclared:
128 break;
129
John McCall7a536902010-08-05 20:39:18 +0000130 case TSK_ExplicitSpecialization:
John McCall65005532010-08-04 23:46:35 +0000131 case TSK_ImplicitInstantiation:
Douglas Gregoraafd1112012-10-24 14:11:55 +0000132 return;
John McCall65005532010-08-04 23:46:35 +0000133 break;
134 }
135
136 // If there's an explicit definition, and that definition is
137 // out-of-line, then we can't assume that all users will have a
138 // definition to emit.
139 const FunctionDecl *Def = 0;
140 if (MD->hasBody(Def) && Def->isOutOfLine())
141 return;
142
143 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
144}
145
John McCall311b4422011-03-09 07:12:35 +0000146#ifndef NDEBUG
147static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
148 const ABIArgInfo &infoR, CanQualType typeR) {
149 return (infoL.getKind() == infoR.getKind() &&
150 (typeL == typeR ||
151 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
152 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
153}
154#endif
155
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000156static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
157 QualType ResultType, RValue RV,
158 const ThunkInfo &Thunk) {
159 // Emit the return adjustment.
160 bool NullCheckValue = !ResultType->isReferenceType();
161
162 llvm::BasicBlock *AdjustNull = 0;
163 llvm::BasicBlock *AdjustNotNull = 0;
164 llvm::BasicBlock *AdjustEnd = 0;
165
166 llvm::Value *ReturnValue = RV.getScalarVal();
167
168 if (NullCheckValue) {
169 AdjustNull = CGF.createBasicBlock("adjust.null");
170 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
171 AdjustEnd = CGF.createBasicBlock("adjust.end");
172
173 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
174 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
175 CGF.EmitBlock(AdjustNotNull);
176 }
177
178 ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
179 Thunk.Return.NonVirtual,
Eli Friedman82bad6b2012-09-14 01:45:09 +0000180 Thunk.Return.VBaseOffsetOffset,
181 /*IsReturnAdjustment*/true);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000182
183 if (NullCheckValue) {
184 CGF.Builder.CreateBr(AdjustEnd);
185 CGF.EmitBlock(AdjustNull);
186 CGF.Builder.CreateBr(AdjustEnd);
187 CGF.EmitBlock(AdjustEnd);
188
189 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
190 PHI->addIncoming(ReturnValue, AdjustNotNull);
191 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
192 AdjustNull);
193 ReturnValue = PHI;
194 }
195
196 return RValue::get(ReturnValue);
197}
198
199// This function does roughly the same thing as GenerateThunk, but in a
200// very different way, so that va_start and va_end work correctly.
201// FIXME: This function assumes "this" is the first non-sret LLVM argument of
202// a function, and that there is an alloca built in the entry block
203// for all accesses to "this".
204// FIXME: This function assumes there is only one "ret" statement per function.
205// FIXME: Cloning isn't correct in the presence of indirect goto!
206// FIXME: This implementation of thunks bloats codesize by duplicating the
207// function definition. There are alternatives:
208// 1. Add some sort of stub support to LLVM for cases where we can
209// do a this adjustment, then a sibcall.
210// 2. We could transform the definition to take a va_list instead of an
211// actual variable argument list, then have the thunks (including a
212// no-op thunk for the regular definition) call va_start/va_end.
213// There's a bit of per-call overhead for this solution, but it's
214// better for codesize if the definition is long.
215void CodeGenFunction::GenerateVarArgsThunk(
216 llvm::Function *Fn,
217 const CGFunctionInfo &FnInfo,
218 GlobalDecl GD, const ThunkInfo &Thunk) {
219 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
220 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
221 QualType ResultType = FPT->getResultType();
222
223 // Get the original function
John McCallde5d3c72012-02-17 03:33:10 +0000224 assert(FnInfo.isVariadic());
225 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000226 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
227 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
228
229 // Clone to thunk.
Benjamin Kramer9b5ede52012-09-19 13:13:52 +0000230 llvm::ValueToValueMapTy VMap;
231 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
232 /*ModuleLevelChanges=*/false);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000233 CGM.getModule().getFunctionList().push_back(NewFn);
234 Fn->replaceAllUsesWith(NewFn);
235 NewFn->takeName(Fn);
236 Fn->eraseFromParent();
237 Fn = NewFn;
238
239 // "Initialize" CGF (minimally).
240 CurFn = Fn;
241
242 // Get the "this" value
243 llvm::Function::arg_iterator AI = Fn->arg_begin();
244 if (CGM.ReturnTypeUsesSRet(FnInfo))
245 ++AI;
246
247 // Find the first store of "this", which will be to the alloca associated
248 // with "this".
249 llvm::Value *ThisPtr = &*AI;
250 llvm::BasicBlock *EntryBB = Fn->begin();
251 llvm::Instruction *ThisStore = 0;
252 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
253 I != E; I++) {
254 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
255 ThisStore = cast<llvm::StoreInst>(I);
256 break;
257 }
258 }
259 assert(ThisStore && "Store of this should be in entry block?");
260 // Adjust "this", if necessary.
261 Builder.SetInsertPoint(ThisStore);
262 llvm::Value *AdjustedThisPtr =
263 PerformTypeAdjustment(*this, ThisPtr,
264 Thunk.This.NonVirtual,
Eli Friedman82bad6b2012-09-14 01:45:09 +0000265 Thunk.This.VCallOffsetOffset,
266 /*IsReturnAdjustment*/false);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000267 ThisStore->setOperand(0, AdjustedThisPtr);
268
269 if (!Thunk.Return.isEmpty()) {
270 // Fix up the returned value, if necessary.
271 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
272 llvm::Instruction *T = I->getTerminator();
273 if (isa<llvm::ReturnInst>(T)) {
274 RValue RV = RValue::get(T->getOperand(0));
275 T->eraseFromParent();
276 Builder.SetInsertPoint(&*I);
277 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
278 Builder.CreateRet(RV.getScalarVal());
279 break;
280 }
281 }
282 }
283}
284
John McCalld26bc762011-03-09 04:27:21 +0000285void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
286 const CGFunctionInfo &FnInfo,
287 GlobalDecl GD, const ThunkInfo &Thunk) {
Anders Carlsson519c3282010-03-24 00:39:18 +0000288 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
289 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlsson519c3282010-03-24 00:39:18 +0000290 QualType ThisType = MD->getThisType(getContext());
Stephen Lind4c0cd02013-06-18 17:00:49 +0000291 QualType ResultType =
292 CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getResultType();
Anders Carlsson519c3282010-03-24 00:39:18 +0000293
294 FunctionArgList FunctionArgs;
295
296 // FIXME: It would be nice if more of this code could be shared with
297 // CodeGenFunction::GenerateCode.
298
299 // Create the implicit 'this' parameter declaration.
John McCall4c40d982010-08-31 07:33:07 +0000300 CurGD = GD;
301 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
Anders Carlsson519c3282010-03-24 00:39:18 +0000302
303 // Add the rest of the parameters.
304 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
305 E = MD->param_end(); I != E; ++I) {
306 ParmVarDecl *Param = *I;
307
John McCalld26bc762011-03-09 04:27:21 +0000308 FunctionArgs.push_back(Param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000309 }
Alexey Samsonov34b41f82012-10-25 10:18:50 +0000310
311 // Initialize debug info if needed.
312 maybeInitializeDebugInfo();
313
John McCalld26bc762011-03-09 04:27:21 +0000314 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
315 SourceLocation());
Anders Carlsson519c3282010-03-24 00:39:18 +0000316
John McCall4c40d982010-08-31 07:33:07 +0000317 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000318 CXXThisValue = CXXABIThisValue;
John McCall4c40d982010-08-31 07:33:07 +0000319
Anders Carlsson519c3282010-03-24 00:39:18 +0000320 // Adjust the 'this' pointer if necessary.
321 llvm::Value *AdjustedThisPtr =
322 PerformTypeAdjustment(*this, LoadCXXThis(),
323 Thunk.This.NonVirtual,
Eli Friedman82bad6b2012-09-14 01:45:09 +0000324 Thunk.This.VCallOffsetOffset,
325 /*IsReturnAdjustment*/false);
Anders Carlsson519c3282010-03-24 00:39:18 +0000326
327 CallArgList CallArgs;
328
329 // Add our adjusted 'this' pointer.
Eli Friedman04c9a492011-05-02 17:57:46 +0000330 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000331
332 // Add the rest of the parameters.
333 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
334 E = MD->param_end(); I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +0000335 ParmVarDecl *param = *I;
336 EmitDelegateCallArg(CallArgs, param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000337 }
338
339 // Get our callee.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000340 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +0000341 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
Anders Carlsson84c49e42011-02-06 17:15:43 +0000342 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson519c3282010-03-24 00:39:18 +0000343
John McCalld26bc762011-03-09 04:27:21 +0000344#ifndef NDEBUG
John McCall0f3d0972012-07-07 06:41:13 +0000345 const CGFunctionInfo &CallFnInfo =
346 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCallde5d3c72012-02-17 03:33:10 +0000347 RequiredArgs::forPrototypePlus(FPT, 1));
John McCall311b4422011-03-09 07:12:35 +0000348 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
349 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
350 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
John McCall0f3d0972012-07-07 06:41:13 +0000351 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
352 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
John McCall311b4422011-03-09 07:12:35 +0000353 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
354 assert(CallFnInfo.arg_size() == FnInfo.arg_size());
355 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
356 assert(similar(CallFnInfo.arg_begin()[i].info,
357 CallFnInfo.arg_begin()[i].type,
358 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
John McCalld26bc762011-03-09 04:27:21 +0000359#endif
Anders Carlsson519c3282010-03-24 00:39:18 +0000360
Douglas Gregorcb359df2010-05-20 05:54:35 +0000361 // Determine whether we have a return value slot to use.
362 ReturnValueSlot Slot;
363 if (!ResultType->isVoidType() &&
364 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +0000365 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregorcb359df2010-05-20 05:54:35 +0000366 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
367
Anders Carlsson519c3282010-03-24 00:39:18 +0000368 // Now emit our call.
Douglas Gregorcb359df2010-05-20 05:54:35 +0000369 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
Anders Carlsson519c3282010-03-24 00:39:18 +0000370
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000371 if (!Thunk.Return.isEmpty())
372 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000373
Douglas Gregorcb359df2010-05-20 05:54:35 +0000374 if (!ResultType->isVoidType() && Slot.isNull())
John McCalld16c2cf2011-02-08 08:22:06 +0000375 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000376
John McCallbd9b65a2012-07-31 00:33:55 +0000377 // Disable the final ARC autorelease.
378 AutoreleaseResult = false;
379
Anders Carlsson519c3282010-03-24 00:39:18 +0000380 FinishFunction();
381
Anders Carlsson519c3282010-03-24 00:39:18 +0000382 // Set the right linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000383 CGM.setFunctionLinkage(GD, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000384
385 // Set the right visibility.
John McCall65005532010-08-04 23:46:35 +0000386 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000387}
388
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000389void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
390 bool UseAvailableExternallyLinkage)
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000391{
John McCallde5d3c72012-02-17 03:33:10 +0000392 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalld26bc762011-03-09 04:27:21 +0000393
394 // FIXME: re-use FnInfo in this computation.
Anders Carlsson84c49e42011-02-06 17:15:43 +0000395 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson19879c92010-03-23 17:17:29 +0000396
Anders Carlsson7986ad52010-03-23 18:18:41 +0000397 // Strip off a bitcast if we got one back.
Anders Carlsson13d68982010-03-24 00:35:44 +0000398 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Anders Carlsson7986ad52010-03-23 18:18:41 +0000399 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Anders Carlsson13d68982010-03-24 00:35:44 +0000400 Entry = CE->getOperand(0);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000401 }
402
Anders Carlsson7986ad52010-03-23 18:18:41 +0000403 // There's already a declaration with the same name, check if it has the same
404 // type or if we need to replace it.
Anders Carlsson13d68982010-03-24 00:35:44 +0000405 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
John McCall4c40d982010-08-31 07:33:07 +0000406 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Anders Carlsson13d68982010-03-24 00:35:44 +0000407 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000408
409 // If the types mismatch then we have to rewrite the definition.
410 assert(OldThunkFn->isDeclaration() &&
411 "Shouldn't replace non-declaration");
412
413 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000414 OldThunkFn->setName(StringRef());
Anders Carlsson84c49e42011-02-06 17:15:43 +0000415 Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000416
417 // If needed, replace the old thunk with a bitcast.
418 if (!OldThunkFn->use_empty()) {
419 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson13d68982010-03-24 00:35:44 +0000420 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson7986ad52010-03-23 18:18:41 +0000421 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
422 }
423
424 // Remove the old thunk.
425 OldThunkFn->eraseFromParent();
426 }
Anders Carlsson519c3282010-03-24 00:39:18 +0000427
Anders Carlsson519c3282010-03-24 00:39:18 +0000428 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000429
430 if (!ThunkFn->isDeclaration()) {
431 if (UseAvailableExternallyLinkage) {
432 // There is already a thunk emitted for this function, do nothing.
433 return;
434 }
435
Anders Carlsson22df7b12011-02-06 20:09:44 +0000436 // If a function has a body, it should have available_externally linkage.
437 assert(ThunkFn->hasAvailableExternallyLinkage() &&
438 "Function should have available_externally linkage!");
439
440 // Change the linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000441 CGM.setFunctionLinkage(GD, ThunkFn);
Anders Carlsson22df7b12011-02-06 20:09:44 +0000442 return;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000443 }
444
Rafael Espindola022301b2012-09-21 20:39:32 +0000445 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
446
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000447 if (ThunkFn->isVarArg()) {
448 // Varargs thunks are special; we can't just generate a call because
449 // we can't copy the varargs. Our implementation is rather
450 // expensive/sucky at the moment, so don't generate the thunk unless
451 // we have to.
452 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
453 if (!UseAvailableExternallyLinkage)
454 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
455 } else {
456 // Normal thunk body generation.
457 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
458 }
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000459
460 if (UseAvailableExternallyLinkage)
461 ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
462}
463
464void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
465 const ThunkInfo &Thunk) {
466 // We only want to do this when building with optimizations.
467 if (!CGM.getCodeGenOpts().OptimizationLevel)
468 return;
469
470 // We can't emit thunks for member functions with incomplete types.
471 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000472 if (!CGM.getTypes().isFuncTypeConvertible(
473 cast<FunctionType>(MD->getType().getTypePtr())))
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000474 return;
475
476 EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000477}
478
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000479void CodeGenVTables::EmitThunks(GlobalDecl GD)
480{
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000481 const CXXMethodDecl *MD =
482 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
483
484 // We don't need to generate thunks for the base destructor.
485 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
486 return;
487
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000488 const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
489 VTContext.getThunkInfo(MD);
490 if (!ThunkInfoVector)
Anders Carlssonccd83d72010-03-24 16:42:11 +0000491 return;
Anders Carlssonccd83d72010-03-24 16:42:11 +0000492
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000493 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
494 EmitThunk(GD, (*ThunkInfoVector)[I],
495 /*UseAvailableExternallyLinkage=*/false);
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000496}
497
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000498llvm::Constant *
499CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000500 const VTableComponent *Components,
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000501 unsigned NumComponents,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000502 const VTableLayout::VTableThunkTy *VTableThunks,
503 unsigned NumVTableThunks) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000505
Chris Lattner8b418682012-02-07 00:39:47 +0000506 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000507
Chris Lattner2acc6e32011-07-18 04:24:23 +0000508 llvm::Type *PtrDiffTy =
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000509 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
510
511 QualType ClassType = CGM.getContext().getTagDeclType(RD);
512 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
513
514 unsigned NextVTableThunkIndex = 0;
515
David Blaikie2eb9a952012-10-16 22:56:05 +0000516 llvm::Constant *PureVirtualFn = 0, *DeletedVirtualFn = 0;
Anders Carlsson67d568a2010-03-29 05:40:50 +0000517
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000518 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000519 VTableComponent Component = Components[I];
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000520
521 llvm::Constant *Init = 0;
522
523 switch (Component.getKind()) {
Anders Carlsson94464812010-04-10 19:13:06 +0000524 case VTableComponent::CK_VCallOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000525 Init = llvm::ConstantInt::get(PtrDiffTy,
526 Component.getVCallOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000527 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
528 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000529 case VTableComponent::CK_VBaseOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000530 Init = llvm::ConstantInt::get(PtrDiffTy,
531 Component.getVBaseOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000532 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
533 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000534 case VTableComponent::CK_OffsetToTop:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000535 Init = llvm::ConstantInt::get(PtrDiffTy,
536 Component.getOffsetToTop().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000537 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
538 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000539 case VTableComponent::CK_RTTI:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000540 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
541 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000542 case VTableComponent::CK_FunctionPointer:
543 case VTableComponent::CK_CompleteDtorPointer:
544 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000545 GlobalDecl GD;
546
547 // Get the right global decl.
548 switch (Component.getKind()) {
549 default:
550 llvm_unreachable("Unexpected vtable component kind");
Anders Carlsson94464812010-04-10 19:13:06 +0000551 case VTableComponent::CK_FunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000552 GD = Component.getFunctionDecl();
553 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000554 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000555 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
556 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000557 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000558 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
559 break;
560 }
561
Anders Carlsson67d568a2010-03-29 05:40:50 +0000562 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
563 // We have a pure virtual member function.
Joao Matose9af3e62012-07-17 19:17:58 +0000564 if (!PureVirtualFn) {
Eli Friedmancf15f172012-09-14 01:19:01 +0000565 llvm::FunctionType *Ty =
566 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
567 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
568 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
569 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matose9af3e62012-07-17 19:17:58 +0000570 CGM.Int8PtrTy);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000571 }
Anders Carlsson67d568a2010-03-29 05:40:50 +0000572 Init = PureVirtualFn;
David Blaikie2eb9a952012-10-16 22:56:05 +0000573 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
574 if (!DeletedVirtualFn) {
575 llvm::FunctionType *Ty =
576 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
577 StringRef DeletedCallName =
578 CGM.getCXXABI().GetDeletedVirtualCallName();
579 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
580 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
581 CGM.Int8PtrTy);
582 }
583 Init = DeletedVirtualFn;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000584 } else {
Anders Carlsson67d568a2010-03-29 05:40:50 +0000585 // Check if we should use a thunk.
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000586 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlsson67d568a2010-03-29 05:40:50 +0000587 VTableThunks[NextVTableThunkIndex].first == I) {
588 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000589
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000590 MaybeEmitThunkAvailableExternally(GD, Thunk);
Benjamin Kramerfce80092012-03-20 20:18:13 +0000591 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000592
Anders Carlsson67d568a2010-03-29 05:40:50 +0000593 NextVTableThunkIndex++;
594 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000595 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000596
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000597 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000598 }
599
600 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000601 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000602 break;
603 }
604
Anders Carlsson94464812010-04-10 19:13:06 +0000605 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000606 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
607 break;
608 };
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000609
610 Inits.push_back(Init);
611 }
612
613 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad97357602011-06-22 09:24:39 +0000614 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000615}
616
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000617llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000618 llvm::GlobalVariable *&VTable = VTables[RD];
619 if (VTable)
620 return VTable;
621
John McCalld5617ee2013-01-25 22:31:03 +0000622 // Queue up this v-table for possible deferred emission.
623 CGM.addDeferredVTable(RD);
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000624
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000625 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000626 llvm::raw_svector_ostream Out(OutName);
627 CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
628 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000629 StringRef Name = OutName.str();
Mike Stump85615df2009-11-19 04:04:36 +0000630
Anders Carlssonccd83d72010-03-24 16:42:11 +0000631 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000632 llvm::ArrayType::get(CGM.Int8PtrTy,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000633 VTContext.getVTableLayout(RD).getNumVTableComponents());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000634
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000635 VTable =
Anders Carlsson96eaf292011-01-29 18:25:07 +0000636 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
637 llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000638 VTable->setUnnamedAddr(true);
639 return VTable;
Mike Stump380dd752009-11-10 07:44:33 +0000640}
Mike Stump8cfcb522009-11-11 20:26:26 +0000641
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000642void
643CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
644 llvm::GlobalVariable::LinkageTypes Linkage,
645 const CXXRecordDecl *RD) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000646 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
647
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000648 // Create and set the initializer.
649 llvm::Constant *Init =
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000650 CreateVTableInitializer(RD,
651 VTLayout.vtable_component_begin(),
652 VTLayout.getNumVTableComponents(),
653 VTLayout.vtable_thunk_begin(),
654 VTLayout.getNumVTableThunks());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000655 VTable->setInitializer(Init);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000656
657 // Set the correct linkage.
658 VTable->setLinkage(Linkage);
Douglas Gregorc66bcfd2010-06-14 23:41:45 +0000659
660 // Set the right visibility.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000661 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000662}
663
Anders Carlssonff143f82010-03-25 00:35:49 +0000664llvm::GlobalVariable *
665CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000666 const BaseSubobject &Base,
667 bool BaseIsVirtual,
John McCallbda0d6b2011-03-27 09:00:25 +0000668 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000669 VTableAddressPointsMapTy& AddressPoints) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000670 OwningPtr<VTableLayout> VTLayout(
Peter Collingbourneab172b52011-09-26 01:57:04 +0000671 VTContext.createConstructionVTableLayout(Base.getBase(),
672 Base.getBaseOffset(),
673 BaseIsVirtual, RD));
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000674
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000675 // Add the address points.
Peter Collingbourneab172b52011-09-26 01:57:04 +0000676 AddressPoints = VTLayout->getAddressPoints();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000677
678 // Get the mangled construction vtable name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000679 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000680 llvm::raw_svector_ostream Out(OutName);
John McCall4c40d982010-08-31 07:33:07 +0000681 CGM.getCXXABI().getMangleContext().
Ken Dyck4230d522011-03-24 01:21:01 +0000682 mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
683 Out);
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000684 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000685 StringRef Name = OutName.str();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000686
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000687 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000688 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000689
Richard Smithb4127a22013-02-16 00:51:21 +0000690 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
691 // guarantee that they actually will be available externally. Instead, when
692 // emitting an available_externally VTT, we provide references to an internal
693 // linkage construction vtable. The ABI only requires complete-object vtables
694 // to be the same for all instances of a type, not construction vtables.
695 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
696 Linkage = llvm::GlobalVariable::InternalLinkage;
697
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000698 // Create the variable that will hold the construction vtable.
699 llvm::GlobalVariable *VTable =
John McCallbda0d6b2011-03-27 09:00:25 +0000700 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
701 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
702
703 // V-tables are always unnamed_addr.
704 VTable->setUnnamedAddr(true);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000705
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000706 // Create and set the initializer.
707 llvm::Constant *Init =
708 CreateVTableInitializer(Base.getBase(),
Peter Collingbourneab172b52011-09-26 01:57:04 +0000709 VTLayout->vtable_component_begin(),
710 VTLayout->getNumVTableComponents(),
711 VTLayout->vtable_thunk_begin(),
712 VTLayout->getNumVTableThunks());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000713 VTable->setInitializer(Init);
714
Anders Carlssonff143f82010-03-25 00:35:49 +0000715 return VTable;
716}
717
John McCalld5617ee2013-01-25 22:31:03 +0000718/// Compute the required linkage of the v-table for the given class.
719///
720/// Note that we only call this at the end of the translation unit.
721llvm::GlobalVariable::LinkageTypes
722CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000723 if (!RD->isExternallyVisible())
John McCalld5617ee2013-01-25 22:31:03 +0000724 return llvm::GlobalVariable::InternalLinkage;
725
726 // We're at the end of the translation unit, so the current key
727 // function is fully correct.
728 if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
729 // If this class has a key function, use that to determine the
730 // linkage of the vtable.
731 const FunctionDecl *def = 0;
732 if (keyFunction->hasBody(def))
733 keyFunction = cast<CXXMethodDecl>(def);
734
735 switch (keyFunction->getTemplateSpecializationKind()) {
736 case TSK_Undeclared:
737 case TSK_ExplicitSpecialization:
738 // When compiling with optimizations turned on, we emit all vtables,
739 // even if the key function is not defined in the current translation
740 // unit. If this is the case, use available_externally linkage.
741 if (!def && CodeGenOpts.OptimizationLevel)
742 return llvm::GlobalVariable::AvailableExternallyLinkage;
743
744 if (keyFunction->isInlined())
745 return !Context.getLangOpts().AppleKext ?
746 llvm::GlobalVariable::LinkOnceODRLinkage :
747 llvm::Function::InternalLinkage;
748
749 return llvm::GlobalVariable::ExternalLinkage;
750
751 case TSK_ImplicitInstantiation:
752 return !Context.getLangOpts().AppleKext ?
753 llvm::GlobalVariable::LinkOnceODRLinkage :
754 llvm::Function::InternalLinkage;
755
756 case TSK_ExplicitInstantiationDefinition:
757 return !Context.getLangOpts().AppleKext ?
758 llvm::GlobalVariable::WeakODRLinkage :
759 llvm::Function::InternalLinkage;
760
761 case TSK_ExplicitInstantiationDeclaration:
John McCalld5617ee2013-01-25 22:31:03 +0000762 return !Context.getLangOpts().AppleKext ?
Richard Smithb4127a22013-02-16 00:51:21 +0000763 llvm::GlobalVariable::AvailableExternallyLinkage :
John McCalld5617ee2013-01-25 22:31:03 +0000764 llvm::Function::InternalLinkage;
765 }
766 }
767
768 // -fapple-kext mode does not support weak linkage, so we must use
769 // internal linkage.
770 if (Context.getLangOpts().AppleKext)
771 return llvm::Function::InternalLinkage;
772
773 switch (RD->getTemplateSpecializationKind()) {
774 case TSK_Undeclared:
775 case TSK_ExplicitSpecialization:
776 case TSK_ImplicitInstantiation:
777 return llvm::GlobalVariable::LinkOnceODRLinkage;
778
779 case TSK_ExplicitInstantiationDeclaration:
Richard Smithb4127a22013-02-16 00:51:21 +0000780 return llvm::GlobalVariable::AvailableExternallyLinkage;
John McCalld5617ee2013-01-25 22:31:03 +0000781
782 case TSK_ExplicitInstantiationDefinition:
783 return llvm::GlobalVariable::WeakODRLinkage;
784 }
785
786 llvm_unreachable("Invalid TemplateSpecializationKind!");
787}
788
789/// This is a callback from Sema to tell us that it believes that a
790/// particular v-table is required to be emitted in this translation
791/// unit.
792///
793/// The reason we don't simply trust this callback is because Sema
794/// will happily report that something is used even when it's used
795/// only in code that we don't actually have to emit.
796///
797/// \param isRequired - if true, the v-table is mandatory, e.g.
798/// because the translation unit defines the key function
799void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
800 if (!isRequired) return;
801
802 VTables.GenerateClassData(theClass);
803}
804
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000805void
John McCalld5617ee2013-01-25 22:31:03 +0000806CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
807 // First off, check whether we've already emitted the v-table and
808 // associated stuff.
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000809 llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
810 if (VTable->hasInitializer())
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000811 return;
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000812
John McCalld5617ee2013-01-25 22:31:03 +0000813 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000814 EmitVTableDefinition(VTable, Linkage, RD);
815
Anders Carlsson1cbce122011-01-29 19:16:51 +0000816 if (RD->getNumVBases()) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000817 if (!CGM.getTarget().getCXXABI().isMicrosoft()) {
818 llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
819 EmitVTTDefinition(VTT, Linkage, RD);
820 } else {
821 // FIXME: Emit vbtables here.
822 }
Anders Carlsson1cbce122011-01-29 19:16:51 +0000823 }
Douglas Gregor1e201b42010-04-08 15:52:03 +0000824
825 // If this is the magic class __cxxabiv1::__fundamental_type_info,
826 // we will emit the typeinfo for the fundamental types. This is the
827 // same behaviour as GCC.
828 const DeclContext *DC = RD->getDeclContext();
829 if (RD->getIdentifier() &&
830 RD->getIdentifier()->isStr("__fundamental_type_info") &&
831 isa<NamespaceDecl>(DC) &&
832 cast<NamespaceDecl>(DC)->getIdentifier() &&
833 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
834 DC->getParent()->isTranslationUnit())
835 CGM.EmitFundamentalRTTIDescriptors();
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000836}
John McCalld5617ee2013-01-25 22:31:03 +0000837
838/// At this point in the translation unit, does it appear that can we
839/// rely on the vtable being defined elsewhere in the program?
840///
841/// The response is really only definitive when called at the end of
842/// the translation unit.
843///
844/// The only semantic restriction here is that the object file should
845/// not contain a v-table definition when that v-table is defined
846/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
847/// v-tables when unnecessary.
848bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
849 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
850
851 // If we have an explicit instantiation declaration (and not a
852 // definition), the v-table is defined elsewhere.
853 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
854 if (TSK == TSK_ExplicitInstantiationDeclaration)
855 return true;
856
857 // Otherwise, if the class is an instantiated template, the
858 // v-table must be defined here.
859 if (TSK == TSK_ImplicitInstantiation ||
860 TSK == TSK_ExplicitInstantiationDefinition)
861 return false;
862
863 // Otherwise, if the class doesn't have a key function (possibly
864 // anymore), the v-table must be defined here.
865 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
866 if (!keyFunction)
867 return false;
868
869 // Otherwise, if we don't have a definition of the key function, the
870 // v-table must be defined somewhere else.
871 return !keyFunction->hasBody();
872}
873
874/// Given that we're currently at the end of the translation unit, and
875/// we've emitted a reference to the v-table for this class, should
876/// we define that v-table?
877static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
878 const CXXRecordDecl *RD) {
879 // If we're building with optimization, we always emit v-tables
880 // since that allows for virtual function calls to be devirtualized.
881 // If the v-table is defined strongly elsewhere, this definition
882 // will be emitted available_externally.
883 //
884 // However, we don't want to do this in -fapple-kext mode, because
885 // kext mode does not permit devirtualization.
886 if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOpts().AppleKext)
887 return true;
888
889 return !CGM.getVTables().isVTableExternal(RD);
890}
891
892/// Given that at some point we emitted a reference to one or more
893/// v-tables, and that we are now at the end of the translation unit,
894/// decide whether we should emit them.
895void CodeGenModule::EmitDeferredVTables() {
896#ifndef NDEBUG
897 // Remember the size of DeferredVTables, because we're going to assume
898 // that this entire operation doesn't modify it.
899 size_t savedSize = DeferredVTables.size();
900#endif
901
902 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
903 for (const_iterator i = DeferredVTables.begin(),
904 e = DeferredVTables.end(); i != e; ++i) {
905 const CXXRecordDecl *RD = *i;
906 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
907 VTables.GenerateClassData(RD);
908 }
909
910 assert(savedSize == DeferredVTables.size() &&
911 "deferred extra v-tables during v-table emission?");
912 DeferredVTables.clear();
913}