blob: 6eb3e89d27332bb107d9fdbcce235e38064f6dcf [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)
Timur Iskhodzhanov635de282013-07-30 09:46:19 +000032 : CGM(CGM), VTContext(CGM.getContext()) {
33 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
34 // FIXME: Eventually, we should only have one of V*TContexts available.
35 // Today we use both in the Microsoft ABI as MicrosoftVFTableContext
36 // is not completely supported in CodeGen yet.
37 VFTContext.reset(new MicrosoftVFTableContext(CGM.getContext()));
38 }
39}
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000040
Anders Carlsson19879c92010-03-23 17:17:29 +000041llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlsson84c49e42011-02-06 17:15:43 +000042 const ThunkInfo &Thunk) {
Anders Carlsson19879c92010-03-23 17:17:29 +000043 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
44
45 // Compute the mangled name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000046 SmallString<256> Name;
Rafael Espindolaf0be9792011-02-11 02:52:17 +000047 llvm::raw_svector_ostream Out(Name);
Anders Carlsson19879c92010-03-23 17:17:29 +000048 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall4c40d982010-08-31 07:33:07 +000049 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindolaf0be9792011-02-11 02:52:17 +000050 Thunk.This, Out);
Anders Carlsson19879c92010-03-23 17:17:29 +000051 else
Rafael Espindolaf0be9792011-02-11 02:52:17 +000052 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
53 Out.flush();
54
Chris Lattner2acc6e32011-07-18 04:24:23 +000055 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson84c49e42011-02-06 17:15:43 +000056 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
Anders Carlsson19879c92010-03-23 17:17:29 +000057}
58
Anders Carlsson519c3282010-03-24 00:39:18 +000059static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
60 llvm::Value *Ptr,
61 int64_t NonVirtualAdjustment,
Eli Friedman82bad6b2012-09-14 01:45:09 +000062 int64_t VirtualAdjustment,
63 bool IsReturnAdjustment) {
Anders Carlsson519c3282010-03-24 00:39:18 +000064 if (!NonVirtualAdjustment && !VirtualAdjustment)
65 return Ptr;
66
Chris Lattner8b418682012-02-07 00:39:47 +000067 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Anders Carlsson519c3282010-03-24 00:39:18 +000068 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
69
Eli Friedman82bad6b2012-09-14 01:45:09 +000070 if (NonVirtualAdjustment && !IsReturnAdjustment) {
71 // Perform the non-virtual adjustment for a base-to-derived cast.
Anders Carlsson519c3282010-03-24 00:39:18 +000072 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
73 }
74
75 if (VirtualAdjustment) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000076 llvm::Type *PtrDiffTy =
Anders Carlsson519c3282010-03-24 00:39:18 +000077 CGF.ConvertType(CGF.getContext().getPointerDiffType());
78
Eli Friedman82bad6b2012-09-14 01:45:09 +000079 // Perform the virtual adjustment.
Anders Carlsson519c3282010-03-24 00:39:18 +000080 llvm::Value *VTablePtrPtr =
81 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
82
83 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
84
85 llvm::Value *OffsetPtr =
86 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
87
88 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
89
90 // Load the adjustment offset from the vtable.
91 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
92
93 // Adjust our pointer.
94 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
95 }
96
Eli Friedman82bad6b2012-09-14 01:45:09 +000097 if (NonVirtualAdjustment && IsReturnAdjustment) {
98 // Perform the non-virtual adjustment for a derived-to-base cast.
99 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
100 }
101
Anders Carlsson519c3282010-03-24 00:39:18 +0000102 // Cast back to the original type.
103 return CGF.Builder.CreateBitCast(V, Ptr->getType());
104}
105
John McCall65005532010-08-04 23:46:35 +0000106static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
107 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000108 CGM.setGlobalVisibility(Fn, MD);
John McCall65005532010-08-04 23:46:35 +0000109
John McCall279b5eb2010-08-12 23:36:15 +0000110 if (!CGM.getCodeGenOpts().HiddenWeakVTables)
111 return;
112
John McCall65005532010-08-04 23:46:35 +0000113 // If the thunk has weak/linkonce linkage, but the function must be
114 // emitted in every translation unit that references it, then we can
115 // emit its thunks with hidden visibility, since its thunks must be
116 // emitted when the function is.
117
John McCall7a536902010-08-05 20:39:18 +0000118 // This follows CodeGenModule::setTypeVisibility; see the comments
119 // there for explanation.
John McCall65005532010-08-04 23:46:35 +0000120
121 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
122 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
123 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
124 return;
125
John McCalld4c3d662013-02-20 01:54:26 +0000126 if (MD->getExplicitVisibility(ValueDecl::VisibilityForValue))
John McCall65005532010-08-04 23:46:35 +0000127 return;
128
129 switch (MD->getTemplateSpecializationKind()) {
John McCall65005532010-08-04 23:46:35 +0000130 case TSK_ExplicitInstantiationDefinition:
131 case TSK_ExplicitInstantiationDeclaration:
132 return;
133
John McCall65005532010-08-04 23:46:35 +0000134 case TSK_Undeclared:
135 break;
136
John McCall7a536902010-08-05 20:39:18 +0000137 case TSK_ExplicitSpecialization:
John McCall65005532010-08-04 23:46:35 +0000138 case TSK_ImplicitInstantiation:
Douglas Gregoraafd1112012-10-24 14:11:55 +0000139 return;
John McCall65005532010-08-04 23:46:35 +0000140 break;
141 }
142
143 // If there's an explicit definition, and that definition is
144 // out-of-line, then we can't assume that all users will have a
145 // definition to emit.
146 const FunctionDecl *Def = 0;
147 if (MD->hasBody(Def) && Def->isOutOfLine())
148 return;
149
150 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
151}
152
John McCall311b4422011-03-09 07:12:35 +0000153#ifndef NDEBUG
154static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
155 const ABIArgInfo &infoR, CanQualType typeR) {
156 return (infoL.getKind() == infoR.getKind() &&
157 (typeL == typeR ||
158 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
159 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
160}
161#endif
162
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000163static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
164 QualType ResultType, RValue RV,
165 const ThunkInfo &Thunk) {
166 // Emit the return adjustment.
167 bool NullCheckValue = !ResultType->isReferenceType();
168
169 llvm::BasicBlock *AdjustNull = 0;
170 llvm::BasicBlock *AdjustNotNull = 0;
171 llvm::BasicBlock *AdjustEnd = 0;
172
173 llvm::Value *ReturnValue = RV.getScalarVal();
174
175 if (NullCheckValue) {
176 AdjustNull = CGF.createBasicBlock("adjust.null");
177 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
178 AdjustEnd = CGF.createBasicBlock("adjust.end");
179
180 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
181 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
182 CGF.EmitBlock(AdjustNotNull);
183 }
184
185 ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
186 Thunk.Return.NonVirtual,
Eli Friedman82bad6b2012-09-14 01:45:09 +0000187 Thunk.Return.VBaseOffsetOffset,
188 /*IsReturnAdjustment*/true);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000189
190 if (NullCheckValue) {
191 CGF.Builder.CreateBr(AdjustEnd);
192 CGF.EmitBlock(AdjustNull);
193 CGF.Builder.CreateBr(AdjustEnd);
194 CGF.EmitBlock(AdjustEnd);
195
196 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
197 PHI->addIncoming(ReturnValue, AdjustNotNull);
198 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
199 AdjustNull);
200 ReturnValue = PHI;
201 }
202
203 return RValue::get(ReturnValue);
204}
205
206// This function does roughly the same thing as GenerateThunk, but in a
207// very different way, so that va_start and va_end work correctly.
208// FIXME: This function assumes "this" is the first non-sret LLVM argument of
209// a function, and that there is an alloca built in the entry block
210// for all accesses to "this".
211// FIXME: This function assumes there is only one "ret" statement per function.
212// FIXME: Cloning isn't correct in the presence of indirect goto!
213// FIXME: This implementation of thunks bloats codesize by duplicating the
214// function definition. There are alternatives:
215// 1. Add some sort of stub support to LLVM for cases where we can
216// do a this adjustment, then a sibcall.
217// 2. We could transform the definition to take a va_list instead of an
218// actual variable argument list, then have the thunks (including a
219// no-op thunk for the regular definition) call va_start/va_end.
220// There's a bit of per-call overhead for this solution, but it's
221// better for codesize if the definition is long.
222void CodeGenFunction::GenerateVarArgsThunk(
223 llvm::Function *Fn,
224 const CGFunctionInfo &FnInfo,
225 GlobalDecl GD, const ThunkInfo &Thunk) {
226 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
227 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
228 QualType ResultType = FPT->getResultType();
229
230 // Get the original function
John McCallde5d3c72012-02-17 03:33:10 +0000231 assert(FnInfo.isVariadic());
232 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000233 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
234 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
235
236 // Clone to thunk.
Benjamin Kramer9b5ede52012-09-19 13:13:52 +0000237 llvm::ValueToValueMapTy VMap;
238 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
239 /*ModuleLevelChanges=*/false);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000240 CGM.getModule().getFunctionList().push_back(NewFn);
241 Fn->replaceAllUsesWith(NewFn);
242 NewFn->takeName(Fn);
243 Fn->eraseFromParent();
244 Fn = NewFn;
245
246 // "Initialize" CGF (minimally).
247 CurFn = Fn;
248
249 // Get the "this" value
250 llvm::Function::arg_iterator AI = Fn->arg_begin();
251 if (CGM.ReturnTypeUsesSRet(FnInfo))
252 ++AI;
253
254 // Find the first store of "this", which will be to the alloca associated
255 // with "this".
256 llvm::Value *ThisPtr = &*AI;
257 llvm::BasicBlock *EntryBB = Fn->begin();
258 llvm::Instruction *ThisStore = 0;
259 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
260 I != E; I++) {
261 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
262 ThisStore = cast<llvm::StoreInst>(I);
263 break;
264 }
265 }
266 assert(ThisStore && "Store of this should be in entry block?");
267 // Adjust "this", if necessary.
268 Builder.SetInsertPoint(ThisStore);
269 llvm::Value *AdjustedThisPtr =
270 PerformTypeAdjustment(*this, ThisPtr,
271 Thunk.This.NonVirtual,
Eli Friedman82bad6b2012-09-14 01:45:09 +0000272 Thunk.This.VCallOffsetOffset,
273 /*IsReturnAdjustment*/false);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000274 ThisStore->setOperand(0, AdjustedThisPtr);
275
276 if (!Thunk.Return.isEmpty()) {
277 // Fix up the returned value, if necessary.
278 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
279 llvm::Instruction *T = I->getTerminator();
280 if (isa<llvm::ReturnInst>(T)) {
281 RValue RV = RValue::get(T->getOperand(0));
282 T->eraseFromParent();
283 Builder.SetInsertPoint(&*I);
284 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
285 Builder.CreateRet(RV.getScalarVal());
286 break;
287 }
288 }
289 }
290}
291
John McCalld26bc762011-03-09 04:27:21 +0000292void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
293 const CGFunctionInfo &FnInfo,
294 GlobalDecl GD, const ThunkInfo &Thunk) {
David Blaikie1942e182013-08-27 05:21:11 +0000295 DebugInfo = NULL; // debug info for thunks is not required or desired
Anders Carlsson519c3282010-03-24 00:39:18 +0000296 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
297 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlsson519c3282010-03-24 00:39:18 +0000298 QualType ThisType = MD->getThisType(getContext());
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000299 QualType ResultType =
300 CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getResultType();
Anders Carlsson519c3282010-03-24 00:39:18 +0000301
302 FunctionArgList FunctionArgs;
303
304 // FIXME: It would be nice if more of this code could be shared with
305 // CodeGenFunction::GenerateCode.
306
307 // Create the implicit 'this' parameter declaration.
John McCall4c40d982010-08-31 07:33:07 +0000308 CurGD = GD;
309 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
Anders Carlsson519c3282010-03-24 00:39:18 +0000310
311 // Add the rest of the parameters.
312 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
313 E = MD->param_end(); I != E; ++I) {
314 ParmVarDecl *Param = *I;
315
John McCalld26bc762011-03-09 04:27:21 +0000316 FunctionArgs.push_back(Param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000317 }
Alexey Samsonov34b41f82012-10-25 10:18:50 +0000318
John McCalld26bc762011-03-09 04:27:21 +0000319 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
320 SourceLocation());
Anders Carlsson519c3282010-03-24 00:39:18 +0000321
John McCall4c40d982010-08-31 07:33:07 +0000322 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000323 CXXThisValue = CXXABIThisValue;
John McCall4c40d982010-08-31 07:33:07 +0000324
Anders Carlsson519c3282010-03-24 00:39:18 +0000325 // Adjust the 'this' pointer if necessary.
326 llvm::Value *AdjustedThisPtr =
327 PerformTypeAdjustment(*this, LoadCXXThis(),
328 Thunk.This.NonVirtual,
Eli Friedman82bad6b2012-09-14 01:45:09 +0000329 Thunk.This.VCallOffsetOffset,
330 /*IsReturnAdjustment*/false);
Anders Carlsson519c3282010-03-24 00:39:18 +0000331
332 CallArgList CallArgs;
333
334 // Add our adjusted 'this' pointer.
Eli Friedman04c9a492011-05-02 17:57:46 +0000335 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000336
337 // Add the rest of the parameters.
338 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
339 E = MD->param_end(); I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +0000340 ParmVarDecl *param = *I;
341 EmitDelegateCallArg(CallArgs, param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000342 }
343
344 // Get our callee.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000345 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +0000346 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
Anders Carlsson84c49e42011-02-06 17:15:43 +0000347 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson519c3282010-03-24 00:39:18 +0000348
John McCalld26bc762011-03-09 04:27:21 +0000349#ifndef NDEBUG
John McCall0f3d0972012-07-07 06:41:13 +0000350 const CGFunctionInfo &CallFnInfo =
351 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCallde5d3c72012-02-17 03:33:10 +0000352 RequiredArgs::forPrototypePlus(FPT, 1));
John McCall311b4422011-03-09 07:12:35 +0000353 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
354 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
355 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
John McCall0f3d0972012-07-07 06:41:13 +0000356 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
357 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
John McCall311b4422011-03-09 07:12:35 +0000358 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
359 assert(CallFnInfo.arg_size() == FnInfo.arg_size());
360 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
361 assert(similar(CallFnInfo.arg_begin()[i].info,
362 CallFnInfo.arg_begin()[i].type,
363 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
John McCalld26bc762011-03-09 04:27:21 +0000364#endif
Anders Carlsson519c3282010-03-24 00:39:18 +0000365
Douglas Gregorcb359df2010-05-20 05:54:35 +0000366 // Determine whether we have a return value slot to use.
367 ReturnValueSlot Slot;
368 if (!ResultType->isVoidType() &&
369 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +0000370 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregorcb359df2010-05-20 05:54:35 +0000371 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
372
Anders Carlsson519c3282010-03-24 00:39:18 +0000373 // Now emit our call.
Douglas Gregorcb359df2010-05-20 05:54:35 +0000374 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
Anders Carlsson519c3282010-03-24 00:39:18 +0000375
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000376 if (!Thunk.Return.isEmpty())
377 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000378
Douglas Gregorcb359df2010-05-20 05:54:35 +0000379 if (!ResultType->isVoidType() && Slot.isNull())
John McCalld16c2cf2011-02-08 08:22:06 +0000380 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000381
John McCallbd9b65a2012-07-31 00:33:55 +0000382 // Disable the final ARC autorelease.
383 AutoreleaseResult = false;
384
Anders Carlsson519c3282010-03-24 00:39:18 +0000385 FinishFunction();
386
Anders Carlsson519c3282010-03-24 00:39:18 +0000387 // Set the right linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000388 CGM.setFunctionLinkage(GD, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000389
390 // Set the right visibility.
John McCall65005532010-08-04 23:46:35 +0000391 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000392}
393
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000394void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
395 bool UseAvailableExternallyLinkage)
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000396{
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000397 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
398 // Emission of thunks is not supported yet in Microsoft ABI.
399 return;
400 }
401
John McCallde5d3c72012-02-17 03:33:10 +0000402 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalld26bc762011-03-09 04:27:21 +0000403
404 // FIXME: re-use FnInfo in this computation.
Anders Carlsson84c49e42011-02-06 17:15:43 +0000405 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson19879c92010-03-23 17:17:29 +0000406
Anders Carlsson7986ad52010-03-23 18:18:41 +0000407 // Strip off a bitcast if we got one back.
Anders Carlsson13d68982010-03-24 00:35:44 +0000408 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Anders Carlsson7986ad52010-03-23 18:18:41 +0000409 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Anders Carlsson13d68982010-03-24 00:35:44 +0000410 Entry = CE->getOperand(0);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000411 }
412
Anders Carlsson7986ad52010-03-23 18:18:41 +0000413 // There's already a declaration with the same name, check if it has the same
414 // type or if we need to replace it.
Anders Carlsson13d68982010-03-24 00:35:44 +0000415 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
John McCall4c40d982010-08-31 07:33:07 +0000416 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Anders Carlsson13d68982010-03-24 00:35:44 +0000417 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000418
419 // If the types mismatch then we have to rewrite the definition.
420 assert(OldThunkFn->isDeclaration() &&
421 "Shouldn't replace non-declaration");
422
423 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000424 OldThunkFn->setName(StringRef());
Anders Carlsson84c49e42011-02-06 17:15:43 +0000425 Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000426
427 // If needed, replace the old thunk with a bitcast.
428 if (!OldThunkFn->use_empty()) {
429 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson13d68982010-03-24 00:35:44 +0000430 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson7986ad52010-03-23 18:18:41 +0000431 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
432 }
433
434 // Remove the old thunk.
435 OldThunkFn->eraseFromParent();
436 }
Anders Carlsson519c3282010-03-24 00:39:18 +0000437
Anders Carlsson519c3282010-03-24 00:39:18 +0000438 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000439
440 if (!ThunkFn->isDeclaration()) {
441 if (UseAvailableExternallyLinkage) {
442 // There is already a thunk emitted for this function, do nothing.
443 return;
444 }
445
Anders Carlsson22df7b12011-02-06 20:09:44 +0000446 // If a function has a body, it should have available_externally linkage.
447 assert(ThunkFn->hasAvailableExternallyLinkage() &&
448 "Function should have available_externally linkage!");
449
450 // Change the linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000451 CGM.setFunctionLinkage(GD, ThunkFn);
Anders Carlsson22df7b12011-02-06 20:09:44 +0000452 return;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000453 }
454
Rafael Espindola022301b2012-09-21 20:39:32 +0000455 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
456
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000457 if (ThunkFn->isVarArg()) {
458 // Varargs thunks are special; we can't just generate a call because
459 // we can't copy the varargs. Our implementation is rather
460 // expensive/sucky at the moment, so don't generate the thunk unless
461 // we have to.
462 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
463 if (!UseAvailableExternallyLinkage)
464 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
465 } else {
466 // Normal thunk body generation.
467 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
468 }
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000469
470 if (UseAvailableExternallyLinkage)
471 ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
472}
473
474void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
475 const ThunkInfo &Thunk) {
476 // We only want to do this when building with optimizations.
477 if (!CGM.getCodeGenOpts().OptimizationLevel)
478 return;
479
480 // We can't emit thunks for member functions with incomplete types.
481 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000482 if (!CGM.getTypes().isFuncTypeConvertible(
483 cast<FunctionType>(MD->getType().getTypePtr())))
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000484 return;
485
486 EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000487}
488
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000489void CodeGenVTables::EmitThunks(GlobalDecl GD)
490{
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000491 const CXXMethodDecl *MD =
492 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
493
494 // We don't need to generate thunks for the base destructor.
495 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
496 return;
497
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000498 if (VFTContext.isValid()) {
499 // FIXME: This is a temporary solution to force generation of vftables in
500 // Microsoft ABI. Remove when we thread VFTableContext through CodeGen.
501 VFTContext->getVFPtrOffsets(MD->getParent());
502 }
503
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000504 const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
505 VTContext.getThunkInfo(MD);
506 if (!ThunkInfoVector)
Anders Carlssonccd83d72010-03-24 16:42:11 +0000507 return;
Anders Carlssonccd83d72010-03-24 16:42:11 +0000508
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000509 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
510 EmitThunk(GD, (*ThunkInfoVector)[I],
511 /*UseAvailableExternallyLinkage=*/false);
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000512}
513
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000514llvm::Constant *
515CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000516 const VTableComponent *Components,
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000517 unsigned NumComponents,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000518 const VTableLayout::VTableThunkTy *VTableThunks,
519 unsigned NumVTableThunks) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000520 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000521
Chris Lattner8b418682012-02-07 00:39:47 +0000522 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000523
Chris Lattner2acc6e32011-07-18 04:24:23 +0000524 llvm::Type *PtrDiffTy =
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000525 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
526
527 QualType ClassType = CGM.getContext().getTagDeclType(RD);
528 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
529
530 unsigned NextVTableThunkIndex = 0;
531
David Blaikie2eb9a952012-10-16 22:56:05 +0000532 llvm::Constant *PureVirtualFn = 0, *DeletedVirtualFn = 0;
Anders Carlsson67d568a2010-03-29 05:40:50 +0000533
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000534 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000535 VTableComponent Component = Components[I];
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000536
537 llvm::Constant *Init = 0;
538
539 switch (Component.getKind()) {
Anders Carlsson94464812010-04-10 19:13:06 +0000540 case VTableComponent::CK_VCallOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000541 Init = llvm::ConstantInt::get(PtrDiffTy,
542 Component.getVCallOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000543 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
544 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000545 case VTableComponent::CK_VBaseOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000546 Init = llvm::ConstantInt::get(PtrDiffTy,
547 Component.getVBaseOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000548 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
549 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000550 case VTableComponent::CK_OffsetToTop:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000551 Init = llvm::ConstantInt::get(PtrDiffTy,
552 Component.getOffsetToTop().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000553 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
554 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000555 case VTableComponent::CK_RTTI:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000556 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
557 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000558 case VTableComponent::CK_FunctionPointer:
559 case VTableComponent::CK_CompleteDtorPointer:
560 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000561 GlobalDecl GD;
562
563 // Get the right global decl.
564 switch (Component.getKind()) {
565 default:
566 llvm_unreachable("Unexpected vtable component kind");
Anders Carlsson94464812010-04-10 19:13:06 +0000567 case VTableComponent::CK_FunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000568 GD = Component.getFunctionDecl();
569 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000570 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000571 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
572 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000573 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000574 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
575 break;
576 }
577
Anders Carlsson67d568a2010-03-29 05:40:50 +0000578 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
579 // We have a pure virtual member function.
Joao Matose9af3e62012-07-17 19:17:58 +0000580 if (!PureVirtualFn) {
Eli Friedmancf15f172012-09-14 01:19:01 +0000581 llvm::FunctionType *Ty =
582 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
583 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
584 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
585 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matose9af3e62012-07-17 19:17:58 +0000586 CGM.Int8PtrTy);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000587 }
Anders Carlsson67d568a2010-03-29 05:40:50 +0000588 Init = PureVirtualFn;
David Blaikie2eb9a952012-10-16 22:56:05 +0000589 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
590 if (!DeletedVirtualFn) {
591 llvm::FunctionType *Ty =
592 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
593 StringRef DeletedCallName =
594 CGM.getCXXABI().GetDeletedVirtualCallName();
595 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
596 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
597 CGM.Int8PtrTy);
598 }
599 Init = DeletedVirtualFn;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000600 } else {
Anders Carlsson67d568a2010-03-29 05:40:50 +0000601 // Check if we should use a thunk.
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000602 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlsson67d568a2010-03-29 05:40:50 +0000603 VTableThunks[NextVTableThunkIndex].first == I) {
604 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000605
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000606 MaybeEmitThunkAvailableExternally(GD, Thunk);
Benjamin Kramerfce80092012-03-20 20:18:13 +0000607 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000608
Anders Carlsson67d568a2010-03-29 05:40:50 +0000609 NextVTableThunkIndex++;
610 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000611 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000612
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000613 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000614 }
615
616 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000617 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000618 break;
619 }
620
Anders Carlsson94464812010-04-10 19:13:06 +0000621 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000622 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
623 break;
624 };
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000625
626 Inits.push_back(Init);
627 }
628
629 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad97357602011-06-22 09:24:39 +0000630 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000631}
632
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000633llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000634 llvm::GlobalVariable *&VTable = VTables[RD];
635 if (VTable)
636 return VTable;
637
John McCalld5617ee2013-01-25 22:31:03 +0000638 // Queue up this v-table for possible deferred emission.
639 CGM.addDeferredVTable(RD);
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000640
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000641 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000642 llvm::raw_svector_ostream Out(OutName);
643 CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
644 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000645 StringRef Name = OutName.str();
Mike Stump85615df2009-11-19 04:04:36 +0000646
Anders Carlssonccd83d72010-03-24 16:42:11 +0000647 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000648 llvm::ArrayType::get(CGM.Int8PtrTy,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000649 VTContext.getVTableLayout(RD).getNumVTableComponents());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000650
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000651 VTable =
Anders Carlsson96eaf292011-01-29 18:25:07 +0000652 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
653 llvm::GlobalValue::ExternalLinkage);
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000654 VTable->setUnnamedAddr(true);
655 return VTable;
Mike Stump380dd752009-11-10 07:44:33 +0000656}
Mike Stump8cfcb522009-11-11 20:26:26 +0000657
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000658void
659CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
660 llvm::GlobalVariable::LinkageTypes Linkage,
661 const CXXRecordDecl *RD) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000662 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
663
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000664 // Create and set the initializer.
665 llvm::Constant *Init =
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000666 CreateVTableInitializer(RD,
667 VTLayout.vtable_component_begin(),
668 VTLayout.getNumVTableComponents(),
669 VTLayout.vtable_thunk_begin(),
670 VTLayout.getNumVTableThunks());
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000671 VTable->setInitializer(Init);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000672
673 // Set the correct linkage.
674 VTable->setLinkage(Linkage);
Douglas Gregorc66bcfd2010-06-14 23:41:45 +0000675
676 // Set the right visibility.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000677 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000678}
679
Anders Carlssonff143f82010-03-25 00:35:49 +0000680llvm::GlobalVariable *
681CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000682 const BaseSubobject &Base,
683 bool BaseIsVirtual,
John McCallbda0d6b2011-03-27 09:00:25 +0000684 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000685 VTableAddressPointsMapTy& AddressPoints) {
David Blaikie6a29f672013-08-22 15:23:05 +0000686 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
687 DI->completeClassData(Base.getBase());
688
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000689 OwningPtr<VTableLayout> VTLayout(
Peter Collingbourneab172b52011-09-26 01:57:04 +0000690 VTContext.createConstructionVTableLayout(Base.getBase(),
691 Base.getBaseOffset(),
692 BaseIsVirtual, RD));
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000693
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000694 // Add the address points.
Peter Collingbourneab172b52011-09-26 01:57:04 +0000695 AddressPoints = VTLayout->getAddressPoints();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000696
697 // Get the mangled construction vtable name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000698 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000699 llvm::raw_svector_ostream Out(OutName);
John McCall4c40d982010-08-31 07:33:07 +0000700 CGM.getCXXABI().getMangleContext().
Ken Dyck4230d522011-03-24 01:21:01 +0000701 mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
702 Out);
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000703 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000704 StringRef Name = OutName.str();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000705
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000706 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000707 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000708
Richard Smithb4127a22013-02-16 00:51:21 +0000709 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
710 // guarantee that they actually will be available externally. Instead, when
711 // emitting an available_externally VTT, we provide references to an internal
712 // linkage construction vtable. The ABI only requires complete-object vtables
713 // to be the same for all instances of a type, not construction vtables.
714 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
715 Linkage = llvm::GlobalVariable::InternalLinkage;
716
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000717 // Create the variable that will hold the construction vtable.
718 llvm::GlobalVariable *VTable =
John McCallbda0d6b2011-03-27 09:00:25 +0000719 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
720 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
721
722 // V-tables are always unnamed_addr.
723 VTable->setUnnamedAddr(true);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000724
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000725 // Create and set the initializer.
726 llvm::Constant *Init =
727 CreateVTableInitializer(Base.getBase(),
Peter Collingbourneab172b52011-09-26 01:57:04 +0000728 VTLayout->vtable_component_begin(),
729 VTLayout->getNumVTableComponents(),
730 VTLayout->vtable_thunk_begin(),
731 VTLayout->getNumVTableThunks());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000732 VTable->setInitializer(Init);
733
Anders Carlssonff143f82010-03-25 00:35:49 +0000734 return VTable;
735}
736
John McCalld5617ee2013-01-25 22:31:03 +0000737/// Compute the required linkage of the v-table for the given class.
738///
739/// Note that we only call this at the end of the translation unit.
740llvm::GlobalVariable::LinkageTypes
741CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000742 if (!RD->isExternallyVisible())
John McCalld5617ee2013-01-25 22:31:03 +0000743 return llvm::GlobalVariable::InternalLinkage;
744
745 // We're at the end of the translation unit, so the current key
746 // function is fully correct.
747 if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
748 // If this class has a key function, use that to determine the
749 // linkage of the vtable.
750 const FunctionDecl *def = 0;
751 if (keyFunction->hasBody(def))
752 keyFunction = cast<CXXMethodDecl>(def);
753
754 switch (keyFunction->getTemplateSpecializationKind()) {
755 case TSK_Undeclared:
756 case TSK_ExplicitSpecialization:
757 // When compiling with optimizations turned on, we emit all vtables,
758 // even if the key function is not defined in the current translation
759 // unit. If this is the case, use available_externally linkage.
760 if (!def && CodeGenOpts.OptimizationLevel)
761 return llvm::GlobalVariable::AvailableExternallyLinkage;
762
763 if (keyFunction->isInlined())
764 return !Context.getLangOpts().AppleKext ?
765 llvm::GlobalVariable::LinkOnceODRLinkage :
766 llvm::Function::InternalLinkage;
767
768 return llvm::GlobalVariable::ExternalLinkage;
769
770 case TSK_ImplicitInstantiation:
771 return !Context.getLangOpts().AppleKext ?
772 llvm::GlobalVariable::LinkOnceODRLinkage :
773 llvm::Function::InternalLinkage;
774
775 case TSK_ExplicitInstantiationDefinition:
776 return !Context.getLangOpts().AppleKext ?
777 llvm::GlobalVariable::WeakODRLinkage :
778 llvm::Function::InternalLinkage;
779
780 case TSK_ExplicitInstantiationDeclaration:
John McCalld5617ee2013-01-25 22:31:03 +0000781 return !Context.getLangOpts().AppleKext ?
Richard Smithb4127a22013-02-16 00:51:21 +0000782 llvm::GlobalVariable::AvailableExternallyLinkage :
John McCalld5617ee2013-01-25 22:31:03 +0000783 llvm::Function::InternalLinkage;
784 }
785 }
786
787 // -fapple-kext mode does not support weak linkage, so we must use
788 // internal linkage.
789 if (Context.getLangOpts().AppleKext)
790 return llvm::Function::InternalLinkage;
791
792 switch (RD->getTemplateSpecializationKind()) {
793 case TSK_Undeclared:
794 case TSK_ExplicitSpecialization:
795 case TSK_ImplicitInstantiation:
796 return llvm::GlobalVariable::LinkOnceODRLinkage;
797
798 case TSK_ExplicitInstantiationDeclaration:
Richard Smithb4127a22013-02-16 00:51:21 +0000799 return llvm::GlobalVariable::AvailableExternallyLinkage;
John McCalld5617ee2013-01-25 22:31:03 +0000800
801 case TSK_ExplicitInstantiationDefinition:
802 return llvm::GlobalVariable::WeakODRLinkage;
803 }
804
805 llvm_unreachable("Invalid TemplateSpecializationKind!");
806}
807
808/// This is a callback from Sema to tell us that it believes that a
809/// particular v-table is required to be emitted in this translation
810/// unit.
811///
812/// The reason we don't simply trust this callback is because Sema
813/// will happily report that something is used even when it's used
814/// only in code that we don't actually have to emit.
815///
816/// \param isRequired - if true, the v-table is mandatory, e.g.
817/// because the translation unit defines the key function
818void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
819 if (!isRequired) return;
820
821 VTables.GenerateClassData(theClass);
822}
823
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000824void
John McCalld5617ee2013-01-25 22:31:03 +0000825CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikie6a29f672013-08-22 15:23:05 +0000826 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
827 DI->completeClassData(RD);
828
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000829 if (VFTContext.isValid()) {
830 // FIXME: This is a temporary solution to force generation of vftables in
831 // Microsoft ABI. Remove when we thread VFTableContext through CodeGen.
832 VFTContext->getVFPtrOffsets(RD);
833 }
834
John McCalld5617ee2013-01-25 22:31:03 +0000835 // First off, check whether we've already emitted the v-table and
836 // associated stuff.
Peter Collingbournebf1c5ae2011-09-26 01:56:36 +0000837 llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
838 if (VTable->hasInitializer())
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000839 return;
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000840
John McCalld5617ee2013-01-25 22:31:03 +0000841 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
Anders Carlsson9dc338a2010-03-30 03:35:35 +0000842 EmitVTableDefinition(VTable, Linkage, RD);
843
Reid Kleckner90633022013-06-19 15:20:38 +0000844 if (RD->getNumVBases())
845 CGM.getCXXABI().EmitVirtualInheritanceTables(Linkage, RD);
Douglas Gregor1e201b42010-04-08 15:52:03 +0000846
847 // If this is the magic class __cxxabiv1::__fundamental_type_info,
848 // we will emit the typeinfo for the fundamental types. This is the
849 // same behaviour as GCC.
850 const DeclContext *DC = RD->getDeclContext();
851 if (RD->getIdentifier() &&
852 RD->getIdentifier()->isStr("__fundamental_type_info") &&
853 isa<NamespaceDecl>(DC) &&
854 cast<NamespaceDecl>(DC)->getIdentifier() &&
855 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
856 DC->getParent()->isTranslationUnit())
857 CGM.EmitFundamentalRTTIDescriptors();
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000858}
John McCalld5617ee2013-01-25 22:31:03 +0000859
860/// At this point in the translation unit, does it appear that can we
861/// rely on the vtable being defined elsewhere in the program?
862///
863/// The response is really only definitive when called at the end of
864/// the translation unit.
865///
866/// The only semantic restriction here is that the object file should
867/// not contain a v-table definition when that v-table is defined
868/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
869/// v-tables when unnecessary.
870bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
871 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
872
873 // If we have an explicit instantiation declaration (and not a
874 // definition), the v-table is defined elsewhere.
875 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
876 if (TSK == TSK_ExplicitInstantiationDeclaration)
877 return true;
878
879 // Otherwise, if the class is an instantiated template, the
880 // v-table must be defined here.
881 if (TSK == TSK_ImplicitInstantiation ||
882 TSK == TSK_ExplicitInstantiationDefinition)
883 return false;
884
885 // Otherwise, if the class doesn't have a key function (possibly
886 // anymore), the v-table must be defined here.
887 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
888 if (!keyFunction)
889 return false;
890
891 // Otherwise, if we don't have a definition of the key function, the
892 // v-table must be defined somewhere else.
893 return !keyFunction->hasBody();
894}
895
896/// Given that we're currently at the end of the translation unit, and
897/// we've emitted a reference to the v-table for this class, should
898/// we define that v-table?
899static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
900 const CXXRecordDecl *RD) {
901 // If we're building with optimization, we always emit v-tables
902 // since that allows for virtual function calls to be devirtualized.
903 // If the v-table is defined strongly elsewhere, this definition
904 // will be emitted available_externally.
905 //
906 // However, we don't want to do this in -fapple-kext mode, because
907 // kext mode does not permit devirtualization.
908 if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOpts().AppleKext)
909 return true;
910
911 return !CGM.getVTables().isVTableExternal(RD);
912}
913
914/// Given that at some point we emitted a reference to one or more
915/// v-tables, and that we are now at the end of the translation unit,
916/// decide whether we should emit them.
917void CodeGenModule::EmitDeferredVTables() {
918#ifndef NDEBUG
919 // Remember the size of DeferredVTables, because we're going to assume
920 // that this entire operation doesn't modify it.
921 size_t savedSize = DeferredVTables.size();
922#endif
923
924 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
925 for (const_iterator i = DeferredVTables.begin(),
926 e = DeferredVTables.end(); i != e; ++i) {
927 const CXXRecordDecl *RD = *i;
928 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
929 VTables.GenerateClassData(RD);
930 }
931
932 assert(savedSize == DeferredVTables.size() &&
933 "deferred extra v-tables during v-table emission?");
934 DeferredVTables.clear();
935}