1f4a2713aSLionel Sambuc //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This contains code dealing with C++ code generation of virtual tables.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc
14f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
15f4a2713aSLionel Sambuc #include "CGCXXABI.h"
16f4a2713aSLionel Sambuc #include "CodeGenModule.h"
17f4a2713aSLionel Sambuc #include "clang/AST/CXXInheritance.h"
18f4a2713aSLionel Sambuc #include "clang/AST/RecordLayout.h"
19f4a2713aSLionel Sambuc #include "clang/CodeGen/CGFunctionInfo.h"
20f4a2713aSLionel Sambuc #include "clang/Frontend/CodeGenOptions.h"
21f4a2713aSLionel Sambuc #include "llvm/ADT/DenseSet.h"
22f4a2713aSLionel Sambuc #include "llvm/ADT/SetVector.h"
23f4a2713aSLionel Sambuc #include "llvm/Support/Compiler.h"
24f4a2713aSLionel Sambuc #include "llvm/Support/Format.h"
25f4a2713aSLionel Sambuc #include "llvm/Transforms/Utils/Cloning.h"
26f4a2713aSLionel Sambuc #include <algorithm>
27f4a2713aSLionel Sambuc #include <cstdio>
28f4a2713aSLionel Sambuc
29f4a2713aSLionel Sambuc using namespace clang;
30f4a2713aSLionel Sambuc using namespace CodeGen;
31f4a2713aSLionel Sambuc
CodeGenVTables(CodeGenModule & CGM)32f4a2713aSLionel Sambuc CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
33*0a6a1f1dSLionel Sambuc : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
34f4a2713aSLionel Sambuc
GetAddrOfThunk(GlobalDecl GD,const ThunkInfo & Thunk)35f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
36f4a2713aSLionel Sambuc const ThunkInfo &Thunk) {
37f4a2713aSLionel Sambuc const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38f4a2713aSLionel Sambuc
39f4a2713aSLionel Sambuc // Compute the mangled name.
40f4a2713aSLionel Sambuc SmallString<256> Name;
41f4a2713aSLionel Sambuc llvm::raw_svector_ostream Out(Name);
42f4a2713aSLionel Sambuc if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
43f4a2713aSLionel Sambuc getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
44f4a2713aSLionel Sambuc Thunk.This, Out);
45f4a2713aSLionel Sambuc else
46f4a2713aSLionel Sambuc getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
47f4a2713aSLionel Sambuc Out.flush();
48f4a2713aSLionel Sambuc
49f4a2713aSLionel Sambuc llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
50*0a6a1f1dSLionel Sambuc return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
51*0a6a1f1dSLionel Sambuc /*DontDefer=*/true, /*IsThunk=*/true);
52f4a2713aSLionel Sambuc }
53f4a2713aSLionel Sambuc
setThunkVisibility(CodeGenModule & CGM,const CXXMethodDecl * MD,const ThunkInfo & Thunk,llvm::Function * Fn)54f4a2713aSLionel Sambuc static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
55f4a2713aSLionel Sambuc const ThunkInfo &Thunk, llvm::Function *Fn) {
56f4a2713aSLionel Sambuc CGM.setGlobalVisibility(Fn, MD);
57f4a2713aSLionel Sambuc }
58f4a2713aSLionel Sambuc
59f4a2713aSLionel Sambuc #ifndef NDEBUG
similar(const ABIArgInfo & infoL,CanQualType typeL,const ABIArgInfo & infoR,CanQualType typeR)60f4a2713aSLionel Sambuc static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61f4a2713aSLionel Sambuc const ABIArgInfo &infoR, CanQualType typeR) {
62f4a2713aSLionel Sambuc return (infoL.getKind() == infoR.getKind() &&
63f4a2713aSLionel Sambuc (typeL == typeR ||
64f4a2713aSLionel Sambuc (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65f4a2713aSLionel Sambuc (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66f4a2713aSLionel Sambuc }
67f4a2713aSLionel Sambuc #endif
68f4a2713aSLionel Sambuc
PerformReturnAdjustment(CodeGenFunction & CGF,QualType ResultType,RValue RV,const ThunkInfo & Thunk)69f4a2713aSLionel Sambuc static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70f4a2713aSLionel Sambuc QualType ResultType, RValue RV,
71f4a2713aSLionel Sambuc const ThunkInfo &Thunk) {
72f4a2713aSLionel Sambuc // Emit the return adjustment.
73f4a2713aSLionel Sambuc bool NullCheckValue = !ResultType->isReferenceType();
74f4a2713aSLionel Sambuc
75*0a6a1f1dSLionel Sambuc llvm::BasicBlock *AdjustNull = nullptr;
76*0a6a1f1dSLionel Sambuc llvm::BasicBlock *AdjustNotNull = nullptr;
77*0a6a1f1dSLionel Sambuc llvm::BasicBlock *AdjustEnd = nullptr;
78f4a2713aSLionel Sambuc
79f4a2713aSLionel Sambuc llvm::Value *ReturnValue = RV.getScalarVal();
80f4a2713aSLionel Sambuc
81f4a2713aSLionel Sambuc if (NullCheckValue) {
82f4a2713aSLionel Sambuc AdjustNull = CGF.createBasicBlock("adjust.null");
83f4a2713aSLionel Sambuc AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84f4a2713aSLionel Sambuc AdjustEnd = CGF.createBasicBlock("adjust.end");
85f4a2713aSLionel Sambuc
86f4a2713aSLionel Sambuc llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87f4a2713aSLionel Sambuc CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88f4a2713aSLionel Sambuc CGF.EmitBlock(AdjustNotNull);
89f4a2713aSLionel Sambuc }
90f4a2713aSLionel Sambuc
91f4a2713aSLionel Sambuc ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
92f4a2713aSLionel Sambuc Thunk.Return);
93f4a2713aSLionel Sambuc
94f4a2713aSLionel Sambuc if (NullCheckValue) {
95f4a2713aSLionel Sambuc CGF.Builder.CreateBr(AdjustEnd);
96f4a2713aSLionel Sambuc CGF.EmitBlock(AdjustNull);
97f4a2713aSLionel Sambuc CGF.Builder.CreateBr(AdjustEnd);
98f4a2713aSLionel Sambuc CGF.EmitBlock(AdjustEnd);
99f4a2713aSLionel Sambuc
100f4a2713aSLionel Sambuc llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
101f4a2713aSLionel Sambuc PHI->addIncoming(ReturnValue, AdjustNotNull);
102f4a2713aSLionel Sambuc PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
103f4a2713aSLionel Sambuc AdjustNull);
104f4a2713aSLionel Sambuc ReturnValue = PHI;
105f4a2713aSLionel Sambuc }
106f4a2713aSLionel Sambuc
107f4a2713aSLionel Sambuc return RValue::get(ReturnValue);
108f4a2713aSLionel Sambuc }
109f4a2713aSLionel Sambuc
110f4a2713aSLionel Sambuc // This function does roughly the same thing as GenerateThunk, but in a
111f4a2713aSLionel Sambuc // very different way, so that va_start and va_end work correctly.
112f4a2713aSLionel Sambuc // FIXME: This function assumes "this" is the first non-sret LLVM argument of
113f4a2713aSLionel Sambuc // a function, and that there is an alloca built in the entry block
114f4a2713aSLionel Sambuc // for all accesses to "this".
115f4a2713aSLionel Sambuc // FIXME: This function assumes there is only one "ret" statement per function.
116f4a2713aSLionel Sambuc // FIXME: Cloning isn't correct in the presence of indirect goto!
117f4a2713aSLionel Sambuc // FIXME: This implementation of thunks bloats codesize by duplicating the
118f4a2713aSLionel Sambuc // function definition. There are alternatives:
119f4a2713aSLionel Sambuc // 1. Add some sort of stub support to LLVM for cases where we can
120f4a2713aSLionel Sambuc // do a this adjustment, then a sibcall.
121f4a2713aSLionel Sambuc // 2. We could transform the definition to take a va_list instead of an
122f4a2713aSLionel Sambuc // actual variable argument list, then have the thunks (including a
123f4a2713aSLionel Sambuc // no-op thunk for the regular definition) call va_start/va_end.
124f4a2713aSLionel Sambuc // There's a bit of per-call overhead for this solution, but it's
125f4a2713aSLionel Sambuc // better for codesize if the definition is long.
GenerateVarArgsThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk)126f4a2713aSLionel Sambuc void CodeGenFunction::GenerateVarArgsThunk(
127f4a2713aSLionel Sambuc llvm::Function *Fn,
128f4a2713aSLionel Sambuc const CGFunctionInfo &FnInfo,
129f4a2713aSLionel Sambuc GlobalDecl GD, const ThunkInfo &Thunk) {
130f4a2713aSLionel Sambuc const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
131f4a2713aSLionel Sambuc const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
132*0a6a1f1dSLionel Sambuc QualType ResultType = FPT->getReturnType();
133f4a2713aSLionel Sambuc
134f4a2713aSLionel Sambuc // Get the original function
135f4a2713aSLionel Sambuc assert(FnInfo.isVariadic());
136f4a2713aSLionel Sambuc llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
137f4a2713aSLionel Sambuc llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
138f4a2713aSLionel Sambuc llvm::Function *BaseFn = cast<llvm::Function>(Callee);
139f4a2713aSLionel Sambuc
140f4a2713aSLionel Sambuc // Clone to thunk.
141f4a2713aSLionel Sambuc llvm::ValueToValueMapTy VMap;
142f4a2713aSLionel Sambuc llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
143f4a2713aSLionel Sambuc /*ModuleLevelChanges=*/false);
144f4a2713aSLionel Sambuc CGM.getModule().getFunctionList().push_back(NewFn);
145f4a2713aSLionel Sambuc Fn->replaceAllUsesWith(NewFn);
146f4a2713aSLionel Sambuc NewFn->takeName(Fn);
147f4a2713aSLionel Sambuc Fn->eraseFromParent();
148f4a2713aSLionel Sambuc Fn = NewFn;
149f4a2713aSLionel Sambuc
150f4a2713aSLionel Sambuc // "Initialize" CGF (minimally).
151f4a2713aSLionel Sambuc CurFn = Fn;
152f4a2713aSLionel Sambuc
153f4a2713aSLionel Sambuc // Get the "this" value
154f4a2713aSLionel Sambuc llvm::Function::arg_iterator AI = Fn->arg_begin();
155f4a2713aSLionel Sambuc if (CGM.ReturnTypeUsesSRet(FnInfo))
156f4a2713aSLionel Sambuc ++AI;
157f4a2713aSLionel Sambuc
158f4a2713aSLionel Sambuc // Find the first store of "this", which will be to the alloca associated
159f4a2713aSLionel Sambuc // with "this".
160f4a2713aSLionel Sambuc llvm::Value *ThisPtr = &*AI;
161f4a2713aSLionel Sambuc llvm::BasicBlock *EntryBB = Fn->begin();
162*0a6a1f1dSLionel Sambuc llvm::Instruction *ThisStore =
163*0a6a1f1dSLionel Sambuc std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
164*0a6a1f1dSLionel Sambuc return isa<llvm::StoreInst>(I) && I.getOperand(0) == ThisPtr;
165*0a6a1f1dSLionel Sambuc });
166f4a2713aSLionel Sambuc assert(ThisStore && "Store of this should be in entry block?");
167f4a2713aSLionel Sambuc // Adjust "this", if necessary.
168f4a2713aSLionel Sambuc Builder.SetInsertPoint(ThisStore);
169f4a2713aSLionel Sambuc llvm::Value *AdjustedThisPtr =
170f4a2713aSLionel Sambuc CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
171f4a2713aSLionel Sambuc ThisStore->setOperand(0, AdjustedThisPtr);
172f4a2713aSLionel Sambuc
173f4a2713aSLionel Sambuc if (!Thunk.Return.isEmpty()) {
174f4a2713aSLionel Sambuc // Fix up the returned value, if necessary.
175f4a2713aSLionel Sambuc for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
176f4a2713aSLionel Sambuc llvm::Instruction *T = I->getTerminator();
177f4a2713aSLionel Sambuc if (isa<llvm::ReturnInst>(T)) {
178f4a2713aSLionel Sambuc RValue RV = RValue::get(T->getOperand(0));
179f4a2713aSLionel Sambuc T->eraseFromParent();
180f4a2713aSLionel Sambuc Builder.SetInsertPoint(&*I);
181f4a2713aSLionel Sambuc RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
182f4a2713aSLionel Sambuc Builder.CreateRet(RV.getScalarVal());
183f4a2713aSLionel Sambuc break;
184f4a2713aSLionel Sambuc }
185f4a2713aSLionel Sambuc }
186f4a2713aSLionel Sambuc }
187f4a2713aSLionel Sambuc }
188f4a2713aSLionel Sambuc
StartThunk(llvm::Function * Fn,GlobalDecl GD,const CGFunctionInfo & FnInfo)189f4a2713aSLionel Sambuc void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
190f4a2713aSLionel Sambuc const CGFunctionInfo &FnInfo) {
191f4a2713aSLionel Sambuc assert(!CurGD.getDecl() && "CurGD was already set!");
192f4a2713aSLionel Sambuc CurGD = GD;
193*0a6a1f1dSLionel Sambuc CurFuncIsThunk = true;
194f4a2713aSLionel Sambuc
195f4a2713aSLionel Sambuc // Build FunctionArgs.
196f4a2713aSLionel Sambuc const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
197f4a2713aSLionel Sambuc QualType ThisType = MD->getThisType(getContext());
198f4a2713aSLionel Sambuc const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
199*0a6a1f1dSLionel Sambuc QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
200*0a6a1f1dSLionel Sambuc ? ThisType
201*0a6a1f1dSLionel Sambuc : CGM.getCXXABI().hasMostDerivedReturn(GD)
202*0a6a1f1dSLionel Sambuc ? CGM.getContext().VoidPtrTy
203*0a6a1f1dSLionel Sambuc : FPT->getReturnType();
204f4a2713aSLionel Sambuc FunctionArgList FunctionArgs;
205f4a2713aSLionel Sambuc
206f4a2713aSLionel Sambuc // Create the implicit 'this' parameter declaration.
207*0a6a1f1dSLionel Sambuc CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
208f4a2713aSLionel Sambuc
209f4a2713aSLionel Sambuc // Add the rest of the parameters.
210*0a6a1f1dSLionel Sambuc FunctionArgs.append(MD->param_begin(), MD->param_end());
211*0a6a1f1dSLionel Sambuc
212*0a6a1f1dSLionel Sambuc if (isa<CXXDestructorDecl>(MD))
213*0a6a1f1dSLionel Sambuc CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
214f4a2713aSLionel Sambuc
215f4a2713aSLionel Sambuc // Start defining the function.
216f4a2713aSLionel Sambuc StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
217*0a6a1f1dSLionel Sambuc MD->getLocation(), MD->getLocation());
218f4a2713aSLionel Sambuc
219f4a2713aSLionel Sambuc // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
220f4a2713aSLionel Sambuc CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
221f4a2713aSLionel Sambuc CXXThisValue = CXXABIThisValue;
222f4a2713aSLionel Sambuc }
223f4a2713aSLionel Sambuc
EmitCallAndReturnForThunk(llvm::Value * Callee,const ThunkInfo * Thunk)224*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
225f4a2713aSLionel Sambuc const ThunkInfo *Thunk) {
226f4a2713aSLionel Sambuc assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
227f4a2713aSLionel Sambuc "Please use a new CGF for this thunk");
228*0a6a1f1dSLionel Sambuc const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
229f4a2713aSLionel Sambuc
230f4a2713aSLionel Sambuc // Adjust the 'this' pointer if necessary
231f4a2713aSLionel Sambuc llvm::Value *AdjustedThisPtr = Thunk ? CGM.getCXXABI().performThisAdjustment(
232f4a2713aSLionel Sambuc *this, LoadCXXThis(), Thunk->This)
233f4a2713aSLionel Sambuc : LoadCXXThis();
234f4a2713aSLionel Sambuc
235*0a6a1f1dSLionel Sambuc if (CurFnInfo->usesInAlloca()) {
236*0a6a1f1dSLionel Sambuc // We don't handle return adjusting thunks, because they require us to call
237*0a6a1f1dSLionel Sambuc // the copy constructor. For now, fall through and pretend the return
238*0a6a1f1dSLionel Sambuc // adjustment was empty so we don't crash.
239*0a6a1f1dSLionel Sambuc if (Thunk && !Thunk->Return.isEmpty()) {
240*0a6a1f1dSLionel Sambuc CGM.ErrorUnsupported(
241*0a6a1f1dSLionel Sambuc MD, "non-trivial argument copy for return-adjusting thunk");
242*0a6a1f1dSLionel Sambuc }
243*0a6a1f1dSLionel Sambuc EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
244*0a6a1f1dSLionel Sambuc return;
245*0a6a1f1dSLionel Sambuc }
246*0a6a1f1dSLionel Sambuc
247f4a2713aSLionel Sambuc // Start building CallArgs.
248f4a2713aSLionel Sambuc CallArgList CallArgs;
249f4a2713aSLionel Sambuc QualType ThisType = MD->getThisType(getContext());
250f4a2713aSLionel Sambuc CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
251f4a2713aSLionel Sambuc
252f4a2713aSLionel Sambuc if (isa<CXXDestructorDecl>(MD))
253*0a6a1f1dSLionel Sambuc CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
254f4a2713aSLionel Sambuc
255f4a2713aSLionel Sambuc // Add the rest of the arguments.
256*0a6a1f1dSLionel Sambuc for (const ParmVarDecl *PD : MD->params())
257*0a6a1f1dSLionel Sambuc EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
258f4a2713aSLionel Sambuc
259f4a2713aSLionel Sambuc const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
260f4a2713aSLionel Sambuc
261f4a2713aSLionel Sambuc #ifndef NDEBUG
262f4a2713aSLionel Sambuc const CGFunctionInfo &CallFnInfo =
263f4a2713aSLionel Sambuc CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
264f4a2713aSLionel Sambuc RequiredArgs::forPrototypePlus(FPT, 1));
265f4a2713aSLionel Sambuc assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
266f4a2713aSLionel Sambuc CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
267f4a2713aSLionel Sambuc CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
268f4a2713aSLionel Sambuc assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
269f4a2713aSLionel Sambuc similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
270f4a2713aSLionel Sambuc CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
271f4a2713aSLionel Sambuc assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
272f4a2713aSLionel Sambuc for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
273f4a2713aSLionel Sambuc assert(similar(CallFnInfo.arg_begin()[i].info,
274f4a2713aSLionel Sambuc CallFnInfo.arg_begin()[i].type,
275f4a2713aSLionel Sambuc CurFnInfo->arg_begin()[i].info,
276f4a2713aSLionel Sambuc CurFnInfo->arg_begin()[i].type));
277f4a2713aSLionel Sambuc #endif
278f4a2713aSLionel Sambuc
279f4a2713aSLionel Sambuc // Determine whether we have a return value slot to use.
280*0a6a1f1dSLionel Sambuc QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
281*0a6a1f1dSLionel Sambuc ? ThisType
282*0a6a1f1dSLionel Sambuc : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
283*0a6a1f1dSLionel Sambuc ? CGM.getContext().VoidPtrTy
284*0a6a1f1dSLionel Sambuc : FPT->getReturnType();
285f4a2713aSLionel Sambuc ReturnValueSlot Slot;
286f4a2713aSLionel Sambuc if (!ResultType->isVoidType() &&
287f4a2713aSLionel Sambuc CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
288f4a2713aSLionel Sambuc !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
289f4a2713aSLionel Sambuc Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
290f4a2713aSLionel Sambuc
291f4a2713aSLionel Sambuc // Now emit our call.
292*0a6a1f1dSLionel Sambuc llvm::Instruction *CallOrInvoke;
293*0a6a1f1dSLionel Sambuc RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
294f4a2713aSLionel Sambuc
295f4a2713aSLionel Sambuc // Consider return adjustment if we have ThunkInfo.
296f4a2713aSLionel Sambuc if (Thunk && !Thunk->Return.isEmpty())
297f4a2713aSLionel Sambuc RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
298f4a2713aSLionel Sambuc
299f4a2713aSLionel Sambuc // Emit return.
300f4a2713aSLionel Sambuc if (!ResultType->isVoidType() && Slot.isNull())
301f4a2713aSLionel Sambuc CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
302f4a2713aSLionel Sambuc
303f4a2713aSLionel Sambuc // Disable the final ARC autorelease.
304f4a2713aSLionel Sambuc AutoreleaseResult = false;
305f4a2713aSLionel Sambuc
306f4a2713aSLionel Sambuc FinishFunction();
307f4a2713aSLionel Sambuc }
308f4a2713aSLionel Sambuc
EmitMustTailThunk(const CXXMethodDecl * MD,llvm::Value * AdjustedThisPtr,llvm::Value * Callee)309*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
310*0a6a1f1dSLionel Sambuc llvm::Value *AdjustedThisPtr,
311*0a6a1f1dSLionel Sambuc llvm::Value *Callee) {
312*0a6a1f1dSLionel Sambuc // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
313*0a6a1f1dSLionel Sambuc // to translate AST arguments into LLVM IR arguments. For thunks, we know
314*0a6a1f1dSLionel Sambuc // that the caller prototype more or less matches the callee prototype with
315*0a6a1f1dSLionel Sambuc // the exception of 'this'.
316*0a6a1f1dSLionel Sambuc SmallVector<llvm::Value *, 8> Args;
317*0a6a1f1dSLionel Sambuc for (llvm::Argument &A : CurFn->args())
318*0a6a1f1dSLionel Sambuc Args.push_back(&A);
319*0a6a1f1dSLionel Sambuc
320*0a6a1f1dSLionel Sambuc // Set the adjusted 'this' pointer.
321*0a6a1f1dSLionel Sambuc const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
322*0a6a1f1dSLionel Sambuc if (ThisAI.isDirect()) {
323*0a6a1f1dSLionel Sambuc const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
324*0a6a1f1dSLionel Sambuc int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
325*0a6a1f1dSLionel Sambuc llvm::Type *ThisType = Args[ThisArgNo]->getType();
326*0a6a1f1dSLionel Sambuc if (ThisType != AdjustedThisPtr->getType())
327*0a6a1f1dSLionel Sambuc AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
328*0a6a1f1dSLionel Sambuc Args[ThisArgNo] = AdjustedThisPtr;
329*0a6a1f1dSLionel Sambuc } else {
330*0a6a1f1dSLionel Sambuc assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
331*0a6a1f1dSLionel Sambuc llvm::Value *ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
332*0a6a1f1dSLionel Sambuc llvm::Type *ThisType =
333*0a6a1f1dSLionel Sambuc cast<llvm::PointerType>(ThisAddr->getType())->getElementType();
334*0a6a1f1dSLionel Sambuc if (ThisType != AdjustedThisPtr->getType())
335*0a6a1f1dSLionel Sambuc AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
336*0a6a1f1dSLionel Sambuc Builder.CreateStore(AdjustedThisPtr, ThisAddr);
337*0a6a1f1dSLionel Sambuc }
338*0a6a1f1dSLionel Sambuc
339*0a6a1f1dSLionel Sambuc // Emit the musttail call manually. Even if the prologue pushed cleanups, we
340*0a6a1f1dSLionel Sambuc // don't actually want to run them.
341*0a6a1f1dSLionel Sambuc llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
342*0a6a1f1dSLionel Sambuc Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
343*0a6a1f1dSLionel Sambuc
344*0a6a1f1dSLionel Sambuc // Apply the standard set of call attributes.
345*0a6a1f1dSLionel Sambuc unsigned CallingConv;
346*0a6a1f1dSLionel Sambuc CodeGen::AttributeListType AttributeList;
347*0a6a1f1dSLionel Sambuc CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
348*0a6a1f1dSLionel Sambuc /*AttrOnCallSite=*/true);
349*0a6a1f1dSLionel Sambuc llvm::AttributeSet Attrs =
350*0a6a1f1dSLionel Sambuc llvm::AttributeSet::get(getLLVMContext(), AttributeList);
351*0a6a1f1dSLionel Sambuc Call->setAttributes(Attrs);
352*0a6a1f1dSLionel Sambuc Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
353*0a6a1f1dSLionel Sambuc
354*0a6a1f1dSLionel Sambuc if (Call->getType()->isVoidTy())
355*0a6a1f1dSLionel Sambuc Builder.CreateRetVoid();
356*0a6a1f1dSLionel Sambuc else
357*0a6a1f1dSLionel Sambuc Builder.CreateRet(Call);
358*0a6a1f1dSLionel Sambuc
359*0a6a1f1dSLionel Sambuc // Finish the function to maintain CodeGenFunction invariants.
360*0a6a1f1dSLionel Sambuc // FIXME: Don't emit unreachable code.
361*0a6a1f1dSLionel Sambuc EmitBlock(createBasicBlock());
362*0a6a1f1dSLionel Sambuc FinishFunction();
363*0a6a1f1dSLionel Sambuc }
364*0a6a1f1dSLionel Sambuc
GenerateThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk)365f4a2713aSLionel Sambuc void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
366f4a2713aSLionel Sambuc const CGFunctionInfo &FnInfo,
367f4a2713aSLionel Sambuc GlobalDecl GD, const ThunkInfo &Thunk) {
368f4a2713aSLionel Sambuc StartThunk(Fn, GD, FnInfo);
369f4a2713aSLionel Sambuc
370f4a2713aSLionel Sambuc // Get our callee.
371f4a2713aSLionel Sambuc llvm::Type *Ty =
372f4a2713aSLionel Sambuc CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
373f4a2713aSLionel Sambuc llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
374f4a2713aSLionel Sambuc
375f4a2713aSLionel Sambuc // Make the call and return the result.
376*0a6a1f1dSLionel Sambuc EmitCallAndReturnForThunk(Callee, &Thunk);
377f4a2713aSLionel Sambuc
378f4a2713aSLionel Sambuc // Set the right linkage.
379f4a2713aSLionel Sambuc CGM.setFunctionLinkage(GD, Fn);
380f4a2713aSLionel Sambuc
381f4a2713aSLionel Sambuc // Set the right visibility.
382f4a2713aSLionel Sambuc const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
383f4a2713aSLionel Sambuc setThunkVisibility(CGM, MD, Thunk, Fn);
384f4a2713aSLionel Sambuc }
385f4a2713aSLionel Sambuc
emitThunk(GlobalDecl GD,const ThunkInfo & Thunk,bool ForVTable)386f4a2713aSLionel Sambuc void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
387f4a2713aSLionel Sambuc bool ForVTable) {
388f4a2713aSLionel Sambuc const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
389f4a2713aSLionel Sambuc
390f4a2713aSLionel Sambuc // FIXME: re-use FnInfo in this computation.
391*0a6a1f1dSLionel Sambuc llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
392*0a6a1f1dSLionel Sambuc llvm::GlobalValue *Entry;
393f4a2713aSLionel Sambuc
394f4a2713aSLionel Sambuc // Strip off a bitcast if we got one back.
395*0a6a1f1dSLionel Sambuc if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
396f4a2713aSLionel Sambuc assert(CE->getOpcode() == llvm::Instruction::BitCast);
397*0a6a1f1dSLionel Sambuc Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
398*0a6a1f1dSLionel Sambuc } else {
399*0a6a1f1dSLionel Sambuc Entry = cast<llvm::GlobalValue>(C);
400f4a2713aSLionel Sambuc }
401f4a2713aSLionel Sambuc
402f4a2713aSLionel Sambuc // There's already a declaration with the same name, check if it has the same
403f4a2713aSLionel Sambuc // type or if we need to replace it.
404*0a6a1f1dSLionel Sambuc if (Entry->getType()->getElementType() !=
405f4a2713aSLionel Sambuc CGM.getTypes().GetFunctionTypeForVTable(GD)) {
406*0a6a1f1dSLionel Sambuc llvm::GlobalValue *OldThunkFn = Entry;
407f4a2713aSLionel Sambuc
408f4a2713aSLionel Sambuc // If the types mismatch then we have to rewrite the definition.
409f4a2713aSLionel Sambuc assert(OldThunkFn->isDeclaration() &&
410f4a2713aSLionel Sambuc "Shouldn't replace non-declaration");
411f4a2713aSLionel Sambuc
412f4a2713aSLionel Sambuc // Remove the name from the old thunk function and get a new thunk.
413f4a2713aSLionel Sambuc OldThunkFn->setName(StringRef());
414*0a6a1f1dSLionel Sambuc Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
415f4a2713aSLionel Sambuc
416f4a2713aSLionel Sambuc // If needed, replace the old thunk with a bitcast.
417f4a2713aSLionel Sambuc if (!OldThunkFn->use_empty()) {
418f4a2713aSLionel Sambuc llvm::Constant *NewPtrForOldDecl =
419f4a2713aSLionel Sambuc llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
420f4a2713aSLionel Sambuc OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
421f4a2713aSLionel Sambuc }
422f4a2713aSLionel Sambuc
423f4a2713aSLionel Sambuc // Remove the old thunk.
424f4a2713aSLionel Sambuc OldThunkFn->eraseFromParent();
425f4a2713aSLionel Sambuc }
426f4a2713aSLionel Sambuc
427f4a2713aSLionel Sambuc llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
428f4a2713aSLionel Sambuc bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
429f4a2713aSLionel Sambuc bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
430f4a2713aSLionel Sambuc
431f4a2713aSLionel Sambuc if (!ThunkFn->isDeclaration()) {
432f4a2713aSLionel Sambuc if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
433f4a2713aSLionel Sambuc // There is already a thunk emitted for this function, do nothing.
434f4a2713aSLionel Sambuc return;
435f4a2713aSLionel Sambuc }
436f4a2713aSLionel Sambuc
437f4a2713aSLionel Sambuc // Change the linkage.
438f4a2713aSLionel Sambuc CGM.setFunctionLinkage(GD, ThunkFn);
439f4a2713aSLionel Sambuc return;
440f4a2713aSLionel Sambuc }
441f4a2713aSLionel Sambuc
442f4a2713aSLionel Sambuc CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
443f4a2713aSLionel Sambuc
444f4a2713aSLionel Sambuc if (ThunkFn->isVarArg()) {
445f4a2713aSLionel Sambuc // Varargs thunks are special; we can't just generate a call because
446f4a2713aSLionel Sambuc // we can't copy the varargs. Our implementation is rather
447f4a2713aSLionel Sambuc // expensive/sucky at the moment, so don't generate the thunk unless
448f4a2713aSLionel Sambuc // we have to.
449f4a2713aSLionel Sambuc // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
450*0a6a1f1dSLionel Sambuc if (!UseAvailableExternallyLinkage) {
451f4a2713aSLionel Sambuc CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
452*0a6a1f1dSLionel Sambuc CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
453*0a6a1f1dSLionel Sambuc !Thunk.Return.isEmpty());
454*0a6a1f1dSLionel Sambuc }
455f4a2713aSLionel Sambuc } else {
456f4a2713aSLionel Sambuc // Normal thunk body generation.
457f4a2713aSLionel Sambuc CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
458*0a6a1f1dSLionel Sambuc CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
459*0a6a1f1dSLionel Sambuc !Thunk.Return.isEmpty());
460f4a2713aSLionel Sambuc }
461f4a2713aSLionel Sambuc }
462f4a2713aSLionel Sambuc
maybeEmitThunkForVTable(GlobalDecl GD,const ThunkInfo & Thunk)463f4a2713aSLionel Sambuc void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
464f4a2713aSLionel Sambuc const ThunkInfo &Thunk) {
465f4a2713aSLionel Sambuc // If the ABI has key functions, only the TU with the key function should emit
466f4a2713aSLionel Sambuc // the thunk. However, we can allow inlining of thunks if we emit them with
467f4a2713aSLionel Sambuc // available_externally linkage together with vtables when optimizations are
468f4a2713aSLionel Sambuc // enabled.
469f4a2713aSLionel Sambuc if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
470f4a2713aSLionel Sambuc !CGM.getCodeGenOpts().OptimizationLevel)
471f4a2713aSLionel Sambuc return;
472f4a2713aSLionel Sambuc
473f4a2713aSLionel Sambuc // We can't emit thunks for member functions with incomplete types.
474f4a2713aSLionel Sambuc const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
475f4a2713aSLionel Sambuc if (!CGM.getTypes().isFuncTypeConvertible(
476f4a2713aSLionel Sambuc MD->getType()->castAs<FunctionType>()))
477f4a2713aSLionel Sambuc return;
478f4a2713aSLionel Sambuc
479f4a2713aSLionel Sambuc emitThunk(GD, Thunk, /*ForVTable=*/true);
480f4a2713aSLionel Sambuc }
481f4a2713aSLionel Sambuc
EmitThunks(GlobalDecl GD)482f4a2713aSLionel Sambuc void CodeGenVTables::EmitThunks(GlobalDecl GD)
483f4a2713aSLionel Sambuc {
484f4a2713aSLionel Sambuc const CXXMethodDecl *MD =
485f4a2713aSLionel Sambuc cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
486f4a2713aSLionel Sambuc
487f4a2713aSLionel Sambuc // We don't need to generate thunks for the base destructor.
488f4a2713aSLionel Sambuc if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
489f4a2713aSLionel Sambuc return;
490f4a2713aSLionel Sambuc
491*0a6a1f1dSLionel Sambuc const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
492*0a6a1f1dSLionel Sambuc VTContext->getThunkInfo(GD);
493f4a2713aSLionel Sambuc
494f4a2713aSLionel Sambuc if (!ThunkInfoVector)
495f4a2713aSLionel Sambuc return;
496f4a2713aSLionel Sambuc
497f4a2713aSLionel Sambuc for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
498f4a2713aSLionel Sambuc emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
499f4a2713aSLionel Sambuc }
500f4a2713aSLionel Sambuc
CreateVTableInitializer(const CXXRecordDecl * RD,const VTableComponent * Components,unsigned NumComponents,const VTableLayout::VTableThunkTy * VTableThunks,unsigned NumVTableThunks,llvm::Constant * RTTI)501*0a6a1f1dSLionel Sambuc llvm::Constant *CodeGenVTables::CreateVTableInitializer(
502*0a6a1f1dSLionel Sambuc const CXXRecordDecl *RD, const VTableComponent *Components,
503*0a6a1f1dSLionel Sambuc unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
504*0a6a1f1dSLionel Sambuc unsigned NumVTableThunks, llvm::Constant *RTTI) {
505f4a2713aSLionel Sambuc SmallVector<llvm::Constant *, 64> Inits;
506f4a2713aSLionel Sambuc
507f4a2713aSLionel Sambuc llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
508f4a2713aSLionel Sambuc
509f4a2713aSLionel Sambuc llvm::Type *PtrDiffTy =
510f4a2713aSLionel Sambuc CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
511f4a2713aSLionel Sambuc
512f4a2713aSLionel Sambuc unsigned NextVTableThunkIndex = 0;
513f4a2713aSLionel Sambuc
514*0a6a1f1dSLionel Sambuc llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
515f4a2713aSLionel Sambuc
516f4a2713aSLionel Sambuc for (unsigned I = 0; I != NumComponents; ++I) {
517f4a2713aSLionel Sambuc VTableComponent Component = Components[I];
518f4a2713aSLionel Sambuc
519*0a6a1f1dSLionel Sambuc llvm::Constant *Init = nullptr;
520f4a2713aSLionel Sambuc
521f4a2713aSLionel Sambuc switch (Component.getKind()) {
522f4a2713aSLionel Sambuc case VTableComponent::CK_VCallOffset:
523f4a2713aSLionel Sambuc Init = llvm::ConstantInt::get(PtrDiffTy,
524f4a2713aSLionel Sambuc Component.getVCallOffset().getQuantity());
525f4a2713aSLionel Sambuc Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
526f4a2713aSLionel Sambuc break;
527f4a2713aSLionel Sambuc case VTableComponent::CK_VBaseOffset:
528f4a2713aSLionel Sambuc Init = llvm::ConstantInt::get(PtrDiffTy,
529f4a2713aSLionel Sambuc Component.getVBaseOffset().getQuantity());
530f4a2713aSLionel Sambuc Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
531f4a2713aSLionel Sambuc break;
532f4a2713aSLionel Sambuc case VTableComponent::CK_OffsetToTop:
533f4a2713aSLionel Sambuc Init = llvm::ConstantInt::get(PtrDiffTy,
534f4a2713aSLionel Sambuc Component.getOffsetToTop().getQuantity());
535f4a2713aSLionel Sambuc Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
536f4a2713aSLionel Sambuc break;
537f4a2713aSLionel Sambuc case VTableComponent::CK_RTTI:
538f4a2713aSLionel Sambuc Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
539f4a2713aSLionel Sambuc break;
540f4a2713aSLionel Sambuc case VTableComponent::CK_FunctionPointer:
541f4a2713aSLionel Sambuc case VTableComponent::CK_CompleteDtorPointer:
542f4a2713aSLionel Sambuc case VTableComponent::CK_DeletingDtorPointer: {
543f4a2713aSLionel Sambuc GlobalDecl GD;
544f4a2713aSLionel Sambuc
545f4a2713aSLionel Sambuc // Get the right global decl.
546f4a2713aSLionel Sambuc switch (Component.getKind()) {
547f4a2713aSLionel Sambuc default:
548f4a2713aSLionel Sambuc llvm_unreachable("Unexpected vtable component kind");
549f4a2713aSLionel Sambuc case VTableComponent::CK_FunctionPointer:
550f4a2713aSLionel Sambuc GD = Component.getFunctionDecl();
551f4a2713aSLionel Sambuc break;
552f4a2713aSLionel Sambuc case VTableComponent::CK_CompleteDtorPointer:
553f4a2713aSLionel Sambuc GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
554f4a2713aSLionel Sambuc break;
555f4a2713aSLionel Sambuc case VTableComponent::CK_DeletingDtorPointer:
556f4a2713aSLionel Sambuc GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
557f4a2713aSLionel Sambuc break;
558f4a2713aSLionel Sambuc }
559f4a2713aSLionel Sambuc
560f4a2713aSLionel Sambuc if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
561f4a2713aSLionel Sambuc // We have a pure virtual member function.
562f4a2713aSLionel Sambuc if (!PureVirtualFn) {
563f4a2713aSLionel Sambuc llvm::FunctionType *Ty =
564f4a2713aSLionel Sambuc llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
565f4a2713aSLionel Sambuc StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
566f4a2713aSLionel Sambuc PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
567f4a2713aSLionel Sambuc PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
568f4a2713aSLionel Sambuc CGM.Int8PtrTy);
569f4a2713aSLionel Sambuc }
570f4a2713aSLionel Sambuc Init = PureVirtualFn;
571f4a2713aSLionel Sambuc } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
572f4a2713aSLionel Sambuc if (!DeletedVirtualFn) {
573f4a2713aSLionel Sambuc llvm::FunctionType *Ty =
574f4a2713aSLionel Sambuc llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
575f4a2713aSLionel Sambuc StringRef DeletedCallName =
576f4a2713aSLionel Sambuc CGM.getCXXABI().GetDeletedVirtualCallName();
577f4a2713aSLionel Sambuc DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
578f4a2713aSLionel Sambuc DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
579f4a2713aSLionel Sambuc CGM.Int8PtrTy);
580f4a2713aSLionel Sambuc }
581f4a2713aSLionel Sambuc Init = DeletedVirtualFn;
582f4a2713aSLionel Sambuc } else {
583f4a2713aSLionel Sambuc // Check if we should use a thunk.
584f4a2713aSLionel Sambuc if (NextVTableThunkIndex < NumVTableThunks &&
585f4a2713aSLionel Sambuc VTableThunks[NextVTableThunkIndex].first == I) {
586f4a2713aSLionel Sambuc const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
587f4a2713aSLionel Sambuc
588f4a2713aSLionel Sambuc maybeEmitThunkForVTable(GD, Thunk);
589f4a2713aSLionel Sambuc Init = CGM.GetAddrOfThunk(GD, Thunk);
590f4a2713aSLionel Sambuc
591f4a2713aSLionel Sambuc NextVTableThunkIndex++;
592f4a2713aSLionel Sambuc } else {
593f4a2713aSLionel Sambuc llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
594f4a2713aSLionel Sambuc
595f4a2713aSLionel Sambuc Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
596f4a2713aSLionel Sambuc }
597f4a2713aSLionel Sambuc
598f4a2713aSLionel Sambuc Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
599f4a2713aSLionel Sambuc }
600f4a2713aSLionel Sambuc break;
601f4a2713aSLionel Sambuc }
602f4a2713aSLionel Sambuc
603f4a2713aSLionel Sambuc case VTableComponent::CK_UnusedFunctionPointer:
604f4a2713aSLionel Sambuc Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
605f4a2713aSLionel Sambuc break;
606f4a2713aSLionel Sambuc };
607f4a2713aSLionel Sambuc
608f4a2713aSLionel Sambuc Inits.push_back(Init);
609f4a2713aSLionel Sambuc }
610f4a2713aSLionel Sambuc
611f4a2713aSLionel Sambuc llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
612f4a2713aSLionel Sambuc return llvm::ConstantArray::get(ArrayType, Inits);
613f4a2713aSLionel Sambuc }
614f4a2713aSLionel Sambuc
615f4a2713aSLionel Sambuc llvm::GlobalVariable *
GenerateConstructionVTable(const CXXRecordDecl * RD,const BaseSubobject & Base,bool BaseIsVirtual,llvm::GlobalVariable::LinkageTypes Linkage,VTableAddressPointsMapTy & AddressPoints)616f4a2713aSLionel Sambuc CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
617f4a2713aSLionel Sambuc const BaseSubobject &Base,
618f4a2713aSLionel Sambuc bool BaseIsVirtual,
619f4a2713aSLionel Sambuc llvm::GlobalVariable::LinkageTypes Linkage,
620f4a2713aSLionel Sambuc VTableAddressPointsMapTy& AddressPoints) {
621f4a2713aSLionel Sambuc if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
622f4a2713aSLionel Sambuc DI->completeClassData(Base.getBase());
623f4a2713aSLionel Sambuc
624*0a6a1f1dSLionel Sambuc std::unique_ptr<VTableLayout> VTLayout(
625*0a6a1f1dSLionel Sambuc getItaniumVTableContext().createConstructionVTableLayout(
626f4a2713aSLionel Sambuc Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
627f4a2713aSLionel Sambuc
628f4a2713aSLionel Sambuc // Add the address points.
629f4a2713aSLionel Sambuc AddressPoints = VTLayout->getAddressPoints();
630f4a2713aSLionel Sambuc
631f4a2713aSLionel Sambuc // Get the mangled construction vtable name.
632f4a2713aSLionel Sambuc SmallString<256> OutName;
633f4a2713aSLionel Sambuc llvm::raw_svector_ostream Out(OutName);
634f4a2713aSLionel Sambuc cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
635f4a2713aSLionel Sambuc .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
636f4a2713aSLionel Sambuc Base.getBase(), Out);
637f4a2713aSLionel Sambuc Out.flush();
638f4a2713aSLionel Sambuc StringRef Name = OutName.str();
639f4a2713aSLionel Sambuc
640f4a2713aSLionel Sambuc llvm::ArrayType *ArrayType =
641f4a2713aSLionel Sambuc llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
642f4a2713aSLionel Sambuc
643f4a2713aSLionel Sambuc // Construction vtable symbols are not part of the Itanium ABI, so we cannot
644f4a2713aSLionel Sambuc // guarantee that they actually will be available externally. Instead, when
645f4a2713aSLionel Sambuc // emitting an available_externally VTT, we provide references to an internal
646f4a2713aSLionel Sambuc // linkage construction vtable. The ABI only requires complete-object vtables
647f4a2713aSLionel Sambuc // to be the same for all instances of a type, not construction vtables.
648f4a2713aSLionel Sambuc if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
649f4a2713aSLionel Sambuc Linkage = llvm::GlobalVariable::InternalLinkage;
650f4a2713aSLionel Sambuc
651f4a2713aSLionel Sambuc // Create the variable that will hold the construction vtable.
652f4a2713aSLionel Sambuc llvm::GlobalVariable *VTable =
653f4a2713aSLionel Sambuc CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
654*0a6a1f1dSLionel Sambuc CGM.setGlobalVisibility(VTable, RD);
655f4a2713aSLionel Sambuc
656f4a2713aSLionel Sambuc // V-tables are always unnamed_addr.
657f4a2713aSLionel Sambuc VTable->setUnnamedAddr(true);
658f4a2713aSLionel Sambuc
659*0a6a1f1dSLionel Sambuc llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
660*0a6a1f1dSLionel Sambuc CGM.getContext().getTagDeclType(Base.getBase()));
661*0a6a1f1dSLionel Sambuc
662f4a2713aSLionel Sambuc // Create and set the initializer.
663*0a6a1f1dSLionel Sambuc llvm::Constant *Init = CreateVTableInitializer(
664*0a6a1f1dSLionel Sambuc Base.getBase(), VTLayout->vtable_component_begin(),
665*0a6a1f1dSLionel Sambuc VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
666*0a6a1f1dSLionel Sambuc VTLayout->getNumVTableThunks(), RTTI);
667f4a2713aSLionel Sambuc VTable->setInitializer(Init);
668f4a2713aSLionel Sambuc
669f4a2713aSLionel Sambuc return VTable;
670f4a2713aSLionel Sambuc }
671f4a2713aSLionel Sambuc
672f4a2713aSLionel Sambuc /// Compute the required linkage of the v-table for the given class.
673f4a2713aSLionel Sambuc ///
674f4a2713aSLionel Sambuc /// Note that we only call this at the end of the translation unit.
675f4a2713aSLionel Sambuc llvm::GlobalVariable::LinkageTypes
getVTableLinkage(const CXXRecordDecl * RD)676f4a2713aSLionel Sambuc CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
677f4a2713aSLionel Sambuc if (!RD->isExternallyVisible())
678f4a2713aSLionel Sambuc return llvm::GlobalVariable::InternalLinkage;
679f4a2713aSLionel Sambuc
680f4a2713aSLionel Sambuc // We're at the end of the translation unit, so the current key
681f4a2713aSLionel Sambuc // function is fully correct.
682*0a6a1f1dSLionel Sambuc const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
683*0a6a1f1dSLionel Sambuc if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
684f4a2713aSLionel Sambuc // If this class has a key function, use that to determine the
685f4a2713aSLionel Sambuc // linkage of the vtable.
686*0a6a1f1dSLionel Sambuc const FunctionDecl *def = nullptr;
687f4a2713aSLionel Sambuc if (keyFunction->hasBody(def))
688f4a2713aSLionel Sambuc keyFunction = cast<CXXMethodDecl>(def);
689f4a2713aSLionel Sambuc
690f4a2713aSLionel Sambuc switch (keyFunction->getTemplateSpecializationKind()) {
691f4a2713aSLionel Sambuc case TSK_Undeclared:
692f4a2713aSLionel Sambuc case TSK_ExplicitSpecialization:
693f4a2713aSLionel Sambuc assert(def && "Should not have been asked to emit this");
694f4a2713aSLionel Sambuc if (keyFunction->isInlined())
695f4a2713aSLionel Sambuc return !Context.getLangOpts().AppleKext ?
696f4a2713aSLionel Sambuc llvm::GlobalVariable::LinkOnceODRLinkage :
697f4a2713aSLionel Sambuc llvm::Function::InternalLinkage;
698f4a2713aSLionel Sambuc
699f4a2713aSLionel Sambuc return llvm::GlobalVariable::ExternalLinkage;
700f4a2713aSLionel Sambuc
701f4a2713aSLionel Sambuc case TSK_ImplicitInstantiation:
702f4a2713aSLionel Sambuc return !Context.getLangOpts().AppleKext ?
703f4a2713aSLionel Sambuc llvm::GlobalVariable::LinkOnceODRLinkage :
704f4a2713aSLionel Sambuc llvm::Function::InternalLinkage;
705f4a2713aSLionel Sambuc
706f4a2713aSLionel Sambuc case TSK_ExplicitInstantiationDefinition:
707f4a2713aSLionel Sambuc return !Context.getLangOpts().AppleKext ?
708f4a2713aSLionel Sambuc llvm::GlobalVariable::WeakODRLinkage :
709f4a2713aSLionel Sambuc llvm::Function::InternalLinkage;
710f4a2713aSLionel Sambuc
711f4a2713aSLionel Sambuc case TSK_ExplicitInstantiationDeclaration:
712f4a2713aSLionel Sambuc llvm_unreachable("Should not have been asked to emit this");
713f4a2713aSLionel Sambuc }
714f4a2713aSLionel Sambuc }
715f4a2713aSLionel Sambuc
716f4a2713aSLionel Sambuc // -fapple-kext mode does not support weak linkage, so we must use
717f4a2713aSLionel Sambuc // internal linkage.
718f4a2713aSLionel Sambuc if (Context.getLangOpts().AppleKext)
719f4a2713aSLionel Sambuc return llvm::Function::InternalLinkage;
720f4a2713aSLionel Sambuc
721*0a6a1f1dSLionel Sambuc llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
722*0a6a1f1dSLionel Sambuc llvm::GlobalValue::LinkOnceODRLinkage;
723*0a6a1f1dSLionel Sambuc llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
724*0a6a1f1dSLionel Sambuc llvm::GlobalValue::WeakODRLinkage;
725*0a6a1f1dSLionel Sambuc if (RD->hasAttr<DLLExportAttr>()) {
726*0a6a1f1dSLionel Sambuc // Cannot discard exported vtables.
727*0a6a1f1dSLionel Sambuc DiscardableODRLinkage = NonDiscardableODRLinkage;
728*0a6a1f1dSLionel Sambuc } else if (RD->hasAttr<DLLImportAttr>()) {
729*0a6a1f1dSLionel Sambuc // Imported vtables are available externally.
730*0a6a1f1dSLionel Sambuc DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
731*0a6a1f1dSLionel Sambuc NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
732*0a6a1f1dSLionel Sambuc }
733*0a6a1f1dSLionel Sambuc
734f4a2713aSLionel Sambuc switch (RD->getTemplateSpecializationKind()) {
735f4a2713aSLionel Sambuc case TSK_Undeclared:
736f4a2713aSLionel Sambuc case TSK_ExplicitSpecialization:
737f4a2713aSLionel Sambuc case TSK_ImplicitInstantiation:
738*0a6a1f1dSLionel Sambuc return DiscardableODRLinkage;
739f4a2713aSLionel Sambuc
740f4a2713aSLionel Sambuc case TSK_ExplicitInstantiationDeclaration:
741f4a2713aSLionel Sambuc llvm_unreachable("Should not have been asked to emit this");
742f4a2713aSLionel Sambuc
743f4a2713aSLionel Sambuc case TSK_ExplicitInstantiationDefinition:
744*0a6a1f1dSLionel Sambuc return NonDiscardableODRLinkage;
745f4a2713aSLionel Sambuc }
746f4a2713aSLionel Sambuc
747f4a2713aSLionel Sambuc llvm_unreachable("Invalid TemplateSpecializationKind!");
748f4a2713aSLionel Sambuc }
749f4a2713aSLionel Sambuc
750f4a2713aSLionel Sambuc /// This is a callback from Sema to tell us that it believes that a
751f4a2713aSLionel Sambuc /// particular v-table is required to be emitted in this translation
752f4a2713aSLionel Sambuc /// unit.
753f4a2713aSLionel Sambuc ///
754f4a2713aSLionel Sambuc /// The reason we don't simply trust this callback is because Sema
755f4a2713aSLionel Sambuc /// will happily report that something is used even when it's used
756f4a2713aSLionel Sambuc /// only in code that we don't actually have to emit.
757f4a2713aSLionel Sambuc ///
758f4a2713aSLionel Sambuc /// \param isRequired - if true, the v-table is mandatory, e.g.
759f4a2713aSLionel Sambuc /// because the translation unit defines the key function
EmitVTable(CXXRecordDecl * theClass,bool isRequired)760f4a2713aSLionel Sambuc void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
761f4a2713aSLionel Sambuc if (!isRequired) return;
762f4a2713aSLionel Sambuc
763f4a2713aSLionel Sambuc VTables.GenerateClassData(theClass);
764f4a2713aSLionel Sambuc }
765f4a2713aSLionel Sambuc
766f4a2713aSLionel Sambuc void
GenerateClassData(const CXXRecordDecl * RD)767f4a2713aSLionel Sambuc CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
768f4a2713aSLionel Sambuc if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
769f4a2713aSLionel Sambuc DI->completeClassData(RD);
770f4a2713aSLionel Sambuc
771f4a2713aSLionel Sambuc if (RD->getNumVBases())
772f4a2713aSLionel Sambuc CGM.getCXXABI().emitVirtualInheritanceTables(RD);
773f4a2713aSLionel Sambuc
774f4a2713aSLionel Sambuc CGM.getCXXABI().emitVTableDefinitions(*this, RD);
775f4a2713aSLionel Sambuc }
776f4a2713aSLionel Sambuc
777f4a2713aSLionel Sambuc /// At this point in the translation unit, does it appear that can we
778f4a2713aSLionel Sambuc /// rely on the vtable being defined elsewhere in the program?
779f4a2713aSLionel Sambuc ///
780f4a2713aSLionel Sambuc /// The response is really only definitive when called at the end of
781f4a2713aSLionel Sambuc /// the translation unit.
782f4a2713aSLionel Sambuc ///
783f4a2713aSLionel Sambuc /// The only semantic restriction here is that the object file should
784f4a2713aSLionel Sambuc /// not contain a v-table definition when that v-table is defined
785f4a2713aSLionel Sambuc /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
786f4a2713aSLionel Sambuc /// v-tables when unnecessary.
isVTableExternal(const CXXRecordDecl * RD)787f4a2713aSLionel Sambuc bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
788*0a6a1f1dSLionel Sambuc assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
789f4a2713aSLionel Sambuc
790f4a2713aSLionel Sambuc // If we have an explicit instantiation declaration (and not a
791f4a2713aSLionel Sambuc // definition), the v-table is defined elsewhere.
792f4a2713aSLionel Sambuc TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
793f4a2713aSLionel Sambuc if (TSK == TSK_ExplicitInstantiationDeclaration)
794f4a2713aSLionel Sambuc return true;
795f4a2713aSLionel Sambuc
796f4a2713aSLionel Sambuc // Otherwise, if the class is an instantiated template, the
797f4a2713aSLionel Sambuc // v-table must be defined here.
798f4a2713aSLionel Sambuc if (TSK == TSK_ImplicitInstantiation ||
799f4a2713aSLionel Sambuc TSK == TSK_ExplicitInstantiationDefinition)
800f4a2713aSLionel Sambuc return false;
801f4a2713aSLionel Sambuc
802f4a2713aSLionel Sambuc // Otherwise, if the class doesn't have a key function (possibly
803f4a2713aSLionel Sambuc // anymore), the v-table must be defined here.
804f4a2713aSLionel Sambuc const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
805f4a2713aSLionel Sambuc if (!keyFunction)
806f4a2713aSLionel Sambuc return false;
807f4a2713aSLionel Sambuc
808f4a2713aSLionel Sambuc // Otherwise, if we don't have a definition of the key function, the
809f4a2713aSLionel Sambuc // v-table must be defined somewhere else.
810f4a2713aSLionel Sambuc return !keyFunction->hasBody();
811f4a2713aSLionel Sambuc }
812f4a2713aSLionel Sambuc
813f4a2713aSLionel Sambuc /// Given that we're currently at the end of the translation unit, and
814f4a2713aSLionel Sambuc /// we've emitted a reference to the v-table for this class, should
815f4a2713aSLionel Sambuc /// we define that v-table?
shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule & CGM,const CXXRecordDecl * RD)816f4a2713aSLionel Sambuc static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
817f4a2713aSLionel Sambuc const CXXRecordDecl *RD) {
818f4a2713aSLionel Sambuc return !CGM.getVTables().isVTableExternal(RD);
819f4a2713aSLionel Sambuc }
820f4a2713aSLionel Sambuc
821f4a2713aSLionel Sambuc /// Given that at some point we emitted a reference to one or more
822f4a2713aSLionel Sambuc /// v-tables, and that we are now at the end of the translation unit,
823f4a2713aSLionel Sambuc /// decide whether we should emit them.
EmitDeferredVTables()824f4a2713aSLionel Sambuc void CodeGenModule::EmitDeferredVTables() {
825f4a2713aSLionel Sambuc #ifndef NDEBUG
826f4a2713aSLionel Sambuc // Remember the size of DeferredVTables, because we're going to assume
827f4a2713aSLionel Sambuc // that this entire operation doesn't modify it.
828f4a2713aSLionel Sambuc size_t savedSize = DeferredVTables.size();
829f4a2713aSLionel Sambuc #endif
830f4a2713aSLionel Sambuc
831f4a2713aSLionel Sambuc typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
832f4a2713aSLionel Sambuc for (const_iterator i = DeferredVTables.begin(),
833f4a2713aSLionel Sambuc e = DeferredVTables.end(); i != e; ++i) {
834f4a2713aSLionel Sambuc const CXXRecordDecl *RD = *i;
835f4a2713aSLionel Sambuc if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
836f4a2713aSLionel Sambuc VTables.GenerateClassData(RD);
837f4a2713aSLionel Sambuc }
838f4a2713aSLionel Sambuc
839f4a2713aSLionel Sambuc assert(savedSize == DeferredVTables.size() &&
840f4a2713aSLionel Sambuc "deferred extra v-tables during v-table emission?");
841f4a2713aSLionel Sambuc DeferredVTables.clear();
842f4a2713aSLionel Sambuc }
843