blob: 276993581117e575f6926e56def76d6b82201502 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson2bb27f52009-10-11 22:13:54 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation of virtual tables.
10//
11//===----------------------------------------------------------------------===//
12
John McCall5d865c322010-08-31 07:33:07 +000013#include "CGCXXABI.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000014#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CodeGenModule.h"
Reid Kleckner98031782019-12-09 16:11:56 -080016#include "clang/AST/Attr.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"
Richard Trieu63688182018-12-11 03:18:39 +000019#include "clang/Basic/CodeGenOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Wolfgang Pieba347c472017-10-31 22:49:48 +000021#include "clang/CodeGen/ConstantInitBuilder.h"
Wolfgang Pieba347c472017-10-31 22:49:48 +000022#include "llvm/IR/IntrinsicInst.h"
Anders Carlsson5d40c6f2010-02-11 08:02:13 +000023#include "llvm/Support/Format.h"
Eli Friedman49a94b12011-05-06 17:27:27 +000024#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson56446142010-03-17 20:06:32 +000025#include <algorithm>
Zhongxing Xu1721ef72009-11-13 05:46:16 +000026#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000027
28using namespace clang;
29using namespace CodeGen;
30
Reid Kleckner96f8f932014-02-05 17:27:08 +000031CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbournea8341662011-09-26 01:56:30 +000033
Reid Kleckner399d96e2018-04-02 20:20:33 +000034llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
35 GlobalDecl GD) {
36 return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
David Majnemerb9bd6fb2014-11-01 05:42:23 +000037 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000038}
39
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000040static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
41 llvm::Function *ThunkFn, bool ForVTable,
42 GlobalDecl GD) {
43 CGM.setFunctionLinkage(GD, ThunkFn);
44 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
45 !Thunk.Return.isEmpty());
46
47 // Set the right visibility.
Rafael Espindolab7350042018-03-01 00:35:47 +000048 CGM.setGVProperties(ThunkFn, GD);
49
50 if (!CGM.getCXXABI().exportThunk()) {
51 ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
52 ThunkFn->setDSOLocal(true);
53 }
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000054
55 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
56 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
57}
58
John McCall5fe00962011-03-09 07:12:35 +000059#ifndef NDEBUG
60static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61 const ABIArgInfo &infoR, CanQualType typeR) {
62 return (infoL.getKind() == infoR.getKind() &&
63 (typeL == typeR ||
64 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66}
67#endif
68
Eli Friedman49a94b12011-05-06 17:27:27 +000069static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70 QualType ResultType, RValue RV,
71 const ThunkInfo &Thunk) {
72 // Emit the return adjustment.
73 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000074
75 llvm::BasicBlock *AdjustNull = nullptr;
76 llvm::BasicBlock *AdjustNotNull = nullptr;
77 llvm::BasicBlock *AdjustEnd = nullptr;
78
Eli Friedman49a94b12011-05-06 17:27:27 +000079 llvm::Value *ReturnValue = RV.getScalarVal();
80
81 if (NullCheckValue) {
82 AdjustNull = CGF.createBasicBlock("adjust.null");
83 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84 AdjustEnd = CGF.createBasicBlock("adjust.end");
Simon Pilgrim48c32b12016-09-08 09:59:58 +000085
Eli Friedman49a94b12011-05-06 17:27:27 +000086 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88 CGF.EmitBlock(AdjustNotNull);
89 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +000090
John McCall7f416cc2015-09-08 08:05:57 +000091 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
92 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
93 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
94 Address(ReturnValue, ClassAlign),
95 Thunk.Return);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +000096
Eli Friedman49a94b12011-05-06 17:27:27 +000097 if (NullCheckValue) {
98 CGF.Builder.CreateBr(AdjustEnd);
99 CGF.EmitBlock(AdjustNull);
100 CGF.Builder.CreateBr(AdjustEnd);
101 CGF.EmitBlock(AdjustEnd);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000102
Eli Friedman49a94b12011-05-06 17:27:27 +0000103 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
104 PHI->addIncoming(ReturnValue, AdjustNotNull);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000105 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
Eli Friedman49a94b12011-05-06 17:27:27 +0000106 AdjustNull);
107 ReturnValue = PHI;
108 }
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000109
Eli Friedman49a94b12011-05-06 17:27:27 +0000110 return RValue::get(ReturnValue);
111}
112
Fangrui Song6907ce22018-07-30 19:24:48 +0000113/// This function clones a function's DISubprogram node and enters it into
Wolfgang Pieba347c472017-10-31 22:49:48 +0000114/// a value map with the intent that the map can be utilized by the cloner
115/// to short-circuit Metadata node mapping.
116/// Furthermore, the function resolves any DILocalVariable nodes referenced
117/// by dbg.value intrinsics so they can be properly mapped during cloning.
118static void resolveTopLevelMetadata(llvm::Function *Fn,
119 llvm::ValueToValueMapTy &VMap) {
120 // Clone the DISubprogram node and put it into the Value map.
121 auto *DIS = Fn->getSubprogram();
122 if (!DIS)
123 return;
124 auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
125 VMap.MD()[DIS].reset(NewDIS);
126
127 // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
128 // they are referencing.
129 for (auto &BB : Fn->getBasicBlockList()) {
130 for (auto &I : BB) {
Hsiangkai Wange7b3da22018-08-06 04:00:08 +0000131 if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
Wolfgang Pieba347c472017-10-31 22:49:48 +0000132 auto *DILocal = DII->getVariable();
133 if (!DILocal->isResolved())
134 DILocal->resolve();
135 }
136 }
137 }
138}
139
Eli Friedman49a94b12011-05-06 17:27:27 +0000140// This function does roughly the same thing as GenerateThunk, but in a
141// very different way, so that va_start and va_end work correctly.
142// FIXME: This function assumes "this" is the first non-sret LLVM argument of
143// a function, and that there is an alloca built in the entry block
144// for all accesses to "this".
145// FIXME: This function assumes there is only one "ret" statement per function.
146// FIXME: Cloning isn't correct in the presence of indirect goto!
147// FIXME: This implementation of thunks bloats codesize by duplicating the
148// function definition. There are alternatives:
149// 1. Add some sort of stub support to LLVM for cases where we can
150// do a this adjustment, then a sibcall.
151// 2. We could transform the definition to take a va_list instead of an
152// actual variable argument list, then have the thunks (including a
153// no-op thunk for the regular definition) call va_start/va_end.
154// There's a bit of per-call overhead for this solution, but it's
155// better for codesize if the definition is long.
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000156llvm::Function *
157CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
Eli Friedman49a94b12011-05-06 17:27:27 +0000158 const CGFunctionInfo &FnInfo,
159 GlobalDecl GD, const ThunkInfo &Thunk) {
160 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Simon Pilgrim5e0a0b72019-10-01 22:02:46 +0000161 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000162 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000163
164 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000165 assert(FnInfo.isVariadic());
166 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000167 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
168 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
169
Reid Kleckner28328c32019-09-06 22:55:26 +0000170 // Cloning can't work if we don't have a definition. The Microsoft ABI may
171 // require thunks when a definition is not available. Emit an error in these
172 // cases.
173 if (!MD->isDefined()) {
174 CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
175 return Fn;
176 }
177 assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
178
Eli Friedman49a94b12011-05-06 17:27:27 +0000179 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000180 llvm::ValueToValueMapTy VMap;
Wolfgang Pieba347c472017-10-31 22:49:48 +0000181
182 // We are cloning a function while some Metadata nodes are still unresolved.
183 // Ensure that the value mapper does not encounter any of them.
184 resolveTopLevelMetadata(BaseFn, VMap);
Peter Collingbourne7d6e81d2016-05-10 20:23:29 +0000185 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
Eli Friedman49a94b12011-05-06 17:27:27 +0000186 Fn->replaceAllUsesWith(NewFn);
187 NewFn->takeName(Fn);
188 Fn->eraseFromParent();
189 Fn = NewFn;
190
191 // "Initialize" CGF (minimally).
192 CurFn = Fn;
193
194 // Get the "this" value
195 llvm::Function::arg_iterator AI = Fn->arg_begin();
196 if (CGM.ReturnTypeUsesSRet(FnInfo))
197 ++AI;
198
199 // Find the first store of "this", which will be to the alloca associated
200 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000201 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000202 llvm::BasicBlock *EntryBB = &Fn->front();
203 llvm::BasicBlock::iterator ThisStore =
David Blaikiea629c0f2014-12-29 22:39:45 +0000204 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000205 return isa<llvm::StoreInst>(I) &&
206 I.getOperand(0) == ThisPtr.getPointer();
207 });
208 assert(ThisStore != EntryBB->end() &&
209 "Store of this should be in entry block?");
Eli Friedman49a94b12011-05-06 17:27:27 +0000210 // Adjust "this", if necessary.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000211 Builder.SetInsertPoint(&*ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000212 llvm::Value *AdjustedThisPtr =
213 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Reid Kleckner28328c32019-09-06 22:55:26 +0000214 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
215 ThisStore->getOperand(0)->getType());
Eli Friedman49a94b12011-05-06 17:27:27 +0000216 ThisStore->setOperand(0, AdjustedThisPtr);
217
218 if (!Thunk.Return.isEmpty()) {
219 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000220 for (llvm::BasicBlock &BB : *Fn) {
221 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000222 if (isa<llvm::ReturnInst>(T)) {
223 RValue RV = RValue::get(T->getOperand(0));
224 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000225 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000226 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
227 Builder.CreateRet(RV.getScalarVal());
228 break;
229 }
230 }
231 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000232
233 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000234}
235
Hans Wennborg88497d62013-11-15 17:24:45 +0000236void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000237 const CGFunctionInfo &FnInfo,
238 bool IsUnprototyped) {
Hans Wennborg88497d62013-11-15 17:24:45 +0000239 assert(!CurGD.getDecl() && "CurGD was already set!");
240 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000241 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000242
243 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000244 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Brian Gesiak5488ab42019-01-11 01:54:53 +0000245 QualType ThisType = MD->getThisType();
Reid Kleckner54a33d72018-04-18 23:21:32 +0000246 QualType ResultType;
247 if (IsUnprototyped)
248 ResultType = CGM.getContext().VoidTy;
249 else if (CGM.getCXXABI().HasThisReturn(GD))
250 ResultType = ThisType;
251 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
252 ResultType = CGM.getContext().VoidPtrTy;
253 else
Simon Pilgrim5e0a0b72019-10-01 22:02:46 +0000254 ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000255 FunctionArgList FunctionArgs;
256
Anders Carlssonbad991d2010-03-24 00:39:18 +0000257 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000258 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000259
Reid Kleckner399d96e2018-04-02 20:20:33 +0000260 // Add the rest of the parameters, if we have a prototype to work with.
261 if (!IsUnprototyped) {
262 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000263
Reid Kleckner399d96e2018-04-02 20:20:33 +0000264 if (isa<CXXDestructorDecl>(MD))
265 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
266 FunctionArgs);
267 }
Reid Kleckner89077a12013-12-17 19:46:40 +0000268
Hans Wennborg88497d62013-11-15 17:24:45 +0000269 // Start defining the function.
Adrian Prantldb763572016-11-09 21:43:51 +0000270 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCalla738c252011-03-09 04:27:21 +0000271 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
Adrian Prantldb763572016-11-09 21:43:51 +0000272 MD->getLocation());
273 // Create a scope with an artificial location for the body of this function.
274 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000275
Hans Wennborg88497d62013-11-15 17:24:45 +0000276 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000277 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000278 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000279 CurCodeDecl = MD;
280 CurFuncDecl = MD;
281}
282
283void CodeGenFunction::FinishThunk() {
284 // Clear these to restore the invariants expected by
285 // StartFunction/FinishFunction.
286 CurCodeDecl = nullptr;
287 CurFuncDecl = nullptr;
288
289 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000290}
John McCall5d865c322010-08-31 07:33:07 +0000291
James Y Knight76f78742019-02-05 19:17:50 +0000292void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000293 const ThunkInfo *Thunk,
294 bool IsUnprototyped) {
Hans Wennborg88497d62013-11-15 17:24:45 +0000295 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
296 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000297 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000298
Hans Wennborg88497d62013-11-15 17:24:45 +0000299 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000300 llvm::Value *AdjustedThisPtr =
301 Thunk ? CGM.getCXXABI().performThisAdjustment(
302 *this, LoadCXXThisAddress(), Thunk->This)
303 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000304
Reid Kleckner28328c32019-09-06 22:55:26 +0000305 // If perfect forwarding is required a variadic method, a method using
306 // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
307 // thunk requires a return adjustment, since that is impossible with musttail.
308 if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
Reid Klecknerab2090d2014-07-26 01:34:32 +0000309 if (Thunk && !Thunk->Return.isEmpty()) {
Reid Kleckner399d96e2018-04-02 20:20:33 +0000310 if (IsUnprototyped)
311 CGM.ErrorUnsupported(
312 MD, "return-adjusting thunk with incomplete parameter type");
Reid Kleckner28328c32019-09-06 22:55:26 +0000313 else if (CurFnInfo->isVariadic())
314 llvm_unreachable("shouldn't try to emit musttail return-adjusting "
315 "thunks for variadic functions");
Reid Kleckner399d96e2018-04-02 20:20:33 +0000316 else
317 CGM.ErrorUnsupported(
318 MD, "non-trivial argument copy for return-adjusting thunk");
Reid Klecknerab2090d2014-07-26 01:34:32 +0000319 }
James Y Knight76f78742019-02-05 19:17:50 +0000320 EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000321 return;
322 }
323
Hans Wennborg88497d62013-11-15 17:24:45 +0000324 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000325 CallArgList CallArgs;
Brian Gesiak5488ab42019-01-11 01:54:53 +0000326 QualType ThisType = MD->getThisType();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000327 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000328
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000329 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000330 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000331
Benjamin Kramerd12317e2017-02-23 22:47:56 +0000332#ifndef NDEBUG
George Burgess IVd0a9e802017-02-23 22:07:35 +0000333 unsigned PrefixArgs = CallArgs.size() - 1;
Benjamin Kramerd12317e2017-02-23 22:47:56 +0000334#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000335 // Add the rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +0000336 for (const ParmVarDecl *PD : MD->parameters())
Adrian Prantldb763572016-11-09 21:43:51 +0000337 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000338
Simon Pilgrimfd8ded92020-01-10 17:40:34 +0000339 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000340
John McCalla738c252011-03-09 04:27:21 +0000341#ifndef NDEBUG
George Burgess IV419996c2016-06-16 23:06:04 +0000342 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
James Y Knight916db652019-02-02 01:48:23 +0000343 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
Hans Wennborg88497d62013-11-15 17:24:45 +0000344 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
345 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
346 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000347 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
348 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000349 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
350 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
351 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000352 assert(similar(CallFnInfo.arg_begin()[i].info,
353 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000354 CurFnInfo->arg_begin()[i].info,
355 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000356#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000357
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000358 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000359 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
360 ? ThisType
361 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
362 ? CGM.getContext().VoidPtrTy
363 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000364 ReturnValueSlot Slot;
365 if (!ResultType->isVoidType() &&
Hans Wennborg86aba5e2018-12-07 08:17:26 +0000366 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect)
Akira Hatanakad35a4542019-11-20 18:13:44 -0800367 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified(),
368 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000369
Anders Carlssonbad991d2010-03-24 00:39:18 +0000370 // Now emit our call.
James Y Knight3933add2019-01-30 02:54:28 +0000371 llvm::CallBase *CallOrInvoke;
James Y Knight76f78742019-02-05 19:17:50 +0000372 RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
373 CallArgs, &CallOrInvoke);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000374
Hans Wennborg88497d62013-11-15 17:24:45 +0000375 // Consider return adjustment if we have ThunkInfo.
376 if (Thunk && !Thunk->Return.isEmpty())
377 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000378 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
379 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000380
Hans Wennborg88497d62013-11-15 17:24:45 +0000381 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000382 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000383 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000384
John McCallff755cd2012-07-31 00:33:55 +0000385 // Disable the final ARC autorelease.
386 AutoreleaseResult = false;
387
John McCall7f416cc2015-09-08 08:05:57 +0000388 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000389}
390
Erich Keanede6480a32018-11-13 15:48:08 +0000391void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
Reid Klecknerab2090d2014-07-26 01:34:32 +0000392 llvm::Value *AdjustedThisPtr,
James Y Knight76f78742019-02-05 19:17:50 +0000393 llvm::FunctionCallee Callee) {
Reid Klecknerab2090d2014-07-26 01:34:32 +0000394 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
395 // to translate AST arguments into LLVM IR arguments. For thunks, we know
396 // that the caller prototype more or less matches the callee prototype with
397 // the exception of 'this'.
398 SmallVector<llvm::Value *, 8> Args;
399 for (llvm::Argument &A : CurFn->args())
400 Args.push_back(&A);
401
402 // Set the adjusted 'this' pointer.
403 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
404 if (ThisAI.isDirect()) {
405 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
406 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
407 llvm::Type *ThisType = Args[ThisArgNo]->getType();
408 if (ThisType != AdjustedThisPtr->getType())
409 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
410 Args[ThisArgNo] = AdjustedThisPtr;
411 } else {
412 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000413 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
414 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000415 if (ThisType != AdjustedThisPtr->getType())
416 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
417 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
418 }
419
420 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
421 // don't actually want to run them.
James Y Knight76f78742019-02-05 19:17:50 +0000422 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000423 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
424
425 // Apply the standard set of call attributes.
426 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +0000427 llvm::AttributeList Attrs;
James Y Knight76f78742019-02-05 19:17:50 +0000428 CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
429 Attrs, CallingConv, /*AttrOnCallSite=*/true);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000430 Call->setAttributes(Attrs);
431 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
432
433 if (Call->getType()->isVoidTy())
434 Builder.CreateRetVoid();
435 else
436 Builder.CreateRet(Call);
437
438 // Finish the function to maintain CodeGenFunction invariants.
439 // FIXME: Don't emit unreachable code.
440 EmitBlock(createBasicBlock());
Reid Klecknerce5173c2020-03-19 11:52:22 -0700441
442 FinishThunk();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000443}
444
Rafael Espindolad6e66942015-07-13 06:07:58 +0000445void CodeGenFunction::generateThunk(llvm::Function *Fn,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000446 const CGFunctionInfo &FnInfo, GlobalDecl GD,
447 const ThunkInfo &Thunk,
448 bool IsUnprototyped) {
449 StartThunk(Fn, GD, FnInfo, IsUnprototyped);
Adrian Prantldb763572016-11-09 21:43:51 +0000450 // Create a scope with an artificial location for the body of this function.
451 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Hans Wennborg88497d62013-11-15 17:24:45 +0000452
Reid Kleckner399d96e2018-04-02 20:20:33 +0000453 // Get our callee. Use a placeholder type if this method is unprototyped so
454 // that CodeGenModule doesn't try to set attributes.
455 llvm::Type *Ty;
456 if (IsUnprototyped)
457 Ty = llvm::StructType::get(getLLVMContext());
458 else
459 Ty = CGM.getTypes().GetFunctionType(FnInfo);
460
John McCallb92ab1a2016-10-26 23:46:34 +0000461 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Hans Wennborg88497d62013-11-15 17:24:45 +0000462
Reid Kleckner399d96e2018-04-02 20:20:33 +0000463 // Fix up the function type for an unprototyped musttail call.
464 if (IsUnprototyped)
465 Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
466
Hans Wennborg88497d62013-11-15 17:24:45 +0000467 // Make the call and return the result.
James Y Knight76f78742019-02-05 19:17:50 +0000468 EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
469 &Thunk, IsUnprototyped);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000470}
471
Reid Kleckner399d96e2018-04-02 20:20:33 +0000472static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
473 bool IsUnprototyped, bool ForVTable) {
474 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
475 // provide thunks for us.
476 if (CGM.getTarget().getCXXABI().isMicrosoft())
477 return true;
John McCalla738c252011-03-09 04:27:21 +0000478
Reid Kleckner399d96e2018-04-02 20:20:33 +0000479 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
480 // definitions of the main method. Therefore, emitting thunks with the vtable
481 // is purely an optimization. Emit the thunk if optimizations are enabled and
482 // all of the parameter types are complete.
483 if (ForVTable)
484 return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000485
Reid Kleckner399d96e2018-04-02 20:20:33 +0000486 // Always emit thunks along with the method definition.
487 return true;
488}
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000489
Reid Kleckner399d96e2018-04-02 20:20:33 +0000490llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
491 const ThunkInfo &TI,
492 bool ForVTable) {
493 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000494
Reid Kleckner399d96e2018-04-02 20:20:33 +0000495 // First, get a declaration. Compute the mangled name. Don't worry about
496 // getting the function prototype right, since we may only need this
497 // declaration to fill in a vtable slot.
498 SmallString<256> Name;
499 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
500 llvm::raw_svector_ostream Out(Name);
501 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
502 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
503 else
504 MCtx.mangleThunk(MD, TI, Out);
505 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
506 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
507
508 // If we don't need to emit a definition, return this declaration as is.
509 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
510 MD->getType()->castAs<FunctionType>());
511 if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
512 return Thunk;
513
514 // Arrange a function prototype appropriate for a function definition. In some
515 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
516 const CGFunctionInfo &FnInfo =
517 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
518 : CGM.getTypes().arrangeGlobalDeclaration(GD);
519 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
520
521 // If the type of the underlying GlobalValue is wrong, we'll have to replace
522 // it. It should be a declaration.
523 llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
524 if (ThunkFn->getFunctionType() != ThunkFnTy) {
525 llvm::GlobalValue *OldThunkFn = ThunkFn;
526
527 assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
Anders Carlsson55e89f82010-03-23 18:18:41 +0000528
529 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000530 OldThunkFn->setName(StringRef());
Reid Kleckner399d96e2018-04-02 20:20:33 +0000531 ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
532 Name.str(), &CGM.getModule());
533 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000534
Anders Carlsson55e89f82010-03-23 18:18:41 +0000535 // If needed, replace the old thunk with a bitcast.
536 if (!OldThunkFn->use_empty()) {
537 llvm::Constant *NewPtrForOldDecl =
Reid Kleckner399d96e2018-04-02 20:20:33 +0000538 llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000539 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
540 }
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000541
Anders Carlsson55e89f82010-03-23 18:18:41 +0000542 // Remove the old thunk.
543 OldThunkFn->eraseFromParent();
544 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000545
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000546 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
547 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000548
549 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000550 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000551 // There is already a thunk emitted for this function, do nothing.
Reid Kleckner399d96e2018-04-02 20:20:33 +0000552 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000553 }
554
Reid Kleckner399d96e2018-04-02 20:20:33 +0000555 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
556 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000557 }
558
Reid Kleckner399d96e2018-04-02 20:20:33 +0000559 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
560 // that the return type is meaningless. These thunks can be used to call
561 // functions with differing return types, and the caller is required to cast
562 // the prototype appropriately to extract the correct value.
563 if (IsUnprototyped)
564 ThunkFn->addFnAttr("thunk");
565
Rafael Espindola86792432012-09-21 20:39:32 +0000566 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
567
Reid Kleckner28328c32019-09-06 22:55:26 +0000568 // Thunks for variadic methods are special because in general variadic
Reid Klecknerce5173c2020-03-19 11:52:22 -0700569 // arguments cannot be perfectly forwarded. In the general case, clang
Reid Kleckner28328c32019-09-06 22:55:26 +0000570 // implements such thunks by cloning the original function body. However, for
571 // thunks with no return adjustment on targets that support musttail, we can
572 // use musttail to perfectly forward the variadic arguments.
573 bool ShouldCloneVarArgs = false;
Reid Kleckner399d96e2018-04-02 20:20:33 +0000574 if (!IsUnprototyped && ThunkFn->isVarArg()) {
Reid Kleckner28328c32019-09-06 22:55:26 +0000575 ShouldCloneVarArgs = true;
576 if (TI.Return.isEmpty()) {
577 switch (CGM.getTriple().getArch()) {
578 case llvm::Triple::x86_64:
579 case llvm::Triple::x86:
580 case llvm::Triple::aarch64:
581 ShouldCloneVarArgs = false;
582 break;
583 default:
584 break;
585 }
586 }
587 }
588
589 if (ShouldCloneVarArgs) {
Peter Collingbourne45a24012015-06-30 19:07:26 +0000590 if (UseAvailableExternallyLinkage)
Reid Kleckner399d96e2018-04-02 20:20:33 +0000591 return ThunkFn;
Reid Kleckner28328c32019-09-06 22:55:26 +0000592 ThunkFn =
593 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
Eli Friedman49a94b12011-05-06 17:27:27 +0000594 } else {
595 // Normal thunk body generation.
Reid Kleckner399d96e2018-04-02 20:20:33 +0000596 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
Eli Friedman49a94b12011-05-06 17:27:27 +0000597 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000598
Reid Kleckner399d96e2018-04-02 20:20:33 +0000599 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
600 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000601}
602
Reid Kleckner399d96e2018-04-02 20:20:33 +0000603void CodeGenVTables::EmitThunks(GlobalDecl GD) {
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000604 const CXXMethodDecl *MD =
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000605 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
606
607 // We don't need to generate thunks for the base destructor.
608 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
609 return;
610
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000611 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
612 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000613
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000614 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000615 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000616
Yaron Kerenede60302015-08-01 19:11:36 +0000617 for (const ThunkInfo& Thunk : *ThunkInfoVector)
Reid Kleckner399d96e2018-04-02 20:20:33 +0000618 maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000619}
620
Leonard Chan71568a92020-06-11 11:17:08 -0700621void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
622 llvm::Constant *component,
623 unsigned vtableAddressPoint,
624 bool vtableHasLocalLinkage,
625 bool isCompleteDtor) const {
626 // No need to get the offset of a nullptr.
627 if (component->isNullValue())
628 return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0));
Anders Carlssona4147142010-03-25 15:26:28 +0000629
Leonard Chan71568a92020-06-11 11:17:08 -0700630 auto *globalVal =
631 cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases());
632 llvm::Module &module = CGM.getModule();
633
634 // We don't want to copy the linkage of the vtable exactly because we still
635 // want the stub/proxy to be emitted for properly calculating the offset.
636 // Examples where there would be no symbol emitted are available_externally
637 // and private linkages.
638 auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
639 : llvm::GlobalValue::ExternalLinkage;
640
641 llvm::Constant *target;
642 if (auto *func = dyn_cast<llvm::Function>(globalVal)) {
643 target = getOrCreateRelativeStub(func, stubLinkage, isCompleteDtor);
644 } else {
645 llvm::SmallString<16> rttiProxyName(globalVal->getName());
646 rttiProxyName.append(".rtti_proxy");
647
648 // The RTTI component may not always be emitted in the same linkage unit as
649 // the vtable. As a general case, we can make a dso_local proxy to the RTTI
650 // that points to the actual RTTI struct somewhere. This will result in a
651 // GOTPCREL relocation when taking the relative offset to the proxy.
652 llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName);
653 if (!proxy) {
654 proxy = new llvm::GlobalVariable(module, globalVal->getType(),
655 /*isConstant=*/true, stubLinkage,
656 globalVal, rttiProxyName);
657 proxy->setDSOLocal(true);
658 proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
659 if (!proxy->hasLocalLinkage()) {
660 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
661 proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
662 }
663 }
664 target = proxy;
665 }
666
667 builder.addRelativeOffsetToPosition(CGM.Int32Ty, target,
668 /*position=*/vtableAddressPoint);
669}
670
671llvm::Function *CodeGenVTables::getOrCreateRelativeStub(
672 llvm::Function *func, llvm::GlobalValue::LinkageTypes stubLinkage,
673 bool isCompleteDtor) const {
674 // A complete object destructor can later be substituted in the vtable for an
675 // appropriate base object destructor when optimizations are enabled. This can
676 // happen for child classes that don't have their own destructor. In the case
677 // where a parent virtual destructor is not guaranteed to be in the same
678 // linkage unit as the child vtable, it's possible for an external reference
679 // for this destructor to be substituted into the child vtable, preventing it
680 // from being in rodata. If this function is a complete virtual destructor, we
681 // can just force a stub to be emitted for it.
682 if (func->isDSOLocal() && !isCompleteDtor)
683 return func;
684
685 llvm::SmallString<16> stubName(func->getName());
686 stubName.append(".stub");
687
688 // Instead of taking the offset between the vtable and virtual function
689 // directly, we emit a dso_local stub that just contains a tail call to the
690 // original virtual function and take the offset between that and the
691 // vtable. We do this because there are some cases where the original
692 // function that would've been inserted into the vtable is not dso_local
693 // which may require some kind of dynamic relocation which prevents the
694 // vtable from being readonly. On x86_64, taking the offset between the
695 // function and the vtable gets lowered to the offset between the PLT entry
696 // for the function and the vtable which gives us a PLT32 reloc. On AArch64,
697 // right now only CALL26 and JUMP26 instructions generate PLT relocations,
698 // so we manifest them with stubs that are just jumps to the original
699 // function.
700 auto &module = CGM.getModule();
701 llvm::Function *stub = module.getFunction(stubName);
702 if (stub) {
703 assert(stub->isDSOLocal() &&
704 "The previous definition of this stub should've been dso_local.");
705 return stub;
706 }
707
708 stub = llvm::Function::Create(func->getFunctionType(), stubLinkage, stubName,
709 module);
710
711 // Propogate function attributes.
712 stub->setAttributes(func->getAttributes());
713
714 stub->setDSOLocal(true);
715 stub->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
716 if (!stub->hasLocalLinkage()) {
717 stub->setVisibility(llvm::GlobalValue::HiddenVisibility);
718 stub->setComdat(module.getOrInsertComdat(stubName));
719 }
720
721 // Fill the stub with a tail call that will be optimized.
722 llvm::BasicBlock *block =
723 llvm::BasicBlock::Create(module.getContext(), "entry", stub);
724 llvm::IRBuilder<> block_builder(block);
725 llvm::SmallVector<llvm::Value *, 8> args;
726 for (auto &arg : stub->args())
727 args.push_back(&arg);
728 llvm::CallInst *call = block_builder.CreateCall(func, args);
729 call->setAttributes(func->getAttributes());
730 call->setTailCall();
731 if (call->getType()->isVoidTy())
732 block_builder.CreateRetVoid();
733 else
734 block_builder.CreateRet(call);
735
736 return stub;
737}
738
739bool CodeGenVTables::useRelativeLayout() const {
740 return CGM.getTarget().getCXXABI().isItaniumFamily() &&
741 CGM.getItaniumVTableContext().isRelativeLayout();
742}
743
744llvm::Type *CodeGenVTables::getVTableComponentType() const {
745 if (useRelativeLayout())
746 return CGM.Int32Ty;
747 return CGM.Int8PtrTy;
748}
749
750static void AddPointerLayoutOffset(const CodeGenModule &CGM,
751 ConstantArrayBuilder &builder,
752 CharUnits offset) {
753 builder.add(llvm::ConstantExpr::getIntToPtr(
754 llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
755 CGM.Int8PtrTy));
756}
757
758static void AddRelativeLayoutOffset(const CodeGenModule &CGM,
759 ConstantArrayBuilder &builder,
760 CharUnits offset) {
761 builder.add(llvm::ConstantInt::get(CGM.Int32Ty, offset.getQuantity()));
762}
763
764void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
765 const VTableLayout &layout,
766 unsigned componentIndex,
767 llvm::Constant *rtti,
768 unsigned &nextVTableThunkIndex,
769 unsigned vtableAddressPoint,
770 bool vtableHasLocalLinkage) {
771 auto &component = layout.vtable_components()[componentIndex];
772
773 auto addOffsetConstant =
774 useRelativeLayout() ? AddRelativeLayoutOffset : AddPointerLayoutOffset;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000775
John McCall9c6cb762016-11-28 22:18:33 +0000776 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000777 case VTableComponent::CK_VCallOffset:
Leonard Chan71568a92020-06-11 11:17:08 -0700778 return addOffsetConstant(CGM, builder, component.getVCallOffset());
Craig Topper8a13c412014-05-21 05:09:00 +0000779
Peter Collingbournee53683f2016-09-08 01:14:39 +0000780 case VTableComponent::CK_VBaseOffset:
Leonard Chan71568a92020-06-11 11:17:08 -0700781 return addOffsetConstant(CGM, builder, component.getVBaseOffset());
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000782
Peter Collingbournee53683f2016-09-08 01:14:39 +0000783 case VTableComponent::CK_OffsetToTop:
Leonard Chan71568a92020-06-11 11:17:08 -0700784 return addOffsetConstant(CGM, builder, component.getOffsetToTop());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000785
Peter Collingbournee53683f2016-09-08 01:14:39 +0000786 case VTableComponent::CK_RTTI:
Leonard Chan71568a92020-06-11 11:17:08 -0700787 if (useRelativeLayout())
788 return addRelativeComponent(builder, rtti, vtableAddressPoint,
789 vtableHasLocalLinkage,
790 /*isCompleteDtor=*/false);
791 else
792 return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
Anders Carlssona5736bd2010-03-25 16:49:53 +0000793
Peter Collingbournee53683f2016-09-08 01:14:39 +0000794 case VTableComponent::CK_FunctionPointer:
795 case VTableComponent::CK_CompleteDtorPointer:
796 case VTableComponent::CK_DeletingDtorPointer: {
797 GlobalDecl GD;
798
799 // Get the right global decl.
John McCall9c6cb762016-11-28 22:18:33 +0000800 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000801 default:
802 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000803 case VTableComponent::CK_FunctionPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000804 GD = component.getFunctionDecl();
Peter Collingbournee53683f2016-09-08 01:14:39 +0000805 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000806 case VTableComponent::CK_CompleteDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000807 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000808 break;
809 case VTableComponent::CK_DeletingDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000810 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000811 break;
812 }
813
Peter Collingbournee53683f2016-09-08 01:14:39 +0000814 if (CGM.getLangOpts().CUDA) {
815 // Emit NULL for methods we can't codegen on this
816 // side. Otherwise we'd end up with vtable with unresolved
817 // references.
818 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
819 // OK on device side: functions w/ __device__ attribute
820 // OK on host side: anything except __device__-only functions.
821 bool CanEmitMethod =
822 CGM.getLangOpts().CUDAIsDevice
823 ? MD->hasAttr<CUDADeviceAttr>()
824 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
825 if (!CanEmitMethod)
Leonard Chan71568a92020-06-11 11:17:08 -0700826 return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy));
Peter Collingbournee53683f2016-09-08 01:14:39 +0000827 // Method is acceptable, continue processing as usual.
828 }
829
Alexey Bataeva48600c2020-01-14 16:42:23 -0500830 auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
Leonard Chan71568a92020-06-11 11:17:08 -0700831 // FIXME(PR43094): When merging comdat groups, lld can select a local
832 // symbol as the signature symbol even though it cannot be accessed
833 // outside that symbol's TU. The relative vtables ABI would make
834 // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and
835 // depending on link order, the comdat groups could resolve to the one
836 // with the local symbol. As a temporary solution, fill these components
837 // with zero. We shouldn't be calling these in the first place anyway.
838 if (useRelativeLayout())
839 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
840
Alexey Bataeva48600c2020-01-14 16:42:23 -0500841 // For NVPTX devices in OpenMP emit special functon as null pointers,
842 // otherwise linking ends up with unresolved references.
843 if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsDevice &&
844 CGM.getTriple().isNVPTX())
845 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
John McCall9c6cb762016-11-28 22:18:33 +0000846 llvm::FunctionType *fnTy =
847 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
James Y Knight9871db02019-02-05 16:42:33 +0000848 llvm::Constant *fn = cast<llvm::Constant>(
849 CGM.CreateRuntimeFunction(fnTy, name).getCallee());
John McCall9c6cb762016-11-28 22:18:33 +0000850 if (auto f = dyn_cast<llvm::Function>(fn))
851 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
852 return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000853 };
Peter Collingbournee53683f2016-09-08 01:14:39 +0000854
John McCall9c6cb762016-11-28 22:18:33 +0000855 llvm::Constant *fnPtr;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000856
John McCall9c6cb762016-11-28 22:18:33 +0000857 // Pure virtual member functions.
858 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
859 if (!PureVirtualFn)
860 PureVirtualFn =
Leonard Chan71568a92020-06-11 11:17:08 -0700861 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
John McCall9c6cb762016-11-28 22:18:33 +0000862 fnPtr = PureVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000863
John McCall9c6cb762016-11-28 22:18:33 +0000864 // Deleted virtual member functions.
865 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
866 if (!DeletedVirtualFn)
867 DeletedVirtualFn =
Leonard Chan71568a92020-06-11 11:17:08 -0700868 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
John McCall9c6cb762016-11-28 22:18:33 +0000869 fnPtr = DeletedVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000870
John McCall9c6cb762016-11-28 22:18:33 +0000871 // Thunks.
872 } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
Leonard Chan71568a92020-06-11 11:17:08 -0700873 layout.vtable_thunks()[nextVTableThunkIndex].first ==
874 componentIndex) {
John McCall9c6cb762016-11-28 22:18:33 +0000875 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
876
John McCall9c6cb762016-11-28 22:18:33 +0000877 nextVTableThunkIndex++;
Reid Kleckner399d96e2018-04-02 20:20:33 +0000878 fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
John McCall9c6cb762016-11-28 22:18:33 +0000879
880 // Otherwise we can use the method definition directly.
881 } else {
882 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
883 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000884 }
885
Leonard Chan71568a92020-06-11 11:17:08 -0700886 if (useRelativeLayout()) {
887 return addRelativeComponent(
888 builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
889 component.getKind() == VTableComponent::CK_CompleteDtorPointer);
890 } else
891 return builder.add(llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy));
Anders Carlssona4147142010-03-25 15:26:28 +0000892 }
Peter Collingbournee53683f2016-09-08 01:14:39 +0000893
894 case VTableComponent::CK_UnusedFunctionPointer:
Leonard Chan71568a92020-06-11 11:17:08 -0700895 if (useRelativeLayout())
896 return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
897 else
898 return builder.addNullPointer(CGM.Int8PtrTy);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000899 }
Simon Pilgrim4acc49e2016-09-08 11:03:41 +0000900
901 llvm_unreachable("Unexpected vtable component kind");
Peter Collingbournee53683f2016-09-08 01:14:39 +0000902}
903
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000904llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
905 SmallVector<llvm::Type *, 4> tys;
Leonard Chan71568a92020-06-11 11:17:08 -0700906 llvm::Type *componentType = getVTableComponentType();
907 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i)
908 tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i)));
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000909
910 return llvm::StructType::get(CGM.getLLVMContext(), tys);
911}
912
913void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
John McCall9c6cb762016-11-28 22:18:33 +0000914 const VTableLayout &layout,
Leonard Chan71568a92020-06-11 11:17:08 -0700915 llvm::Constant *rtti,
916 bool vtableHasLocalLinkage) {
917 llvm::Type *componentType = getVTableComponentType();
918
919 const auto &addressPoints = layout.getAddressPointIndices();
John McCall9c6cb762016-11-28 22:18:33 +0000920 unsigned nextVTableThunkIndex = 0;
Leonard Chan71568a92020-06-11 11:17:08 -0700921 for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
922 vtableIndex != endIndex; ++vtableIndex) {
923 auto vtableElem = builder.beginArray(componentType);
924
925 size_t vtableStart = layout.getVTableOffset(vtableIndex);
926 size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex);
927 for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
928 ++componentIndex) {
929 addVTableComponent(vtableElem, layout, componentIndex, rtti,
930 nextVTableThunkIndex, addressPoints[vtableIndex],
931 vtableHasLocalLinkage);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000932 }
933 vtableElem.finishAndAddTo(builder);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000934 }
Anders Carlssona4147142010-03-25 15:26:28 +0000935}
936
Leonard Chan71568a92020-06-11 11:17:08 -0700937llvm::GlobalVariable *CodeGenVTables::GenerateConstructionVTable(
938 const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
939 llvm::GlobalVariable::LinkageTypes Linkage,
940 VTableAddressPointsMapTy &AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000941 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
942 DI->completeClassData(Base.getBase());
943
Ahmed Charlesb8984322014-03-07 20:03:18 +0000944 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000945 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000946 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000947
Anders Carlssona5736bd2010-03-25 16:49:53 +0000948 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000949 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000950
951 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000952 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000953 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000954 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
955 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
956 Base.getBase(), Out);
Leonard Chan71568a92020-06-11 11:17:08 -0700957 SmallString<256> Name(OutName);
958
959 bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout();
960 bool VTableAliasExists =
961 UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
962 if (VTableAliasExists) {
963 // We previously made the vtable hidden and changed its name.
964 Name.append(".local");
965 }
Anders Carlssona4147142010-03-25 15:26:28 +0000966
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000967 llvm::Type *VTType = getVTableType(*VTLayout);
Anders Carlssona4147142010-03-25 15:26:28 +0000968
Richard Smith65fd2a42013-02-16 00:51:21 +0000969 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
970 // guarantee that they actually will be available externally. Instead, when
971 // emitting an available_externally VTT, we provide references to an internal
972 // linkage construction vtable. The ABI only requires complete-object vtables
973 // to be the same for all instances of a type, not construction vtables.
974 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
975 Linkage = llvm::GlobalVariable::InternalLinkage;
976
David Greenbe0c5b62018-09-12 14:09:06 +0000977 unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
978
Anders Carlssona4147142010-03-25 15:26:28 +0000979 // Create the variable that will hold the construction vtable.
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000980 llvm::GlobalVariable *VTable =
David Greenbe0c5b62018-09-12 14:09:06 +0000981 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
John McCall358d0562011-03-27 09:00:25 +0000982
983 // V-tables are always unnamed_addr.
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000984 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Anders Carlssona4147142010-03-25 15:26:28 +0000985
David Majnemerd905da42014-07-01 20:30:31 +0000986 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
987 CGM.getContext().getTagDeclType(Base.getBase()));
988
Anders Carlssona4147142010-03-25 15:26:28 +0000989 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +0000990 ConstantInitBuilder builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000991 auto components = builder.beginStruct();
Leonard Chan71568a92020-06-11 11:17:08 -0700992 createVTableInitializer(components, *VTLayout, RTTI,
993 VTable->hasLocalLinkage());
John McCall9c6cb762016-11-28 22:18:33 +0000994 components.finishAndSetAsInitializer(VTable);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000995
Petr Hosek7c895212019-02-11 20:13:42 +0000996 // Set properties only after the initializer has been set to ensure that the
997 // GV is treated as definition and not declaration.
998 assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
999 CGM.setGVProperties(VTable, RD);
1000
Oliver Stannard3b598b92019-10-17 09:58:57 +00001001 CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001002
Leonard Chan71568a92020-06-11 11:17:08 -07001003 if (UsingRelativeLayout && !VTable->isDSOLocal())
1004 GenerateRelativeVTableAlias(VTable, OutName);
1005
Anders Carlsson0534b022010-03-25 00:35:49 +00001006 return VTable;
1007}
1008
Leonard Chan71568a92020-06-11 11:17:08 -07001009// If the VTable is not dso_local, then we will not be able to indicate that
1010// the VTable does not need a relocation and move into rodata. A frequent
1011// time this can occur is for classes that should be made public from a DSO
1012// (like in libc++). For cases like these, we can make the vtable hidden or
1013// private and create a public alias with the same visibility and linkage as
1014// the original vtable type.
1015void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
1016 llvm::StringRef AliasNameRef) {
1017 assert(getItaniumVTableContext().isRelativeLayout() &&
1018 "Can only use this if the relative vtable ABI is used");
1019 assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
1020 "not guaranteed to be dso_local");
1021
1022 // If the vtable is available_externally, we shouldn't (or need to) generate
1023 // an alias for it in the first place since the vtable won't actually by
1024 // emitted in this compilation unit.
1025 if (VTable->hasAvailableExternallyLinkage())
1026 return;
1027
1028 // Create a new string in the event the alias is already the name of the
1029 // vtable. Using the reference directly could lead to use of an inititialized
1030 // value in the module's StringMap.
1031 llvm::SmallString<256> AliasName(AliasNameRef);
1032 VTable->setName(AliasName + ".local");
1033
1034 auto Linkage = VTable->getLinkage();
1035 assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
1036 "Invalid vtable alias linkage");
1037
1038 llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
1039 if (!VTableAlias) {
1040 VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
1041 VTable->getAddressSpace(), Linkage,
1042 AliasName, &CGM.getModule());
1043 } else {
1044 assert(VTableAlias->getValueType() == VTable->getValueType());
1045 assert(VTableAlias->getLinkage() == Linkage);
1046 }
1047 VTableAlias->setVisibility(VTable->getVisibility());
1048 VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
1049
1050 // Both of these imply dso_local for the vtable.
1051 if (!VTable->hasComdat()) {
1052 // If this is in a comdat, then we shouldn't make the linkage private due to
1053 // an issue in lld where private symbols can be used as the key symbol when
1054 // choosing the prevelant group. This leads to "relocation refers to a
1055 // symbol in a discarded section".
1056 VTable->setLinkage(llvm::GlobalValue::PrivateLinkage);
1057 } else {
1058 // We should at least make this hidden since we don't want to expose it.
1059 VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1060 }
1061
1062 VTableAlias->setAliasee(VTable);
1063}
1064
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001065static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
1066 const CXXRecordDecl *RD) {
1067 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001068 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001069}
1070
Eric Christopherd160c502016-01-29 01:35:53 +00001071/// Compute the required linkage of the vtable for the given class.
John McCall6bd2a892013-01-25 22:31:03 +00001072///
1073/// Note that we only call this at the end of the translation unit.
Simon Pilgrim48c32b12016-09-08 09:59:58 +00001074llvm::GlobalVariable::LinkageTypes
John McCall6bd2a892013-01-25 22:31:03 +00001075CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00001076 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +00001077 return llvm::GlobalVariable::InternalLinkage;
1078
1079 // We're at the end of the translation unit, so the current key
1080 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +00001081 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
1082 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +00001083 // If this class has a key function, use that to determine the
1084 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +00001085 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +00001086 if (keyFunction->hasBody(def))
1087 keyFunction = cast<CXXMethodDecl>(def);
Simon Pilgrim48c32b12016-09-08 09:59:58 +00001088
John McCall6bd2a892013-01-25 22:31:03 +00001089 switch (keyFunction->getTemplateSpecializationKind()) {
1090 case TSK_Undeclared:
1091 case TSK_ExplicitSpecialization:
David Blaikieb11c8732017-01-30 06:36:08 +00001092 assert((def || CodeGenOpts.OptimizationLevel > 0 ||
1093 CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
1094 "Shouldn't query vtable linkage without key function, "
1095 "optimizations, or debug info");
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001096 if (!def && CodeGenOpts.OptimizationLevel > 0)
1097 return llvm::GlobalVariable::AvailableExternallyLinkage;
1098
John McCall6bd2a892013-01-25 22:31:03 +00001099 if (keyFunction->isInlined())
1100 return !Context.getLangOpts().AppleKext ?
1101 llvm::GlobalVariable::LinkOnceODRLinkage :
1102 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +00001103
John McCall6bd2a892013-01-25 22:31:03 +00001104 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +00001105
John McCall6bd2a892013-01-25 22:31:03 +00001106 case TSK_ImplicitInstantiation:
1107 return !Context.getLangOpts().AppleKext ?
1108 llvm::GlobalVariable::LinkOnceODRLinkage :
1109 llvm::Function::InternalLinkage;
1110
1111 case TSK_ExplicitInstantiationDefinition:
1112 return !Context.getLangOpts().AppleKext ?
1113 llvm::GlobalVariable::WeakODRLinkage :
1114 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +00001115
John McCall6bd2a892013-01-25 22:31:03 +00001116 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +00001117 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +00001118 }
1119 }
1120
1121 // -fapple-kext mode does not support weak linkage, so we must use
1122 // internal linkage.
1123 if (Context.getLangOpts().AppleKext)
1124 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +00001125
1126 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1127 llvm::GlobalValue::LinkOnceODRLinkage;
1128 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1129 llvm::GlobalValue::WeakODRLinkage;
1130 if (RD->hasAttr<DLLExportAttr>()) {
1131 // Cannot discard exported vtables.
1132 DiscardableODRLinkage = NonDiscardableODRLinkage;
1133 } else if (RD->hasAttr<DLLImportAttr>()) {
1134 // Imported vtables are available externally.
1135 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1136 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1137 }
1138
John McCall6bd2a892013-01-25 22:31:03 +00001139 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001140 case TSK_Undeclared:
1141 case TSK_ExplicitSpecialization:
1142 case TSK_ImplicitInstantiation:
1143 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +00001144
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001145 case TSK_ExplicitInstantiationDeclaration:
Reid Klecknerad1e22b2016-06-29 18:29:21 +00001146 // Explicit instantiations in MSVC do not provide vtables, so we must emit
1147 // our own.
1148 if (getTarget().getCXXABI().isMicrosoft())
1149 return DiscardableODRLinkage;
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001150 return shouldEmitAvailableExternallyVTable(*this, RD)
1151 ? llvm::GlobalVariable::AvailableExternallyLinkage
1152 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +00001153
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001154 case TSK_ExplicitInstantiationDefinition:
1155 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +00001156 }
1157
1158 llvm_unreachable("Invalid TemplateSpecializationKind!");
1159}
1160
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001161/// This is a callback from Sema to tell us that a particular vtable is
Nico Weberb6a5d052015-01-15 04:07:35 +00001162/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +00001163///
Nico Weberb6a5d052015-01-15 04:07:35 +00001164/// This is only called for vtables that _must_ be emitted (mainly due to key
1165/// functions). For weak vtables, CodeGen tracks when they are needed and
1166/// emits them as-needed.
1167void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +00001168 VTables.GenerateClassData(theClass);
1169}
1170
Simon Pilgrim48c32b12016-09-08 09:59:58 +00001171void
John McCall6bd2a892013-01-25 22:31:03 +00001172CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +00001173 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
1174 DI->completeClassData(RD);
1175
Reid Kleckner7810af02013-06-19 15:20:38 +00001176 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001177 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +00001178
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001179 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +00001180}
John McCall6bd2a892013-01-25 22:31:03 +00001181
1182/// At this point in the translation unit, does it appear that can we
1183/// rely on the vtable being defined elsewhere in the program?
1184///
1185/// The response is really only definitive when called at the end of
1186/// the translation unit.
1187///
1188/// The only semantic restriction here is that the object file should
Eric Christopherd160c502016-01-29 01:35:53 +00001189/// not contain a vtable definition when that vtable is defined
John McCall6bd2a892013-01-25 22:31:03 +00001190/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
Eric Christopherd160c502016-01-29 01:35:53 +00001191/// vtables when unnecessary.
John McCall6bd2a892013-01-25 22:31:03 +00001192bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +00001193 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +00001194
Reid Klecknerad1e22b2016-06-29 18:29:21 +00001195 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1196 // emit them even if there is an explicit template instantiation.
1197 if (CGM.getTarget().getCXXABI().isMicrosoft())
David Majnemer2d8b2002016-02-11 17:49:28 +00001198 return false;
1199
John McCall6bd2a892013-01-25 22:31:03 +00001200 // If we have an explicit instantiation declaration (and not a
Eric Christopherd160c502016-01-29 01:35:53 +00001201 // definition), the vtable is defined elsewhere.
John McCall6bd2a892013-01-25 22:31:03 +00001202 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1203 if (TSK == TSK_ExplicitInstantiationDeclaration)
1204 return true;
1205
1206 // Otherwise, if the class is an instantiated template, the
Eric Christopherd160c502016-01-29 01:35:53 +00001207 // vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +00001208 if (TSK == TSK_ImplicitInstantiation ||
1209 TSK == TSK_ExplicitInstantiationDefinition)
1210 return false;
1211
1212 // Otherwise, if the class doesn't have a key function (possibly
Eric Christopherd160c502016-01-29 01:35:53 +00001213 // anymore), the vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +00001214 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1215 if (!keyFunction)
1216 return false;
1217
1218 // Otherwise, if we don't have a definition of the key function, the
Eric Christopherd160c502016-01-29 01:35:53 +00001219 // vtable must be defined somewhere else.
John McCall6bd2a892013-01-25 22:31:03 +00001220 return !keyFunction->hasBody();
1221}
1222
1223/// Given that we're currently at the end of the translation unit, and
Eric Christopherd160c502016-01-29 01:35:53 +00001224/// we've emitted a reference to the vtable for this class, should
1225/// we define that vtable?
John McCall6bd2a892013-01-25 22:31:03 +00001226static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
1227 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001228 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001229 if (!CGM.getVTables().isVTableExternal(RD))
1230 return true;
1231
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00001232 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +00001233 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +00001234}
1235
1236/// Given that at some point we emitted a reference to one or more
Eric Christopherd160c502016-01-29 01:35:53 +00001237/// vtables, and that we are now at the end of the translation unit,
John McCall6bd2a892013-01-25 22:31:03 +00001238/// decide whether we should emit them.
1239void CodeGenModule::EmitDeferredVTables() {
1240#ifndef NDEBUG
1241 // Remember the size of DeferredVTables, because we're going to assume
1242 // that this entire operation doesn't modify it.
1243 size_t savedSize = DeferredVTables.size();
1244#endif
1245
Piotr Padlewski44b4ce82015-07-28 16:10:58 +00001246 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +00001247 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
1248 VTables.GenerateClassData(RD);
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001249 else if (shouldOpportunisticallyEmitVTables())
1250 OpportunisticVTables.push_back(RD);
John McCall6bd2a892013-01-25 22:31:03 +00001251
1252 assert(savedSize == DeferredVTables.size() &&
Eric Christopherd160c502016-01-29 01:35:53 +00001253 "deferred extra vtables during vtable emission?");
John McCall6bd2a892013-01-25 22:31:03 +00001254 DeferredVTables.clear();
1255}
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001256
Teresa Johnson2f63d542020-01-24 12:24:18 -08001257bool CodeGenModule::HasLTOVisibilityPublicStd(const CXXRecordDecl *RD) {
1258 if (!getCodeGenOpts().LTOVisibilityPublicStd)
1259 return false;
1260
1261 const DeclContext *DC = RD;
1262 while (1) {
1263 auto *D = cast<Decl>(DC);
1264 DC = DC->getParent();
1265 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1266 if (auto *ND = dyn_cast<NamespaceDecl>(D))
1267 if (const IdentifierInfo *II = ND->getIdentifier())
1268 if (II->isStr("std") || II->isStr("stdext"))
1269 return true;
1270 break;
1271 }
1272 }
1273
1274 return false;
1275}
1276
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001277bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1278 LinkageInfo LV = RD->getLinkageAndVisibility();
1279 if (!isExternallyVisible(LV.getLinkage()))
1280 return true;
Peter Collingbourne6fccf952015-07-15 12:15:56 +00001281
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001282 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
1283 return false;
Peter Collingbournefb532b92016-02-24 20:46:36 +00001284
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001285 if (getTriple().isOSBinFormatCOFF()) {
1286 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1287 return false;
1288 } else {
1289 if (LV.getVisibility() != HiddenVisibility)
1290 return false;
1291 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00001292
Teresa Johnson2f63d542020-01-24 12:24:18 -08001293 return !HasLTOVisibilityPublicStd(RD);
Peter Collingbournee5706442015-07-09 19:56:14 +00001294}
1295
Oliver Stannard3b598b92019-10-17 09:58:57 +00001296llvm::GlobalObject::VCallVisibility
1297CodeGenModule::GetVCallVisibilityLevel(const CXXRecordDecl *RD) {
1298 LinkageInfo LV = RD->getLinkageAndVisibility();
1299 llvm::GlobalObject::VCallVisibility TypeVis;
1300 if (!isExternallyVisible(LV.getLinkage()))
1301 TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1302 else if (HasHiddenLTOVisibility(RD))
1303 TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1304 else
1305 TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1306
1307 for (auto B : RD->bases())
1308 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1309 TypeVis = std::min(TypeVis,
1310 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1311
1312 for (auto B : RD->vbases())
1313 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1314 TypeVis = std::min(TypeVis,
1315 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1316
1317 return TypeVis;
1318}
1319
1320void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1321 llvm::GlobalVariable *VTable,
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001322 const VTableLayout &VTLayout) {
Peter Collingbourne1e1475a2017-01-18 23:55:27 +00001323 if (!getCodeGenOpts().LTOUnit)
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001324 return;
1325
Peter Collingbourne86d34a72015-06-17 19:08:05 +00001326 CharUnits PointerWidth =
1327 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001328
Peter Collingbournee44acad2018-06-26 02:15:47 +00001329 typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1330 std::vector<AddressPoint> AddressPoints;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001331 for (auto &&AP : VTLayout.getAddressPoints())
Peter Collingbournee44acad2018-06-26 02:15:47 +00001332 AddressPoints.push_back(std::make_pair(
Peter Collingbourneac94ca52018-05-30 22:29:08 +00001333 AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1334 AP.second.AddressPointIndex));
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001335
Peter Collingbournee44acad2018-06-26 02:15:47 +00001336 // Sort the address points for determinism.
Fangrui Song55fab262018-09-26 22:16:28 +00001337 llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1338 const AddressPoint &AP2) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00001339 if (&AP1 == &AP2)
Peter Collingbourne47941902015-02-24 01:12:53 +00001340 return false;
1341
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001342 std::string S1;
1343 llvm::raw_string_ostream O1(S1);
1344 getCXXABI().getMangleContext().mangleTypeName(
Peter Collingbournee44acad2018-06-26 02:15:47 +00001345 QualType(AP1.first->getTypeForDecl(), 0), O1);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001346 O1.flush();
1347
1348 std::string S2;
1349 llvm::raw_string_ostream O2(S2);
1350 getCXXABI().getMangleContext().mangleTypeName(
Peter Collingbournee44acad2018-06-26 02:15:47 +00001351 QualType(AP2.first->getTypeForDecl(), 0), O2);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001352 O2.flush();
1353
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001354 if (S1 < S2)
1355 return true;
1356 if (S1 != S2)
1357 return false;
1358
Peter Collingbournee44acad2018-06-26 02:15:47 +00001359 return AP1.second < AP2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001360 });
1361
Peter Collingbournee44acad2018-06-26 02:15:47 +00001362 ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1363 for (auto AP : AddressPoints) {
1364 // Create type metadata for the address point.
1365 AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1366
1367 // The class associated with each address point could also potentially be
1368 // used for indirect calls via a member function pointer, so we need to
1369 // annotate the address of each function pointer with the appropriate member
1370 // function pointer type.
1371 for (unsigned I = 0; I != Comps.size(); ++I) {
1372 if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1373 continue;
1374 llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1375 Context.getMemberPointerType(
1376 Comps[I].getFunctionDecl()->getType(),
1377 Context.getRecordType(AP.first).getTypePtr()));
1378 VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1379 }
1380 }
Oliver Stannard3b598b92019-10-17 09:58:57 +00001381
Teresa Johnson458676d2019-12-26 08:32:42 -08001382 if (getCodeGenOpts().VirtualFunctionElimination ||
1383 getCodeGenOpts().WholeProgramVTables) {
Oliver Stannard3b598b92019-10-17 09:58:57 +00001384 llvm::GlobalObject::VCallVisibility TypeVis = GetVCallVisibilityLevel(RD);
1385 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
Teresa Johnson458676d2019-12-26 08:32:42 -08001386 VTable->setVCallVisibilityMetadata(TypeVis);
Oliver Stannard3b598b92019-10-17 09:58:57 +00001387 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001388}