blob: 6f749056ad6ee5852aa933530f9303c891dca981 [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
Anders Carlsson2bb27f52009-10-11 22:13:54 +000014#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.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 Carlssond420a312009-11-26 19:32:45 +000021#include "llvm/ADT/DenseSet.h"
Anders Carlssond46ed892010-02-27 16:18:19 +000022#include "llvm/ADT/SetVector.h"
Chandler Carruth94eab4a2010-02-13 10:38:52 +000023#include "llvm/Support/Compiler.h"
Anders Carlsson5d40c6f2010-02-11 08:02:13 +000024#include "llvm/Support/Format.h"
Eli Friedman49a94b12011-05-06 17:27:27 +000025#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson56446142010-03-17 20:06:32 +000026#include <algorithm>
Zhongxing Xu1721ef72009-11-13 05:46:16 +000027#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000028
29using namespace clang;
30using namespace CodeGen;
31
Reid Kleckner96f8f932014-02-05 17:27:08 +000032CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
33 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbournea8341662011-09-26 01:56:30 +000034
Anders Carlssoncd836f02010-03-23 17:17:29 +000035llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlssonfe8a9932011-02-06 17:15:43 +000036 const ThunkInfo &Thunk) {
Anders Carlssoncd836f02010-03-23 17:17:29 +000037 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38
39 // Compute the mangled name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000040 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +000041 llvm::raw_svector_ostream Out(Name);
Anders Carlssoncd836f02010-03-23 17:17:29 +000042 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall5d865c322010-08-31 07:33:07 +000043 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindola3968cd02011-02-11 02:52:17 +000044 Thunk.This, Out);
Anders Carlssoncd836f02010-03-23 17:17:29 +000045 else
Rafael Espindola3968cd02011-02-11 02:52:17 +000046 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
Rafael Espindola3968cd02011-02-11 02:52:17 +000047
Chris Lattner2192fe52011-07-18 04:24:23 +000048 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +000049 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
David Majnemerb9bd6fb2014-11-01 05:42:23 +000050 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000051}
52
John McCallc8bd9c22010-08-04 23:46:35 +000053static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
54 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlssonc6a47892011-01-29 19:39:23 +000055 CGM.setGlobalVisibility(Fn, MD);
John McCallc8bd9c22010-08-04 23:46:35 +000056}
57
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000058static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
59 llvm::Function *ThunkFn, bool ForVTable,
60 GlobalDecl GD) {
61 CGM.setFunctionLinkage(GD, ThunkFn);
62 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
63 !Thunk.Return.isEmpty());
64
65 // Set the right visibility.
66 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
67 setThunkVisibility(CGM, MD, Thunk, ThunkFn);
68
69 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
70 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
71}
72
John McCall5fe00962011-03-09 07:12:35 +000073#ifndef NDEBUG
74static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
75 const ABIArgInfo &infoR, CanQualType typeR) {
76 return (infoL.getKind() == infoR.getKind() &&
77 (typeL == typeR ||
78 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
79 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
80}
81#endif
82
Eli Friedman49a94b12011-05-06 17:27:27 +000083static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
84 QualType ResultType, RValue RV,
85 const ThunkInfo &Thunk) {
86 // Emit the return adjustment.
87 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000088
89 llvm::BasicBlock *AdjustNull = nullptr;
90 llvm::BasicBlock *AdjustNotNull = nullptr;
91 llvm::BasicBlock *AdjustEnd = nullptr;
92
Eli Friedman49a94b12011-05-06 17:27:27 +000093 llvm::Value *ReturnValue = RV.getScalarVal();
94
95 if (NullCheckValue) {
96 AdjustNull = CGF.createBasicBlock("adjust.null");
97 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
98 AdjustEnd = CGF.createBasicBlock("adjust.end");
99
100 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
101 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
102 CGF.EmitBlock(AdjustNotNull);
103 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000104
John McCall7f416cc2015-09-08 08:05:57 +0000105 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
106 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
107 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
108 Address(ReturnValue, ClassAlign),
109 Thunk.Return);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000110
Eli Friedman49a94b12011-05-06 17:27:27 +0000111 if (NullCheckValue) {
112 CGF.Builder.CreateBr(AdjustEnd);
113 CGF.EmitBlock(AdjustNull);
114 CGF.Builder.CreateBr(AdjustEnd);
115 CGF.EmitBlock(AdjustEnd);
116
117 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
118 PHI->addIncoming(ReturnValue, AdjustNotNull);
119 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
120 AdjustNull);
121 ReturnValue = PHI;
122 }
123
124 return RValue::get(ReturnValue);
125}
126
127// This function does roughly the same thing as GenerateThunk, but in a
128// very different way, so that va_start and va_end work correctly.
129// FIXME: This function assumes "this" is the first non-sret LLVM argument of
130// a function, and that there is an alloca built in the entry block
131// for all accesses to "this".
132// FIXME: This function assumes there is only one "ret" statement per function.
133// FIXME: Cloning isn't correct in the presence of indirect goto!
134// FIXME: This implementation of thunks bloats codesize by duplicating the
135// function definition. There are alternatives:
136// 1. Add some sort of stub support to LLVM for cases where we can
137// do a this adjustment, then a sibcall.
138// 2. We could transform the definition to take a va_list instead of an
139// actual variable argument list, then have the thunks (including a
140// no-op thunk for the regular definition) call va_start/va_end.
141// There's a bit of per-call overhead for this solution, but it's
142// better for codesize if the definition is long.
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000143llvm::Function *
144CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
Eli Friedman49a94b12011-05-06 17:27:27 +0000145 const CGFunctionInfo &FnInfo,
146 GlobalDecl GD, const ThunkInfo &Thunk) {
147 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
148 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000149 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000150
151 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000152 assert(FnInfo.isVariadic());
153 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000154 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
155 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
156
157 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000158 llvm::ValueToValueMapTy VMap;
Peter Collingbourne7d6e81d2016-05-10 20:23:29 +0000159 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
Eli Friedman49a94b12011-05-06 17:27:27 +0000160 Fn->replaceAllUsesWith(NewFn);
161 NewFn->takeName(Fn);
162 Fn->eraseFromParent();
163 Fn = NewFn;
164
165 // "Initialize" CGF (minimally).
166 CurFn = Fn;
167
168 // Get the "this" value
169 llvm::Function::arg_iterator AI = Fn->arg_begin();
170 if (CGM.ReturnTypeUsesSRet(FnInfo))
171 ++AI;
172
173 // Find the first store of "this", which will be to the alloca associated
174 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000175 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000176 llvm::BasicBlock *EntryBB = &Fn->front();
177 llvm::BasicBlock::iterator ThisStore =
David Blaikiea629c0f2014-12-29 22:39:45 +0000178 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000179 return isa<llvm::StoreInst>(I) &&
180 I.getOperand(0) == ThisPtr.getPointer();
181 });
182 assert(ThisStore != EntryBB->end() &&
183 "Store of this should be in entry block?");
Eli Friedman49a94b12011-05-06 17:27:27 +0000184 // Adjust "this", if necessary.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000185 Builder.SetInsertPoint(&*ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000186 llvm::Value *AdjustedThisPtr =
187 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000188 ThisStore->setOperand(0, AdjustedThisPtr);
189
190 if (!Thunk.Return.isEmpty()) {
191 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000192 for (llvm::BasicBlock &BB : *Fn) {
193 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000194 if (isa<llvm::ReturnInst>(T)) {
195 RValue RV = RValue::get(T->getOperand(0));
196 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000197 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000198 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
199 Builder.CreateRet(RV.getScalarVal());
200 break;
201 }
202 }
203 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000204
205 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000206}
207
Hans Wennborg88497d62013-11-15 17:24:45 +0000208void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
209 const CGFunctionInfo &FnInfo) {
210 assert(!CurGD.getDecl() && "CurGD was already set!");
211 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000212 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000213
214 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000215 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000216 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000217 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000218 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
219 ? ThisType
220 : CGM.getCXXABI().hasMostDerivedReturn(GD)
221 ? CGM.getContext().VoidPtrTy
222 : FPT->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000223 FunctionArgList FunctionArgs;
224
Anders Carlssonbad991d2010-03-24 00:39:18 +0000225 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000226 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000227
228 // Add the rest of the parameters.
Alexey Samsonov3551e312014-08-13 20:06:24 +0000229 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000230
Reid Kleckner89077a12013-12-17 19:46:40 +0000231 if (isa<CXXDestructorDecl>(MD))
232 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
233
Hans Wennborg88497d62013-11-15 17:24:45 +0000234 // Start defining the function.
John McCalla738c252011-03-09 04:27:21 +0000235 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
David Blaikie4d5c7282014-12-29 22:53:52 +0000236 MD->getLocation(), MD->getLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000237
Hans Wennborg88497d62013-11-15 17:24:45 +0000238 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000239 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000240 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000241 CurCodeDecl = MD;
242 CurFuncDecl = MD;
243}
244
245void CodeGenFunction::FinishThunk() {
246 // Clear these to restore the invariants expected by
247 // StartFunction/FinishFunction.
248 CurCodeDecl = nullptr;
249 CurFuncDecl = nullptr;
250
251 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000252}
John McCall5d865c322010-08-31 07:33:07 +0000253
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000254void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
Hans Wennborg88497d62013-11-15 17:24:45 +0000255 const ThunkInfo *Thunk) {
256 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
257 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000258 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000259
Hans Wennborg88497d62013-11-15 17:24:45 +0000260 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000261 llvm::Value *AdjustedThisPtr =
262 Thunk ? CGM.getCXXABI().performThisAdjustment(
263 *this, LoadCXXThisAddress(), Thunk->This)
264 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000265
Reid Klecknerab2090d2014-07-26 01:34:32 +0000266 if (CurFnInfo->usesInAlloca()) {
267 // We don't handle return adjusting thunks, because they require us to call
268 // the copy constructor. For now, fall through and pretend the return
269 // adjustment was empty so we don't crash.
270 if (Thunk && !Thunk->Return.isEmpty()) {
271 CGM.ErrorUnsupported(
272 MD, "non-trivial argument copy for return-adjusting thunk");
273 }
274 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
275 return;
276 }
277
Hans Wennborg88497d62013-11-15 17:24:45 +0000278 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000279 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000280 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000281 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000282
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000283 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000284 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000285
Hans Wennborg88497d62013-11-15 17:24:45 +0000286 // Add the rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +0000287 for (const ParmVarDecl *PD : MD->parameters())
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000288 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000289
Hans Wennborg88497d62013-11-15 17:24:45 +0000290 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000291
John McCalla738c252011-03-09 04:27:21 +0000292#ifndef NDEBUG
George Burgess IV419996c2016-06-16 23:06:04 +0000293 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
294 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD));
Hans Wennborg88497d62013-11-15 17:24:45 +0000295 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
296 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
297 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000298 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
299 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000300 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
301 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
302 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000303 assert(similar(CallFnInfo.arg_begin()[i].info,
304 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000305 CurFnInfo->arg_begin()[i].info,
306 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000307#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000308
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000309 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000310 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
311 ? ThisType
312 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
313 ? CGM.getContext().VoidPtrTy
314 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000315 ReturnValueSlot Slot;
316 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000317 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000318 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000319 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
320
Anders Carlssonbad991d2010-03-24 00:39:18 +0000321 // Now emit our call.
Reid Klecknerab2090d2014-07-26 01:34:32 +0000322 llvm::Instruction *CallOrInvoke;
323 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
324
Hans Wennborg88497d62013-11-15 17:24:45 +0000325 // Consider return adjustment if we have ThunkInfo.
326 if (Thunk && !Thunk->Return.isEmpty())
327 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000328 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
329 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000330
Hans Wennborg88497d62013-11-15 17:24:45 +0000331 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000332 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000333 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000334
John McCallff755cd2012-07-31 00:33:55 +0000335 // Disable the final ARC autorelease.
336 AutoreleaseResult = false;
337
John McCall7f416cc2015-09-08 08:05:57 +0000338 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000339}
340
Reid Klecknerab2090d2014-07-26 01:34:32 +0000341void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
342 llvm::Value *AdjustedThisPtr,
343 llvm::Value *Callee) {
344 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
345 // to translate AST arguments into LLVM IR arguments. For thunks, we know
346 // that the caller prototype more or less matches the callee prototype with
347 // the exception of 'this'.
348 SmallVector<llvm::Value *, 8> Args;
349 for (llvm::Argument &A : CurFn->args())
350 Args.push_back(&A);
351
352 // Set the adjusted 'this' pointer.
353 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
354 if (ThisAI.isDirect()) {
355 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
356 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
357 llvm::Type *ThisType = Args[ThisArgNo]->getType();
358 if (ThisType != AdjustedThisPtr->getType())
359 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
360 Args[ThisArgNo] = AdjustedThisPtr;
361 } else {
362 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000363 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
364 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000365 if (ThisType != AdjustedThisPtr->getType())
366 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
367 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
368 }
369
370 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
371 // don't actually want to run them.
372 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
373 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
374
375 // Apply the standard set of call attributes.
376 unsigned CallingConv;
377 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000378 CGM.ConstructAttributeList(Callee->getName(), *CurFnInfo, MD, AttributeList,
379 CallingConv, /*AttrOnCallSite=*/true);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000380 llvm::AttributeSet Attrs =
381 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
382 Call->setAttributes(Attrs);
383 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
384
385 if (Call->getType()->isVoidTy())
386 Builder.CreateRetVoid();
387 else
388 Builder.CreateRet(Call);
389
390 // Finish the function to maintain CodeGenFunction invariants.
391 // FIXME: Don't emit unreachable code.
392 EmitBlock(createBasicBlock());
393 FinishFunction();
394}
395
Rafael Espindolad6e66942015-07-13 06:07:58 +0000396void CodeGenFunction::generateThunk(llvm::Function *Fn,
Hans Wennborg88497d62013-11-15 17:24:45 +0000397 const CGFunctionInfo &FnInfo,
398 GlobalDecl GD, const ThunkInfo &Thunk) {
399 StartThunk(Fn, GD, FnInfo);
400
401 // Get our callee.
402 llvm::Type *Ty =
403 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
404 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
405
406 // Make the call and return the result.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000407 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000408}
409
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000410void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
411 bool ForVTable) {
John McCalla729c622012-02-17 03:33:10 +0000412 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalla738c252011-03-09 04:27:21 +0000413
414 // FIXME: re-use FnInfo in this computation.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000415 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
416 llvm::GlobalValue *Entry;
417
Anders Carlsson55e89f82010-03-23 18:18:41 +0000418 // Strip off a bitcast if we got one back.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000419 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson55e89f82010-03-23 18:18:41 +0000420 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000421 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
422 } else {
423 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000424 }
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000425
Anders Carlsson55e89f82010-03-23 18:18:41 +0000426 // There's already a declaration with the same name, check if it has the same
427 // type or if we need to replace it.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000428 if (Entry->getType()->getElementType() !=
John McCall5d865c322010-08-31 07:33:07 +0000429 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000430 llvm::GlobalValue *OldThunkFn = Entry;
431
Anders Carlsson55e89f82010-03-23 18:18:41 +0000432 // If the types mismatch then we have to rewrite the definition.
433 assert(OldThunkFn->isDeclaration() &&
434 "Shouldn't replace non-declaration");
435
436 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 OldThunkFn->setName(StringRef());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000438 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Anders Carlsson55e89f82010-03-23 18:18:41 +0000439
440 // If needed, replace the old thunk with a bitcast.
441 if (!OldThunkFn->use_empty()) {
442 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000443 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000444 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
445 }
446
447 // Remove the old thunk.
448 OldThunkFn->eraseFromParent();
449 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000450
Anders Carlssonbad991d2010-03-24 00:39:18 +0000451 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000452 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
453 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000454
455 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000456 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000457 // There is already a thunk emitted for this function, do nothing.
458 return;
459 }
460
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000461 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlssone866d442011-02-06 20:09:44 +0000462 return;
Anders Carlsson8b021832011-02-06 18:31:40 +0000463 }
464
Rafael Espindola86792432012-09-21 20:39:32 +0000465 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
466
Eli Friedman49a94b12011-05-06 17:27:27 +0000467 if (ThunkFn->isVarArg()) {
468 // Varargs thunks are special; we can't just generate a call because
469 // we can't copy the varargs. Our implementation is rather
470 // expensive/sucky at the moment, so don't generate the thunk unless
471 // we have to.
472 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Peter Collingbourne45a24012015-06-30 19:07:26 +0000473 if (UseAvailableExternallyLinkage)
474 return;
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000475 ThunkFn =
476 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000477 } else {
478 // Normal thunk body generation.
Rafael Espindolad6e66942015-07-13 06:07:58 +0000479 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000480 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000481
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000482 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlsson8b021832011-02-06 18:31:40 +0000483}
484
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000485void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
486 const ThunkInfo &Thunk) {
487 // If the ABI has key functions, only the TU with the key function should emit
488 // the thunk. However, we can allow inlining of thunks if we emit them with
489 // available_externally linkage together with vtables when optimizations are
490 // enabled.
491 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
492 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson8b021832011-02-06 18:31:40 +0000493 return;
494
495 // We can't emit thunks for member functions with incomplete types.
496 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattner8806e322011-07-10 00:18:59 +0000497 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Klecknerfe56be52013-10-11 20:46:27 +0000498 MD->getType()->castAs<FunctionType>()))
Anders Carlsson8b021832011-02-06 18:31:40 +0000499 return;
500
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000501 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000502}
503
Anders Carlsson917229c2010-03-23 04:59:02 +0000504void CodeGenVTables::EmitThunks(GlobalDecl GD)
505{
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000506 const CXXMethodDecl *MD =
507 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
508
509 // We don't need to generate thunks for the base destructor.
510 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
511 return;
512
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000513 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
514 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000515
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000516 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000517 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000518
Yaron Kerenede60302015-08-01 19:11:36 +0000519 for (const ThunkInfo& Thunk : *ThunkInfoVector)
520 emitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000521}
522
David Majnemerd905da42014-07-01 20:30:31 +0000523llvm::Constant *CodeGenVTables::CreateVTableInitializer(
524 const CXXRecordDecl *RD, const VTableComponent *Components,
525 unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
526 unsigned NumVTableThunks, llvm::Constant *RTTI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000527 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlssona4147142010-03-25 15:26:28 +0000528
Chris Lattnerece04092012-02-07 00:39:47 +0000529 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlssona4147142010-03-25 15:26:28 +0000530
Chris Lattner2192fe52011-07-18 04:24:23 +0000531 llvm::Type *PtrDiffTy =
Anders Carlssona5736bd2010-03-25 16:49:53 +0000532 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
533
Anders Carlssona5736bd2010-03-25 16:49:53 +0000534 unsigned NextVTableThunkIndex = 0;
Craig Topper8a13c412014-05-21 05:09:00 +0000535
536 llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000537
Anders Carlssona4147142010-03-25 15:26:28 +0000538 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000539 VTableComponent Component = Components[I];
Anders Carlssona5736bd2010-03-25 16:49:53 +0000540
Craig Topper8a13c412014-05-21 05:09:00 +0000541 llvm::Constant *Init = nullptr;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000542
543 switch (Component.getKind()) {
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000544 case VTableComponent::CK_VCallOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000545 Init = llvm::ConstantInt::get(PtrDiffTy,
546 Component.getVCallOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000547 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
548 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000549 case VTableComponent::CK_VBaseOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000550 Init = llvm::ConstantInt::get(PtrDiffTy,
551 Component.getVBaseOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000552 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
553 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000554 case VTableComponent::CK_OffsetToTop:
Ken Dyck872d74a2011-04-02 01:14:48 +0000555 Init = llvm::ConstantInt::get(PtrDiffTy,
556 Component.getOffsetToTop().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000557 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
558 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000559 case VTableComponent::CK_RTTI:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000560 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
561 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000562 case VTableComponent::CK_FunctionPointer:
563 case VTableComponent::CK_CompleteDtorPointer:
564 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlssona5736bd2010-03-25 16:49:53 +0000565 GlobalDecl GD;
566
567 // Get the right global decl.
568 switch (Component.getKind()) {
569 default:
570 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000571 case VTableComponent::CK_FunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000572 GD = Component.getFunctionDecl();
573 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000574 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000575 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
576 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000577 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000578 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
579 break;
580 }
581
Artem Belevich9b929462015-12-17 18:12:36 +0000582 if (CGM.getLangOpts().CUDA) {
583 // Emit NULL for methods we can't codegen on this
584 // side. Otherwise we'd end up with vtable with unresolved
585 // references.
586 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
587 // OK on device side: functions w/ __device__ attribute
588 // OK on host side: anything except __device__-only functions.
589 bool CanEmitMethod = CGM.getLangOpts().CUDAIsDevice
590 ? MD->hasAttr<CUDADeviceAttr>()
591 : (MD->hasAttr<CUDAHostAttr>() ||
592 !MD->hasAttr<CUDADeviceAttr>());
593 if (!CanEmitMethod) {
594 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
595 break;
596 }
597 // Method is acceptable, continue processing as usual.
598 }
599
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000600 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
601 // We have a pure virtual member function.
Joao Matos718a8832012-07-17 19:17:58 +0000602 if (!PureVirtualFn) {
Eli Friedman48a32912012-09-14 01:19:01 +0000603 llvm::FunctionType *Ty =
604 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
605 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
606 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +0000607 if (auto *F = dyn_cast<llvm::Function>(PureVirtualFn))
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000608 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eli Friedman48a32912012-09-14 01:19:01 +0000609 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matos718a8832012-07-17 19:17:58 +0000610 CGM.Int8PtrTy);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000611 }
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000612 Init = PureVirtualFn;
David Blaikieeb7d5982012-10-16 22:56:05 +0000613 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
614 if (!DeletedVirtualFn) {
615 llvm::FunctionType *Ty =
616 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
617 StringRef DeletedCallName =
618 CGM.getCXXABI().GetDeletedVirtualCallName();
619 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +0000620 if (auto *F = dyn_cast<llvm::Function>(DeletedVirtualFn))
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000621 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
David Blaikieeb7d5982012-10-16 22:56:05 +0000622 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
623 CGM.Int8PtrTy);
624 }
625 Init = DeletedVirtualFn;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000626 } else {
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000627 // Check if we should use a thunk.
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000628 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000629 VTableThunks[NextVTableThunkIndex].first == I) {
630 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000631
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000632 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramere6b4a162012-03-20 20:18:13 +0000633 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson8b021832011-02-06 18:31:40 +0000634
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000635 NextVTableThunkIndex++;
636 } else {
Chris Lattner2192fe52011-07-18 04:24:23 +0000637 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000638
Anders Carlsson3c239482011-02-05 04:35:53 +0000639 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000640 }
641
642 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000643 }
Anders Carlssona5736bd2010-03-25 16:49:53 +0000644 break;
645 }
646
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000647 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000648 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
649 break;
650 };
Anders Carlssona4147142010-03-25 15:26:28 +0000651
652 Inits.push_back(Init);
653 }
654
655 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad83be3612011-06-22 09:24:39 +0000656 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlssona4147142010-03-25 15:26:28 +0000657}
658
Anders Carlsson0534b022010-03-25 00:35:49 +0000659llvm::GlobalVariable *
660CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlssona208b392010-03-26 03:56:54 +0000661 const BaseSubobject &Base,
662 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000663 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000664 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000665 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
666 DI->completeClassData(Base.getBase());
667
Ahmed Charlesb8984322014-03-07 20:03:18 +0000668 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000669 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000670 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000671
Anders Carlssona5736bd2010-03-25 16:49:53 +0000672 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000673 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000674
675 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000676 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000677 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000678 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
679 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
680 Base.getBase(), Out);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000681 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000682
Anders Carlssona4147142010-03-25 15:26:28 +0000683 llvm::ArrayType *ArrayType =
Chris Lattnerece04092012-02-07 00:39:47 +0000684 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlssona4147142010-03-25 15:26:28 +0000685
Richard Smith65fd2a42013-02-16 00:51:21 +0000686 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
687 // guarantee that they actually will be available externally. Instead, when
688 // emitting an available_externally VTT, we provide references to an internal
689 // linkage construction vtable. The ABI only requires complete-object vtables
690 // to be the same for all instances of a type, not construction vtables.
691 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
692 Linkage = llvm::GlobalVariable::InternalLinkage;
693
Anders Carlssona4147142010-03-25 15:26:28 +0000694 // Create the variable that will hold the construction vtable.
695 llvm::GlobalVariable *VTable =
John McCall358d0562011-03-27 09:00:25 +0000696 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
John McCall8f80a612014-02-08 00:41:16 +0000697 CGM.setGlobalVisibility(VTable, RD);
John McCall358d0562011-03-27 09:00:25 +0000698
699 // V-tables are always unnamed_addr.
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000700 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Anders Carlssona4147142010-03-25 15:26:28 +0000701
David Majnemerd905da42014-07-01 20:30:31 +0000702 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
703 CGM.getContext().getTagDeclType(Base.getBase()));
704
Anders Carlssona4147142010-03-25 15:26:28 +0000705 // Create and set the initializer.
David Majnemerd905da42014-07-01 20:30:31 +0000706 llvm::Constant *Init = CreateVTableInitializer(
707 Base.getBase(), VTLayout->vtable_component_begin(),
708 VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
709 VTLayout->getNumVTableThunks(), RTTI);
Anders Carlssona4147142010-03-25 15:26:28 +0000710 VTable->setInitializer(Init);
711
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000712 CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
713
Anders Carlsson0534b022010-03-25 00:35:49 +0000714 return VTable;
715}
716
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000717static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
718 const CXXRecordDecl *RD) {
719 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000720 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000721}
722
Eric Christopherd160c502016-01-29 01:35:53 +0000723/// Compute the required linkage of the vtable for the given class.
John McCall6bd2a892013-01-25 22:31:03 +0000724///
725/// Note that we only call this at the end of the translation unit.
726llvm::GlobalVariable::LinkageTypes
727CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000728 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000729 return llvm::GlobalVariable::InternalLinkage;
730
731 // We're at the end of the translation unit, so the current key
732 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +0000733 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
734 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +0000735 // If this class has a key function, use that to determine the
736 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000737 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000738 if (keyFunction->hasBody(def))
739 keyFunction = cast<CXXMethodDecl>(def);
740
741 switch (keyFunction->getTemplateSpecializationKind()) {
742 case TSK_Undeclared:
743 case TSK_ExplicitSpecialization:
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000744 assert((def || CodeGenOpts.OptimizationLevel > 0) &&
745 "Shouldn't query vtable linkage without key function or "
746 "optimizations");
747 if (!def && CodeGenOpts.OptimizationLevel > 0)
748 return llvm::GlobalVariable::AvailableExternallyLinkage;
749
John McCall6bd2a892013-01-25 22:31:03 +0000750 if (keyFunction->isInlined())
751 return !Context.getLangOpts().AppleKext ?
752 llvm::GlobalVariable::LinkOnceODRLinkage :
753 llvm::Function::InternalLinkage;
754
755 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +0000756
John McCall6bd2a892013-01-25 22:31:03 +0000757 case TSK_ImplicitInstantiation:
758 return !Context.getLangOpts().AppleKext ?
759 llvm::GlobalVariable::LinkOnceODRLinkage :
760 llvm::Function::InternalLinkage;
761
762 case TSK_ExplicitInstantiationDefinition:
763 return !Context.getLangOpts().AppleKext ?
764 llvm::GlobalVariable::WeakODRLinkage :
765 llvm::Function::InternalLinkage;
766
767 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000768 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000769 }
770 }
771
772 // -fapple-kext mode does not support weak linkage, so we must use
773 // internal linkage.
774 if (Context.getLangOpts().AppleKext)
775 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000776
777 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
778 llvm::GlobalValue::LinkOnceODRLinkage;
779 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
780 llvm::GlobalValue::WeakODRLinkage;
781 if (RD->hasAttr<DLLExportAttr>()) {
782 // Cannot discard exported vtables.
783 DiscardableODRLinkage = NonDiscardableODRLinkage;
784 } else if (RD->hasAttr<DLLImportAttr>()) {
785 // Imported vtables are available externally.
786 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
787 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
788 }
789
John McCall6bd2a892013-01-25 22:31:03 +0000790 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000791 case TSK_Undeclared:
792 case TSK_ExplicitSpecialization:
793 case TSK_ImplicitInstantiation:
794 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000795
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000796 case TSK_ExplicitInstantiationDeclaration:
797 return shouldEmitAvailableExternallyVTable(*this, RD)
798 ? llvm::GlobalVariable::AvailableExternallyLinkage
799 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000800
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000801 case TSK_ExplicitInstantiationDefinition:
802 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000803 }
804
805 llvm_unreachable("Invalid TemplateSpecializationKind!");
806}
807
Eric Christopherd160c502016-01-29 01:35:53 +0000808/// This is a callback from Sema to tell us that that a particular vtable is
Nico Weberb6a5d052015-01-15 04:07:35 +0000809/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +0000810///
Nico Weberb6a5d052015-01-15 04:07:35 +0000811/// This is only called for vtables that _must_ be emitted (mainly due to key
812/// functions). For weak vtables, CodeGen tracks when they are needed and
813/// emits them as-needed.
814void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +0000815 VTables.GenerateClassData(theClass);
816}
817
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000818void
John McCall6bd2a892013-01-25 22:31:03 +0000819CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000820 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
821 DI->completeClassData(RD);
822
Reid Kleckner7810af02013-06-19 15:20:38 +0000823 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000824 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000825
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000826 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000827}
John McCall6bd2a892013-01-25 22:31:03 +0000828
829/// At this point in the translation unit, does it appear that can we
830/// rely on the vtable being defined elsewhere in the program?
831///
832/// The response is really only definitive when called at the end of
833/// the translation unit.
834///
835/// The only semantic restriction here is that the object file should
Eric Christopherd160c502016-01-29 01:35:53 +0000836/// not contain a vtable definition when that vtable is defined
John McCall6bd2a892013-01-25 22:31:03 +0000837/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
Eric Christopherd160c502016-01-29 01:35:53 +0000838/// vtables when unnecessary.
John McCall6bd2a892013-01-25 22:31:03 +0000839bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000840 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000841
Reid Klecknerf981bcb2016-06-21 19:51:52 +0000842 // We always synthesize vtables on the import side regardless of whether or
843 // not it is an explicit instantiation declaration.
844 if (CGM.getTarget().getCXXABI().isMicrosoft() && RD->hasAttr<DLLImportAttr>())
David Majnemer2d8b2002016-02-11 17:49:28 +0000845 return false;
846
John McCall6bd2a892013-01-25 22:31:03 +0000847 // If we have an explicit instantiation declaration (and not a
Eric Christopherd160c502016-01-29 01:35:53 +0000848 // definition), the vtable is defined elsewhere.
John McCall6bd2a892013-01-25 22:31:03 +0000849 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
850 if (TSK == TSK_ExplicitInstantiationDeclaration)
851 return true;
852
853 // Otherwise, if the class is an instantiated template, the
Eric Christopherd160c502016-01-29 01:35:53 +0000854 // vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000855 if (TSK == TSK_ImplicitInstantiation ||
856 TSK == TSK_ExplicitInstantiationDefinition)
857 return false;
858
859 // Otherwise, if the class doesn't have a key function (possibly
Eric Christopherd160c502016-01-29 01:35:53 +0000860 // anymore), the vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000861 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
862 if (!keyFunction)
863 return false;
864
865 // Otherwise, if we don't have a definition of the key function, the
Eric Christopherd160c502016-01-29 01:35:53 +0000866 // vtable must be defined somewhere else.
John McCall6bd2a892013-01-25 22:31:03 +0000867 return !keyFunction->hasBody();
868}
869
870/// Given that we're currently at the end of the translation unit, and
Eric Christopherd160c502016-01-29 01:35:53 +0000871/// we've emitted a reference to the vtable for this class, should
872/// we define that vtable?
John McCall6bd2a892013-01-25 22:31:03 +0000873static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
874 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000875 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000876 if (!CGM.getVTables().isVTableExternal(RD))
877 return true;
878
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000879 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000880 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +0000881}
882
883/// Given that at some point we emitted a reference to one or more
Eric Christopherd160c502016-01-29 01:35:53 +0000884/// vtables, and that we are now at the end of the translation unit,
John McCall6bd2a892013-01-25 22:31:03 +0000885/// decide whether we should emit them.
886void CodeGenModule::EmitDeferredVTables() {
887#ifndef NDEBUG
888 // Remember the size of DeferredVTables, because we're going to assume
889 // that this entire operation doesn't modify it.
890 size_t savedSize = DeferredVTables.size();
891#endif
892
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000893 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +0000894 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
895 VTables.GenerateClassData(RD);
John McCall6bd2a892013-01-25 22:31:03 +0000896
897 assert(savedSize == DeferredVTables.size() &&
Eric Christopherd160c502016-01-29 01:35:53 +0000898 "deferred extra vtables during vtable emission?");
John McCall6bd2a892013-01-25 22:31:03 +0000899 DeferredVTables.clear();
900}
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000901
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000902bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
903 LinkageInfo LV = RD->getLinkageAndVisibility();
904 if (!isExternallyVisible(LV.getLinkage()))
905 return true;
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000906
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000907 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
908 return false;
Peter Collingbournefb532b92016-02-24 20:46:36 +0000909
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000910 if (getTriple().isOSBinFormatCOFF()) {
911 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
912 return false;
913 } else {
914 if (LV.getVisibility() != HiddenVisibility)
915 return false;
916 }
Peter Collingbournefb532b92016-02-24 20:46:36 +0000917
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000918 if (getCodeGenOpts().LTOVisibilityPublicStd) {
919 const DeclContext *DC = RD;
920 while (1) {
921 auto *D = cast<Decl>(DC);
922 DC = DC->getParent();
923 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
924 if (auto *ND = dyn_cast<NamespaceDecl>(D))
925 if (const IdentifierInfo *II = ND->getIdentifier())
926 if (II->isStr("std") || II->isStr("stdext"))
927 return false;
928 break;
929 }
930 }
931 }
932
933 return true;
Peter Collingbournee5706442015-07-09 19:56:14 +0000934}
935
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000936void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
937 const VTableLayout &VTLayout) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000938 if (!getCodeGenOpts().PrepareForLTO)
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000939 return;
940
Peter Collingbourne86d34a72015-06-17 19:08:05 +0000941 CharUnits PointerWidth =
942 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000943
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000944 typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
945 std::vector<BSEntry> BitsetEntries;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000946 // Create a bit set entry for each address point.
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000947 for (auto &&AP : VTLayout.getAddressPoints())
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000948 BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000949
950 // Sort the bit set entries for determinism.
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000951 std::sort(BitsetEntries.begin(), BitsetEntries.end(),
952 [this](const BSEntry &E1, const BSEntry &E2) {
953 if (&E1 == &E2)
Peter Collingbourne47941902015-02-24 01:12:53 +0000954 return false;
955
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000956 std::string S1;
957 llvm::raw_string_ostream O1(S1);
958 getCXXABI().getMangleContext().mangleTypeName(
959 QualType(E1.first->getTypeForDecl(), 0), O1);
960 O1.flush();
961
962 std::string S2;
963 llvm::raw_string_ostream O2(S2);
964 getCXXABI().getMangleContext().mangleTypeName(
965 QualType(E2.first->getTypeForDecl(), 0), O2);
966 O2.flush();
967
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000968 if (S1 < S2)
969 return true;
970 if (S1 != S2)
971 return false;
972
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000973 return E1.second < E2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000974 });
975
976 llvm::NamedMDNode *BitsetsMD =
977 getModule().getOrInsertNamedMetadata("llvm.bitsets");
978 for (auto BitsetEntry : BitsetEntries)
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000979 CreateVTableBitSetEntry(BitsetsMD, VTable,
980 PointerWidth * BitsetEntry.second,
981 BitsetEntry.first);
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000982}