blob: 2e8471eeb6c71f8bfd7e369d2dbb65ff5b77d78f [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"
Mark Lacey8b549992013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
John McCall7a536902010-08-05 20:39:18 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000021#include "llvm/ADT/DenseSet.h"
Anders Carlssonb9021e92010-02-27 16:18:19 +000022#include "llvm/ADT/SetVector.h"
Chandler Carruthe087f072010-02-13 10:38:52 +000023#include "llvm/Support/Compiler.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000024#include "llvm/Support/Format.h"
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000025#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson5e454aa2010-03-17 20:06:32 +000026#include <algorithm>
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000027#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000028
29using namespace clang;
30using namespace CodeGen;
31
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000032CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
Stephen Hines651f13c2014-04-23 16:59:28 -070033 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000034
Anders Carlsson19879c92010-03-23 17:17:29 +000035llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlsson84c49e42011-02-06 17:15:43 +000036 const ThunkInfo &Thunk) {
Anders Carlsson19879c92010-03-23 17:17:29 +000037 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38
39 // Compute the mangled name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000040 SmallString<256> Name;
Rafael Espindolaf0be9792011-02-11 02:52:17 +000041 llvm::raw_svector_ostream Out(Name);
Anders Carlsson19879c92010-03-23 17:17:29 +000042 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall4c40d982010-08-31 07:33:07 +000043 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindolaf0be9792011-02-11 02:52:17 +000044 Thunk.This, Out);
Anders Carlsson19879c92010-03-23 17:17:29 +000045 else
Rafael Espindolaf0be9792011-02-11 02:52:17 +000046 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
47 Out.flush();
48
Chris Lattner2acc6e32011-07-18 04:24:23 +000049 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -070050 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
Stephen Hines176edba2014-12-01 14:53:08 -080051 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlsson19879c92010-03-23 17:17:29 +000052}
53
John McCall65005532010-08-04 23:46:35 +000054static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
55 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +000056 CGM.setGlobalVisibility(Fn, MD);
John McCall65005532010-08-04 23:46:35 +000057}
58
John McCall311b4422011-03-09 07:12:35 +000059#ifndef NDEBUG
60static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61 const ABIArgInfo &infoR, CanQualType typeR) {
62 return (infoL.getKind() == infoR.getKind() &&
63 (typeL == typeR ||
64 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66}
67#endif
68
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000069static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70 QualType ResultType, RValue RV,
71 const ThunkInfo &Thunk) {
72 // Emit the return adjustment.
73 bool NullCheckValue = !ResultType->isReferenceType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070074
75 llvm::BasicBlock *AdjustNull = nullptr;
76 llvm::BasicBlock *AdjustNotNull = nullptr;
77 llvm::BasicBlock *AdjustEnd = nullptr;
78
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000079 llvm::Value *ReturnValue = RV.getScalarVal();
80
81 if (NullCheckValue) {
82 AdjustNull = CGF.createBasicBlock("adjust.null");
83 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84 AdjustEnd = CGF.createBasicBlock("adjust.end");
85
86 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88 CGF.EmitBlock(AdjustNotNull);
89 }
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +000090
91 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
92 Thunk.Return);
93
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000094 if (NullCheckValue) {
95 CGF.Builder.CreateBr(AdjustEnd);
96 CGF.EmitBlock(AdjustNull);
97 CGF.Builder.CreateBr(AdjustEnd);
98 CGF.EmitBlock(AdjustEnd);
99
100 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
101 PHI->addIncoming(ReturnValue, AdjustNotNull);
102 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
103 AdjustNull);
104 ReturnValue = PHI;
105 }
106
107 return RValue::get(ReturnValue);
108}
109
110// This function does roughly the same thing as GenerateThunk, but in a
111// very different way, so that va_start and va_end work correctly.
112// FIXME: This function assumes "this" is the first non-sret LLVM argument of
113// a function, and that there is an alloca built in the entry block
114// for all accesses to "this".
115// FIXME: This function assumes there is only one "ret" statement per function.
116// FIXME: Cloning isn't correct in the presence of indirect goto!
117// FIXME: This implementation of thunks bloats codesize by duplicating the
118// function definition. There are alternatives:
119// 1. Add some sort of stub support to LLVM for cases where we can
120// do a this adjustment, then a sibcall.
121// 2. We could transform the definition to take a va_list instead of an
122// actual variable argument list, then have the thunks (including a
123// no-op thunk for the regular definition) call va_start/va_end.
124// There's a bit of per-call overhead for this solution, but it's
125// better for codesize if the definition is long.
126void CodeGenFunction::GenerateVarArgsThunk(
127 llvm::Function *Fn,
128 const CGFunctionInfo &FnInfo,
129 GlobalDecl GD, const ThunkInfo &Thunk) {
130 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
131 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -0700132 QualType ResultType = FPT->getReturnType();
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000133
134 // Get the original function
John McCallde5d3c72012-02-17 03:33:10 +0000135 assert(FnInfo.isVariadic());
136 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000137 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
138 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
139
140 // Clone to thunk.
Benjamin Kramer9b5ede52012-09-19 13:13:52 +0000141 llvm::ValueToValueMapTy VMap;
142 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
143 /*ModuleLevelChanges=*/false);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000144 CGM.getModule().getFunctionList().push_back(NewFn);
145 Fn->replaceAllUsesWith(NewFn);
146 NewFn->takeName(Fn);
147 Fn->eraseFromParent();
148 Fn = NewFn;
149
150 // "Initialize" CGF (minimally).
151 CurFn = Fn;
152
153 // Get the "this" value
154 llvm::Function::arg_iterator AI = Fn->arg_begin();
155 if (CGM.ReturnTypeUsesSRet(FnInfo))
156 ++AI;
157
158 // Find the first store of "this", which will be to the alloca associated
159 // with "this".
160 llvm::Value *ThisPtr = &*AI;
161 llvm::BasicBlock *EntryBB = Fn->begin();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700162 llvm::Instruction *ThisStore =
163 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
164 return isa<llvm::StoreInst>(I) && I.getOperand(0) == ThisPtr;
165 });
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000166 assert(ThisStore && "Store of this should be in entry block?");
167 // Adjust "this", if necessary.
168 Builder.SetInsertPoint(ThisStore);
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000169 llvm::Value *AdjustedThisPtr =
170 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000171 ThisStore->setOperand(0, AdjustedThisPtr);
172
173 if (!Thunk.Return.isEmpty()) {
174 // Fix up the returned value, if necessary.
175 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
176 llvm::Instruction *T = I->getTerminator();
177 if (isa<llvm::ReturnInst>(T)) {
178 RValue RV = RValue::get(T->getOperand(0));
179 T->eraseFromParent();
180 Builder.SetInsertPoint(&*I);
181 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
182 Builder.CreateRet(RV.getScalarVal());
183 break;
184 }
185 }
186 }
187}
188
Hans Wennborg93b717a2013-11-15 17:24:45 +0000189void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
190 const CGFunctionInfo &FnInfo) {
191 assert(!CurGD.getDecl() && "CurGD was already set!");
192 CurGD = GD;
Stephen Hines176edba2014-12-01 14:53:08 -0800193 CurFuncIsThunk = true;
Hans Wennborg93b717a2013-11-15 17:24:45 +0000194
195 // Build FunctionArgs.
Anders Carlsson519c3282010-03-24 00:39:18 +0000196 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson519c3282010-03-24 00:39:18 +0000197 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg93b717a2013-11-15 17:24:45 +0000198 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Stephen Hines176edba2014-12-01 14:53:08 -0800199 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
200 ? ThisType
201 : CGM.getCXXABI().hasMostDerivedReturn(GD)
202 ? CGM.getContext().VoidPtrTy
203 : FPT->getReturnType();
Anders Carlsson519c3282010-03-24 00:39:18 +0000204 FunctionArgList FunctionArgs;
205
Anders Carlsson519c3282010-03-24 00:39:18 +0000206 // Create the implicit 'this' parameter declaration.
Stephen Hines651f13c2014-04-23 16:59:28 -0700207 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlsson519c3282010-03-24 00:39:18 +0000208
209 // Add the rest of the parameters.
Stephen Hines176edba2014-12-01 14:53:08 -0800210 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov34b41f82012-10-25 10:18:50 +0000211
Stephen Hines651f13c2014-04-23 16:59:28 -0700212 if (isa<CXXDestructorDecl>(MD))
213 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
214
Hans Wennborg93b717a2013-11-15 17:24:45 +0000215 // Start defining the function.
John McCalld26bc762011-03-09 04:27:21 +0000216 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700217 MD->getLocation(), MD->getLocation());
Anders Carlsson519c3282010-03-24 00:39:18 +0000218
Hans Wennborg93b717a2013-11-15 17:24:45 +0000219 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall4c40d982010-08-31 07:33:07 +0000220 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000221 CXXThisValue = CXXABIThisValue;
Hans Wennborg93b717a2013-11-15 17:24:45 +0000222}
John McCall4c40d982010-08-31 07:33:07 +0000223
Stephen Hines176edba2014-12-01 14:53:08 -0800224void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
Hans Wennborg93b717a2013-11-15 17:24:45 +0000225 const ThunkInfo *Thunk) {
226 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
227 "Please use a new CGF for this thunk");
Stephen Hines176edba2014-12-01 14:53:08 -0800228 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000229
Hans Wennborg93b717a2013-11-15 17:24:45 +0000230 // Adjust the 'this' pointer if necessary
231 llvm::Value *AdjustedThisPtr = Thunk ? CGM.getCXXABI().performThisAdjustment(
232 *this, LoadCXXThis(), Thunk->This)
233 : LoadCXXThis();
234
Stephen Hines176edba2014-12-01 14:53:08 -0800235 if (CurFnInfo->usesInAlloca()) {
236 // We don't handle return adjusting thunks, because they require us to call
237 // the copy constructor. For now, fall through and pretend the return
238 // adjustment was empty so we don't crash.
239 if (Thunk && !Thunk->Return.isEmpty()) {
240 CGM.ErrorUnsupported(
241 MD, "non-trivial argument copy for return-adjusting thunk");
242 }
243 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
244 return;
245 }
246
Hans Wennborg93b717a2013-11-15 17:24:45 +0000247 // Start building CallArgs.
Anders Carlsson519c3282010-03-24 00:39:18 +0000248 CallArgList CallArgs;
Hans Wennborg93b717a2013-11-15 17:24:45 +0000249 QualType ThisType = MD->getThisType(getContext());
Eli Friedman04c9a492011-05-02 17:57:46 +0000250 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000251
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000252 if (isa<CXXDestructorDecl>(MD))
Stephen Hines176edba2014-12-01 14:53:08 -0800253 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000254
Hans Wennborg93b717a2013-11-15 17:24:45 +0000255 // Add the rest of the arguments.
Stephen Hines176edba2014-12-01 14:53:08 -0800256 for (const ParmVarDecl *PD : MD->params())
257 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
Anders Carlsson519c3282010-03-24 00:39:18 +0000258
Hans Wennborg93b717a2013-11-15 17:24:45 +0000259 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlsson519c3282010-03-24 00:39:18 +0000260
John McCalld26bc762011-03-09 04:27:21 +0000261#ifndef NDEBUG
John McCall0f3d0972012-07-07 06:41:13 +0000262 const CGFunctionInfo &CallFnInfo =
263 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCallde5d3c72012-02-17 03:33:10 +0000264 RequiredArgs::forPrototypePlus(FPT, 1));
Hans Wennborg93b717a2013-11-15 17:24:45 +0000265 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
266 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
267 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall0f3d0972012-07-07 06:41:13 +0000268 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
269 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg93b717a2013-11-15 17:24:45 +0000270 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
271 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
272 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall311b4422011-03-09 07:12:35 +0000273 assert(similar(CallFnInfo.arg_begin()[i].info,
274 CallFnInfo.arg_begin()[i].type,
Hans Wennborg93b717a2013-11-15 17:24:45 +0000275 CurFnInfo->arg_begin()[i].info,
276 CurFnInfo->arg_begin()[i].type));
John McCalld26bc762011-03-09 04:27:21 +0000277#endif
Hans Wennborg93b717a2013-11-15 17:24:45 +0000278
Douglas Gregorcb359df2010-05-20 05:54:35 +0000279 // Determine whether we have a return value slot to use.
Stephen Hines176edba2014-12-01 14:53:08 -0800280 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
281 ? ThisType
282 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
283 ? CGM.getContext().VoidPtrTy
284 : FPT->getReturnType();
Douglas Gregorcb359df2010-05-20 05:54:35 +0000285 ReturnValueSlot Slot;
286 if (!ResultType->isVoidType() &&
Hans Wennborg93b717a2013-11-15 17:24:45 +0000287 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +0000288 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregorcb359df2010-05-20 05:54:35 +0000289 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
290
Anders Carlsson519c3282010-03-24 00:39:18 +0000291 // Now emit our call.
Stephen Hines176edba2014-12-01 14:53:08 -0800292 llvm::Instruction *CallOrInvoke;
293 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
294
Hans Wennborg93b717a2013-11-15 17:24:45 +0000295 // Consider return adjustment if we have ThunkInfo.
296 if (Thunk && !Thunk->Return.isEmpty())
297 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000298
Hans Wennborg93b717a2013-11-15 17:24:45 +0000299 // Emit return.
Douglas Gregorcb359df2010-05-20 05:54:35 +0000300 if (!ResultType->isVoidType() && Slot.isNull())
John McCalld16c2cf2011-02-08 08:22:06 +0000301 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000302
John McCallbd9b65a2012-07-31 00:33:55 +0000303 // Disable the final ARC autorelease.
304 AutoreleaseResult = false;
305
Anders Carlsson519c3282010-03-24 00:39:18 +0000306 FinishFunction();
Hans Wennborg93b717a2013-11-15 17:24:45 +0000307}
308
Stephen Hines176edba2014-12-01 14:53:08 -0800309void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
310 llvm::Value *AdjustedThisPtr,
311 llvm::Value *Callee) {
312 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
313 // to translate AST arguments into LLVM IR arguments. For thunks, we know
314 // that the caller prototype more or less matches the callee prototype with
315 // the exception of 'this'.
316 SmallVector<llvm::Value *, 8> Args;
317 for (llvm::Argument &A : CurFn->args())
318 Args.push_back(&A);
319
320 // Set the adjusted 'this' pointer.
321 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
322 if (ThisAI.isDirect()) {
323 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
324 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
325 llvm::Type *ThisType = Args[ThisArgNo]->getType();
326 if (ThisType != AdjustedThisPtr->getType())
327 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
328 Args[ThisArgNo] = AdjustedThisPtr;
329 } else {
330 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
331 llvm::Value *ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
332 llvm::Type *ThisType =
333 cast<llvm::PointerType>(ThisAddr->getType())->getElementType();
334 if (ThisType != AdjustedThisPtr->getType())
335 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
336 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
337 }
338
339 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
340 // don't actually want to run them.
341 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
342 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
343
344 // Apply the standard set of call attributes.
345 unsigned CallingConv;
346 CodeGen::AttributeListType AttributeList;
347 CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
348 /*AttrOnCallSite=*/true);
349 llvm::AttributeSet Attrs =
350 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
351 Call->setAttributes(Attrs);
352 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
353
354 if (Call->getType()->isVoidTy())
355 Builder.CreateRetVoid();
356 else
357 Builder.CreateRet(Call);
358
359 // Finish the function to maintain CodeGenFunction invariants.
360 // FIXME: Don't emit unreachable code.
361 EmitBlock(createBasicBlock());
362 FinishFunction();
363}
364
Hans Wennborg93b717a2013-11-15 17:24:45 +0000365void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
366 const CGFunctionInfo &FnInfo,
367 GlobalDecl GD, const ThunkInfo &Thunk) {
368 StartThunk(Fn, GD, FnInfo);
369
370 // Get our callee.
371 llvm::Type *Ty =
372 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
373 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
374
375 // Make the call and return the result.
Stephen Hines176edba2014-12-01 14:53:08 -0800376 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000377
Anders Carlsson519c3282010-03-24 00:39:18 +0000378 // Set the right linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000379 CGM.setFunctionLinkage(GD, Fn);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700380
381 if (CGM.supportsCOMDAT() && Fn->isWeakForLinker())
382 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
383
Anders Carlsson519c3282010-03-24 00:39:18 +0000384 // Set the right visibility.
Hans Wennborg93b717a2013-11-15 17:24:45 +0000385 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCall65005532010-08-04 23:46:35 +0000386 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000387}
388
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000389void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
390 bool ForVTable) {
John McCallde5d3c72012-02-17 03:33:10 +0000391 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalld26bc762011-03-09 04:27:21 +0000392
393 // FIXME: re-use FnInfo in this computation.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700394 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
395 llvm::GlobalValue *Entry;
396
Anders Carlsson7986ad52010-03-23 18:18:41 +0000397 // Strip off a bitcast if we got one back.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700398 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson7986ad52010-03-23 18:18:41 +0000399 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700400 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
401 } else {
402 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000403 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700404
Anders Carlsson7986ad52010-03-23 18:18:41 +0000405 // There's already a declaration with the same name, check if it has the same
406 // type or if we need to replace it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700407 if (Entry->getType()->getElementType() !=
John McCall4c40d982010-08-31 07:33:07 +0000408 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700409 llvm::GlobalValue *OldThunkFn = Entry;
410
Anders Carlsson7986ad52010-03-23 18:18:41 +0000411 // If the types mismatch then we have to rewrite the definition.
412 assert(OldThunkFn->isDeclaration() &&
413 "Shouldn't replace non-declaration");
414
415 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000416 OldThunkFn->setName(StringRef());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700417 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Anders Carlsson7986ad52010-03-23 18:18:41 +0000418
419 // If needed, replace the old thunk with a bitcast.
420 if (!OldThunkFn->use_empty()) {
421 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson13d68982010-03-24 00:35:44 +0000422 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson7986ad52010-03-23 18:18:41 +0000423 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
424 }
425
426 // Remove the old thunk.
427 OldThunkFn->eraseFromParent();
428 }
Anders Carlsson519c3282010-03-24 00:39:18 +0000429
Anders Carlsson519c3282010-03-24 00:39:18 +0000430 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000431 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
432 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000433
434 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000435 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000436 // There is already a thunk emitted for this function, do nothing.
437 return;
438 }
439
Anders Carlsson22df7b12011-02-06 20:09:44 +0000440 // 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.
Bill Wendling8e3eec52013-12-07 21:19:02 +0000453 if (!UseAvailableExternallyLinkage) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000454 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700455 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
456 !Thunk.Return.isEmpty());
Bill Wendling8e3eec52013-12-07 21:19:02 +0000457 }
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000458 } else {
459 // Normal thunk body generation.
460 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700461 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
462 !Thunk.Return.isEmpty());
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000463 }
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000464}
465
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000466void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
467 const ThunkInfo &Thunk) {
468 // If the ABI has key functions, only the TU with the key function should emit
469 // the thunk. However, we can allow inlining of thunks if we emit them with
470 // available_externally linkage together with vtables when optimizations are
471 // enabled.
472 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
473 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000474 return;
475
476 // We can't emit thunks for member functions with incomplete types.
477 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000478 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Kleckner7bb72302013-10-11 20:46:27 +0000479 MD->getType()->castAs<FunctionType>()))
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000480 return;
481
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000482 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000483}
484
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000485void CodeGenVTables::EmitThunks(GlobalDecl GD)
486{
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000487 const CXXMethodDecl *MD =
488 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
489
490 // We don't need to generate thunks for the base destructor.
491 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
492 return;
493
Stephen Hines651f13c2014-04-23 16:59:28 -0700494 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
495 VTContext->getThunkInfo(GD);
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000496
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000497 if (!ThunkInfoVector)
Anders Carlssonccd83d72010-03-24 16:42:11 +0000498 return;
Anders Carlssonccd83d72010-03-24 16:42:11 +0000499
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000500 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000501 emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000502}
503
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700504llvm::Constant *CodeGenVTables::CreateVTableInitializer(
505 const CXXRecordDecl *RD, const VTableComponent *Components,
506 unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
507 unsigned NumVTableThunks, llvm::Constant *RTTI) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000508 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000509
Chris Lattner8b418682012-02-07 00:39:47 +0000510 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000511
Chris Lattner2acc6e32011-07-18 04:24:23 +0000512 llvm::Type *PtrDiffTy =
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000513 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
514
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000515 unsigned NextVTableThunkIndex = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700516
517 llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
Anders Carlsson67d568a2010-03-29 05:40:50 +0000518
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000519 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000520 VTableComponent Component = Components[I];
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000521
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700522 llvm::Constant *Init = nullptr;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000523
524 switch (Component.getKind()) {
Anders Carlsson94464812010-04-10 19:13:06 +0000525 case VTableComponent::CK_VCallOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000526 Init = llvm::ConstantInt::get(PtrDiffTy,
527 Component.getVCallOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000528 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
529 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000530 case VTableComponent::CK_VBaseOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000531 Init = llvm::ConstantInt::get(PtrDiffTy,
532 Component.getVBaseOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000533 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
534 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000535 case VTableComponent::CK_OffsetToTop:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000536 Init = llvm::ConstantInt::get(PtrDiffTy,
537 Component.getOffsetToTop().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000538 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
539 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000540 case VTableComponent::CK_RTTI:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000541 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
542 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000543 case VTableComponent::CK_FunctionPointer:
544 case VTableComponent::CK_CompleteDtorPointer:
545 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000546 GlobalDecl GD;
547
548 // Get the right global decl.
549 switch (Component.getKind()) {
550 default:
551 llvm_unreachable("Unexpected vtable component kind");
Anders Carlsson94464812010-04-10 19:13:06 +0000552 case VTableComponent::CK_FunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000553 GD = Component.getFunctionDecl();
554 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000555 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000556 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
557 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000558 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000559 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
560 break;
561 }
562
Anders Carlsson67d568a2010-03-29 05:40:50 +0000563 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
564 // We have a pure virtual member function.
Joao Matose9af3e62012-07-17 19:17:58 +0000565 if (!PureVirtualFn) {
Eli Friedmancf15f172012-09-14 01:19:01 +0000566 llvm::FunctionType *Ty =
567 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
568 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
569 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
570 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matose9af3e62012-07-17 19:17:58 +0000571 CGM.Int8PtrTy);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000572 }
Anders Carlsson67d568a2010-03-29 05:40:50 +0000573 Init = PureVirtualFn;
David Blaikie2eb9a952012-10-16 22:56:05 +0000574 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
575 if (!DeletedVirtualFn) {
576 llvm::FunctionType *Ty =
577 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
578 StringRef DeletedCallName =
579 CGM.getCXXABI().GetDeletedVirtualCallName();
580 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
581 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
582 CGM.Int8PtrTy);
583 }
584 Init = DeletedVirtualFn;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000585 } else {
Anders Carlsson67d568a2010-03-29 05:40:50 +0000586 // Check if we should use a thunk.
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000587 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlsson67d568a2010-03-29 05:40:50 +0000588 VTableThunks[NextVTableThunkIndex].first == I) {
589 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000590
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000591 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramerfce80092012-03-20 20:18:13 +0000592 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000593
Anders Carlsson67d568a2010-03-29 05:40:50 +0000594 NextVTableThunkIndex++;
595 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000596 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000597
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000598 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000599 }
600
601 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000602 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000603 break;
604 }
605
Anders Carlsson94464812010-04-10 19:13:06 +0000606 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000607 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
608 break;
609 };
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000610
611 Inits.push_back(Init);
612 }
613
614 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad97357602011-06-22 09:24:39 +0000615 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000616}
617
Anders Carlssonff143f82010-03-25 00:35:49 +0000618llvm::GlobalVariable *
619CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000620 const BaseSubobject &Base,
621 bool BaseIsVirtual,
John McCallbda0d6b2011-03-27 09:00:25 +0000622 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000623 VTableAddressPointsMapTy& AddressPoints) {
David Blaikie6a29f672013-08-22 15:23:05 +0000624 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
625 DI->completeClassData(Base.getBase());
626
Stephen Hines651f13c2014-04-23 16:59:28 -0700627 std::unique_ptr<VTableLayout> VTLayout(
628 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +0000629 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000630
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000631 // Add the address points.
Peter Collingbourneab172b52011-09-26 01:57:04 +0000632 AddressPoints = VTLayout->getAddressPoints();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000633
634 // Get the mangled construction vtable name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000635 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000636 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000637 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
638 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
639 Base.getBase(), Out);
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000640 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000641 StringRef Name = OutName.str();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000642
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000643 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000644 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000645
Richard Smithb4127a22013-02-16 00:51:21 +0000646 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
647 // guarantee that they actually will be available externally. Instead, when
648 // emitting an available_externally VTT, we provide references to an internal
649 // linkage construction vtable. The ABI only requires complete-object vtables
650 // to be the same for all instances of a type, not construction vtables.
651 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
652 Linkage = llvm::GlobalVariable::InternalLinkage;
653
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000654 // Create the variable that will hold the construction vtable.
655 llvm::GlobalVariable *VTable =
John McCallbda0d6b2011-03-27 09:00:25 +0000656 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
Stephen Hines651f13c2014-04-23 16:59:28 -0700657 CGM.setGlobalVisibility(VTable, RD);
John McCallbda0d6b2011-03-27 09:00:25 +0000658
659 // V-tables are always unnamed_addr.
660 VTable->setUnnamedAddr(true);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000661
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700662 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
663 CGM.getContext().getTagDeclType(Base.getBase()));
664
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000665 // Create and set the initializer.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700666 llvm::Constant *Init = CreateVTableInitializer(
667 Base.getBase(), VTLayout->vtable_component_begin(),
668 VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
669 VTLayout->getNumVTableThunks(), RTTI);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000670 VTable->setInitializer(Init);
671
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700672 CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
673
Anders Carlssonff143f82010-03-25 00:35:49 +0000674 return VTable;
675}
676
John McCalld5617ee2013-01-25 22:31:03 +0000677/// Compute the required linkage of the v-table for the given class.
678///
679/// Note that we only call this at the end of the translation unit.
680llvm::GlobalVariable::LinkageTypes
681CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000682 if (!RD->isExternallyVisible())
John McCalld5617ee2013-01-25 22:31:03 +0000683 return llvm::GlobalVariable::InternalLinkage;
684
685 // We're at the end of the translation unit, so the current key
686 // function is fully correct.
Stephen Hines176edba2014-12-01 14:53:08 -0800687 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
688 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCalld5617ee2013-01-25 22:31:03 +0000689 // If this class has a key function, use that to determine the
690 // linkage of the vtable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700691 const FunctionDecl *def = nullptr;
John McCalld5617ee2013-01-25 22:31:03 +0000692 if (keyFunction->hasBody(def))
693 keyFunction = cast<CXXMethodDecl>(def);
694
695 switch (keyFunction->getTemplateSpecializationKind()) {
696 case TSK_Undeclared:
697 case TSK_ExplicitSpecialization:
Rafael Espindola889a6752013-09-03 21:05:13 +0000698 assert(def && "Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000699 if (keyFunction->isInlined())
700 return !Context.getLangOpts().AppleKext ?
701 llvm::GlobalVariable::LinkOnceODRLinkage :
702 llvm::Function::InternalLinkage;
703
704 return llvm::GlobalVariable::ExternalLinkage;
705
706 case TSK_ImplicitInstantiation:
707 return !Context.getLangOpts().AppleKext ?
708 llvm::GlobalVariable::LinkOnceODRLinkage :
709 llvm::Function::InternalLinkage;
710
711 case TSK_ExplicitInstantiationDefinition:
712 return !Context.getLangOpts().AppleKext ?
713 llvm::GlobalVariable::WeakODRLinkage :
714 llvm::Function::InternalLinkage;
715
716 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola889a6752013-09-03 21:05:13 +0000717 llvm_unreachable("Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000718 }
719 }
720
721 // -fapple-kext mode does not support weak linkage, so we must use
722 // internal linkage.
723 if (Context.getLangOpts().AppleKext)
724 return llvm::Function::InternalLinkage;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700725
726 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
727 llvm::GlobalValue::LinkOnceODRLinkage;
728 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
729 llvm::GlobalValue::WeakODRLinkage;
730 if (RD->hasAttr<DLLExportAttr>()) {
731 // Cannot discard exported vtables.
732 DiscardableODRLinkage = NonDiscardableODRLinkage;
733 } else if (RD->hasAttr<DLLImportAttr>()) {
734 // Imported vtables are available externally.
735 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
736 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
737 }
738
John McCalld5617ee2013-01-25 22:31:03 +0000739 switch (RD->getTemplateSpecializationKind()) {
740 case TSK_Undeclared:
741 case TSK_ExplicitSpecialization:
742 case TSK_ImplicitInstantiation:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700743 return DiscardableODRLinkage;
John McCalld5617ee2013-01-25 22:31:03 +0000744
745 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola889a6752013-09-03 21:05:13 +0000746 llvm_unreachable("Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000747
748 case TSK_ExplicitInstantiationDefinition:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700749 return NonDiscardableODRLinkage;
John McCalld5617ee2013-01-25 22:31:03 +0000750 }
751
752 llvm_unreachable("Invalid TemplateSpecializationKind!");
753}
754
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700755/// This is a callback from Sema to tell us that that a particular v-table is
756/// required to be emitted in this translation unit.
John McCalld5617ee2013-01-25 22:31:03 +0000757///
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700758/// This is only called for vtables that _must_ be emitted (mainly due to key
759/// functions). For weak vtables, CodeGen tracks when they are needed and
760/// emits them as-needed.
761void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCalld5617ee2013-01-25 22:31:03 +0000762 VTables.GenerateClassData(theClass);
763}
764
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000765void
John McCalld5617ee2013-01-25 22:31:03 +0000766CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikie6a29f672013-08-22 15:23:05 +0000767 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
768 DI->completeClassData(RD);
769
Reid Kleckner90633022013-06-19 15:20:38 +0000770 if (RD->getNumVBases())
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000771 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregor1e201b42010-04-08 15:52:03 +0000772
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000773 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000774}
John McCalld5617ee2013-01-25 22:31:03 +0000775
776/// At this point in the translation unit, does it appear that can we
777/// rely on the vtable being defined elsewhere in the program?
778///
779/// The response is really only definitive when called at the end of
780/// the translation unit.
781///
782/// The only semantic restriction here is that the object file should
783/// not contain a v-table definition when that v-table is defined
784/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
785/// v-tables when unnecessary.
786bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700787 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCalld5617ee2013-01-25 22:31:03 +0000788
789 // If we have an explicit instantiation declaration (and not a
790 // definition), the v-table is defined elsewhere.
791 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
792 if (TSK == TSK_ExplicitInstantiationDeclaration)
793 return true;
794
795 // Otherwise, if the class is an instantiated template, the
796 // v-table must be defined here.
797 if (TSK == TSK_ImplicitInstantiation ||
798 TSK == TSK_ExplicitInstantiationDefinition)
799 return false;
800
801 // Otherwise, if the class doesn't have a key function (possibly
802 // anymore), the v-table must be defined here.
803 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
804 if (!keyFunction)
805 return false;
806
807 // Otherwise, if we don't have a definition of the key function, the
808 // v-table must be defined somewhere else.
809 return !keyFunction->hasBody();
810}
811
812/// Given that we're currently at the end of the translation unit, and
813/// we've emitted a reference to the v-table for this class, should
814/// we define that v-table?
815static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
816 const CXXRecordDecl *RD) {
John McCalld5617ee2013-01-25 22:31:03 +0000817 return !CGM.getVTables().isVTableExternal(RD);
818}
819
820/// Given that at some point we emitted a reference to one or more
821/// v-tables, and that we are now at the end of the translation unit,
822/// decide whether we should emit them.
823void CodeGenModule::EmitDeferredVTables() {
824#ifndef NDEBUG
825 // Remember the size of DeferredVTables, because we're going to assume
826 // that this entire operation doesn't modify it.
827 size_t savedSize = DeferredVTables.size();
828#endif
829
830 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
831 for (const_iterator i = DeferredVTables.begin(),
832 e = DeferredVTables.end(); i != e; ++i) {
833 const CXXRecordDecl *RD = *i;
834 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
835 VTables.GenerateClassData(RD);
836 }
837
838 assert(savedSize == DeferredVTables.size() &&
839 "deferred extra v-tables during v-table emission?");
840 DeferredVTables.clear();
841}
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700842
843void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
844 const VTableLayout &VTLayout) {
845 if (!LangOpts.Sanitize.has(SanitizerKind::CFIVptr))
846 return;
847
848 llvm::Metadata *VTableMD = llvm::ConstantAsMetadata::get(VTable);
849
850 std::vector<llvm::MDTuple *> BitsetEntries;
851 // Create a bit set entry for each address point.
852 for (auto &&AP : VTLayout.getAddressPoints()) {
853 // FIXME: Add blacklisting scheme.
854 if (AP.first.getBase()->isInStdNamespace())
855 continue;
856
857 std::string OutName;
858 llvm::raw_string_ostream Out(OutName);
859 getCXXABI().getMangleContext().mangleCXXVTableBitSet(AP.first.getBase(),
860 Out);
861
862 CharUnits PointerWidth =
863 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
864 uint64_t AddrPointOffset = AP.second * PointerWidth.getQuantity();
865
866 llvm::Metadata *BitsetOps[] = {
867 llvm::MDString::get(getLLVMContext(), Out.str()),
868 VTableMD,
869 llvm::ConstantAsMetadata::get(
870 llvm::ConstantInt::get(Int64Ty, AddrPointOffset))};
871 llvm::MDTuple *BitsetEntry =
872 llvm::MDTuple::get(getLLVMContext(), BitsetOps);
873 BitsetEntries.push_back(BitsetEntry);
874 }
875
876 // Sort the bit set entries for determinism.
877 std::sort(BitsetEntries.begin(), BitsetEntries.end(), [](llvm::MDTuple *T1,
878 llvm::MDTuple *T2) {
879 if (T1 == T2)
880 return false;
881
882 StringRef S1 = cast<llvm::MDString>(T1->getOperand(0))->getString();
883 StringRef S2 = cast<llvm::MDString>(T2->getOperand(0))->getString();
884 if (S1 < S2)
885 return true;
886 if (S1 != S2)
887 return false;
888
889 uint64_t Offset1 = cast<llvm::ConstantInt>(
890 cast<llvm::ConstantAsMetadata>(T1->getOperand(2))
891 ->getValue())->getZExtValue();
892 uint64_t Offset2 = cast<llvm::ConstantInt>(
893 cast<llvm::ConstantAsMetadata>(T2->getOperand(2))
894 ->getValue())->getZExtValue();
895 assert(Offset1 != Offset2);
896 return Offset1 < Offset2;
897 });
898
899 llvm::NamedMDNode *BitsetsMD =
900 getModule().getOrInsertNamedMetadata("llvm.bitsets");
901 for (auto BitsetEntry : BitsetEntries)
902 BitsetsMD->addOperand(BitsetEntry);
903}