1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code dealing with C++ code generation of virtual tables.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CGCXXABI.h"
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/Basic/CodeGenOptions.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "clang/CodeGen/ConstantInitBuilder.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
25 #include <algorithm>
26 #include <cstdio>
27
28 using namespace clang;
29 using namespace CodeGen;
30
CodeGenVTables(CodeGenModule & CGM)31 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
33
GetAddrOfThunk(StringRef Name,llvm::Type * FnTy,GlobalDecl GD)34 llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
35 GlobalDecl GD) {
36 return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
37 /*DontDefer=*/true, /*IsThunk=*/true);
38 }
39
setThunkProperties(CodeGenModule & CGM,const ThunkInfo & Thunk,llvm::Function * ThunkFn,bool ForVTable,GlobalDecl GD)40 static 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.
48 CGM.setGVProperties(ThunkFn, GD);
49
50 if (!CGM.getCXXABI().exportThunk()) {
51 ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
52 ThunkFn->setDSOLocal(true);
53 }
54
55 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
56 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
57 }
58
59 #ifndef NDEBUG
similar(const ABIArgInfo & infoL,CanQualType typeL,const ABIArgInfo & infoR,CanQualType typeR)60 static 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
PerformReturnAdjustment(CodeGenFunction & CGF,QualType ResultType,RValue RV,const ThunkInfo & Thunk)69 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70 QualType ResultType, RValue RV,
71 const ThunkInfo &Thunk) {
72 // Emit the return adjustment.
73 bool NullCheckValue = !ResultType->isReferenceType();
74
75 llvm::BasicBlock *AdjustNull = nullptr;
76 llvm::BasicBlock *AdjustNotNull = nullptr;
77 llvm::BasicBlock *AdjustEnd = nullptr;
78
79 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");
85
86 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88 CGF.EmitBlock(AdjustNotNull);
89 }
90
91 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
92 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
93 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(
94 CGF,
95 Address(ReturnValue, CGF.ConvertTypeForMem(ResultType->getPointeeType()),
96 ClassAlign),
97 Thunk.Return);
98
99 if (NullCheckValue) {
100 CGF.Builder.CreateBr(AdjustEnd);
101 CGF.EmitBlock(AdjustNull);
102 CGF.Builder.CreateBr(AdjustEnd);
103 CGF.EmitBlock(AdjustEnd);
104
105 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
106 PHI->addIncoming(ReturnValue, AdjustNotNull);
107 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
108 AdjustNull);
109 ReturnValue = PHI;
110 }
111
112 return RValue::get(ReturnValue);
113 }
114
115 /// This function clones a function's DISubprogram node and enters it into
116 /// a value map with the intent that the map can be utilized by the cloner
117 /// to short-circuit Metadata node mapping.
118 /// Furthermore, the function resolves any DILocalVariable nodes referenced
119 /// by dbg.value intrinsics so they can be properly mapped during cloning.
resolveTopLevelMetadata(llvm::Function * Fn,llvm::ValueToValueMapTy & VMap)120 static void resolveTopLevelMetadata(llvm::Function *Fn,
121 llvm::ValueToValueMapTy &VMap) {
122 // Clone the DISubprogram node and put it into the Value map.
123 auto *DIS = Fn->getSubprogram();
124 if (!DIS)
125 return;
126 auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
127 VMap.MD()[DIS].reset(NewDIS);
128
129 // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
130 // they are referencing.
131 for (auto &BB : Fn->getBasicBlockList()) {
132 for (auto &I : BB) {
133 if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
134 auto *DILocal = DII->getVariable();
135 if (!DILocal->isResolved())
136 DILocal->resolve();
137 }
138 }
139 }
140 }
141
142 // This function does roughly the same thing as GenerateThunk, but in a
143 // very different way, so that va_start and va_end work correctly.
144 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
145 // a function, and that there is an alloca built in the entry block
146 // for all accesses to "this".
147 // FIXME: This function assumes there is only one "ret" statement per function.
148 // FIXME: Cloning isn't correct in the presence of indirect goto!
149 // FIXME: This implementation of thunks bloats codesize by duplicating the
150 // function definition. There are alternatives:
151 // 1. Add some sort of stub support to LLVM for cases where we can
152 // do a this adjustment, then a sibcall.
153 // 2. We could transform the definition to take a va_list instead of an
154 // actual variable argument list, then have the thunks (including a
155 // no-op thunk for the regular definition) call va_start/va_end.
156 // There's a bit of per-call overhead for this solution, but it's
157 // better for codesize if the definition is long.
158 llvm::Function *
GenerateVarArgsThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk)159 CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
160 const CGFunctionInfo &FnInfo,
161 GlobalDecl GD, const ThunkInfo &Thunk) {
162 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
163 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
164 QualType ResultType = FPT->getReturnType();
165
166 // Get the original function
167 assert(FnInfo.isVariadic());
168 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
169 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
170 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
171
172 // Cloning can't work if we don't have a definition. The Microsoft ABI may
173 // require thunks when a definition is not available. Emit an error in these
174 // cases.
175 if (!MD->isDefined()) {
176 CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
177 return Fn;
178 }
179 assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
180
181 // Clone to thunk.
182 llvm::ValueToValueMapTy VMap;
183
184 // We are cloning a function while some Metadata nodes are still unresolved.
185 // Ensure that the value mapper does not encounter any of them.
186 resolveTopLevelMetadata(BaseFn, VMap);
187 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
188 Fn->replaceAllUsesWith(NewFn);
189 NewFn->takeName(Fn);
190 Fn->eraseFromParent();
191 Fn = NewFn;
192
193 // "Initialize" CGF (minimally).
194 CurFn = Fn;
195
196 // Get the "this" value
197 llvm::Function::arg_iterator AI = Fn->arg_begin();
198 if (CGM.ReturnTypeUsesSRet(FnInfo))
199 ++AI;
200
201 // Find the first store of "this", which will be to the alloca associated
202 // with "this".
203 Address ThisPtr =
204 Address(&*AI, ConvertTypeForMem(MD->getThisType()->getPointeeType()),
205 CGM.getClassPointerAlignment(MD->getParent()));
206 llvm::BasicBlock *EntryBB = &Fn->front();
207 llvm::BasicBlock::iterator ThisStore =
208 llvm::find_if(*EntryBB, [&](llvm::Instruction &I) {
209 return isa<llvm::StoreInst>(I) &&
210 I.getOperand(0) == ThisPtr.getPointer();
211 });
212 assert(ThisStore != EntryBB->end() &&
213 "Store of this should be in entry block?");
214 // Adjust "this", if necessary.
215 Builder.SetInsertPoint(&*ThisStore);
216 llvm::Value *AdjustedThisPtr =
217 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
218 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
219 ThisStore->getOperand(0)->getType());
220 ThisStore->setOperand(0, AdjustedThisPtr);
221
222 if (!Thunk.Return.isEmpty()) {
223 // Fix up the returned value, if necessary.
224 for (llvm::BasicBlock &BB : *Fn) {
225 llvm::Instruction *T = BB.getTerminator();
226 if (isa<llvm::ReturnInst>(T)) {
227 RValue RV = RValue::get(T->getOperand(0));
228 T->eraseFromParent();
229 Builder.SetInsertPoint(&BB);
230 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
231 Builder.CreateRet(RV.getScalarVal());
232 break;
233 }
234 }
235 }
236
237 return Fn;
238 }
239
StartThunk(llvm::Function * Fn,GlobalDecl GD,const CGFunctionInfo & FnInfo,bool IsUnprototyped)240 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
241 const CGFunctionInfo &FnInfo,
242 bool IsUnprototyped) {
243 assert(!CurGD.getDecl() && "CurGD was already set!");
244 CurGD = GD;
245 CurFuncIsThunk = true;
246
247 // Build FunctionArgs.
248 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
249 QualType ThisType = MD->getThisType();
250 QualType ResultType;
251 if (IsUnprototyped)
252 ResultType = CGM.getContext().VoidTy;
253 else if (CGM.getCXXABI().HasThisReturn(GD))
254 ResultType = ThisType;
255 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
256 ResultType = CGM.getContext().VoidPtrTy;
257 else
258 ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
259 FunctionArgList FunctionArgs;
260
261 // Create the implicit 'this' parameter declaration.
262 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
263
264 // Add the rest of the parameters, if we have a prototype to work with.
265 if (!IsUnprototyped) {
266 FunctionArgs.append(MD->param_begin(), MD->param_end());
267
268 if (isa<CXXDestructorDecl>(MD))
269 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
270 FunctionArgs);
271 }
272
273 // Start defining the function.
274 auto NL = ApplyDebugLocation::CreateEmpty(*this);
275 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
276 MD->getLocation());
277 // Create a scope with an artificial location for the body of this function.
278 auto AL = ApplyDebugLocation::CreateArtificial(*this);
279
280 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
281 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
282 CXXThisValue = CXXABIThisValue;
283 CurCodeDecl = MD;
284 CurFuncDecl = MD;
285 }
286
FinishThunk()287 void CodeGenFunction::FinishThunk() {
288 // Clear these to restore the invariants expected by
289 // StartFunction/FinishFunction.
290 CurCodeDecl = nullptr;
291 CurFuncDecl = nullptr;
292
293 FinishFunction();
294 }
295
EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,const ThunkInfo * Thunk,bool IsUnprototyped)296 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
297 const ThunkInfo *Thunk,
298 bool IsUnprototyped) {
299 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
300 "Please use a new CGF for this thunk");
301 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
302
303 // Adjust the 'this' pointer if necessary
304 llvm::Value *AdjustedThisPtr =
305 Thunk ? CGM.getCXXABI().performThisAdjustment(
306 *this, LoadCXXThisAddress(), Thunk->This)
307 : LoadCXXThis();
308
309 // If perfect forwarding is required a variadic method, a method using
310 // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
311 // thunk requires a return adjustment, since that is impossible with musttail.
312 if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
313 if (Thunk && !Thunk->Return.isEmpty()) {
314 if (IsUnprototyped)
315 CGM.ErrorUnsupported(
316 MD, "return-adjusting thunk with incomplete parameter type");
317 else if (CurFnInfo->isVariadic())
318 llvm_unreachable("shouldn't try to emit musttail return-adjusting "
319 "thunks for variadic functions");
320 else
321 CGM.ErrorUnsupported(
322 MD, "non-trivial argument copy for return-adjusting thunk");
323 }
324 EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
325 return;
326 }
327
328 // Start building CallArgs.
329 CallArgList CallArgs;
330 QualType ThisType = MD->getThisType();
331 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
332
333 if (isa<CXXDestructorDecl>(MD))
334 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
335
336 #ifndef NDEBUG
337 unsigned PrefixArgs = CallArgs.size() - 1;
338 #endif
339 // Add the rest of the arguments.
340 for (const ParmVarDecl *PD : MD->parameters())
341 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
342
343 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
344
345 #ifndef NDEBUG
346 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
347 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
348 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
349 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
350 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
351 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
352 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
353 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
354 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
355 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
356 assert(similar(CallFnInfo.arg_begin()[i].info,
357 CallFnInfo.arg_begin()[i].type,
358 CurFnInfo->arg_begin()[i].info,
359 CurFnInfo->arg_begin()[i].type));
360 #endif
361
362 // Determine whether we have a return value slot to use.
363 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
364 ? ThisType
365 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
366 ? CGM.getContext().VoidPtrTy
367 : FPT->getReturnType();
368 ReturnValueSlot Slot;
369 if (!ResultType->isVoidType() &&
370 (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect ||
371 hasAggregateEvaluationKind(ResultType)))
372 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified(),
373 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
374
375 // Now emit our call.
376 llvm::CallBase *CallOrInvoke;
377 RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
378 CallArgs, &CallOrInvoke);
379
380 // Consider return adjustment if we have ThunkInfo.
381 if (Thunk && !Thunk->Return.isEmpty())
382 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
383 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
384 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
385
386 // Emit return.
387 if (!ResultType->isVoidType() && Slot.isNull())
388 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
389
390 // Disable the final ARC autorelease.
391 AutoreleaseResult = false;
392
393 FinishThunk();
394 }
395
EmitMustTailThunk(GlobalDecl GD,llvm::Value * AdjustedThisPtr,llvm::FunctionCallee Callee)396 void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
397 llvm::Value *AdjustedThisPtr,
398 llvm::FunctionCallee Callee) {
399 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
400 // to translate AST arguments into LLVM IR arguments. For thunks, we know
401 // that the caller prototype more or less matches the callee prototype with
402 // the exception of 'this'.
403 SmallVector<llvm::Value *, 8> Args(llvm::make_pointer_range(CurFn->args()));
404
405 // Set the adjusted 'this' pointer.
406 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
407 if (ThisAI.isDirect()) {
408 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
409 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
410 llvm::Type *ThisType = Args[ThisArgNo]->getType();
411 if (ThisType != AdjustedThisPtr->getType())
412 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
413 Args[ThisArgNo] = AdjustedThisPtr;
414 } else {
415 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
416 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
417 llvm::Type *ThisType = ThisAddr.getElementType();
418 if (ThisType != AdjustedThisPtr->getType())
419 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
420 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
421 }
422
423 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
424 // don't actually want to run them.
425 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
426 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
427
428 // Apply the standard set of call attributes.
429 unsigned CallingConv;
430 llvm::AttributeList Attrs;
431 CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
432 Attrs, CallingConv, /*AttrOnCallSite=*/true,
433 /*IsThunk=*/false);
434 Call->setAttributes(Attrs);
435 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
436
437 if (Call->getType()->isVoidTy())
438 Builder.CreateRetVoid();
439 else
440 Builder.CreateRet(Call);
441
442 // Finish the function to maintain CodeGenFunction invariants.
443 // FIXME: Don't emit unreachable code.
444 EmitBlock(createBasicBlock());
445
446 FinishThunk();
447 }
448
generateThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk,bool IsUnprototyped)449 void CodeGenFunction::generateThunk(llvm::Function *Fn,
450 const CGFunctionInfo &FnInfo, GlobalDecl GD,
451 const ThunkInfo &Thunk,
452 bool IsUnprototyped) {
453 StartThunk(Fn, GD, FnInfo, IsUnprototyped);
454 // Create a scope with an artificial location for the body of this function.
455 auto AL = ApplyDebugLocation::CreateArtificial(*this);
456
457 // Get our callee. Use a placeholder type if this method is unprototyped so
458 // that CodeGenModule doesn't try to set attributes.
459 llvm::Type *Ty;
460 if (IsUnprototyped)
461 Ty = llvm::StructType::get(getLLVMContext());
462 else
463 Ty = CGM.getTypes().GetFunctionType(FnInfo);
464
465 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
466
467 // Fix up the function type for an unprototyped musttail call.
468 if (IsUnprototyped)
469 Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
470
471 // Make the call and return the result.
472 EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
473 &Thunk, IsUnprototyped);
474 }
475
shouldEmitVTableThunk(CodeGenModule & CGM,const CXXMethodDecl * MD,bool IsUnprototyped,bool ForVTable)476 static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
477 bool IsUnprototyped, bool ForVTable) {
478 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
479 // provide thunks for us.
480 if (CGM.getTarget().getCXXABI().isMicrosoft())
481 return true;
482
483 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
484 // definitions of the main method. Therefore, emitting thunks with the vtable
485 // is purely an optimization. Emit the thunk if optimizations are enabled and
486 // all of the parameter types are complete.
487 if (ForVTable)
488 return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
489
490 // Always emit thunks along with the method definition.
491 return true;
492 }
493
maybeEmitThunk(GlobalDecl GD,const ThunkInfo & TI,bool ForVTable)494 llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
495 const ThunkInfo &TI,
496 bool ForVTable) {
497 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
498
499 // First, get a declaration. Compute the mangled name. Don't worry about
500 // getting the function prototype right, since we may only need this
501 // declaration to fill in a vtable slot.
502 SmallString<256> Name;
503 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
504 llvm::raw_svector_ostream Out(Name);
505 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
506 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
507 else
508 MCtx.mangleThunk(MD, TI, Out);
509 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
510 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
511
512 // If we don't need to emit a definition, return this declaration as is.
513 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
514 MD->getType()->castAs<FunctionType>());
515 if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
516 return Thunk;
517
518 // Arrange a function prototype appropriate for a function definition. In some
519 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
520 const CGFunctionInfo &FnInfo =
521 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
522 : CGM.getTypes().arrangeGlobalDeclaration(GD);
523 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
524
525 // If the type of the underlying GlobalValue is wrong, we'll have to replace
526 // it. It should be a declaration.
527 llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
528 if (ThunkFn->getFunctionType() != ThunkFnTy) {
529 llvm::GlobalValue *OldThunkFn = ThunkFn;
530
531 assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
532
533 // Remove the name from the old thunk function and get a new thunk.
534 OldThunkFn->setName(StringRef());
535 ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
536 Name.str(), &CGM.getModule());
537 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
538
539 // If needed, replace the old thunk with a bitcast.
540 if (!OldThunkFn->use_empty()) {
541 llvm::Constant *NewPtrForOldDecl =
542 llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
543 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
544 }
545
546 // Remove the old thunk.
547 OldThunkFn->eraseFromParent();
548 }
549
550 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
551 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
552
553 if (!ThunkFn->isDeclaration()) {
554 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
555 // There is already a thunk emitted for this function, do nothing.
556 return ThunkFn;
557 }
558
559 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
560 return ThunkFn;
561 }
562
563 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
564 // that the return type is meaningless. These thunks can be used to call
565 // functions with differing return types, and the caller is required to cast
566 // the prototype appropriately to extract the correct value.
567 if (IsUnprototyped)
568 ThunkFn->addFnAttr("thunk");
569
570 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
571
572 // Thunks for variadic methods are special because in general variadic
573 // arguments cannot be perfectly forwarded. In the general case, clang
574 // implements such thunks by cloning the original function body. However, for
575 // thunks with no return adjustment on targets that support musttail, we can
576 // use musttail to perfectly forward the variadic arguments.
577 bool ShouldCloneVarArgs = false;
578 if (!IsUnprototyped && ThunkFn->isVarArg()) {
579 ShouldCloneVarArgs = true;
580 if (TI.Return.isEmpty()) {
581 switch (CGM.getTriple().getArch()) {
582 case llvm::Triple::x86_64:
583 case llvm::Triple::x86:
584 case llvm::Triple::aarch64:
585 ShouldCloneVarArgs = false;
586 break;
587 default:
588 break;
589 }
590 }
591 }
592
593 if (ShouldCloneVarArgs) {
594 if (UseAvailableExternallyLinkage)
595 return ThunkFn;
596 ThunkFn =
597 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
598 } else {
599 // Normal thunk body generation.
600 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
601 }
602
603 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
604 return ThunkFn;
605 }
606
EmitThunks(GlobalDecl GD)607 void CodeGenVTables::EmitThunks(GlobalDecl GD) {
608 const CXXMethodDecl *MD =
609 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
610
611 // We don't need to generate thunks for the base destructor.
612 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
613 return;
614
615 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
616 VTContext->getThunkInfo(GD);
617
618 if (!ThunkInfoVector)
619 return;
620
621 for (const ThunkInfo& Thunk : *ThunkInfoVector)
622 maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
623 }
624
addRelativeComponent(ConstantArrayBuilder & builder,llvm::Constant * component,unsigned vtableAddressPoint,bool vtableHasLocalLinkage,bool isCompleteDtor) const625 void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
626 llvm::Constant *component,
627 unsigned vtableAddressPoint,
628 bool vtableHasLocalLinkage,
629 bool isCompleteDtor) const {
630 // No need to get the offset of a nullptr.
631 if (component->isNullValue())
632 return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0));
633
634 auto *globalVal =
635 cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases());
636 llvm::Module &module = CGM.getModule();
637
638 // We don't want to copy the linkage of the vtable exactly because we still
639 // want the stub/proxy to be emitted for properly calculating the offset.
640 // Examples where there would be no symbol emitted are available_externally
641 // and private linkages.
642 auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
643 : llvm::GlobalValue::ExternalLinkage;
644
645 llvm::Constant *target;
646 if (auto *func = dyn_cast<llvm::Function>(globalVal)) {
647 target = llvm::DSOLocalEquivalent::get(func);
648 } else {
649 llvm::SmallString<16> rttiProxyName(globalVal->getName());
650 rttiProxyName.append(".rtti_proxy");
651
652 // The RTTI component may not always be emitted in the same linkage unit as
653 // the vtable. As a general case, we can make a dso_local proxy to the RTTI
654 // that points to the actual RTTI struct somewhere. This will result in a
655 // GOTPCREL relocation when taking the relative offset to the proxy.
656 llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName);
657 if (!proxy) {
658 proxy = new llvm::GlobalVariable(module, globalVal->getType(),
659 /*isConstant=*/true, stubLinkage,
660 globalVal, rttiProxyName);
661 proxy->setDSOLocal(true);
662 proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
663 if (!proxy->hasLocalLinkage()) {
664 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
665 proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
666 }
667 }
668 target = proxy;
669 }
670
671 builder.addRelativeOffsetToPosition(CGM.Int32Ty, target,
672 /*position=*/vtableAddressPoint);
673 }
674
useRelativeLayout() const675 bool CodeGenVTables::useRelativeLayout() const {
676 return CGM.getTarget().getCXXABI().isItaniumFamily() &&
677 CGM.getItaniumVTableContext().isRelativeLayout();
678 }
679
getVTableComponentType() const680 llvm::Type *CodeGenVTables::getVTableComponentType() const {
681 if (useRelativeLayout())
682 return CGM.Int32Ty;
683 return CGM.Int8PtrTy;
684 }
685
AddPointerLayoutOffset(const CodeGenModule & CGM,ConstantArrayBuilder & builder,CharUnits offset)686 static void AddPointerLayoutOffset(const CodeGenModule &CGM,
687 ConstantArrayBuilder &builder,
688 CharUnits offset) {
689 builder.add(llvm::ConstantExpr::getIntToPtr(
690 llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
691 CGM.Int8PtrTy));
692 }
693
AddRelativeLayoutOffset(const CodeGenModule & CGM,ConstantArrayBuilder & builder,CharUnits offset)694 static void AddRelativeLayoutOffset(const CodeGenModule &CGM,
695 ConstantArrayBuilder &builder,
696 CharUnits offset) {
697 builder.add(llvm::ConstantInt::get(CGM.Int32Ty, offset.getQuantity()));
698 }
699
addVTableComponent(ConstantArrayBuilder & builder,const VTableLayout & layout,unsigned componentIndex,llvm::Constant * rtti,unsigned & nextVTableThunkIndex,unsigned vtableAddressPoint,bool vtableHasLocalLinkage)700 void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
701 const VTableLayout &layout,
702 unsigned componentIndex,
703 llvm::Constant *rtti,
704 unsigned &nextVTableThunkIndex,
705 unsigned vtableAddressPoint,
706 bool vtableHasLocalLinkage) {
707 auto &component = layout.vtable_components()[componentIndex];
708
709 auto addOffsetConstant =
710 useRelativeLayout() ? AddRelativeLayoutOffset : AddPointerLayoutOffset;
711
712 switch (component.getKind()) {
713 case VTableComponent::CK_VCallOffset:
714 return addOffsetConstant(CGM, builder, component.getVCallOffset());
715
716 case VTableComponent::CK_VBaseOffset:
717 return addOffsetConstant(CGM, builder, component.getVBaseOffset());
718
719 case VTableComponent::CK_OffsetToTop:
720 return addOffsetConstant(CGM, builder, component.getOffsetToTop());
721
722 case VTableComponent::CK_RTTI:
723 if (useRelativeLayout())
724 return addRelativeComponent(builder, rtti, vtableAddressPoint,
725 vtableHasLocalLinkage,
726 /*isCompleteDtor=*/false);
727 else
728 return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
729
730 case VTableComponent::CK_FunctionPointer:
731 case VTableComponent::CK_CompleteDtorPointer:
732 case VTableComponent::CK_DeletingDtorPointer: {
733 GlobalDecl GD = component.getGlobalDecl();
734
735 if (CGM.getLangOpts().CUDA) {
736 // Emit NULL for methods we can't codegen on this
737 // side. Otherwise we'd end up with vtable with unresolved
738 // references.
739 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
740 // OK on device side: functions w/ __device__ attribute
741 // OK on host side: anything except __device__-only functions.
742 bool CanEmitMethod =
743 CGM.getLangOpts().CUDAIsDevice
744 ? MD->hasAttr<CUDADeviceAttr>()
745 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
746 if (!CanEmitMethod)
747 return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy));
748 // Method is acceptable, continue processing as usual.
749 }
750
751 auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
752 // FIXME(PR43094): When merging comdat groups, lld can select a local
753 // symbol as the signature symbol even though it cannot be accessed
754 // outside that symbol's TU. The relative vtables ABI would make
755 // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and
756 // depending on link order, the comdat groups could resolve to the one
757 // with the local symbol. As a temporary solution, fill these components
758 // with zero. We shouldn't be calling these in the first place anyway.
759 if (useRelativeLayout())
760 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
761
762 // For NVPTX devices in OpenMP emit special functon as null pointers,
763 // otherwise linking ends up with unresolved references.
764 if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsDevice &&
765 CGM.getTriple().isNVPTX())
766 return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
767 llvm::FunctionType *fnTy =
768 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
769 llvm::Constant *fn = cast<llvm::Constant>(
770 CGM.CreateRuntimeFunction(fnTy, name).getCallee());
771 if (auto f = dyn_cast<llvm::Function>(fn))
772 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
773 return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
774 };
775
776 llvm::Constant *fnPtr;
777
778 // Pure virtual member functions.
779 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
780 if (!PureVirtualFn)
781 PureVirtualFn =
782 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
783 fnPtr = PureVirtualFn;
784
785 // Deleted virtual member functions.
786 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
787 if (!DeletedVirtualFn)
788 DeletedVirtualFn =
789 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
790 fnPtr = DeletedVirtualFn;
791
792 // Thunks.
793 } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
794 layout.vtable_thunks()[nextVTableThunkIndex].first ==
795 componentIndex) {
796 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
797
798 nextVTableThunkIndex++;
799 fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
800
801 // Otherwise we can use the method definition directly.
802 } else {
803 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
804 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
805 }
806
807 if (useRelativeLayout()) {
808 return addRelativeComponent(
809 builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
810 component.getKind() == VTableComponent::CK_CompleteDtorPointer);
811 } else
812 return builder.add(llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy));
813 }
814
815 case VTableComponent::CK_UnusedFunctionPointer:
816 if (useRelativeLayout())
817 return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
818 else
819 return builder.addNullPointer(CGM.Int8PtrTy);
820 }
821
822 llvm_unreachable("Unexpected vtable component kind");
823 }
824
getVTableType(const VTableLayout & layout)825 llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
826 SmallVector<llvm::Type *, 4> tys;
827 llvm::Type *componentType = getVTableComponentType();
828 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i)
829 tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i)));
830
831 return llvm::StructType::get(CGM.getLLVMContext(), tys);
832 }
833
createVTableInitializer(ConstantStructBuilder & builder,const VTableLayout & layout,llvm::Constant * rtti,bool vtableHasLocalLinkage)834 void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
835 const VTableLayout &layout,
836 llvm::Constant *rtti,
837 bool vtableHasLocalLinkage) {
838 llvm::Type *componentType = getVTableComponentType();
839
840 const auto &addressPoints = layout.getAddressPointIndices();
841 unsigned nextVTableThunkIndex = 0;
842 for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
843 vtableIndex != endIndex; ++vtableIndex) {
844 auto vtableElem = builder.beginArray(componentType);
845
846 size_t vtableStart = layout.getVTableOffset(vtableIndex);
847 size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex);
848 for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
849 ++componentIndex) {
850 addVTableComponent(vtableElem, layout, componentIndex, rtti,
851 nextVTableThunkIndex, addressPoints[vtableIndex],
852 vtableHasLocalLinkage);
853 }
854 vtableElem.finishAndAddTo(builder);
855 }
856 }
857
GenerateConstructionVTable(const CXXRecordDecl * RD,const BaseSubobject & Base,bool BaseIsVirtual,llvm::GlobalVariable::LinkageTypes Linkage,VTableAddressPointsMapTy & AddressPoints)858 llvm::GlobalVariable *CodeGenVTables::GenerateConstructionVTable(
859 const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
860 llvm::GlobalVariable::LinkageTypes Linkage,
861 VTableAddressPointsMapTy &AddressPoints) {
862 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
863 DI->completeClassData(Base.getBase());
864
865 std::unique_ptr<VTableLayout> VTLayout(
866 getItaniumVTableContext().createConstructionVTableLayout(
867 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
868
869 // Add the address points.
870 AddressPoints = VTLayout->getAddressPoints();
871
872 // Get the mangled construction vtable name.
873 SmallString<256> OutName;
874 llvm::raw_svector_ostream Out(OutName);
875 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
876 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
877 Base.getBase(), Out);
878 SmallString<256> Name(OutName);
879
880 bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout();
881 bool VTableAliasExists =
882 UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
883 if (VTableAliasExists) {
884 // We previously made the vtable hidden and changed its name.
885 Name.append(".local");
886 }
887
888 llvm::Type *VTType = getVTableType(*VTLayout);
889
890 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
891 // guarantee that they actually will be available externally. Instead, when
892 // emitting an available_externally VTT, we provide references to an internal
893 // linkage construction vtable. The ABI only requires complete-object vtables
894 // to be the same for all instances of a type, not construction vtables.
895 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
896 Linkage = llvm::GlobalVariable::InternalLinkage;
897
898 unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
899
900 // Create the variable that will hold the construction vtable.
901 llvm::GlobalVariable *VTable =
902 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
903
904 // V-tables are always unnamed_addr.
905 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
906
907 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
908 CGM.getContext().getTagDeclType(Base.getBase()));
909
910 // Create and set the initializer.
911 ConstantInitBuilder builder(CGM);
912 auto components = builder.beginStruct();
913 createVTableInitializer(components, *VTLayout, RTTI,
914 VTable->hasLocalLinkage());
915 components.finishAndSetAsInitializer(VTable);
916
917 // Set properties only after the initializer has been set to ensure that the
918 // GV is treated as definition and not declaration.
919 assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
920 CGM.setGVProperties(VTable, RD);
921
922 CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
923
924 if (UsingRelativeLayout && !VTable->isDSOLocal())
925 GenerateRelativeVTableAlias(VTable, OutName);
926
927 return VTable;
928 }
929
930 // If the VTable is not dso_local, then we will not be able to indicate that
931 // the VTable does not need a relocation and move into rodata. A frequent
932 // time this can occur is for classes that should be made public from a DSO
933 // (like in libc++). For cases like these, we can make the vtable hidden or
934 // private and create a public alias with the same visibility and linkage as
935 // the original vtable type.
GenerateRelativeVTableAlias(llvm::GlobalVariable * VTable,llvm::StringRef AliasNameRef)936 void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
937 llvm::StringRef AliasNameRef) {
938 assert(getItaniumVTableContext().isRelativeLayout() &&
939 "Can only use this if the relative vtable ABI is used");
940 assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
941 "not guaranteed to be dso_local");
942
943 // If the vtable is available_externally, we shouldn't (or need to) generate
944 // an alias for it in the first place since the vtable won't actually by
945 // emitted in this compilation unit.
946 if (VTable->hasAvailableExternallyLinkage())
947 return;
948
949 // Create a new string in the event the alias is already the name of the
950 // vtable. Using the reference directly could lead to use of an inititialized
951 // value in the module's StringMap.
952 llvm::SmallString<256> AliasName(AliasNameRef);
953 VTable->setName(AliasName + ".local");
954
955 auto Linkage = VTable->getLinkage();
956 assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
957 "Invalid vtable alias linkage");
958
959 llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
960 if (!VTableAlias) {
961 VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
962 VTable->getAddressSpace(), Linkage,
963 AliasName, &CGM.getModule());
964 } else {
965 assert(VTableAlias->getValueType() == VTable->getValueType());
966 assert(VTableAlias->getLinkage() == Linkage);
967 }
968 VTableAlias->setVisibility(VTable->getVisibility());
969 VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
970
971 // Both of these imply dso_local for the vtable.
972 if (!VTable->hasComdat()) {
973 // If this is in a comdat, then we shouldn't make the linkage private due to
974 // an issue in lld where private symbols can be used as the key symbol when
975 // choosing the prevelant group. This leads to "relocation refers to a
976 // symbol in a discarded section".
977 VTable->setLinkage(llvm::GlobalValue::PrivateLinkage);
978 } else {
979 // We should at least make this hidden since we don't want to expose it.
980 VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
981 }
982
983 VTableAlias->setAliasee(VTable);
984 }
985
shouldEmitAvailableExternallyVTable(const CodeGenModule & CGM,const CXXRecordDecl * RD)986 static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
987 const CXXRecordDecl *RD) {
988 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
989 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
990 }
991
992 /// Compute the required linkage of the vtable for the given class.
993 ///
994 /// Note that we only call this at the end of the translation unit.
995 llvm::GlobalVariable::LinkageTypes
getVTableLinkage(const CXXRecordDecl * RD)996 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
997 if (!RD->isExternallyVisible())
998 return llvm::GlobalVariable::InternalLinkage;
999
1000 // We're at the end of the translation unit, so the current key
1001 // function is fully correct.
1002 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
1003 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
1004 // If this class has a key function, use that to determine the
1005 // linkage of the vtable.
1006 const FunctionDecl *def = nullptr;
1007 if (keyFunction->hasBody(def))
1008 keyFunction = cast<CXXMethodDecl>(def);
1009
1010 switch (keyFunction->getTemplateSpecializationKind()) {
1011 case TSK_Undeclared:
1012 case TSK_ExplicitSpecialization:
1013 assert((def || CodeGenOpts.OptimizationLevel > 0 ||
1014 CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
1015 "Shouldn't query vtable linkage without key function, "
1016 "optimizations, or debug info");
1017 if (!def && CodeGenOpts.OptimizationLevel > 0)
1018 return llvm::GlobalVariable::AvailableExternallyLinkage;
1019
1020 if (keyFunction->isInlined())
1021 return !Context.getLangOpts().AppleKext ?
1022 llvm::GlobalVariable::LinkOnceODRLinkage :
1023 llvm::Function::InternalLinkage;
1024
1025 return llvm::GlobalVariable::ExternalLinkage;
1026
1027 case TSK_ImplicitInstantiation:
1028 return !Context.getLangOpts().AppleKext ?
1029 llvm::GlobalVariable::LinkOnceODRLinkage :
1030 llvm::Function::InternalLinkage;
1031
1032 case TSK_ExplicitInstantiationDefinition:
1033 return !Context.getLangOpts().AppleKext ?
1034 llvm::GlobalVariable::WeakODRLinkage :
1035 llvm::Function::InternalLinkage;
1036
1037 case TSK_ExplicitInstantiationDeclaration:
1038 llvm_unreachable("Should not have been asked to emit this");
1039 }
1040 }
1041
1042 // -fapple-kext mode does not support weak linkage, so we must use
1043 // internal linkage.
1044 if (Context.getLangOpts().AppleKext)
1045 return llvm::Function::InternalLinkage;
1046
1047 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1048 llvm::GlobalValue::LinkOnceODRLinkage;
1049 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1050 llvm::GlobalValue::WeakODRLinkage;
1051 if (RD->hasAttr<DLLExportAttr>()) {
1052 // Cannot discard exported vtables.
1053 DiscardableODRLinkage = NonDiscardableODRLinkage;
1054 } else if (RD->hasAttr<DLLImportAttr>()) {
1055 // Imported vtables are available externally.
1056 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1057 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1058 }
1059
1060 switch (RD->getTemplateSpecializationKind()) {
1061 case TSK_Undeclared:
1062 case TSK_ExplicitSpecialization:
1063 case TSK_ImplicitInstantiation:
1064 return DiscardableODRLinkage;
1065
1066 case TSK_ExplicitInstantiationDeclaration:
1067 // Explicit instantiations in MSVC do not provide vtables, so we must emit
1068 // our own.
1069 if (getTarget().getCXXABI().isMicrosoft())
1070 return DiscardableODRLinkage;
1071 return shouldEmitAvailableExternallyVTable(*this, RD)
1072 ? llvm::GlobalVariable::AvailableExternallyLinkage
1073 : llvm::GlobalVariable::ExternalLinkage;
1074
1075 case TSK_ExplicitInstantiationDefinition:
1076 return NonDiscardableODRLinkage;
1077 }
1078
1079 llvm_unreachable("Invalid TemplateSpecializationKind!");
1080 }
1081
1082 /// This is a callback from Sema to tell us that a particular vtable is
1083 /// required to be emitted in this translation unit.
1084 ///
1085 /// This is only called for vtables that _must_ be emitted (mainly due to key
1086 /// functions). For weak vtables, CodeGen tracks when they are needed and
1087 /// emits them as-needed.
EmitVTable(CXXRecordDecl * theClass)1088 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
1089 VTables.GenerateClassData(theClass);
1090 }
1091
1092 void
GenerateClassData(const CXXRecordDecl * RD)1093 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
1094 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
1095 DI->completeClassData(RD);
1096
1097 if (RD->getNumVBases())
1098 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
1099
1100 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
1101 }
1102
1103 /// At this point in the translation unit, does it appear that can we
1104 /// rely on the vtable being defined elsewhere in the program?
1105 ///
1106 /// The response is really only definitive when called at the end of
1107 /// the translation unit.
1108 ///
1109 /// The only semantic restriction here is that the object file should
1110 /// not contain a vtable definition when that vtable is defined
1111 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
1112 /// vtables when unnecessary.
isVTableExternal(const CXXRecordDecl * RD)1113 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
1114 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
1115
1116 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1117 // emit them even if there is an explicit template instantiation.
1118 if (CGM.getTarget().getCXXABI().isMicrosoft())
1119 return false;
1120
1121 // If we have an explicit instantiation declaration (and not a
1122 // definition), the vtable is defined elsewhere.
1123 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1124 if (TSK == TSK_ExplicitInstantiationDeclaration)
1125 return true;
1126
1127 // Otherwise, if the class is an instantiated template, the
1128 // vtable must be defined here.
1129 if (TSK == TSK_ImplicitInstantiation ||
1130 TSK == TSK_ExplicitInstantiationDefinition)
1131 return false;
1132
1133 // Otherwise, if the class doesn't have a key function (possibly
1134 // anymore), the vtable must be defined here.
1135 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1136 if (!keyFunction)
1137 return false;
1138
1139 // Otherwise, if we don't have a definition of the key function, the
1140 // vtable must be defined somewhere else.
1141 return !keyFunction->hasBody();
1142 }
1143
1144 /// Given that we're currently at the end of the translation unit, and
1145 /// we've emitted a reference to the vtable for this class, should
1146 /// we define that vtable?
shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule & CGM,const CXXRecordDecl * RD)1147 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
1148 const CXXRecordDecl *RD) {
1149 // If vtable is internal then it has to be done.
1150 if (!CGM.getVTables().isVTableExternal(RD))
1151 return true;
1152
1153 // If it's external then maybe we will need it as available_externally.
1154 return shouldEmitAvailableExternallyVTable(CGM, RD);
1155 }
1156
1157 /// Given that at some point we emitted a reference to one or more
1158 /// vtables, and that we are now at the end of the translation unit,
1159 /// decide whether we should emit them.
EmitDeferredVTables()1160 void CodeGenModule::EmitDeferredVTables() {
1161 #ifndef NDEBUG
1162 // Remember the size of DeferredVTables, because we're going to assume
1163 // that this entire operation doesn't modify it.
1164 size_t savedSize = DeferredVTables.size();
1165 #endif
1166
1167 for (const CXXRecordDecl *RD : DeferredVTables)
1168 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
1169 VTables.GenerateClassData(RD);
1170 else if (shouldOpportunisticallyEmitVTables())
1171 OpportunisticVTables.push_back(RD);
1172
1173 assert(savedSize == DeferredVTables.size() &&
1174 "deferred extra vtables during vtable emission?");
1175 DeferredVTables.clear();
1176 }
1177
AlwaysHasLTOVisibilityPublic(const CXXRecordDecl * RD)1178 bool CodeGenModule::AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD) {
1179 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
1180 return true;
1181
1182 if (!getCodeGenOpts().LTOVisibilityPublicStd)
1183 return false;
1184
1185 const DeclContext *DC = RD;
1186 while (true) {
1187 auto *D = cast<Decl>(DC);
1188 DC = DC->getParent();
1189 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1190 if (auto *ND = dyn_cast<NamespaceDecl>(D))
1191 if (const IdentifierInfo *II = ND->getIdentifier())
1192 if (II->isStr("std") || II->isStr("stdext"))
1193 return true;
1194 break;
1195 }
1196 }
1197
1198 return false;
1199 }
1200
HasHiddenLTOVisibility(const CXXRecordDecl * RD)1201 bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1202 LinkageInfo LV = RD->getLinkageAndVisibility();
1203 if (!isExternallyVisible(LV.getLinkage()))
1204 return true;
1205
1206 if (getTriple().isOSBinFormatCOFF()) {
1207 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1208 return false;
1209 } else {
1210 if (LV.getVisibility() != HiddenVisibility)
1211 return false;
1212 }
1213
1214 return !AlwaysHasLTOVisibilityPublic(RD);
1215 }
1216
GetVCallVisibilityLevel(const CXXRecordDecl * RD,llvm::DenseSet<const CXXRecordDecl * > & Visited)1217 llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel(
1218 const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
1219 // If we have already visited this RD (which means this is a recursive call
1220 // since the initial call should have an empty Visited set), return the max
1221 // visibility. The recursive calls below compute the min between the result
1222 // of the recursive call and the current TypeVis, so returning the max here
1223 // ensures that it will have no effect on the current TypeVis.
1224 if (!Visited.insert(RD).second)
1225 return llvm::GlobalObject::VCallVisibilityTranslationUnit;
1226
1227 LinkageInfo LV = RD->getLinkageAndVisibility();
1228 llvm::GlobalObject::VCallVisibility TypeVis;
1229 if (!isExternallyVisible(LV.getLinkage()))
1230 TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1231 else if (HasHiddenLTOVisibility(RD))
1232 TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1233 else
1234 TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1235
1236 for (auto B : RD->bases())
1237 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1238 TypeVis = std::min(
1239 TypeVis,
1240 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1241
1242 for (auto B : RD->vbases())
1243 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1244 TypeVis = std::min(
1245 TypeVis,
1246 GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1247
1248 return TypeVis;
1249 }
1250
EmitVTableTypeMetadata(const CXXRecordDecl * RD,llvm::GlobalVariable * VTable,const VTableLayout & VTLayout)1251 void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1252 llvm::GlobalVariable *VTable,
1253 const VTableLayout &VTLayout) {
1254 if (!getCodeGenOpts().LTOUnit)
1255 return;
1256
1257 CharUnits PointerWidth =
1258 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1259
1260 typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1261 std::vector<AddressPoint> AddressPoints;
1262 for (auto &&AP : VTLayout.getAddressPoints())
1263 AddressPoints.push_back(std::make_pair(
1264 AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1265 AP.second.AddressPointIndex));
1266
1267 // Sort the address points for determinism.
1268 llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1269 const AddressPoint &AP2) {
1270 if (&AP1 == &AP2)
1271 return false;
1272
1273 std::string S1;
1274 llvm::raw_string_ostream O1(S1);
1275 getCXXABI().getMangleContext().mangleTypeName(
1276 QualType(AP1.first->getTypeForDecl(), 0), O1);
1277 O1.flush();
1278
1279 std::string S2;
1280 llvm::raw_string_ostream O2(S2);
1281 getCXXABI().getMangleContext().mangleTypeName(
1282 QualType(AP2.first->getTypeForDecl(), 0), O2);
1283 O2.flush();
1284
1285 if (S1 < S2)
1286 return true;
1287 if (S1 != S2)
1288 return false;
1289
1290 return AP1.second < AP2.second;
1291 });
1292
1293 ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1294 for (auto AP : AddressPoints) {
1295 // Create type metadata for the address point.
1296 AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1297
1298 // The class associated with each address point could also potentially be
1299 // used for indirect calls via a member function pointer, so we need to
1300 // annotate the address of each function pointer with the appropriate member
1301 // function pointer type.
1302 for (unsigned I = 0; I != Comps.size(); ++I) {
1303 if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1304 continue;
1305 llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1306 Context.getMemberPointerType(
1307 Comps[I].getFunctionDecl()->getType(),
1308 Context.getRecordType(AP.first).getTypePtr()));
1309 VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1310 }
1311 }
1312
1313 if (getCodeGenOpts().VirtualFunctionElimination ||
1314 getCodeGenOpts().WholeProgramVTables) {
1315 llvm::DenseSet<const CXXRecordDecl *> Visited;
1316 llvm::GlobalObject::VCallVisibility TypeVis =
1317 GetVCallVisibilityLevel(RD, Visited);
1318 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1319 VTable->setVCallVisibilityMetadata(TypeVis);
1320 }
1321 }
1322