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 
31 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32     : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
33 
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 
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
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 
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(CGF,
94                                             Address(ReturnValue, ClassAlign),
95                                             Thunk.Return);
96 
97   if (NullCheckValue) {
98     CGF.Builder.CreateBr(AdjustEnd);
99     CGF.EmitBlock(AdjustNull);
100     CGF.Builder.CreateBr(AdjustEnd);
101     CGF.EmitBlock(AdjustEnd);
102 
103     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
104     PHI->addIncoming(ReturnValue, AdjustNotNull);
105     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
106                      AdjustNull);
107     ReturnValue = PHI;
108   }
109 
110   return RValue::get(ReturnValue);
111 }
112 
113 /// 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.
118 static 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::DbgVariableIntrinsic>(&I)) {
132         auto *DILocal = DII->getVariable();
133         if (!DILocal->isResolved())
134           DILocal->resolve();
135       }
136     }
137   }
138 }
139 
140 // 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.
156 llvm::Function *
157 CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
158                                       const CGFunctionInfo &FnInfo,
159                                       GlobalDecl GD, const ThunkInfo &Thunk) {
160   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
161   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
162   QualType ResultType = FPT->getReturnType();
163 
164   // Get the original function
165   assert(FnInfo.isVariadic());
166   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
167   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
168   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
169 
170   // Cloning can't work if we don't have a definition. The Microsoft ABI may
171   // require thunks when a definition is not available. Emit an error in these
172   // cases.
173   if (!MD->isDefined()) {
174     CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
175     return Fn;
176   }
177   assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
178 
179   // Clone to thunk.
180   llvm::ValueToValueMapTy VMap;
181 
182   // We are cloning a function while some Metadata nodes are still unresolved.
183   // Ensure that the value mapper does not encounter any of them.
184   resolveTopLevelMetadata(BaseFn, VMap);
185   llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
186   Fn->replaceAllUsesWith(NewFn);
187   NewFn->takeName(Fn);
188   Fn->eraseFromParent();
189   Fn = NewFn;
190 
191   // "Initialize" CGF (minimally).
192   CurFn = Fn;
193 
194   // Get the "this" value
195   llvm::Function::arg_iterator AI = Fn->arg_begin();
196   if (CGM.ReturnTypeUsesSRet(FnInfo))
197     ++AI;
198 
199   // Find the first store of "this", which will be to the alloca associated
200   // with "this".
201   Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
202   llvm::BasicBlock *EntryBB = &Fn->front();
203   llvm::BasicBlock::iterator ThisStore =
204       std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
205         return isa<llvm::StoreInst>(I) &&
206                I.getOperand(0) == ThisPtr.getPointer();
207       });
208   assert(ThisStore != EntryBB->end() &&
209          "Store of this should be in entry block?");
210   // Adjust "this", if necessary.
211   Builder.SetInsertPoint(&*ThisStore);
212   llvm::Value *AdjustedThisPtr =
213       CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
214   AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
215                                           ThisStore->getOperand(0)->getType());
216   ThisStore->setOperand(0, AdjustedThisPtr);
217 
218   if (!Thunk.Return.isEmpty()) {
219     // Fix up the returned value, if necessary.
220     for (llvm::BasicBlock &BB : *Fn) {
221       llvm::Instruction *T = BB.getTerminator();
222       if (isa<llvm::ReturnInst>(T)) {
223         RValue RV = RValue::get(T->getOperand(0));
224         T->eraseFromParent();
225         Builder.SetInsertPoint(&BB);
226         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
227         Builder.CreateRet(RV.getScalarVal());
228         break;
229       }
230     }
231   }
232 
233   return Fn;
234 }
235 
236 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
237                                  const CGFunctionInfo &FnInfo,
238                                  bool IsUnprototyped) {
239   assert(!CurGD.getDecl() && "CurGD was already set!");
240   CurGD = GD;
241   CurFuncIsThunk = true;
242 
243   // Build FunctionArgs.
244   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
245   QualType ThisType = MD->getThisType();
246   QualType ResultType;
247   if (IsUnprototyped)
248     ResultType = CGM.getContext().VoidTy;
249   else if (CGM.getCXXABI().HasThisReturn(GD))
250     ResultType = ThisType;
251   else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
252     ResultType = CGM.getContext().VoidPtrTy;
253   else
254     ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
255   FunctionArgList FunctionArgs;
256 
257   // Create the implicit 'this' parameter declaration.
258   CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
259 
260   // Add the rest of the parameters, if we have a prototype to work with.
261   if (!IsUnprototyped) {
262     FunctionArgs.append(MD->param_begin(), MD->param_end());
263 
264     if (isa<CXXDestructorDecl>(MD))
265       CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
266                                                 FunctionArgs);
267   }
268 
269   // Start defining the function.
270   auto NL = ApplyDebugLocation::CreateEmpty(*this);
271   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
272                 MD->getLocation());
273   // Create a scope with an artificial location for the body of this function.
274   auto AL = ApplyDebugLocation::CreateArtificial(*this);
275 
276   // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
277   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
278   CXXThisValue = CXXABIThisValue;
279   CurCodeDecl = MD;
280   CurFuncDecl = MD;
281 }
282 
283 void CodeGenFunction::FinishThunk() {
284   // Clear these to restore the invariants expected by
285   // StartFunction/FinishFunction.
286   CurCodeDecl = nullptr;
287   CurFuncDecl = nullptr;
288 
289   FinishFunction();
290 }
291 
292 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
293                                                 const ThunkInfo *Thunk,
294                                                 bool IsUnprototyped) {
295   assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
296          "Please use a new CGF for this thunk");
297   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
298 
299   // Adjust the 'this' pointer if necessary
300   llvm::Value *AdjustedThisPtr =
301     Thunk ? CGM.getCXXABI().performThisAdjustment(
302                           *this, LoadCXXThisAddress(), Thunk->This)
303           : LoadCXXThis();
304 
305   // If perfect forwarding is required a variadic method, a method using
306   // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
307   // thunk requires a return adjustment, since that is impossible with musttail.
308   if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
309     if (Thunk && !Thunk->Return.isEmpty()) {
310       if (IsUnprototyped)
311         CGM.ErrorUnsupported(
312             MD, "return-adjusting thunk with incomplete parameter type");
313       else if (CurFnInfo->isVariadic())
314         llvm_unreachable("shouldn't try to emit musttail return-adjusting "
315                          "thunks for variadic functions");
316       else
317         CGM.ErrorUnsupported(
318             MD, "non-trivial argument copy for return-adjusting thunk");
319     }
320     EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
321     return;
322   }
323 
324   // Start building CallArgs.
325   CallArgList CallArgs;
326   QualType ThisType = MD->getThisType();
327   CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
328 
329   if (isa<CXXDestructorDecl>(MD))
330     CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
331 
332 #ifndef NDEBUG
333   unsigned PrefixArgs = CallArgs.size() - 1;
334 #endif
335   // Add the rest of the arguments.
336   for (const ParmVarDecl *PD : MD->parameters())
337     EmitDelegateCallArg(CallArgs, PD, SourceLocation());
338 
339   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
340 
341 #ifndef NDEBUG
342   const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
343       CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
344   assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
345          CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
346          CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
347   assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
348          similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
349                  CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
350   assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
351   for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
352     assert(similar(CallFnInfo.arg_begin()[i].info,
353                    CallFnInfo.arg_begin()[i].type,
354                    CurFnInfo->arg_begin()[i].info,
355                    CurFnInfo->arg_begin()[i].type));
356 #endif
357 
358   // Determine whether we have a return value slot to use.
359   QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
360                             ? ThisType
361                             : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
362                                   ? CGM.getContext().VoidPtrTy
363                                   : FPT->getReturnType();
364   ReturnValueSlot Slot;
365   if (!ResultType->isVoidType() &&
366       CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect)
367     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
368 
369   // Now emit our call.
370   llvm::CallBase *CallOrInvoke;
371   RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
372                        CallArgs, &CallOrInvoke);
373 
374   // Consider return adjustment if we have ThunkInfo.
375   if (Thunk && !Thunk->Return.isEmpty())
376     RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
377   else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
378     Call->setTailCallKind(llvm::CallInst::TCK_Tail);
379 
380   // Emit return.
381   if (!ResultType->isVoidType() && Slot.isNull())
382     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
383 
384   // Disable the final ARC autorelease.
385   AutoreleaseResult = false;
386 
387   FinishThunk();
388 }
389 
390 void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
391                                         llvm::Value *AdjustedThisPtr,
392                                         llvm::FunctionCallee Callee) {
393   // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
394   // to translate AST arguments into LLVM IR arguments.  For thunks, we know
395   // that the caller prototype more or less matches the callee prototype with
396   // the exception of 'this'.
397   SmallVector<llvm::Value *, 8> Args;
398   for (llvm::Argument &A : CurFn->args())
399     Args.push_back(&A);
400 
401   // Set the adjusted 'this' pointer.
402   const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
403   if (ThisAI.isDirect()) {
404     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
405     int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
406     llvm::Type *ThisType = Args[ThisArgNo]->getType();
407     if (ThisType != AdjustedThisPtr->getType())
408       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
409     Args[ThisArgNo] = AdjustedThisPtr;
410   } else {
411     assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
412     Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
413     llvm::Type *ThisType = ThisAddr.getElementType();
414     if (ThisType != AdjustedThisPtr->getType())
415       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
416     Builder.CreateStore(AdjustedThisPtr, ThisAddr);
417   }
418 
419   // Emit the musttail call manually.  Even if the prologue pushed cleanups, we
420   // don't actually want to run them.
421   llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
422   Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
423 
424   // Apply the standard set of call attributes.
425   unsigned CallingConv;
426   llvm::AttributeList Attrs;
427   CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
428                              Attrs, CallingConv, /*AttrOnCallSite=*/true);
429   Call->setAttributes(Attrs);
430   Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
431 
432   if (Call->getType()->isVoidTy())
433     Builder.CreateRetVoid();
434   else
435     Builder.CreateRet(Call);
436 
437   // Finish the function to maintain CodeGenFunction invariants.
438   // FIXME: Don't emit unreachable code.
439   EmitBlock(createBasicBlock());
440 
441   FinishThunk();
442 }
443 
444 void CodeGenFunction::generateThunk(llvm::Function *Fn,
445                                     const CGFunctionInfo &FnInfo, GlobalDecl GD,
446                                     const ThunkInfo &Thunk,
447                                     bool IsUnprototyped) {
448   StartThunk(Fn, GD, FnInfo, IsUnprototyped);
449   // Create a scope with an artificial location for the body of this function.
450   auto AL = ApplyDebugLocation::CreateArtificial(*this);
451 
452   // Get our callee. Use a placeholder type if this method is unprototyped so
453   // that CodeGenModule doesn't try to set attributes.
454   llvm::Type *Ty;
455   if (IsUnprototyped)
456     Ty = llvm::StructType::get(getLLVMContext());
457   else
458     Ty = CGM.getTypes().GetFunctionType(FnInfo);
459 
460   llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
461 
462   // Fix up the function type for an unprototyped musttail call.
463   if (IsUnprototyped)
464     Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
465 
466   // Make the call and return the result.
467   EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
468                             &Thunk, IsUnprototyped);
469 }
470 
471 static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
472                                   bool IsUnprototyped, bool ForVTable) {
473   // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
474   // provide thunks for us.
475   if (CGM.getTarget().getCXXABI().isMicrosoft())
476     return true;
477 
478   // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
479   // definitions of the main method. Therefore, emitting thunks with the vtable
480   // is purely an optimization. Emit the thunk if optimizations are enabled and
481   // all of the parameter types are complete.
482   if (ForVTable)
483     return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
484 
485   // Always emit thunks along with the method definition.
486   return true;
487 }
488 
489 llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
490                                                const ThunkInfo &TI,
491                                                bool ForVTable) {
492   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
493 
494   // First, get a declaration. Compute the mangled name. Don't worry about
495   // getting the function prototype right, since we may only need this
496   // declaration to fill in a vtable slot.
497   SmallString<256> Name;
498   MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
499   llvm::raw_svector_ostream Out(Name);
500   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
501     MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
502   else
503     MCtx.mangleThunk(MD, TI, Out);
504   llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
505   llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
506 
507   // If we don't need to emit a definition, return this declaration as is.
508   bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
509       MD->getType()->castAs<FunctionType>());
510   if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
511     return Thunk;
512 
513   // Arrange a function prototype appropriate for a function definition. In some
514   // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
515   const CGFunctionInfo &FnInfo =
516       IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
517                      : CGM.getTypes().arrangeGlobalDeclaration(GD);
518   llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
519 
520   // If the type of the underlying GlobalValue is wrong, we'll have to replace
521   // it. It should be a declaration.
522   llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
523   if (ThunkFn->getFunctionType() != ThunkFnTy) {
524     llvm::GlobalValue *OldThunkFn = ThunkFn;
525 
526     assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
527 
528     // Remove the name from the old thunk function and get a new thunk.
529     OldThunkFn->setName(StringRef());
530     ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
531                                      Name.str(), &CGM.getModule());
532     CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
533 
534     // If needed, replace the old thunk with a bitcast.
535     if (!OldThunkFn->use_empty()) {
536       llvm::Constant *NewPtrForOldDecl =
537           llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
538       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
539     }
540 
541     // Remove the old thunk.
542     OldThunkFn->eraseFromParent();
543   }
544 
545   bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
546   bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
547 
548   if (!ThunkFn->isDeclaration()) {
549     if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
550       // There is already a thunk emitted for this function, do nothing.
551       return ThunkFn;
552     }
553 
554     setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
555     return ThunkFn;
556   }
557 
558   // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
559   // that the return type is meaningless. These thunks can be used to call
560   // functions with differing return types, and the caller is required to cast
561   // the prototype appropriately to extract the correct value.
562   if (IsUnprototyped)
563     ThunkFn->addFnAttr("thunk");
564 
565   CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
566 
567   // Thunks for variadic methods are special because in general variadic
568   // arguments cannot be perfectly forwarded. In the general case, clang
569   // implements such thunks by cloning the original function body. However, for
570   // thunks with no return adjustment on targets that support musttail, we can
571   // use musttail to perfectly forward the variadic arguments.
572   bool ShouldCloneVarArgs = false;
573   if (!IsUnprototyped && ThunkFn->isVarArg()) {
574     ShouldCloneVarArgs = true;
575     if (TI.Return.isEmpty()) {
576       switch (CGM.getTriple().getArch()) {
577       case llvm::Triple::x86_64:
578       case llvm::Triple::x86:
579       case llvm::Triple::aarch64:
580         ShouldCloneVarArgs = false;
581         break;
582       default:
583         break;
584       }
585     }
586   }
587 
588   if (ShouldCloneVarArgs) {
589     if (UseAvailableExternallyLinkage)
590       return ThunkFn;
591     ThunkFn =
592         CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
593   } else {
594     // Normal thunk body generation.
595     CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
596   }
597 
598   setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
599   return ThunkFn;
600 }
601 
602 void CodeGenVTables::EmitThunks(GlobalDecl GD) {
603   const CXXMethodDecl *MD =
604     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
605 
606   // We don't need to generate thunks for the base destructor.
607   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
608     return;
609 
610   const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
611       VTContext->getThunkInfo(GD);
612 
613   if (!ThunkInfoVector)
614     return;
615 
616   for (const ThunkInfo& Thunk : *ThunkInfoVector)
617     maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
618 }
619 
620 void CodeGenVTables::addVTableComponent(
621     ConstantArrayBuilder &builder, const VTableLayout &layout,
622     unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
623   auto &component = layout.vtable_components()[idx];
624 
625   auto addOffsetConstant = [&](CharUnits offset) {
626     builder.add(llvm::ConstantExpr::getIntToPtr(
627         llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
628         CGM.Int8PtrTy));
629   };
630 
631   switch (component.getKind()) {
632   case VTableComponent::CK_VCallOffset:
633     return addOffsetConstant(component.getVCallOffset());
634 
635   case VTableComponent::CK_VBaseOffset:
636     return addOffsetConstant(component.getVBaseOffset());
637 
638   case VTableComponent::CK_OffsetToTop:
639     return addOffsetConstant(component.getOffsetToTop());
640 
641   case VTableComponent::CK_RTTI:
642     return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
643 
644   case VTableComponent::CK_FunctionPointer:
645   case VTableComponent::CK_CompleteDtorPointer:
646   case VTableComponent::CK_DeletingDtorPointer: {
647     GlobalDecl GD;
648 
649     // Get the right global decl.
650     switch (component.getKind()) {
651     default:
652       llvm_unreachable("Unexpected vtable component kind");
653     case VTableComponent::CK_FunctionPointer:
654       GD = component.getFunctionDecl();
655       break;
656     case VTableComponent::CK_CompleteDtorPointer:
657       GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
658       break;
659     case VTableComponent::CK_DeletingDtorPointer:
660       GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
661       break;
662     }
663 
664     if (CGM.getLangOpts().CUDA) {
665       // Emit NULL for methods we can't codegen on this
666       // side. Otherwise we'd end up with vtable with unresolved
667       // references.
668       const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
669       // OK on device side: functions w/ __device__ attribute
670       // OK on host side: anything except __device__-only functions.
671       bool CanEmitMethod =
672           CGM.getLangOpts().CUDAIsDevice
673               ? MD->hasAttr<CUDADeviceAttr>()
674               : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
675       if (!CanEmitMethod)
676         return builder.addNullPointer(CGM.Int8PtrTy);
677       // Method is acceptable, continue processing as usual.
678     }
679 
680     auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
681       // For NVPTX devices in OpenMP emit special functon as null pointers,
682       // otherwise linking ends up with unresolved references.
683       if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsDevice &&
684           CGM.getTriple().isNVPTX())
685         return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
686       llvm::FunctionType *fnTy =
687           llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
688       llvm::Constant *fn = cast<llvm::Constant>(
689           CGM.CreateRuntimeFunction(fnTy, name).getCallee());
690       if (auto f = dyn_cast<llvm::Function>(fn))
691         f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
692       return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
693     };
694 
695     llvm::Constant *fnPtr;
696 
697     // Pure virtual member functions.
698     if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
699       if (!PureVirtualFn)
700         PureVirtualFn =
701           getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
702       fnPtr = PureVirtualFn;
703 
704     // Deleted virtual member functions.
705     } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
706       if (!DeletedVirtualFn)
707         DeletedVirtualFn =
708           getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
709       fnPtr = DeletedVirtualFn;
710 
711     // Thunks.
712     } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
713                layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
714       auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
715 
716       nextVTableThunkIndex++;
717       fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
718 
719     // Otherwise we can use the method definition directly.
720     } else {
721       llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
722       fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
723     }
724 
725     fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
726     builder.add(fnPtr);
727     return;
728   }
729 
730   case VTableComponent::CK_UnusedFunctionPointer:
731     return builder.addNullPointer(CGM.Int8PtrTy);
732   }
733 
734   llvm_unreachable("Unexpected vtable component kind");
735 }
736 
737 llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
738   SmallVector<llvm::Type *, 4> tys;
739   for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
740     tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
741   }
742 
743   return llvm::StructType::get(CGM.getLLVMContext(), tys);
744 }
745 
746 void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
747                                              const VTableLayout &layout,
748                                              llvm::Constant *rtti) {
749   unsigned nextVTableThunkIndex = 0;
750   for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
751     auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
752     size_t thisIndex = layout.getVTableOffset(i);
753     size_t nextIndex = thisIndex + layout.getVTableSize(i);
754     for (unsigned i = thisIndex; i != nextIndex; ++i) {
755       addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
756     }
757     vtableElem.finishAndAddTo(builder);
758   }
759 }
760 
761 llvm::GlobalVariable *
762 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
763                                       const BaseSubobject &Base,
764                                       bool BaseIsVirtual,
765                                    llvm::GlobalVariable::LinkageTypes Linkage,
766                                       VTableAddressPointsMapTy& AddressPoints) {
767   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
768     DI->completeClassData(Base.getBase());
769 
770   std::unique_ptr<VTableLayout> VTLayout(
771       getItaniumVTableContext().createConstructionVTableLayout(
772           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
773 
774   // Add the address points.
775   AddressPoints = VTLayout->getAddressPoints();
776 
777   // Get the mangled construction vtable name.
778   SmallString<256> OutName;
779   llvm::raw_svector_ostream Out(OutName);
780   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
781       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
782                            Base.getBase(), Out);
783   StringRef Name = OutName.str();
784 
785   llvm::Type *VTType = getVTableType(*VTLayout);
786 
787   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
788   // guarantee that they actually will be available externally. Instead, when
789   // emitting an available_externally VTT, we provide references to an internal
790   // linkage construction vtable. The ABI only requires complete-object vtables
791   // to be the same for all instances of a type, not construction vtables.
792   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
793     Linkage = llvm::GlobalVariable::InternalLinkage;
794 
795   unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
796 
797   // Create the variable that will hold the construction vtable.
798   llvm::GlobalVariable *VTable =
799       CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
800 
801   // V-tables are always unnamed_addr.
802   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
803 
804   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
805       CGM.getContext().getTagDeclType(Base.getBase()));
806 
807   // Create and set the initializer.
808   ConstantInitBuilder builder(CGM);
809   auto components = builder.beginStruct();
810   createVTableInitializer(components, *VTLayout, RTTI);
811   components.finishAndSetAsInitializer(VTable);
812 
813   // Set properties only after the initializer has been set to ensure that the
814   // GV is treated as definition and not declaration.
815   assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
816   CGM.setGVProperties(VTable, RD);
817 
818   CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
819 
820   return VTable;
821 }
822 
823 static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
824                                                 const CXXRecordDecl *RD) {
825   return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
826          CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
827 }
828 
829 /// Compute the required linkage of the vtable for the given class.
830 ///
831 /// Note that we only call this at the end of the translation unit.
832 llvm::GlobalVariable::LinkageTypes
833 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
834   if (!RD->isExternallyVisible())
835     return llvm::GlobalVariable::InternalLinkage;
836 
837   // We're at the end of the translation unit, so the current key
838   // function is fully correct.
839   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
840   if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
841     // If this class has a key function, use that to determine the
842     // linkage of the vtable.
843     const FunctionDecl *def = nullptr;
844     if (keyFunction->hasBody(def))
845       keyFunction = cast<CXXMethodDecl>(def);
846 
847     switch (keyFunction->getTemplateSpecializationKind()) {
848       case TSK_Undeclared:
849       case TSK_ExplicitSpecialization:
850         assert((def || CodeGenOpts.OptimizationLevel > 0 ||
851                 CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
852                "Shouldn't query vtable linkage without key function, "
853                "optimizations, or debug info");
854         if (!def && CodeGenOpts.OptimizationLevel > 0)
855           return llvm::GlobalVariable::AvailableExternallyLinkage;
856 
857         if (keyFunction->isInlined())
858           return !Context.getLangOpts().AppleKext ?
859                    llvm::GlobalVariable::LinkOnceODRLinkage :
860                    llvm::Function::InternalLinkage;
861 
862         return llvm::GlobalVariable::ExternalLinkage;
863 
864       case TSK_ImplicitInstantiation:
865         return !Context.getLangOpts().AppleKext ?
866                  llvm::GlobalVariable::LinkOnceODRLinkage :
867                  llvm::Function::InternalLinkage;
868 
869       case TSK_ExplicitInstantiationDefinition:
870         return !Context.getLangOpts().AppleKext ?
871                  llvm::GlobalVariable::WeakODRLinkage :
872                  llvm::Function::InternalLinkage;
873 
874       case TSK_ExplicitInstantiationDeclaration:
875         llvm_unreachable("Should not have been asked to emit this");
876     }
877   }
878 
879   // -fapple-kext mode does not support weak linkage, so we must use
880   // internal linkage.
881   if (Context.getLangOpts().AppleKext)
882     return llvm::Function::InternalLinkage;
883 
884   llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
885       llvm::GlobalValue::LinkOnceODRLinkage;
886   llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
887       llvm::GlobalValue::WeakODRLinkage;
888   if (RD->hasAttr<DLLExportAttr>()) {
889     // Cannot discard exported vtables.
890     DiscardableODRLinkage = NonDiscardableODRLinkage;
891   } else if (RD->hasAttr<DLLImportAttr>()) {
892     // Imported vtables are available externally.
893     DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
894     NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
895   }
896 
897   switch (RD->getTemplateSpecializationKind()) {
898     case TSK_Undeclared:
899     case TSK_ExplicitSpecialization:
900     case TSK_ImplicitInstantiation:
901       return DiscardableODRLinkage;
902 
903     case TSK_ExplicitInstantiationDeclaration:
904       // Explicit instantiations in MSVC do not provide vtables, so we must emit
905       // our own.
906       if (getTarget().getCXXABI().isMicrosoft())
907         return DiscardableODRLinkage;
908       return shouldEmitAvailableExternallyVTable(*this, RD)
909                  ? llvm::GlobalVariable::AvailableExternallyLinkage
910                  : llvm::GlobalVariable::ExternalLinkage;
911 
912     case TSK_ExplicitInstantiationDefinition:
913       return NonDiscardableODRLinkage;
914   }
915 
916   llvm_unreachable("Invalid TemplateSpecializationKind!");
917 }
918 
919 /// This is a callback from Sema to tell us that a particular vtable is
920 /// required to be emitted in this translation unit.
921 ///
922 /// This is only called for vtables that _must_ be emitted (mainly due to key
923 /// functions).  For weak vtables, CodeGen tracks when they are needed and
924 /// emits them as-needed.
925 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
926   VTables.GenerateClassData(theClass);
927 }
928 
929 void
930 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
931   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
932     DI->completeClassData(RD);
933 
934   if (RD->getNumVBases())
935     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
936 
937   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
938 }
939 
940 /// At this point in the translation unit, does it appear that can we
941 /// rely on the vtable being defined elsewhere in the program?
942 ///
943 /// The response is really only definitive when called at the end of
944 /// the translation unit.
945 ///
946 /// The only semantic restriction here is that the object file should
947 /// not contain a vtable definition when that vtable is defined
948 /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
949 /// vtables when unnecessary.
950 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
951   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
952 
953   // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
954   // emit them even if there is an explicit template instantiation.
955   if (CGM.getTarget().getCXXABI().isMicrosoft())
956     return false;
957 
958   // If we have an explicit instantiation declaration (and not a
959   // definition), the vtable is defined elsewhere.
960   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
961   if (TSK == TSK_ExplicitInstantiationDeclaration)
962     return true;
963 
964   // Otherwise, if the class is an instantiated template, the
965   // vtable must be defined here.
966   if (TSK == TSK_ImplicitInstantiation ||
967       TSK == TSK_ExplicitInstantiationDefinition)
968     return false;
969 
970   // Otherwise, if the class doesn't have a key function (possibly
971   // anymore), the vtable must be defined here.
972   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
973   if (!keyFunction)
974     return false;
975 
976   // Otherwise, if we don't have a definition of the key function, the
977   // vtable must be defined somewhere else.
978   return !keyFunction->hasBody();
979 }
980 
981 /// Given that we're currently at the end of the translation unit, and
982 /// we've emitted a reference to the vtable for this class, should
983 /// we define that vtable?
984 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
985                                                    const CXXRecordDecl *RD) {
986   // If vtable is internal then it has to be done.
987   if (!CGM.getVTables().isVTableExternal(RD))
988     return true;
989 
990   // If it's external then maybe we will need it as available_externally.
991   return shouldEmitAvailableExternallyVTable(CGM, RD);
992 }
993 
994 /// Given that at some point we emitted a reference to one or more
995 /// vtables, and that we are now at the end of the translation unit,
996 /// decide whether we should emit them.
997 void CodeGenModule::EmitDeferredVTables() {
998 #ifndef NDEBUG
999   // Remember the size of DeferredVTables, because we're going to assume
1000   // that this entire operation doesn't modify it.
1001   size_t savedSize = DeferredVTables.size();
1002 #endif
1003 
1004   for (const CXXRecordDecl *RD : DeferredVTables)
1005     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
1006       VTables.GenerateClassData(RD);
1007     else if (shouldOpportunisticallyEmitVTables())
1008       OpportunisticVTables.push_back(RD);
1009 
1010   assert(savedSize == DeferredVTables.size() &&
1011          "deferred extra vtables during vtable emission?");
1012   DeferredVTables.clear();
1013 }
1014 
1015 bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1016   LinkageInfo LV = RD->getLinkageAndVisibility();
1017   if (!isExternallyVisible(LV.getLinkage()))
1018     return true;
1019 
1020   if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
1021     return false;
1022 
1023   if (getTriple().isOSBinFormatCOFF()) {
1024     if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1025       return false;
1026   } else {
1027     if (LV.getVisibility() != HiddenVisibility)
1028       return false;
1029   }
1030 
1031   if (getCodeGenOpts().LTOVisibilityPublicStd) {
1032     const DeclContext *DC = RD;
1033     while (1) {
1034       auto *D = cast<Decl>(DC);
1035       DC = DC->getParent();
1036       if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1037         if (auto *ND = dyn_cast<NamespaceDecl>(D))
1038           if (const IdentifierInfo *II = ND->getIdentifier())
1039             if (II->isStr("std") || II->isStr("stdext"))
1040               return false;
1041         break;
1042       }
1043     }
1044   }
1045 
1046   return true;
1047 }
1048 
1049 llvm::GlobalObject::VCallVisibility
1050 CodeGenModule::GetVCallVisibilityLevel(const CXXRecordDecl *RD) {
1051   LinkageInfo LV = RD->getLinkageAndVisibility();
1052   llvm::GlobalObject::VCallVisibility TypeVis;
1053   if (!isExternallyVisible(LV.getLinkage()))
1054     TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1055   else if (HasHiddenLTOVisibility(RD))
1056     TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1057   else
1058     TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1059 
1060   for (auto B : RD->bases())
1061     if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1062       TypeVis = std::min(TypeVis,
1063                     GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1064 
1065   for (auto B : RD->vbases())
1066     if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1067       TypeVis = std::min(TypeVis,
1068                     GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1069 
1070   return TypeVis;
1071 }
1072 
1073 void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1074                                            llvm::GlobalVariable *VTable,
1075                                            const VTableLayout &VTLayout) {
1076   if (!getCodeGenOpts().LTOUnit)
1077     return;
1078 
1079   CharUnits PointerWidth =
1080       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1081 
1082   typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1083   std::vector<AddressPoint> AddressPoints;
1084   for (auto &&AP : VTLayout.getAddressPoints())
1085     AddressPoints.push_back(std::make_pair(
1086         AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1087                                 AP.second.AddressPointIndex));
1088 
1089   // Sort the address points for determinism.
1090   llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1091                                    const AddressPoint &AP2) {
1092     if (&AP1 == &AP2)
1093       return false;
1094 
1095     std::string S1;
1096     llvm::raw_string_ostream O1(S1);
1097     getCXXABI().getMangleContext().mangleTypeName(
1098         QualType(AP1.first->getTypeForDecl(), 0), O1);
1099     O1.flush();
1100 
1101     std::string S2;
1102     llvm::raw_string_ostream O2(S2);
1103     getCXXABI().getMangleContext().mangleTypeName(
1104         QualType(AP2.first->getTypeForDecl(), 0), O2);
1105     O2.flush();
1106 
1107     if (S1 < S2)
1108       return true;
1109     if (S1 != S2)
1110       return false;
1111 
1112     return AP1.second < AP2.second;
1113   });
1114 
1115   ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1116   for (auto AP : AddressPoints) {
1117     // Create type metadata for the address point.
1118     AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1119 
1120     // The class associated with each address point could also potentially be
1121     // used for indirect calls via a member function pointer, so we need to
1122     // annotate the address of each function pointer with the appropriate member
1123     // function pointer type.
1124     for (unsigned I = 0; I != Comps.size(); ++I) {
1125       if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1126         continue;
1127       llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1128           Context.getMemberPointerType(
1129               Comps[I].getFunctionDecl()->getType(),
1130               Context.getRecordType(AP.first).getTypePtr()));
1131       VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1132     }
1133   }
1134 
1135   if (getCodeGenOpts().VirtualFunctionElimination) {
1136     llvm::GlobalObject::VCallVisibility TypeVis = GetVCallVisibilityLevel(RD);
1137     if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1138       VTable->addVCallVisibilityMetadata(TypeVis);
1139   }
1140 }
1141