blob: e1bf1db008e11203f5809e0d9d3486f4fed77dc8 [file] [log] [blame]
Anders Carlsson11e51402010-04-17 20:15:18 +00001//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
Anders Carlsson2bb27f52009-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
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Anders Carlssonf942ee02009-11-27 20:47:55 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000018#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson5d40c6f2010-02-11 08:02:13 +000021#include "llvm/Support/Format.h"
Eli Friedman49a94b12011-05-06 17:27:27 +000022#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson56446142010-03-17 20:06:32 +000023#include <algorithm>
Zhongxing Xu1721ef72009-11-13 05:46:16 +000024#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000025
26using namespace clang;
27using namespace CodeGen;
28
Reid Kleckner96f8f932014-02-05 17:27:08 +000029CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
30 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbournea8341662011-09-26 01:56:30 +000031
Anders Carlssoncd836f02010-03-23 17:17:29 +000032llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlssonfe8a9932011-02-06 17:15:43 +000033 const ThunkInfo &Thunk) {
Anders Carlssoncd836f02010-03-23 17:17:29 +000034 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
35
36 // Compute the mangled name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000037 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +000038 llvm::raw_svector_ostream Out(Name);
Anders Carlssoncd836f02010-03-23 17:17:29 +000039 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall5d865c322010-08-31 07:33:07 +000040 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindola3968cd02011-02-11 02:52:17 +000041 Thunk.This, Out);
Anders Carlssoncd836f02010-03-23 17:17:29 +000042 else
Rafael Espindola3968cd02011-02-11 02:52:17 +000043 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
Rafael Espindola3968cd02011-02-11 02:52:17 +000044
Chris Lattner2192fe52011-07-18 04:24:23 +000045 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +000046 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
David Majnemerb9bd6fb2014-11-01 05:42:23 +000047 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000048}
49
John McCallc8bd9c22010-08-04 23:46:35 +000050static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
51 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlssonc6a47892011-01-29 19:39:23 +000052 CGM.setGlobalVisibility(Fn, MD);
John McCallc8bd9c22010-08-04 23:46:35 +000053}
54
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000055static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
56 llvm::Function *ThunkFn, bool ForVTable,
57 GlobalDecl GD) {
58 CGM.setFunctionLinkage(GD, ThunkFn);
59 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
60 !Thunk.Return.isEmpty());
61
62 // Set the right visibility.
63 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
64 setThunkVisibility(CGM, MD, Thunk, ThunkFn);
65
66 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
67 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
68}
69
John McCall5fe00962011-03-09 07:12:35 +000070#ifndef NDEBUG
71static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
72 const ABIArgInfo &infoR, CanQualType typeR) {
73 return (infoL.getKind() == infoR.getKind() &&
74 (typeL == typeR ||
75 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
76 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
77}
78#endif
79
Eli Friedman49a94b12011-05-06 17:27:27 +000080static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
81 QualType ResultType, RValue RV,
82 const ThunkInfo &Thunk) {
83 // Emit the return adjustment.
84 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000085
86 llvm::BasicBlock *AdjustNull = nullptr;
87 llvm::BasicBlock *AdjustNotNull = nullptr;
88 llvm::BasicBlock *AdjustEnd = nullptr;
89
Eli Friedman49a94b12011-05-06 17:27:27 +000090 llvm::Value *ReturnValue = RV.getScalarVal();
91
92 if (NullCheckValue) {
93 AdjustNull = CGF.createBasicBlock("adjust.null");
94 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
95 AdjustEnd = CGF.createBasicBlock("adjust.end");
96
97 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
98 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
99 CGF.EmitBlock(AdjustNotNull);
100 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000101
John McCall7f416cc2015-09-08 08:05:57 +0000102 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
103 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
104 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
105 Address(ReturnValue, ClassAlign),
106 Thunk.Return);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000107
Eli Friedman49a94b12011-05-06 17:27:27 +0000108 if (NullCheckValue) {
109 CGF.Builder.CreateBr(AdjustEnd);
110 CGF.EmitBlock(AdjustNull);
111 CGF.Builder.CreateBr(AdjustEnd);
112 CGF.EmitBlock(AdjustEnd);
113
114 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
115 PHI->addIncoming(ReturnValue, AdjustNotNull);
116 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
117 AdjustNull);
118 ReturnValue = PHI;
119 }
120
121 return RValue::get(ReturnValue);
122}
123
124// This function does roughly the same thing as GenerateThunk, but in a
125// very different way, so that va_start and va_end work correctly.
126// FIXME: This function assumes "this" is the first non-sret LLVM argument of
127// a function, and that there is an alloca built in the entry block
128// for all accesses to "this".
129// FIXME: This function assumes there is only one "ret" statement per function.
130// FIXME: Cloning isn't correct in the presence of indirect goto!
131// FIXME: This implementation of thunks bloats codesize by duplicating the
132// function definition. There are alternatives:
133// 1. Add some sort of stub support to LLVM for cases where we can
134// do a this adjustment, then a sibcall.
135// 2. We could transform the definition to take a va_list instead of an
136// actual variable argument list, then have the thunks (including a
137// no-op thunk for the regular definition) call va_start/va_end.
138// There's a bit of per-call overhead for this solution, but it's
139// better for codesize if the definition is long.
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000140llvm::Function *
141CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
Eli Friedman49a94b12011-05-06 17:27:27 +0000142 const CGFunctionInfo &FnInfo,
143 GlobalDecl GD, const ThunkInfo &Thunk) {
144 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
145 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000146 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000147
148 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000149 assert(FnInfo.isVariadic());
150 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000151 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
152 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
153
154 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000155 llvm::ValueToValueMapTy VMap;
Peter Collingbourne7d6e81d2016-05-10 20:23:29 +0000156 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
Eli Friedman49a94b12011-05-06 17:27:27 +0000157 Fn->replaceAllUsesWith(NewFn);
158 NewFn->takeName(Fn);
159 Fn->eraseFromParent();
160 Fn = NewFn;
161
162 // "Initialize" CGF (minimally).
163 CurFn = Fn;
164
165 // Get the "this" value
166 llvm::Function::arg_iterator AI = Fn->arg_begin();
167 if (CGM.ReturnTypeUsesSRet(FnInfo))
168 ++AI;
169
170 // Find the first store of "this", which will be to the alloca associated
171 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000172 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000173 llvm::BasicBlock *EntryBB = &Fn->front();
174 llvm::BasicBlock::iterator ThisStore =
David Blaikiea629c0f2014-12-29 22:39:45 +0000175 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000176 return isa<llvm::StoreInst>(I) &&
177 I.getOperand(0) == ThisPtr.getPointer();
178 });
179 assert(ThisStore != EntryBB->end() &&
180 "Store of this should be in entry block?");
Eli Friedman49a94b12011-05-06 17:27:27 +0000181 // Adjust "this", if necessary.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000182 Builder.SetInsertPoint(&*ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000183 llvm::Value *AdjustedThisPtr =
184 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000185 ThisStore->setOperand(0, AdjustedThisPtr);
186
187 if (!Thunk.Return.isEmpty()) {
188 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000189 for (llvm::BasicBlock &BB : *Fn) {
190 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000191 if (isa<llvm::ReturnInst>(T)) {
192 RValue RV = RValue::get(T->getOperand(0));
193 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000194 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000195 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
196 Builder.CreateRet(RV.getScalarVal());
197 break;
198 }
199 }
200 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000201
202 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000203}
204
Hans Wennborg88497d62013-11-15 17:24:45 +0000205void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
206 const CGFunctionInfo &FnInfo) {
207 assert(!CurGD.getDecl() && "CurGD was already set!");
208 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000209 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000210
211 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000212 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000213 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000214 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000215 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
216 ? ThisType
217 : CGM.getCXXABI().hasMostDerivedReturn(GD)
218 ? CGM.getContext().VoidPtrTy
219 : FPT->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000220 FunctionArgList FunctionArgs;
221
Anders Carlssonbad991d2010-03-24 00:39:18 +0000222 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000223 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000224
225 // Add the rest of the parameters.
Alexey Samsonov3551e312014-08-13 20:06:24 +0000226 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000227
Reid Kleckner89077a12013-12-17 19:46:40 +0000228 if (isa<CXXDestructorDecl>(MD))
229 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
230
Hans Wennborg88497d62013-11-15 17:24:45 +0000231 // Start defining the function.
John McCalla738c252011-03-09 04:27:21 +0000232 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
David Blaikie4d5c7282014-12-29 22:53:52 +0000233 MD->getLocation(), MD->getLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000234
Hans Wennborg88497d62013-11-15 17:24:45 +0000235 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000236 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000237 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000238 CurCodeDecl = MD;
239 CurFuncDecl = MD;
240}
241
242void CodeGenFunction::FinishThunk() {
243 // Clear these to restore the invariants expected by
244 // StartFunction/FinishFunction.
245 CurCodeDecl = nullptr;
246 CurFuncDecl = nullptr;
247
248 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000249}
John McCall5d865c322010-08-31 07:33:07 +0000250
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000251void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
Hans Wennborg88497d62013-11-15 17:24:45 +0000252 const ThunkInfo *Thunk) {
253 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
254 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000255 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000256
Hans Wennborg88497d62013-11-15 17:24:45 +0000257 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000258 llvm::Value *AdjustedThisPtr =
259 Thunk ? CGM.getCXXABI().performThisAdjustment(
260 *this, LoadCXXThisAddress(), Thunk->This)
261 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000262
Reid Klecknerab2090d2014-07-26 01:34:32 +0000263 if (CurFnInfo->usesInAlloca()) {
264 // We don't handle return adjusting thunks, because they require us to call
265 // the copy constructor. For now, fall through and pretend the return
266 // adjustment was empty so we don't crash.
267 if (Thunk && !Thunk->Return.isEmpty()) {
268 CGM.ErrorUnsupported(
269 MD, "non-trivial argument copy for return-adjusting thunk");
270 }
271 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
272 return;
273 }
274
Hans Wennborg88497d62013-11-15 17:24:45 +0000275 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000276 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000277 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000278 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000279
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000280 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000281 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000282
Hans Wennborg88497d62013-11-15 17:24:45 +0000283 // Add the rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +0000284 for (const ParmVarDecl *PD : MD->parameters())
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000285 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000286
Hans Wennborg88497d62013-11-15 17:24:45 +0000287 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000288
John McCalla738c252011-03-09 04:27:21 +0000289#ifndef NDEBUG
George Burgess IV419996c2016-06-16 23:06:04 +0000290 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
291 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD));
Hans Wennborg88497d62013-11-15 17:24:45 +0000292 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
293 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
294 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000295 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
296 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000297 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
298 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
299 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000300 assert(similar(CallFnInfo.arg_begin()[i].info,
301 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000302 CurFnInfo->arg_begin()[i].info,
303 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000304#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000305
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000306 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000307 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
308 ? ThisType
309 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
310 ? CGM.getContext().VoidPtrTy
311 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000312 ReturnValueSlot Slot;
313 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000314 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000315 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000316 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
317
Anders Carlssonbad991d2010-03-24 00:39:18 +0000318 // Now emit our call.
Reid Klecknerab2090d2014-07-26 01:34:32 +0000319 llvm::Instruction *CallOrInvoke;
320 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
321
Hans Wennborg88497d62013-11-15 17:24:45 +0000322 // Consider return adjustment if we have ThunkInfo.
323 if (Thunk && !Thunk->Return.isEmpty())
324 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000325 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
326 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000327
Hans Wennborg88497d62013-11-15 17:24:45 +0000328 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000329 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000330 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000331
John McCallff755cd2012-07-31 00:33:55 +0000332 // Disable the final ARC autorelease.
333 AutoreleaseResult = false;
334
John McCall7f416cc2015-09-08 08:05:57 +0000335 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000336}
337
Reid Klecknerab2090d2014-07-26 01:34:32 +0000338void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
339 llvm::Value *AdjustedThisPtr,
340 llvm::Value *Callee) {
341 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
342 // to translate AST arguments into LLVM IR arguments. For thunks, we know
343 // that the caller prototype more or less matches the callee prototype with
344 // the exception of 'this'.
345 SmallVector<llvm::Value *, 8> Args;
346 for (llvm::Argument &A : CurFn->args())
347 Args.push_back(&A);
348
349 // Set the adjusted 'this' pointer.
350 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
351 if (ThisAI.isDirect()) {
352 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
353 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
354 llvm::Type *ThisType = Args[ThisArgNo]->getType();
355 if (ThisType != AdjustedThisPtr->getType())
356 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
357 Args[ThisArgNo] = AdjustedThisPtr;
358 } else {
359 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000360 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
361 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000362 if (ThisType != AdjustedThisPtr->getType())
363 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
364 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
365 }
366
367 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
368 // don't actually want to run them.
369 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
370 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
371
372 // Apply the standard set of call attributes.
373 unsigned CallingConv;
374 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000375 CGM.ConstructAttributeList(Callee->getName(), *CurFnInfo, MD, AttributeList,
376 CallingConv, /*AttrOnCallSite=*/true);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000377 llvm::AttributeSet Attrs =
378 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
379 Call->setAttributes(Attrs);
380 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
381
382 if (Call->getType()->isVoidTy())
383 Builder.CreateRetVoid();
384 else
385 Builder.CreateRet(Call);
386
387 // Finish the function to maintain CodeGenFunction invariants.
388 // FIXME: Don't emit unreachable code.
389 EmitBlock(createBasicBlock());
390 FinishFunction();
391}
392
Rafael Espindolad6e66942015-07-13 06:07:58 +0000393void CodeGenFunction::generateThunk(llvm::Function *Fn,
Hans Wennborg88497d62013-11-15 17:24:45 +0000394 const CGFunctionInfo &FnInfo,
395 GlobalDecl GD, const ThunkInfo &Thunk) {
396 StartThunk(Fn, GD, FnInfo);
397
398 // Get our callee.
399 llvm::Type *Ty =
400 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
401 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
402
403 // Make the call and return the result.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000404 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000405}
406
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000407void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
408 bool ForVTable) {
John McCalla729c622012-02-17 03:33:10 +0000409 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalla738c252011-03-09 04:27:21 +0000410
411 // FIXME: re-use FnInfo in this computation.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000412 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
413 llvm::GlobalValue *Entry;
414
Anders Carlsson55e89f82010-03-23 18:18:41 +0000415 // Strip off a bitcast if we got one back.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000416 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson55e89f82010-03-23 18:18:41 +0000417 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000418 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
419 } else {
420 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000421 }
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000422
Anders Carlsson55e89f82010-03-23 18:18:41 +0000423 // There's already a declaration with the same name, check if it has the same
424 // type or if we need to replace it.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000425 if (Entry->getType()->getElementType() !=
John McCall5d865c322010-08-31 07:33:07 +0000426 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000427 llvm::GlobalValue *OldThunkFn = Entry;
428
Anders Carlsson55e89f82010-03-23 18:18:41 +0000429 // If the types mismatch then we have to rewrite the definition.
430 assert(OldThunkFn->isDeclaration() &&
431 "Shouldn't replace non-declaration");
432
433 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000434 OldThunkFn->setName(StringRef());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000435 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Anders Carlsson55e89f82010-03-23 18:18:41 +0000436
437 // If needed, replace the old thunk with a bitcast.
438 if (!OldThunkFn->use_empty()) {
439 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000440 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000441 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
442 }
443
444 // Remove the old thunk.
445 OldThunkFn->eraseFromParent();
446 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000447
Anders Carlssonbad991d2010-03-24 00:39:18 +0000448 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000449 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
450 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000451
452 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000453 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000454 // There is already a thunk emitted for this function, do nothing.
455 return;
456 }
457
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000458 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlssone866d442011-02-06 20:09:44 +0000459 return;
Anders Carlsson8b021832011-02-06 18:31:40 +0000460 }
461
Rafael Espindola86792432012-09-21 20:39:32 +0000462 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
463
Eli Friedman49a94b12011-05-06 17:27:27 +0000464 if (ThunkFn->isVarArg()) {
465 // Varargs thunks are special; we can't just generate a call because
466 // we can't copy the varargs. Our implementation is rather
467 // expensive/sucky at the moment, so don't generate the thunk unless
468 // we have to.
469 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Peter Collingbourne45a24012015-06-30 19:07:26 +0000470 if (UseAvailableExternallyLinkage)
471 return;
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000472 ThunkFn =
473 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000474 } else {
475 // Normal thunk body generation.
Rafael Espindolad6e66942015-07-13 06:07:58 +0000476 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000477 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000478
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000479 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlsson8b021832011-02-06 18:31:40 +0000480}
481
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000482void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
483 const ThunkInfo &Thunk) {
484 // If the ABI has key functions, only the TU with the key function should emit
485 // the thunk. However, we can allow inlining of thunks if we emit them with
486 // available_externally linkage together with vtables when optimizations are
487 // enabled.
488 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
489 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson8b021832011-02-06 18:31:40 +0000490 return;
491
492 // We can't emit thunks for member functions with incomplete types.
493 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattner8806e322011-07-10 00:18:59 +0000494 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Klecknerfe56be52013-10-11 20:46:27 +0000495 MD->getType()->castAs<FunctionType>()))
Anders Carlsson8b021832011-02-06 18:31:40 +0000496 return;
497
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000498 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000499}
500
Anders Carlsson917229c2010-03-23 04:59:02 +0000501void CodeGenVTables::EmitThunks(GlobalDecl GD)
502{
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000503 const CXXMethodDecl *MD =
504 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
505
506 // We don't need to generate thunks for the base destructor.
507 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
508 return;
509
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000510 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
511 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000512
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000513 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000514 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000515
Yaron Kerenede60302015-08-01 19:11:36 +0000516 for (const ThunkInfo& Thunk : *ThunkInfoVector)
517 emitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000518}
519
Peter Collingbournee53683f2016-09-08 01:14:39 +0000520llvm::Constant *CodeGenVTables::CreateVTableComponent(
521 unsigned Idx, const VTableLayout &VTLayout, llvm::Constant *RTTI,
522 unsigned &NextVTableThunkIndex) {
523 VTableComponent Component = VTLayout.vtable_components()[Idx];
Anders Carlssona4147142010-03-25 15:26:28 +0000524
Peter Collingbournee53683f2016-09-08 01:14:39 +0000525 auto OffsetConstant = [&](CharUnits Offset) {
526 return llvm::ConstantExpr::getIntToPtr(
527 llvm::ConstantInt::get(CGM.PtrDiffTy, Offset.getQuantity()),
528 CGM.Int8PtrTy);
529 };
Anders Carlssona5736bd2010-03-25 16:49:53 +0000530
Peter Collingbournee53683f2016-09-08 01:14:39 +0000531 switch (Component.getKind()) {
532 case VTableComponent::CK_VCallOffset:
533 return OffsetConstant(Component.getVCallOffset());
Craig Topper8a13c412014-05-21 05:09:00 +0000534
Peter Collingbournee53683f2016-09-08 01:14:39 +0000535 case VTableComponent::CK_VBaseOffset:
536 return OffsetConstant(Component.getVBaseOffset());
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000537
Peter Collingbournee53683f2016-09-08 01:14:39 +0000538 case VTableComponent::CK_OffsetToTop:
539 return OffsetConstant(Component.getOffsetToTop());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000540
Peter Collingbournee53683f2016-09-08 01:14:39 +0000541 case VTableComponent::CK_RTTI:
542 return RTTI;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000543
Peter Collingbournee53683f2016-09-08 01:14:39 +0000544 case VTableComponent::CK_FunctionPointer:
545 case VTableComponent::CK_CompleteDtorPointer:
546 case VTableComponent::CK_DeletingDtorPointer: {
547 GlobalDecl GD;
548
549 // Get the right global decl.
Anders Carlssona5736bd2010-03-25 16:49:53 +0000550 switch (Component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000551 default:
552 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000553 case VTableComponent::CK_FunctionPointer:
Peter Collingbournee53683f2016-09-08 01:14:39 +0000554 GD = Component.getFunctionDecl();
555 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000556 case VTableComponent::CK_CompleteDtorPointer:
Peter Collingbournee53683f2016-09-08 01:14:39 +0000557 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
558 break;
559 case VTableComponent::CK_DeletingDtorPointer:
560 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000561 break;
562 }
563
Peter Collingbournee53683f2016-09-08 01:14:39 +0000564 if (CGM.getLangOpts().CUDA) {
565 // Emit NULL for methods we can't codegen on this
566 // side. Otherwise we'd end up with vtable with unresolved
567 // references.
568 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
569 // OK on device side: functions w/ __device__ attribute
570 // OK on host side: anything except __device__-only functions.
571 bool CanEmitMethod =
572 CGM.getLangOpts().CUDAIsDevice
573 ? MD->hasAttr<CUDADeviceAttr>()
574 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
575 if (!CanEmitMethod)
576 return llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy);
577 // Method is acceptable, continue processing as usual.
578 }
579
580 auto SpecialVirtualFn = [&](llvm::Constant *&Cache, StringRef Name) {
581 if (!Cache) {
582 llvm::FunctionType *Ty =
583 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
584 Cache = CGM.CreateRuntimeFunction(Ty, Name);
585 if (auto *F = dyn_cast<llvm::Function>(Cache))
586 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
587 Cache = llvm::ConstantExpr::getBitCast(Cache, CGM.Int8PtrTy);
588 }
589 return Cache;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000590 };
Peter Collingbournee53683f2016-09-08 01:14:39 +0000591
592 if (cast<CXXMethodDecl>(GD.getDecl())->isPure())
593 // We have a pure virtual member function.
594 return SpecialVirtualFn(PureVirtualFn,
595 CGM.getCXXABI().GetPureVirtualCallName());
596
597 if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted())
598 return SpecialVirtualFn(DeletedVirtualFn,
599 CGM.getCXXABI().GetDeletedVirtualCallName());
600
601 // Check if we should use a thunk.
602 if (NextVTableThunkIndex < VTLayout.vtable_thunks().size() &&
603 VTLayout.vtable_thunks()[NextVTableThunkIndex].first == Idx) {
604 const ThunkInfo &Thunk =
605 VTLayout.vtable_thunks()[NextVTableThunkIndex].second;
606
607 maybeEmitThunkForVTable(GD, Thunk);
608 NextVTableThunkIndex++;
609 return CGM.GetAddrOfThunk(GD, Thunk);
610 }
611
612 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
613 return CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlssona4147142010-03-25 15:26:28 +0000614 }
Peter Collingbournee53683f2016-09-08 01:14:39 +0000615
616 case VTableComponent::CK_UnusedFunctionPointer:
617 return llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy);
618 }
619}
620
621llvm::Constant *
622CodeGenVTables::CreateVTableInitializer(const VTableLayout &VTLayout,
623 llvm::Constant *RTTI) {
624 SmallVector<llvm::Constant *, 64> Inits;
625 unsigned NextVTableThunkIndex = 0;
626
627 for (unsigned I = 0, E = VTLayout.vtable_components().size(); I != E; ++I) {
628 llvm::Constant *Init =
629 CreateVTableComponent(I, VTLayout, RTTI, NextVTableThunkIndex);
630 Inits.push_back(llvm::ConstantExpr::getBitCast(Init, CGM.Int8PtrTy));
631 }
632
633 llvm::ArrayType *ArrayType =
634 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout.vtable_components().size());
Jay Foad83be3612011-06-22 09:24:39 +0000635 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlssona4147142010-03-25 15:26:28 +0000636}
637
Anders Carlsson0534b022010-03-25 00:35:49 +0000638llvm::GlobalVariable *
639CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlssona208b392010-03-26 03:56:54 +0000640 const BaseSubobject &Base,
641 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000642 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000643 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000644 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
645 DI->completeClassData(Base.getBase());
646
Ahmed Charlesb8984322014-03-07 20:03:18 +0000647 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000648 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000649 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000650
Anders Carlssona5736bd2010-03-25 16:49:53 +0000651 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000652 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000653
654 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000655 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000656 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000657 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
658 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
659 Base.getBase(), Out);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000660 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000661
Peter Collingbournee53683f2016-09-08 01:14:39 +0000662 llvm::ArrayType *ArrayType =
663 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->vtable_components().size());
Anders Carlssona4147142010-03-25 15:26:28 +0000664
Richard Smith65fd2a42013-02-16 00:51:21 +0000665 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
666 // guarantee that they actually will be available externally. Instead, when
667 // emitting an available_externally VTT, we provide references to an internal
668 // linkage construction vtable. The ABI only requires complete-object vtables
669 // to be the same for all instances of a type, not construction vtables.
670 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
671 Linkage = llvm::GlobalVariable::InternalLinkage;
672
Anders Carlssona4147142010-03-25 15:26:28 +0000673 // Create the variable that will hold the construction vtable.
674 llvm::GlobalVariable *VTable =
John McCall358d0562011-03-27 09:00:25 +0000675 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
John McCall8f80a612014-02-08 00:41:16 +0000676 CGM.setGlobalVisibility(VTable, RD);
John McCall358d0562011-03-27 09:00:25 +0000677
678 // V-tables are always unnamed_addr.
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000679 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Anders Carlssona4147142010-03-25 15:26:28 +0000680
David Majnemerd905da42014-07-01 20:30:31 +0000681 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
682 CGM.getContext().getTagDeclType(Base.getBase()));
683
Anders Carlssona4147142010-03-25 15:26:28 +0000684 // Create and set the initializer.
Peter Collingbournee53683f2016-09-08 01:14:39 +0000685 llvm::Constant *Init = CreateVTableInitializer(*VTLayout, RTTI);
Anders Carlssona4147142010-03-25 15:26:28 +0000686 VTable->setInitializer(Init);
687
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000688 CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000689
Anders Carlsson0534b022010-03-25 00:35:49 +0000690 return VTable;
691}
692
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000693static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
694 const CXXRecordDecl *RD) {
695 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000696 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000697}
698
Eric Christopherd160c502016-01-29 01:35:53 +0000699/// Compute the required linkage of the vtable for the given class.
John McCall6bd2a892013-01-25 22:31:03 +0000700///
701/// Note that we only call this at the end of the translation unit.
702llvm::GlobalVariable::LinkageTypes
703CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000704 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000705 return llvm::GlobalVariable::InternalLinkage;
706
707 // We're at the end of the translation unit, so the current key
708 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +0000709 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
710 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +0000711 // If this class has a key function, use that to determine the
712 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000713 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000714 if (keyFunction->hasBody(def))
715 keyFunction = cast<CXXMethodDecl>(def);
716
717 switch (keyFunction->getTemplateSpecializationKind()) {
718 case TSK_Undeclared:
719 case TSK_ExplicitSpecialization:
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000720 assert((def || CodeGenOpts.OptimizationLevel > 0) &&
721 "Shouldn't query vtable linkage without key function or "
722 "optimizations");
723 if (!def && CodeGenOpts.OptimizationLevel > 0)
724 return llvm::GlobalVariable::AvailableExternallyLinkage;
725
John McCall6bd2a892013-01-25 22:31:03 +0000726 if (keyFunction->isInlined())
727 return !Context.getLangOpts().AppleKext ?
728 llvm::GlobalVariable::LinkOnceODRLinkage :
729 llvm::Function::InternalLinkage;
730
731 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +0000732
John McCall6bd2a892013-01-25 22:31:03 +0000733 case TSK_ImplicitInstantiation:
734 return !Context.getLangOpts().AppleKext ?
735 llvm::GlobalVariable::LinkOnceODRLinkage :
736 llvm::Function::InternalLinkage;
737
738 case TSK_ExplicitInstantiationDefinition:
739 return !Context.getLangOpts().AppleKext ?
740 llvm::GlobalVariable::WeakODRLinkage :
741 llvm::Function::InternalLinkage;
742
743 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000744 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000745 }
746 }
747
748 // -fapple-kext mode does not support weak linkage, so we must use
749 // internal linkage.
750 if (Context.getLangOpts().AppleKext)
751 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000752
753 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
754 llvm::GlobalValue::LinkOnceODRLinkage;
755 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
756 llvm::GlobalValue::WeakODRLinkage;
757 if (RD->hasAttr<DLLExportAttr>()) {
758 // Cannot discard exported vtables.
759 DiscardableODRLinkage = NonDiscardableODRLinkage;
760 } else if (RD->hasAttr<DLLImportAttr>()) {
761 // Imported vtables are available externally.
762 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
763 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
764 }
765
John McCall6bd2a892013-01-25 22:31:03 +0000766 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000767 case TSK_Undeclared:
768 case TSK_ExplicitSpecialization:
769 case TSK_ImplicitInstantiation:
770 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000771
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000772 case TSK_ExplicitInstantiationDeclaration:
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000773 // Explicit instantiations in MSVC do not provide vtables, so we must emit
774 // our own.
775 if (getTarget().getCXXABI().isMicrosoft())
776 return DiscardableODRLinkage;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000777 return shouldEmitAvailableExternallyVTable(*this, RD)
778 ? llvm::GlobalVariable::AvailableExternallyLinkage
779 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000780
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000781 case TSK_ExplicitInstantiationDefinition:
782 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000783 }
784
785 llvm_unreachable("Invalid TemplateSpecializationKind!");
786}
787
Eric Christopherd160c502016-01-29 01:35:53 +0000788/// This is a callback from Sema to tell us that that a particular vtable is
Nico Weberb6a5d052015-01-15 04:07:35 +0000789/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +0000790///
Nico Weberb6a5d052015-01-15 04:07:35 +0000791/// This is only called for vtables that _must_ be emitted (mainly due to key
792/// functions). For weak vtables, CodeGen tracks when they are needed and
793/// emits them as-needed.
794void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +0000795 VTables.GenerateClassData(theClass);
796}
797
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000798void
John McCall6bd2a892013-01-25 22:31:03 +0000799CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000800 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
801 DI->completeClassData(RD);
802
Reid Kleckner7810af02013-06-19 15:20:38 +0000803 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000804 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000805
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000806 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000807}
John McCall6bd2a892013-01-25 22:31:03 +0000808
809/// At this point in the translation unit, does it appear that can we
810/// rely on the vtable being defined elsewhere in the program?
811///
812/// The response is really only definitive when called at the end of
813/// the translation unit.
814///
815/// The only semantic restriction here is that the object file should
Eric Christopherd160c502016-01-29 01:35:53 +0000816/// not contain a vtable definition when that vtable is defined
John McCall6bd2a892013-01-25 22:31:03 +0000817/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
Eric Christopherd160c502016-01-29 01:35:53 +0000818/// vtables when unnecessary.
John McCall6bd2a892013-01-25 22:31:03 +0000819bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000820 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000821
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000822 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
823 // emit them even if there is an explicit template instantiation.
824 if (CGM.getTarget().getCXXABI().isMicrosoft())
David Majnemer2d8b2002016-02-11 17:49:28 +0000825 return false;
826
John McCall6bd2a892013-01-25 22:31:03 +0000827 // If we have an explicit instantiation declaration (and not a
Eric Christopherd160c502016-01-29 01:35:53 +0000828 // definition), the vtable is defined elsewhere.
John McCall6bd2a892013-01-25 22:31:03 +0000829 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
830 if (TSK == TSK_ExplicitInstantiationDeclaration)
831 return true;
832
833 // Otherwise, if the class is an instantiated template, the
Eric Christopherd160c502016-01-29 01:35:53 +0000834 // vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000835 if (TSK == TSK_ImplicitInstantiation ||
836 TSK == TSK_ExplicitInstantiationDefinition)
837 return false;
838
839 // Otherwise, if the class doesn't have a key function (possibly
Eric Christopherd160c502016-01-29 01:35:53 +0000840 // anymore), the vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000841 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
842 if (!keyFunction)
843 return false;
844
845 // Otherwise, if we don't have a definition of the key function, the
Eric Christopherd160c502016-01-29 01:35:53 +0000846 // vtable must be defined somewhere else.
John McCall6bd2a892013-01-25 22:31:03 +0000847 return !keyFunction->hasBody();
848}
849
850/// Given that we're currently at the end of the translation unit, and
Eric Christopherd160c502016-01-29 01:35:53 +0000851/// we've emitted a reference to the vtable for this class, should
852/// we define that vtable?
John McCall6bd2a892013-01-25 22:31:03 +0000853static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
854 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000855 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000856 if (!CGM.getVTables().isVTableExternal(RD))
857 return true;
858
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000859 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000860 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +0000861}
862
863/// Given that at some point we emitted a reference to one or more
Eric Christopherd160c502016-01-29 01:35:53 +0000864/// vtables, and that we are now at the end of the translation unit,
John McCall6bd2a892013-01-25 22:31:03 +0000865/// decide whether we should emit them.
866void CodeGenModule::EmitDeferredVTables() {
867#ifndef NDEBUG
868 // Remember the size of DeferredVTables, because we're going to assume
869 // that this entire operation doesn't modify it.
870 size_t savedSize = DeferredVTables.size();
871#endif
872
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000873 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +0000874 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
875 VTables.GenerateClassData(RD);
John McCall6bd2a892013-01-25 22:31:03 +0000876
877 assert(savedSize == DeferredVTables.size() &&
Eric Christopherd160c502016-01-29 01:35:53 +0000878 "deferred extra vtables during vtable emission?");
John McCall6bd2a892013-01-25 22:31:03 +0000879 DeferredVTables.clear();
880}
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000881
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000882bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
883 LinkageInfo LV = RD->getLinkageAndVisibility();
884 if (!isExternallyVisible(LV.getLinkage()))
885 return true;
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000886
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000887 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
888 return false;
Peter Collingbournefb532b92016-02-24 20:46:36 +0000889
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000890 if (getTriple().isOSBinFormatCOFF()) {
891 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
892 return false;
893 } else {
894 if (LV.getVisibility() != HiddenVisibility)
895 return false;
896 }
Peter Collingbournefb532b92016-02-24 20:46:36 +0000897
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000898 if (getCodeGenOpts().LTOVisibilityPublicStd) {
899 const DeclContext *DC = RD;
900 while (1) {
901 auto *D = cast<Decl>(DC);
902 DC = DC->getParent();
903 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
904 if (auto *ND = dyn_cast<NamespaceDecl>(D))
905 if (const IdentifierInfo *II = ND->getIdentifier())
906 if (II->isStr("std") || II->isStr("stdext"))
907 return false;
908 break;
909 }
910 }
911 }
912
913 return true;
Peter Collingbournee5706442015-07-09 19:56:14 +0000914}
915
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000916void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
917 const VTableLayout &VTLayout) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000918 if (!getCodeGenOpts().PrepareForLTO)
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000919 return;
920
Peter Collingbourne86d34a72015-06-17 19:08:05 +0000921 CharUnits PointerWidth =
922 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000923
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000924 typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
925 std::vector<BSEntry> BitsetEntries;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000926 // Create a bit set entry for each address point.
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000927 for (auto &&AP : VTLayout.getAddressPoints())
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000928 BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000929
930 // Sort the bit set entries for determinism.
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000931 std::sort(BitsetEntries.begin(), BitsetEntries.end(),
932 [this](const BSEntry &E1, const BSEntry &E2) {
933 if (&E1 == &E2)
Peter Collingbourne47941902015-02-24 01:12:53 +0000934 return false;
935
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000936 std::string S1;
937 llvm::raw_string_ostream O1(S1);
938 getCXXABI().getMangleContext().mangleTypeName(
939 QualType(E1.first->getTypeForDecl(), 0), O1);
940 O1.flush();
941
942 std::string S2;
943 llvm::raw_string_ostream O2(S2);
944 getCXXABI().getMangleContext().mangleTypeName(
945 QualType(E2.first->getTypeForDecl(), 0), O2);
946 O2.flush();
947
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000948 if (S1 < S2)
949 return true;
950 if (S1 != S2)
951 return false;
952
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000953 return E1.second < E2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000954 });
955
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000956 for (auto BitsetEntry : BitsetEntries)
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000957 AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,
958 BitsetEntry.first);
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000959}