blob: 7ac15ba6153d5fed6c5d6e94884007b7cf4d6012 [file] [log] [blame]
Anders Carlsson11e51402010-04-17 20:15:18 +00001//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
Anders Carlsson2bb27f52009-10-11 22:13:54 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Anders Carlssonf942ee02009-11-27 20:47:55 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000018#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Wolfgang Pieba347c472017-10-31 22:49:48 +000020#include "clang/CodeGen/ConstantInitBuilder.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000021#include "clang/Frontend/CodeGenOptions.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
Wolfgang Pieba347c472017-10-31 22:49:48 +0000113/// This function clones a function's DISubprogram node and enters it into
114/// 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) {
131 if (auto *DII = dyn_cast<llvm::DbgInfoIntrinsic>(&I)) {
132 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());
161 const FunctionProtoType *FPT = MD->getType()->getAs<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
170 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000171 llvm::ValueToValueMapTy VMap;
Wolfgang Pieba347c472017-10-31 22:49:48 +0000172
173 // We are cloning a function while some Metadata nodes are still unresolved.
174 // Ensure that the value mapper does not encounter any of them.
175 resolveTopLevelMetadata(BaseFn, VMap);
Peter Collingbourne7d6e81d2016-05-10 20:23:29 +0000176 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
Eli Friedman49a94b12011-05-06 17:27:27 +0000177 Fn->replaceAllUsesWith(NewFn);
178 NewFn->takeName(Fn);
179 Fn->eraseFromParent();
180 Fn = NewFn;
181
182 // "Initialize" CGF (minimally).
183 CurFn = Fn;
184
185 // Get the "this" value
186 llvm::Function::arg_iterator AI = Fn->arg_begin();
187 if (CGM.ReturnTypeUsesSRet(FnInfo))
188 ++AI;
189
190 // Find the first store of "this", which will be to the alloca associated
191 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000192 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000193 llvm::BasicBlock *EntryBB = &Fn->front();
194 llvm::BasicBlock::iterator ThisStore =
David Blaikiea629c0f2014-12-29 22:39:45 +0000195 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000196 return isa<llvm::StoreInst>(I) &&
197 I.getOperand(0) == ThisPtr.getPointer();
198 });
199 assert(ThisStore != EntryBB->end() &&
200 "Store of this should be in entry block?");
Eli Friedman49a94b12011-05-06 17:27:27 +0000201 // Adjust "this", if necessary.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000202 Builder.SetInsertPoint(&*ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000203 llvm::Value *AdjustedThisPtr =
204 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000205 ThisStore->setOperand(0, AdjustedThisPtr);
206
207 if (!Thunk.Return.isEmpty()) {
208 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000209 for (llvm::BasicBlock &BB : *Fn) {
210 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000211 if (isa<llvm::ReturnInst>(T)) {
212 RValue RV = RValue::get(T->getOperand(0));
213 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000214 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000215 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
216 Builder.CreateRet(RV.getScalarVal());
217 break;
218 }
219 }
220 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000221
222 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000223}
224
Hans Wennborg88497d62013-11-15 17:24:45 +0000225void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000226 const CGFunctionInfo &FnInfo,
227 bool IsUnprototyped) {
Hans Wennborg88497d62013-11-15 17:24:45 +0000228 assert(!CurGD.getDecl() && "CurGD was already set!");
229 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000230 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000231
232 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000233 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000234 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000235 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Reid Kleckner54a33d72018-04-18 23:21:32 +0000236 QualType ResultType;
237 if (IsUnprototyped)
238 ResultType = CGM.getContext().VoidTy;
239 else if (CGM.getCXXABI().HasThisReturn(GD))
240 ResultType = ThisType;
241 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
242 ResultType = CGM.getContext().VoidPtrTy;
243 else
244 ResultType = FPT->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000245 FunctionArgList FunctionArgs;
246
Anders Carlssonbad991d2010-03-24 00:39:18 +0000247 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000248 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000249
Reid Kleckner399d96e2018-04-02 20:20:33 +0000250 // Add the rest of the parameters, if we have a prototype to work with.
251 if (!IsUnprototyped) {
252 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000253
Reid Kleckner399d96e2018-04-02 20:20:33 +0000254 if (isa<CXXDestructorDecl>(MD))
255 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
256 FunctionArgs);
257 }
Reid Kleckner89077a12013-12-17 19:46:40 +0000258
Hans Wennborg88497d62013-11-15 17:24:45 +0000259 // Start defining the function.
Adrian Prantldb763572016-11-09 21:43:51 +0000260 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCalla738c252011-03-09 04:27:21 +0000261 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
Adrian Prantldb763572016-11-09 21:43:51 +0000262 MD->getLocation());
263 // Create a scope with an artificial location for the body of this function.
264 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000265
Hans Wennborg88497d62013-11-15 17:24:45 +0000266 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000267 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000268 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000269 CurCodeDecl = MD;
270 CurFuncDecl = MD;
271}
272
273void CodeGenFunction::FinishThunk() {
274 // Clear these to restore the invariants expected by
275 // StartFunction/FinishFunction.
276 CurCodeDecl = nullptr;
277 CurFuncDecl = nullptr;
278
279 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000280}
John McCall5d865c322010-08-31 07:33:07 +0000281
John McCallb92ab1a2016-10-26 23:46:34 +0000282void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Constant *CalleePtr,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000283 const ThunkInfo *Thunk,
284 bool IsUnprototyped) {
Hans Wennborg88497d62013-11-15 17:24:45 +0000285 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
286 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000287 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000288
Hans Wennborg88497d62013-11-15 17:24:45 +0000289 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000290 llvm::Value *AdjustedThisPtr =
291 Thunk ? CGM.getCXXABI().performThisAdjustment(
292 *this, LoadCXXThisAddress(), Thunk->This)
293 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000294
Reid Kleckner399d96e2018-04-02 20:20:33 +0000295 if (CurFnInfo->usesInAlloca() || IsUnprototyped) {
Reid Klecknerab2090d2014-07-26 01:34:32 +0000296 // We don't handle return adjusting thunks, because they require us to call
297 // the copy constructor. For now, fall through and pretend the return
298 // adjustment was empty so we don't crash.
299 if (Thunk && !Thunk->Return.isEmpty()) {
Reid Kleckner399d96e2018-04-02 20:20:33 +0000300 if (IsUnprototyped)
301 CGM.ErrorUnsupported(
302 MD, "return-adjusting thunk with incomplete parameter type");
303 else
304 CGM.ErrorUnsupported(
305 MD, "non-trivial argument copy for return-adjusting thunk");
Reid Klecknerab2090d2014-07-26 01:34:32 +0000306 }
John McCallb92ab1a2016-10-26 23:46:34 +0000307 EmitMustTailThunk(MD, AdjustedThisPtr, CalleePtr);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000308 return;
309 }
310
Hans Wennborg88497d62013-11-15 17:24:45 +0000311 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000312 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000313 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000314 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000315
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000316 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000317 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000318
Benjamin Kramerd12317e2017-02-23 22:47:56 +0000319#ifndef NDEBUG
George Burgess IVd0a9e802017-02-23 22:07:35 +0000320 unsigned PrefixArgs = CallArgs.size() - 1;
Benjamin Kramerd12317e2017-02-23 22:47:56 +0000321#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000322 // Add the rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +0000323 for (const ParmVarDecl *PD : MD->parameters())
Adrian Prantldb763572016-11-09 21:43:51 +0000324 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000325
Hans Wennborg88497d62013-11-15 17:24:45 +0000326 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000327
John McCalla738c252011-03-09 04:27:21 +0000328#ifndef NDEBUG
George Burgess IV419996c2016-06-16 23:06:04 +0000329 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +0000330 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD), PrefixArgs);
Hans Wennborg88497d62013-11-15 17:24:45 +0000331 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
332 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
333 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000334 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
335 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000336 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
337 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
338 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000339 assert(similar(CallFnInfo.arg_begin()[i].info,
340 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000341 CurFnInfo->arg_begin()[i].info,
342 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000343#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000344
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000345 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000346 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
347 ? ThisType
348 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
349 ? CGM.getContext().VoidPtrTy
350 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000351 ReturnValueSlot Slot;
352 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000353 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000354 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000355 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000356
Anders Carlssonbad991d2010-03-24 00:39:18 +0000357 // Now emit our call.
Reid Klecknerab2090d2014-07-26 01:34:32 +0000358 llvm::Instruction *CallOrInvoke;
John McCallb92ab1a2016-10-26 23:46:34 +0000359 CGCallee Callee = CGCallee::forDirect(CalleePtr, MD);
360 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, &CallOrInvoke);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000361
Hans Wennborg88497d62013-11-15 17:24:45 +0000362 // Consider return adjustment if we have ThunkInfo.
363 if (Thunk && !Thunk->Return.isEmpty())
364 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000365 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
366 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000367
Hans Wennborg88497d62013-11-15 17:24:45 +0000368 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000369 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000370 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000371
John McCallff755cd2012-07-31 00:33:55 +0000372 // Disable the final ARC autorelease.
373 AutoreleaseResult = false;
374
John McCall7f416cc2015-09-08 08:05:57 +0000375 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000376}
377
Reid Klecknerab2090d2014-07-26 01:34:32 +0000378void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
379 llvm::Value *AdjustedThisPtr,
John McCallb92ab1a2016-10-26 23:46:34 +0000380 llvm::Value *CalleePtr) {
Reid Klecknerab2090d2014-07-26 01:34:32 +0000381 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
382 // to translate AST arguments into LLVM IR arguments. For thunks, we know
383 // that the caller prototype more or less matches the callee prototype with
384 // the exception of 'this'.
385 SmallVector<llvm::Value *, 8> Args;
386 for (llvm::Argument &A : CurFn->args())
387 Args.push_back(&A);
388
389 // Set the adjusted 'this' pointer.
390 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
391 if (ThisAI.isDirect()) {
392 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
393 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
394 llvm::Type *ThisType = Args[ThisArgNo]->getType();
395 if (ThisType != AdjustedThisPtr->getType())
396 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
397 Args[ThisArgNo] = AdjustedThisPtr;
398 } else {
399 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000400 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
401 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000402 if (ThisType != AdjustedThisPtr->getType())
403 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
404 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
405 }
406
407 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
408 // don't actually want to run them.
John McCallb92ab1a2016-10-26 23:46:34 +0000409 llvm::CallInst *Call = Builder.CreateCall(CalleePtr, Args);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000410 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
411
412 // Apply the standard set of call attributes.
413 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +0000414 llvm::AttributeList Attrs;
415 CGM.ConstructAttributeList(CalleePtr->getName(), *CurFnInfo, MD, Attrs,
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000416 CallingConv, /*AttrOnCallSite=*/true);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000417 Call->setAttributes(Attrs);
418 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
419
420 if (Call->getType()->isVoidTy())
421 Builder.CreateRetVoid();
422 else
423 Builder.CreateRet(Call);
424
425 // Finish the function to maintain CodeGenFunction invariants.
426 // FIXME: Don't emit unreachable code.
427 EmitBlock(createBasicBlock());
428 FinishFunction();
429}
430
Rafael Espindolad6e66942015-07-13 06:07:58 +0000431void CodeGenFunction::generateThunk(llvm::Function *Fn,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000432 const CGFunctionInfo &FnInfo, GlobalDecl GD,
433 const ThunkInfo &Thunk,
434 bool IsUnprototyped) {
435 StartThunk(Fn, GD, FnInfo, IsUnprototyped);
Adrian Prantldb763572016-11-09 21:43:51 +0000436 // Create a scope with an artificial location for the body of this function.
437 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Hans Wennborg88497d62013-11-15 17:24:45 +0000438
Reid Kleckner399d96e2018-04-02 20:20:33 +0000439 // Get our callee. Use a placeholder type if this method is unprototyped so
440 // that CodeGenModule doesn't try to set attributes.
441 llvm::Type *Ty;
442 if (IsUnprototyped)
443 Ty = llvm::StructType::get(getLLVMContext());
444 else
445 Ty = CGM.getTypes().GetFunctionType(FnInfo);
446
John McCallb92ab1a2016-10-26 23:46:34 +0000447 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Hans Wennborg88497d62013-11-15 17:24:45 +0000448
Reid Kleckner399d96e2018-04-02 20:20:33 +0000449 // Fix up the function type for an unprototyped musttail call.
450 if (IsUnprototyped)
451 Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
452
Hans Wennborg88497d62013-11-15 17:24:45 +0000453 // Make the call and return the result.
Reid Kleckner399d96e2018-04-02 20:20:33 +0000454 EmitCallAndReturnForThunk(Callee, &Thunk, IsUnprototyped);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000455}
456
Reid Kleckner399d96e2018-04-02 20:20:33 +0000457static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
458 bool IsUnprototyped, bool ForVTable) {
459 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
460 // provide thunks for us.
461 if (CGM.getTarget().getCXXABI().isMicrosoft())
462 return true;
John McCalla738c252011-03-09 04:27:21 +0000463
Reid Kleckner399d96e2018-04-02 20:20:33 +0000464 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
465 // definitions of the main method. Therefore, emitting thunks with the vtable
466 // is purely an optimization. Emit the thunk if optimizations are enabled and
467 // all of the parameter types are complete.
468 if (ForVTable)
469 return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000470
Reid Kleckner399d96e2018-04-02 20:20:33 +0000471 // Always emit thunks along with the method definition.
472 return true;
473}
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000474
Reid Kleckner399d96e2018-04-02 20:20:33 +0000475llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
476 const ThunkInfo &TI,
477 bool ForVTable) {
478 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000479
Reid Kleckner399d96e2018-04-02 20:20:33 +0000480 // First, get a declaration. Compute the mangled name. Don't worry about
481 // getting the function prototype right, since we may only need this
482 // declaration to fill in a vtable slot.
483 SmallString<256> Name;
484 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
485 llvm::raw_svector_ostream Out(Name);
486 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
487 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
488 else
489 MCtx.mangleThunk(MD, TI, Out);
490 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
491 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
492
493 // If we don't need to emit a definition, return this declaration as is.
494 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
495 MD->getType()->castAs<FunctionType>());
496 if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
497 return Thunk;
498
499 // Arrange a function prototype appropriate for a function definition. In some
500 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
501 const CGFunctionInfo &FnInfo =
502 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
503 : CGM.getTypes().arrangeGlobalDeclaration(GD);
504 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
505
506 // If the type of the underlying GlobalValue is wrong, we'll have to replace
507 // it. It should be a declaration.
508 llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
509 if (ThunkFn->getFunctionType() != ThunkFnTy) {
510 llvm::GlobalValue *OldThunkFn = ThunkFn;
511
512 assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
Anders Carlsson55e89f82010-03-23 18:18:41 +0000513
514 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000515 OldThunkFn->setName(StringRef());
Reid Kleckner399d96e2018-04-02 20:20:33 +0000516 ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
517 Name.str(), &CGM.getModule());
518 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000519
Anders Carlsson55e89f82010-03-23 18:18:41 +0000520 // If needed, replace the old thunk with a bitcast.
521 if (!OldThunkFn->use_empty()) {
522 llvm::Constant *NewPtrForOldDecl =
Reid Kleckner399d96e2018-04-02 20:20:33 +0000523 llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000524 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
525 }
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000526
Anders Carlsson55e89f82010-03-23 18:18:41 +0000527 // Remove the old thunk.
528 OldThunkFn->eraseFromParent();
529 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000530
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000531 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
532 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000533
534 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000535 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000536 // There is already a thunk emitted for this function, do nothing.
Reid Kleckner399d96e2018-04-02 20:20:33 +0000537 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000538 }
539
Reid Kleckner399d96e2018-04-02 20:20:33 +0000540 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
541 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000542 }
543
Reid Kleckner399d96e2018-04-02 20:20:33 +0000544 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
545 // that the return type is meaningless. These thunks can be used to call
546 // functions with differing return types, and the caller is required to cast
547 // the prototype appropriately to extract the correct value.
548 if (IsUnprototyped)
549 ThunkFn->addFnAttr("thunk");
550
Rafael Espindola86792432012-09-21 20:39:32 +0000551 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
552
Reid Kleckner399d96e2018-04-02 20:20:33 +0000553 if (!IsUnprototyped && ThunkFn->isVarArg()) {
Eli Friedman49a94b12011-05-06 17:27:27 +0000554 // Varargs thunks are special; we can't just generate a call because
555 // we can't copy the varargs. Our implementation is rather
556 // expensive/sucky at the moment, so don't generate the thunk unless
557 // we have to.
558 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Peter Collingbourne45a24012015-06-30 19:07:26 +0000559 if (UseAvailableExternallyLinkage)
Reid Kleckner399d96e2018-04-02 20:20:33 +0000560 return ThunkFn;
561 ThunkFn = CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD,
562 TI);
Eli Friedman49a94b12011-05-06 17:27:27 +0000563 } else {
564 // Normal thunk body generation.
Reid Kleckner399d96e2018-04-02 20:20:33 +0000565 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
Eli Friedman49a94b12011-05-06 17:27:27 +0000566 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000567
Reid Kleckner399d96e2018-04-02 20:20:33 +0000568 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
569 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000570}
571
Reid Kleckner399d96e2018-04-02 20:20:33 +0000572void CodeGenVTables::EmitThunks(GlobalDecl GD) {
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000573 const CXXMethodDecl *MD =
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000574 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
575
576 // We don't need to generate thunks for the base destructor.
577 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
578 return;
579
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000580 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
581 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000582
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000583 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000584 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000585
Yaron Kerenede60302015-08-01 19:11:36 +0000586 for (const ThunkInfo& Thunk : *ThunkInfoVector)
Reid Kleckner399d96e2018-04-02 20:20:33 +0000587 maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000588}
589
John McCall9c6cb762016-11-28 22:18:33 +0000590void CodeGenVTables::addVTableComponent(
591 ConstantArrayBuilder &builder, const VTableLayout &layout,
592 unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
593 auto &component = layout.vtable_components()[idx];
Anders Carlssona4147142010-03-25 15:26:28 +0000594
John McCall9c6cb762016-11-28 22:18:33 +0000595 auto addOffsetConstant = [&](CharUnits offset) {
596 builder.add(llvm::ConstantExpr::getIntToPtr(
597 llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
598 CGM.Int8PtrTy));
Peter Collingbournee53683f2016-09-08 01:14:39 +0000599 };
Anders Carlssona5736bd2010-03-25 16:49:53 +0000600
John McCall9c6cb762016-11-28 22:18:33 +0000601 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000602 case VTableComponent::CK_VCallOffset:
John McCall9c6cb762016-11-28 22:18:33 +0000603 return addOffsetConstant(component.getVCallOffset());
Craig Topper8a13c412014-05-21 05:09:00 +0000604
Peter Collingbournee53683f2016-09-08 01:14:39 +0000605 case VTableComponent::CK_VBaseOffset:
John McCall9c6cb762016-11-28 22:18:33 +0000606 return addOffsetConstant(component.getVBaseOffset());
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000607
Peter Collingbournee53683f2016-09-08 01:14:39 +0000608 case VTableComponent::CK_OffsetToTop:
John McCall9c6cb762016-11-28 22:18:33 +0000609 return addOffsetConstant(component.getOffsetToTop());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000610
Peter Collingbournee53683f2016-09-08 01:14:39 +0000611 case VTableComponent::CK_RTTI:
John McCall9c6cb762016-11-28 22:18:33 +0000612 return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
Anders Carlssona5736bd2010-03-25 16:49:53 +0000613
Peter Collingbournee53683f2016-09-08 01:14:39 +0000614 case VTableComponent::CK_FunctionPointer:
615 case VTableComponent::CK_CompleteDtorPointer:
616 case VTableComponent::CK_DeletingDtorPointer: {
617 GlobalDecl GD;
618
619 // Get the right global decl.
John McCall9c6cb762016-11-28 22:18:33 +0000620 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000621 default:
622 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000623 case VTableComponent::CK_FunctionPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000624 GD = component.getFunctionDecl();
Peter Collingbournee53683f2016-09-08 01:14:39 +0000625 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000626 case VTableComponent::CK_CompleteDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000627 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000628 break;
629 case VTableComponent::CK_DeletingDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000630 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000631 break;
632 }
633
Peter Collingbournee53683f2016-09-08 01:14:39 +0000634 if (CGM.getLangOpts().CUDA) {
635 // Emit NULL for methods we can't codegen on this
636 // side. Otherwise we'd end up with vtable with unresolved
637 // references.
638 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
639 // OK on device side: functions w/ __device__ attribute
640 // OK on host side: anything except __device__-only functions.
641 bool CanEmitMethod =
642 CGM.getLangOpts().CUDAIsDevice
643 ? MD->hasAttr<CUDADeviceAttr>()
644 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
645 if (!CanEmitMethod)
John McCall9c6cb762016-11-28 22:18:33 +0000646 return builder.addNullPointer(CGM.Int8PtrTy);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000647 // Method is acceptable, continue processing as usual.
648 }
649
John McCall9c6cb762016-11-28 22:18:33 +0000650 auto getSpecialVirtualFn = [&](StringRef name) {
651 llvm::FunctionType *fnTy =
652 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
653 llvm::Constant *fn = CGM.CreateRuntimeFunction(fnTy, name);
654 if (auto f = dyn_cast<llvm::Function>(fn))
655 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
656 return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000657 };
Peter Collingbournee53683f2016-09-08 01:14:39 +0000658
John McCall9c6cb762016-11-28 22:18:33 +0000659 llvm::Constant *fnPtr;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000660
John McCall9c6cb762016-11-28 22:18:33 +0000661 // Pure virtual member functions.
662 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
663 if (!PureVirtualFn)
664 PureVirtualFn =
665 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
666 fnPtr = PureVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000667
John McCall9c6cb762016-11-28 22:18:33 +0000668 // Deleted virtual member functions.
669 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
670 if (!DeletedVirtualFn)
671 DeletedVirtualFn =
672 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
673 fnPtr = DeletedVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000674
John McCall9c6cb762016-11-28 22:18:33 +0000675 // Thunks.
676 } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
677 layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
678 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
679
John McCall9c6cb762016-11-28 22:18:33 +0000680 nextVTableThunkIndex++;
Reid Kleckner399d96e2018-04-02 20:20:33 +0000681 fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
John McCall9c6cb762016-11-28 22:18:33 +0000682
683 // Otherwise we can use the method definition directly.
684 } else {
685 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
686 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000687 }
688
John McCall9c6cb762016-11-28 22:18:33 +0000689 fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
690 builder.add(fnPtr);
691 return;
Anders Carlssona4147142010-03-25 15:26:28 +0000692 }
Peter Collingbournee53683f2016-09-08 01:14:39 +0000693
694 case VTableComponent::CK_UnusedFunctionPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000695 return builder.addNullPointer(CGM.Int8PtrTy);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000696 }
Simon Pilgrim4acc49e2016-09-08 11:03:41 +0000697
698 llvm_unreachable("Unexpected vtable component kind");
Peter Collingbournee53683f2016-09-08 01:14:39 +0000699}
700
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000701llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
702 SmallVector<llvm::Type *, 4> tys;
703 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
704 tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
705 }
706
707 return llvm::StructType::get(CGM.getLLVMContext(), tys);
708}
709
710void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
John McCall9c6cb762016-11-28 22:18:33 +0000711 const VTableLayout &layout,
712 llvm::Constant *rtti) {
713 unsigned nextVTableThunkIndex = 0;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000714 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
715 auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
716 size_t thisIndex = layout.getVTableOffset(i);
717 size_t nextIndex = thisIndex + layout.getVTableSize(i);
718 for (unsigned i = thisIndex; i != nextIndex; ++i) {
719 addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
720 }
721 vtableElem.finishAndAddTo(builder);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000722 }
Anders Carlssona4147142010-03-25 15:26:28 +0000723}
724
Anders Carlsson0534b022010-03-25 00:35:49 +0000725llvm::GlobalVariable *
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000726CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
727 const BaseSubobject &Base,
728 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000729 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000730 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000731 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
732 DI->completeClassData(Base.getBase());
733
Ahmed Charlesb8984322014-03-07 20:03:18 +0000734 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000735 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000736 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000737
Anders Carlssona5736bd2010-03-25 16:49:53 +0000738 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000739 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000740
741 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000742 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000743 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000744 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
745 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
746 Base.getBase(), Out);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000747 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000748
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000749 llvm::Type *VTType = getVTableType(*VTLayout);
Anders Carlssona4147142010-03-25 15:26:28 +0000750
Richard Smith65fd2a42013-02-16 00:51:21 +0000751 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
752 // guarantee that they actually will be available externally. Instead, when
753 // emitting an available_externally VTT, we provide references to an internal
754 // linkage construction vtable. The ABI only requires complete-object vtables
755 // to be the same for all instances of a type, not construction vtables.
756 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
757 Linkage = llvm::GlobalVariable::InternalLinkage;
758
Anders Carlssona4147142010-03-25 15:26:28 +0000759 // Create the variable that will hold the construction vtable.
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000760 llvm::GlobalVariable *VTable =
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000761 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000762 CGM.setGVProperties(VTable, RD);
John McCall358d0562011-03-27 09:00:25 +0000763
764 // V-tables are always unnamed_addr.
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000765 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Anders Carlssona4147142010-03-25 15:26:28 +0000766
David Majnemerd905da42014-07-01 20:30:31 +0000767 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
768 CGM.getContext().getTagDeclType(Base.getBase()));
769
Anders Carlssona4147142010-03-25 15:26:28 +0000770 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +0000771 ConstantInitBuilder builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000772 auto components = builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +0000773 createVTableInitializer(components, *VTLayout, RTTI);
774 components.finishAndSetAsInitializer(VTable);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000775
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000776 CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000777
Anders Carlsson0534b022010-03-25 00:35:49 +0000778 return VTable;
779}
780
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000781static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
782 const CXXRecordDecl *RD) {
783 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000784 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000785}
786
Eric Christopherd160c502016-01-29 01:35:53 +0000787/// Compute the required linkage of the vtable for the given class.
John McCall6bd2a892013-01-25 22:31:03 +0000788///
789/// Note that we only call this at the end of the translation unit.
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000790llvm::GlobalVariable::LinkageTypes
John McCall6bd2a892013-01-25 22:31:03 +0000791CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000792 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000793 return llvm::GlobalVariable::InternalLinkage;
794
795 // We're at the end of the translation unit, so the current key
796 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +0000797 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
798 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +0000799 // If this class has a key function, use that to determine the
800 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000801 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000802 if (keyFunction->hasBody(def))
803 keyFunction = cast<CXXMethodDecl>(def);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000804
John McCall6bd2a892013-01-25 22:31:03 +0000805 switch (keyFunction->getTemplateSpecializationKind()) {
806 case TSK_Undeclared:
807 case TSK_ExplicitSpecialization:
David Blaikieb11c8732017-01-30 06:36:08 +0000808 assert((def || CodeGenOpts.OptimizationLevel > 0 ||
809 CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
810 "Shouldn't query vtable linkage without key function, "
811 "optimizations, or debug info");
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000812 if (!def && CodeGenOpts.OptimizationLevel > 0)
813 return llvm::GlobalVariable::AvailableExternallyLinkage;
814
John McCall6bd2a892013-01-25 22:31:03 +0000815 if (keyFunction->isInlined())
816 return !Context.getLangOpts().AppleKext ?
817 llvm::GlobalVariable::LinkOnceODRLinkage :
818 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000819
John McCall6bd2a892013-01-25 22:31:03 +0000820 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +0000821
John McCall6bd2a892013-01-25 22:31:03 +0000822 case TSK_ImplicitInstantiation:
823 return !Context.getLangOpts().AppleKext ?
824 llvm::GlobalVariable::LinkOnceODRLinkage :
825 llvm::Function::InternalLinkage;
826
827 case TSK_ExplicitInstantiationDefinition:
828 return !Context.getLangOpts().AppleKext ?
829 llvm::GlobalVariable::WeakODRLinkage :
830 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000831
John McCall6bd2a892013-01-25 22:31:03 +0000832 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000833 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000834 }
835 }
836
837 // -fapple-kext mode does not support weak linkage, so we must use
838 // internal linkage.
839 if (Context.getLangOpts().AppleKext)
840 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000841
842 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
843 llvm::GlobalValue::LinkOnceODRLinkage;
844 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
845 llvm::GlobalValue::WeakODRLinkage;
846 if (RD->hasAttr<DLLExportAttr>()) {
847 // Cannot discard exported vtables.
848 DiscardableODRLinkage = NonDiscardableODRLinkage;
849 } else if (RD->hasAttr<DLLImportAttr>()) {
850 // Imported vtables are available externally.
851 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
852 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
853 }
854
John McCall6bd2a892013-01-25 22:31:03 +0000855 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000856 case TSK_Undeclared:
857 case TSK_ExplicitSpecialization:
858 case TSK_ImplicitInstantiation:
859 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000860
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000861 case TSK_ExplicitInstantiationDeclaration:
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000862 // Explicit instantiations in MSVC do not provide vtables, so we must emit
863 // our own.
864 if (getTarget().getCXXABI().isMicrosoft())
865 return DiscardableODRLinkage;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000866 return shouldEmitAvailableExternallyVTable(*this, RD)
867 ? llvm::GlobalVariable::AvailableExternallyLinkage
868 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000869
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000870 case TSK_ExplicitInstantiationDefinition:
871 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000872 }
873
874 llvm_unreachable("Invalid TemplateSpecializationKind!");
875}
876
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000877/// This is a callback from Sema to tell us that a particular vtable is
Nico Weberb6a5d052015-01-15 04:07:35 +0000878/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +0000879///
Nico Weberb6a5d052015-01-15 04:07:35 +0000880/// This is only called for vtables that _must_ be emitted (mainly due to key
881/// functions). For weak vtables, CodeGen tracks when they are needed and
882/// emits them as-needed.
883void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +0000884 VTables.GenerateClassData(theClass);
885}
886
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000887void
John McCall6bd2a892013-01-25 22:31:03 +0000888CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000889 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
890 DI->completeClassData(RD);
891
Reid Kleckner7810af02013-06-19 15:20:38 +0000892 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000893 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000894
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000895 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000896}
John McCall6bd2a892013-01-25 22:31:03 +0000897
898/// At this point in the translation unit, does it appear that can we
899/// rely on the vtable being defined elsewhere in the program?
900///
901/// The response is really only definitive when called at the end of
902/// the translation unit.
903///
904/// The only semantic restriction here is that the object file should
Eric Christopherd160c502016-01-29 01:35:53 +0000905/// not contain a vtable definition when that vtable is defined
John McCall6bd2a892013-01-25 22:31:03 +0000906/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
Eric Christopherd160c502016-01-29 01:35:53 +0000907/// vtables when unnecessary.
John McCall6bd2a892013-01-25 22:31:03 +0000908bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000909 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000910
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000911 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
912 // emit them even if there is an explicit template instantiation.
913 if (CGM.getTarget().getCXXABI().isMicrosoft())
David Majnemer2d8b2002016-02-11 17:49:28 +0000914 return false;
915
John McCall6bd2a892013-01-25 22:31:03 +0000916 // If we have an explicit instantiation declaration (and not a
Eric Christopherd160c502016-01-29 01:35:53 +0000917 // definition), the vtable is defined elsewhere.
John McCall6bd2a892013-01-25 22:31:03 +0000918 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
919 if (TSK == TSK_ExplicitInstantiationDeclaration)
920 return true;
921
922 // Otherwise, if the class is an instantiated template, the
Eric Christopherd160c502016-01-29 01:35:53 +0000923 // vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000924 if (TSK == TSK_ImplicitInstantiation ||
925 TSK == TSK_ExplicitInstantiationDefinition)
926 return false;
927
928 // Otherwise, if the class doesn't have a key function (possibly
Eric Christopherd160c502016-01-29 01:35:53 +0000929 // anymore), the vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000930 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
931 if (!keyFunction)
932 return false;
933
934 // Otherwise, if we don't have a definition of the key function, the
Eric Christopherd160c502016-01-29 01:35:53 +0000935 // vtable must be defined somewhere else.
John McCall6bd2a892013-01-25 22:31:03 +0000936 return !keyFunction->hasBody();
937}
938
939/// Given that we're currently at the end of the translation unit, and
Eric Christopherd160c502016-01-29 01:35:53 +0000940/// we've emitted a reference to the vtable for this class, should
941/// we define that vtable?
John McCall6bd2a892013-01-25 22:31:03 +0000942static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
943 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000944 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000945 if (!CGM.getVTables().isVTableExternal(RD))
946 return true;
947
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000948 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000949 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +0000950}
951
952/// Given that at some point we emitted a reference to one or more
Eric Christopherd160c502016-01-29 01:35:53 +0000953/// vtables, and that we are now at the end of the translation unit,
John McCall6bd2a892013-01-25 22:31:03 +0000954/// decide whether we should emit them.
955void CodeGenModule::EmitDeferredVTables() {
956#ifndef NDEBUG
957 // Remember the size of DeferredVTables, because we're going to assume
958 // that this entire operation doesn't modify it.
959 size_t savedSize = DeferredVTables.size();
960#endif
961
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000962 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +0000963 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
964 VTables.GenerateClassData(RD);
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000965 else if (shouldOpportunisticallyEmitVTables())
966 OpportunisticVTables.push_back(RD);
John McCall6bd2a892013-01-25 22:31:03 +0000967
968 assert(savedSize == DeferredVTables.size() &&
Eric Christopherd160c502016-01-29 01:35:53 +0000969 "deferred extra vtables during vtable emission?");
John McCall6bd2a892013-01-25 22:31:03 +0000970 DeferredVTables.clear();
971}
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000972
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000973bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
974 LinkageInfo LV = RD->getLinkageAndVisibility();
975 if (!isExternallyVisible(LV.getLinkage()))
976 return true;
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000977
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000978 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
979 return false;
Peter Collingbournefb532b92016-02-24 20:46:36 +0000980
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000981 if (getTriple().isOSBinFormatCOFF()) {
982 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
983 return false;
984 } else {
985 if (LV.getVisibility() != HiddenVisibility)
986 return false;
987 }
Peter Collingbournefb532b92016-02-24 20:46:36 +0000988
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000989 if (getCodeGenOpts().LTOVisibilityPublicStd) {
990 const DeclContext *DC = RD;
991 while (1) {
992 auto *D = cast<Decl>(DC);
993 DC = DC->getParent();
994 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
995 if (auto *ND = dyn_cast<NamespaceDecl>(D))
996 if (const IdentifierInfo *II = ND->getIdentifier())
997 if (II->isStr("std") || II->isStr("stdext"))
998 return false;
999 break;
1000 }
1001 }
1002 }
1003
1004 return true;
Peter Collingbournee5706442015-07-09 19:56:14 +00001005}
1006
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001007void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1008 const VTableLayout &VTLayout) {
Peter Collingbourne1e1475a2017-01-18 23:55:27 +00001009 if (!getCodeGenOpts().LTOUnit)
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001010 return;
1011
Peter Collingbourne86d34a72015-06-17 19:08:05 +00001012 CharUnits PointerWidth =
1013 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001014
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001015 typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
1016 std::vector<BSEntry> BitsetEntries;
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001017 // Create a bit set entry for each address point.
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001018 for (auto &&AP : VTLayout.getAddressPoints())
Peter Collingbourne2849c4e2016-12-13 20:40:39 +00001019 BitsetEntries.push_back(
1020 std::make_pair(AP.first.getBase(),
1021 VTLayout.getVTableOffset(AP.second.VTableIndex) +
1022 AP.second.AddressPointIndex));
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001023
1024 // Sort the bit set entries for determinism.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001025 llvm::sort(BitsetEntries.begin(), BitsetEntries.end(),
1026 [this](const BSEntry &E1, const BSEntry &E2) {
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001027 if (&E1 == &E2)
Peter Collingbourne47941902015-02-24 01:12:53 +00001028 return false;
1029
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001030 std::string S1;
1031 llvm::raw_string_ostream O1(S1);
1032 getCXXABI().getMangleContext().mangleTypeName(
1033 QualType(E1.first->getTypeForDecl(), 0), O1);
1034 O1.flush();
1035
1036 std::string S2;
1037 llvm::raw_string_ostream O2(S2);
1038 getCXXABI().getMangleContext().mangleTypeName(
1039 QualType(E2.first->getTypeForDecl(), 0), O2);
1040 O2.flush();
1041
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001042 if (S1 < S2)
1043 return true;
1044 if (S1 != S2)
1045 return false;
1046
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001047 return E1.second < E2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001048 });
1049
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001050 for (auto BitsetEntry : BitsetEntries)
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001051 AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,
1052 BitsetEntry.first);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001053}