1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with C++ code generation of virtual tables.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGCXXABI.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/CodeGen/CGFunctionInfo.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Transforms/Utils/Cloning.h"
23 #include <algorithm>
24 #include <cstdio>
25 
26 using namespace clang;
27 using namespace CodeGen;
28 
29 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
30     : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
31 
32 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
33                                               const ThunkInfo &Thunk) {
34   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
35 
36   // Compute the mangled name.
37   SmallString<256> Name;
38   llvm::raw_svector_ostream Out(Name);
39   if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
40     getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
41                                                       Thunk.This, Out);
42   else
43     getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
44 
45   llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
46   return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
47                                  /*DontDefer=*/true, /*IsThunk=*/true);
48 }
49 
50 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
51                                const ThunkInfo &Thunk, llvm::Function *Fn) {
52   CGM.setGlobalVisibility(Fn, MD);
53 }
54 
55 static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
56                                llvm::Function *ThunkFn, bool ForVTable,
57                                GlobalDecl GD) {
58   CGM.setFunctionLinkage(GD, ThunkFn);
59   CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
60                                   !Thunk.Return.isEmpty());
61 
62   // Set the right visibility.
63   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
64   setThunkVisibility(CGM, MD, Thunk, ThunkFn);
65 
66   if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
67     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
68 }
69 
70 #ifndef NDEBUG
71 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
72                     const ABIArgInfo &infoR, CanQualType typeR) {
73   return (infoL.getKind() == infoR.getKind() &&
74           (typeL == typeR ||
75            (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
76            (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
77 }
78 #endif
79 
80 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
81                                       QualType ResultType, RValue RV,
82                                       const ThunkInfo &Thunk) {
83   // Emit the return adjustment.
84   bool NullCheckValue = !ResultType->isReferenceType();
85 
86   llvm::BasicBlock *AdjustNull = nullptr;
87   llvm::BasicBlock *AdjustNotNull = nullptr;
88   llvm::BasicBlock *AdjustEnd = nullptr;
89 
90   llvm::Value *ReturnValue = RV.getScalarVal();
91 
92   if (NullCheckValue) {
93     AdjustNull = CGF.createBasicBlock("adjust.null");
94     AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
95     AdjustEnd = CGF.createBasicBlock("adjust.end");
96 
97     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
98     CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
99     CGF.EmitBlock(AdjustNotNull);
100   }
101 
102   auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
103   auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
104   ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
105                                             Address(ReturnValue, ClassAlign),
106                                             Thunk.Return);
107 
108   if (NullCheckValue) {
109     CGF.Builder.CreateBr(AdjustEnd);
110     CGF.EmitBlock(AdjustNull);
111     CGF.Builder.CreateBr(AdjustEnd);
112     CGF.EmitBlock(AdjustEnd);
113 
114     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
115     PHI->addIncoming(ReturnValue, AdjustNotNull);
116     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
117                      AdjustNull);
118     ReturnValue = PHI;
119   }
120 
121   return RValue::get(ReturnValue);
122 }
123 
124 // This function does roughly the same thing as GenerateThunk, but in a
125 // very different way, so that va_start and va_end work correctly.
126 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
127 //        a function, and that there is an alloca built in the entry block
128 //        for all accesses to "this".
129 // FIXME: This function assumes there is only one "ret" statement per function.
130 // FIXME: Cloning isn't correct in the presence of indirect goto!
131 // FIXME: This implementation of thunks bloats codesize by duplicating the
132 //        function definition.  There are alternatives:
133 //        1. Add some sort of stub support to LLVM for cases where we can
134 //           do a this adjustment, then a sibcall.
135 //        2. We could transform the definition to take a va_list instead of an
136 //           actual variable argument list, then have the thunks (including a
137 //           no-op thunk for the regular definition) call va_start/va_end.
138 //           There's a bit of per-call overhead for this solution, but it's
139 //           better for codesize if the definition is long.
140 llvm::Function *
141 CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
142                                       const CGFunctionInfo &FnInfo,
143                                       GlobalDecl GD, const ThunkInfo &Thunk) {
144   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
145   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
146   QualType ResultType = FPT->getReturnType();
147 
148   // Get the original function
149   assert(FnInfo.isVariadic());
150   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
151   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
152   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
153 
154   // Clone to thunk.
155   llvm::ValueToValueMapTy VMap;
156   llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
157   Fn->replaceAllUsesWith(NewFn);
158   NewFn->takeName(Fn);
159   Fn->eraseFromParent();
160   Fn = NewFn;
161 
162   // "Initialize" CGF (minimally).
163   CurFn = Fn;
164 
165   // Get the "this" value
166   llvm::Function::arg_iterator AI = Fn->arg_begin();
167   if (CGM.ReturnTypeUsesSRet(FnInfo))
168     ++AI;
169 
170   // Find the first store of "this", which will be to the alloca associated
171   // with "this".
172   Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
173   llvm::BasicBlock *EntryBB = &Fn->front();
174   llvm::BasicBlock::iterator ThisStore =
175       std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
176         return isa<llvm::StoreInst>(I) &&
177                I.getOperand(0) == ThisPtr.getPointer();
178       });
179   assert(ThisStore != EntryBB->end() &&
180          "Store of this should be in entry block?");
181   // Adjust "this", if necessary.
182   Builder.SetInsertPoint(&*ThisStore);
183   llvm::Value *AdjustedThisPtr =
184       CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
185   ThisStore->setOperand(0, AdjustedThisPtr);
186 
187   if (!Thunk.Return.isEmpty()) {
188     // Fix up the returned value, if necessary.
189     for (llvm::BasicBlock &BB : *Fn) {
190       llvm::Instruction *T = BB.getTerminator();
191       if (isa<llvm::ReturnInst>(T)) {
192         RValue RV = RValue::get(T->getOperand(0));
193         T->eraseFromParent();
194         Builder.SetInsertPoint(&BB);
195         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
196         Builder.CreateRet(RV.getScalarVal());
197         break;
198       }
199     }
200   }
201 
202   return Fn;
203 }
204 
205 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
206                                  const CGFunctionInfo &FnInfo) {
207   assert(!CurGD.getDecl() && "CurGD was already set!");
208   CurGD = GD;
209   CurFuncIsThunk = true;
210 
211   // Build FunctionArgs.
212   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
213   QualType ThisType = MD->getThisType(getContext());
214   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
215   QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
216                             ? ThisType
217                             : CGM.getCXXABI().hasMostDerivedReturn(GD)
218                                   ? CGM.getContext().VoidPtrTy
219                                   : FPT->getReturnType();
220   FunctionArgList FunctionArgs;
221 
222   // Create the implicit 'this' parameter declaration.
223   CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
224 
225   // Add the rest of the parameters.
226   FunctionArgs.append(MD->param_begin(), MD->param_end());
227 
228   if (isa<CXXDestructorDecl>(MD))
229     CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
230 
231   // Start defining the function.
232   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
233                 MD->getLocation(), MD->getLocation());
234 
235   // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
236   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
237   CXXThisValue = CXXABIThisValue;
238   CurCodeDecl = MD;
239   CurFuncDecl = MD;
240 }
241 
242 void CodeGenFunction::FinishThunk() {
243   // Clear these to restore the invariants expected by
244   // StartFunction/FinishFunction.
245   CurCodeDecl = nullptr;
246   CurFuncDecl = nullptr;
247 
248   FinishFunction();
249 }
250 
251 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
252                                                 const ThunkInfo *Thunk) {
253   assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
254          "Please use a new CGF for this thunk");
255   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
256 
257   // Adjust the 'this' pointer if necessary
258   llvm::Value *AdjustedThisPtr =
259     Thunk ? CGM.getCXXABI().performThisAdjustment(
260                           *this, LoadCXXThisAddress(), Thunk->This)
261           : LoadCXXThis();
262 
263   if (CurFnInfo->usesInAlloca()) {
264     // We don't handle return adjusting thunks, because they require us to call
265     // the copy constructor.  For now, fall through and pretend the return
266     // adjustment was empty so we don't crash.
267     if (Thunk && !Thunk->Return.isEmpty()) {
268       CGM.ErrorUnsupported(
269           MD, "non-trivial argument copy for return-adjusting thunk");
270     }
271     EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
272     return;
273   }
274 
275   // Start building CallArgs.
276   CallArgList CallArgs;
277   QualType ThisType = MD->getThisType(getContext());
278   CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
279 
280   if (isa<CXXDestructorDecl>(MD))
281     CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
282 
283   // Add the rest of the arguments.
284   for (const ParmVarDecl *PD : MD->parameters())
285     EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
286 
287   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
288 
289 #ifndef NDEBUG
290   const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
291       CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD));
292   assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
293          CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
294          CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
295   assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
296          similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
297                  CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
298   assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
299   for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
300     assert(similar(CallFnInfo.arg_begin()[i].info,
301                    CallFnInfo.arg_begin()[i].type,
302                    CurFnInfo->arg_begin()[i].info,
303                    CurFnInfo->arg_begin()[i].type));
304 #endif
305 
306   // Determine whether we have a return value slot to use.
307   QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
308                             ? ThisType
309                             : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
310                                   ? CGM.getContext().VoidPtrTy
311                                   : FPT->getReturnType();
312   ReturnValueSlot Slot;
313   if (!ResultType->isVoidType() &&
314       CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
315       !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
316     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
317 
318   // Now emit our call.
319   llvm::Instruction *CallOrInvoke;
320   RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
321 
322   // Consider return adjustment if we have ThunkInfo.
323   if (Thunk && !Thunk->Return.isEmpty())
324     RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
325   else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
326     Call->setTailCallKind(llvm::CallInst::TCK_Tail);
327 
328   // Emit return.
329   if (!ResultType->isVoidType() && Slot.isNull())
330     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
331 
332   // Disable the final ARC autorelease.
333   AutoreleaseResult = false;
334 
335   FinishThunk();
336 }
337 
338 void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
339                                         llvm::Value *AdjustedThisPtr,
340                                         llvm::Value *Callee) {
341   // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
342   // to translate AST arguments into LLVM IR arguments.  For thunks, we know
343   // that the caller prototype more or less matches the callee prototype with
344   // the exception of 'this'.
345   SmallVector<llvm::Value *, 8> Args;
346   for (llvm::Argument &A : CurFn->args())
347     Args.push_back(&A);
348 
349   // Set the adjusted 'this' pointer.
350   const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
351   if (ThisAI.isDirect()) {
352     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
353     int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
354     llvm::Type *ThisType = Args[ThisArgNo]->getType();
355     if (ThisType != AdjustedThisPtr->getType())
356       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
357     Args[ThisArgNo] = AdjustedThisPtr;
358   } else {
359     assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
360     Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
361     llvm::Type *ThisType = ThisAddr.getElementType();
362     if (ThisType != AdjustedThisPtr->getType())
363       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
364     Builder.CreateStore(AdjustedThisPtr, ThisAddr);
365   }
366 
367   // Emit the musttail call manually.  Even if the prologue pushed cleanups, we
368   // don't actually want to run them.
369   llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
370   Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
371 
372   // Apply the standard set of call attributes.
373   unsigned CallingConv;
374   CodeGen::AttributeListType AttributeList;
375   CGM.ConstructAttributeList(Callee->getName(), *CurFnInfo, MD, AttributeList,
376                              CallingConv, /*AttrOnCallSite=*/true);
377   llvm::AttributeSet Attrs =
378       llvm::AttributeSet::get(getLLVMContext(), AttributeList);
379   Call->setAttributes(Attrs);
380   Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
381 
382   if (Call->getType()->isVoidTy())
383     Builder.CreateRetVoid();
384   else
385     Builder.CreateRet(Call);
386 
387   // Finish the function to maintain CodeGenFunction invariants.
388   // FIXME: Don't emit unreachable code.
389   EmitBlock(createBasicBlock());
390   FinishFunction();
391 }
392 
393 void CodeGenFunction::generateThunk(llvm::Function *Fn,
394                                     const CGFunctionInfo &FnInfo,
395                                     GlobalDecl GD, const ThunkInfo &Thunk) {
396   StartThunk(Fn, GD, FnInfo);
397 
398   // Get our callee.
399   llvm::Type *Ty =
400     CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
401   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
402 
403   // Make the call and return the result.
404   EmitCallAndReturnForThunk(Callee, &Thunk);
405 }
406 
407 void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
408                                bool ForVTable) {
409   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
410 
411   // FIXME: re-use FnInfo in this computation.
412   llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
413   llvm::GlobalValue *Entry;
414 
415   // Strip off a bitcast if we got one back.
416   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
417     assert(CE->getOpcode() == llvm::Instruction::BitCast);
418     Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
419   } else {
420     Entry = cast<llvm::GlobalValue>(C);
421   }
422 
423   // There's already a declaration with the same name, check if it has the same
424   // type or if we need to replace it.
425   if (Entry->getType()->getElementType() !=
426       CGM.getTypes().GetFunctionTypeForVTable(GD)) {
427     llvm::GlobalValue *OldThunkFn = Entry;
428 
429     // If the types mismatch then we have to rewrite the definition.
430     assert(OldThunkFn->isDeclaration() &&
431            "Shouldn't replace non-declaration");
432 
433     // Remove the name from the old thunk function and get a new thunk.
434     OldThunkFn->setName(StringRef());
435     Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
436 
437     // If needed, replace the old thunk with a bitcast.
438     if (!OldThunkFn->use_empty()) {
439       llvm::Constant *NewPtrForOldDecl =
440         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
441       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
442     }
443 
444     // Remove the old thunk.
445     OldThunkFn->eraseFromParent();
446   }
447 
448   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
449   bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
450   bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
451 
452   if (!ThunkFn->isDeclaration()) {
453     if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
454       // There is already a thunk emitted for this function, do nothing.
455       return;
456     }
457 
458     setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
459     return;
460   }
461 
462   CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
463 
464   if (ThunkFn->isVarArg()) {
465     // Varargs thunks are special; we can't just generate a call because
466     // we can't copy the varargs.  Our implementation is rather
467     // expensive/sucky at the moment, so don't generate the thunk unless
468     // we have to.
469     // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
470     if (UseAvailableExternallyLinkage)
471       return;
472     ThunkFn =
473         CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
474   } else {
475     // Normal thunk body generation.
476     CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
477   }
478 
479   setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
480 }
481 
482 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
483                                              const ThunkInfo &Thunk) {
484   // If the ABI has key functions, only the TU with the key function should emit
485   // the thunk. However, we can allow inlining of thunks if we emit them with
486   // available_externally linkage together with vtables when optimizations are
487   // enabled.
488   if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
489       !CGM.getCodeGenOpts().OptimizationLevel)
490     return;
491 
492   // We can't emit thunks for member functions with incomplete types.
493   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
494   if (!CGM.getTypes().isFuncTypeConvertible(
495            MD->getType()->castAs<FunctionType>()))
496     return;
497 
498   emitThunk(GD, Thunk, /*ForVTable=*/true);
499 }
500 
501 void CodeGenVTables::EmitThunks(GlobalDecl GD)
502 {
503   const CXXMethodDecl *MD =
504     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
505 
506   // We don't need to generate thunks for the base destructor.
507   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
508     return;
509 
510   const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
511       VTContext->getThunkInfo(GD);
512 
513   if (!ThunkInfoVector)
514     return;
515 
516   for (const ThunkInfo& Thunk : *ThunkInfoVector)
517     emitThunk(GD, Thunk, /*ForVTable=*/false);
518 }
519 
520 llvm::Constant *CodeGenVTables::CreateVTableComponent(
521     unsigned Idx, const VTableLayout &VTLayout, llvm::Constant *RTTI,
522     unsigned &NextVTableThunkIndex) {
523   VTableComponent Component = VTLayout.vtable_components()[Idx];
524 
525   auto OffsetConstant = [&](CharUnits Offset) {
526     return llvm::ConstantExpr::getIntToPtr(
527         llvm::ConstantInt::get(CGM.PtrDiffTy, Offset.getQuantity()),
528         CGM.Int8PtrTy);
529   };
530 
531   switch (Component.getKind()) {
532   case VTableComponent::CK_VCallOffset:
533     return OffsetConstant(Component.getVCallOffset());
534 
535   case VTableComponent::CK_VBaseOffset:
536     return OffsetConstant(Component.getVBaseOffset());
537 
538   case VTableComponent::CK_OffsetToTop:
539     return OffsetConstant(Component.getOffsetToTop());
540 
541   case VTableComponent::CK_RTTI:
542     return RTTI;
543 
544   case VTableComponent::CK_FunctionPointer:
545   case VTableComponent::CK_CompleteDtorPointer:
546   case VTableComponent::CK_DeletingDtorPointer: {
547     GlobalDecl GD;
548 
549     // Get the right global decl.
550     switch (Component.getKind()) {
551     default:
552       llvm_unreachable("Unexpected vtable component kind");
553     case VTableComponent::CK_FunctionPointer:
554       GD = Component.getFunctionDecl();
555       break;
556     case VTableComponent::CK_CompleteDtorPointer:
557       GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
558       break;
559     case VTableComponent::CK_DeletingDtorPointer:
560       GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
561       break;
562     }
563 
564     if (CGM.getLangOpts().CUDA) {
565       // Emit NULL for methods we can't codegen on this
566       // side. Otherwise we'd end up with vtable with unresolved
567       // references.
568       const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
569       // OK on device side: functions w/ __device__ attribute
570       // OK on host side: anything except __device__-only functions.
571       bool CanEmitMethod =
572           CGM.getLangOpts().CUDAIsDevice
573               ? MD->hasAttr<CUDADeviceAttr>()
574               : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
575       if (!CanEmitMethod)
576         return llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy);
577       // Method is acceptable, continue processing as usual.
578     }
579 
580     auto SpecialVirtualFn = [&](llvm::Constant *&Cache, StringRef Name) {
581       if (!Cache) {
582         llvm::FunctionType *Ty =
583             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
584         Cache = CGM.CreateRuntimeFunction(Ty, Name);
585         if (auto *F = dyn_cast<llvm::Function>(Cache))
586           F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
587         Cache = llvm::ConstantExpr::getBitCast(Cache, CGM.Int8PtrTy);
588       }
589       return Cache;
590     };
591 
592     if (cast<CXXMethodDecl>(GD.getDecl())->isPure())
593       // We have a pure virtual member function.
594       return SpecialVirtualFn(PureVirtualFn,
595                               CGM.getCXXABI().GetPureVirtualCallName());
596 
597     if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted())
598       return SpecialVirtualFn(DeletedVirtualFn,
599                               CGM.getCXXABI().GetDeletedVirtualCallName());
600 
601     // Check if we should use a thunk.
602     if (NextVTableThunkIndex < VTLayout.vtable_thunks().size() &&
603         VTLayout.vtable_thunks()[NextVTableThunkIndex].first == Idx) {
604       const ThunkInfo &Thunk =
605           VTLayout.vtable_thunks()[NextVTableThunkIndex].second;
606 
607       maybeEmitThunkForVTable(GD, Thunk);
608       NextVTableThunkIndex++;
609       return CGM.GetAddrOfThunk(GD, Thunk);
610     }
611 
612     llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
613     return CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
614   }
615 
616   case VTableComponent::CK_UnusedFunctionPointer:
617     return llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy);
618   }
619 
620   llvm_unreachable("Unexpected vtable component kind");
621 }
622 
623 llvm::Constant *
624 CodeGenVTables::CreateVTableInitializer(const VTableLayout &VTLayout,
625                                         llvm::Constant *RTTI) {
626   SmallVector<llvm::Constant *, 64> Inits;
627   unsigned NextVTableThunkIndex = 0;
628 
629   for (unsigned I = 0, E = VTLayout.vtable_components().size(); I != E; ++I) {
630     llvm::Constant *Init =
631         CreateVTableComponent(I, VTLayout, RTTI, NextVTableThunkIndex);
632     Inits.push_back(llvm::ConstantExpr::getBitCast(Init, CGM.Int8PtrTy));
633   }
634 
635   llvm::ArrayType *ArrayType =
636       llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout.vtable_components().size());
637   return llvm::ConstantArray::get(ArrayType, Inits);
638 }
639 
640 llvm::GlobalVariable *
641 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
642                                       const BaseSubobject &Base,
643                                       bool BaseIsVirtual,
644                                    llvm::GlobalVariable::LinkageTypes Linkage,
645                                       VTableAddressPointsMapTy& AddressPoints) {
646   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
647     DI->completeClassData(Base.getBase());
648 
649   std::unique_ptr<VTableLayout> VTLayout(
650       getItaniumVTableContext().createConstructionVTableLayout(
651           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
652 
653   // Add the address points.
654   AddressPoints = VTLayout->getAddressPoints();
655 
656   // Get the mangled construction vtable name.
657   SmallString<256> OutName;
658   llvm::raw_svector_ostream Out(OutName);
659   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
660       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
661                            Base.getBase(), Out);
662   StringRef Name = OutName.str();
663 
664   llvm::ArrayType *ArrayType =
665       llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->vtable_components().size());
666 
667   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
668   // guarantee that they actually will be available externally. Instead, when
669   // emitting an available_externally VTT, we provide references to an internal
670   // linkage construction vtable. The ABI only requires complete-object vtables
671   // to be the same for all instances of a type, not construction vtables.
672   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
673     Linkage = llvm::GlobalVariable::InternalLinkage;
674 
675   // Create the variable that will hold the construction vtable.
676   llvm::GlobalVariable *VTable =
677     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
678   CGM.setGlobalVisibility(VTable, RD);
679 
680   // V-tables are always unnamed_addr.
681   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
682 
683   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
684       CGM.getContext().getTagDeclType(Base.getBase()));
685 
686   // Create and set the initializer.
687   llvm::Constant *Init = CreateVTableInitializer(*VTLayout, RTTI);
688   VTable->setInitializer(Init);
689 
690   CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
691 
692   return VTable;
693 }
694 
695 static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
696                                                 const CXXRecordDecl *RD) {
697   return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
698          CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
699 }
700 
701 /// Compute the required linkage of the vtable for the given class.
702 ///
703 /// Note that we only call this at the end of the translation unit.
704 llvm::GlobalVariable::LinkageTypes
705 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
706   if (!RD->isExternallyVisible())
707     return llvm::GlobalVariable::InternalLinkage;
708 
709   // We're at the end of the translation unit, so the current key
710   // function is fully correct.
711   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
712   if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
713     // If this class has a key function, use that to determine the
714     // linkage of the vtable.
715     const FunctionDecl *def = nullptr;
716     if (keyFunction->hasBody(def))
717       keyFunction = cast<CXXMethodDecl>(def);
718 
719     switch (keyFunction->getTemplateSpecializationKind()) {
720       case TSK_Undeclared:
721       case TSK_ExplicitSpecialization:
722         assert((def || CodeGenOpts.OptimizationLevel > 0) &&
723                "Shouldn't query vtable linkage without key function or "
724                "optimizations");
725         if (!def && CodeGenOpts.OptimizationLevel > 0)
726           return llvm::GlobalVariable::AvailableExternallyLinkage;
727 
728         if (keyFunction->isInlined())
729           return !Context.getLangOpts().AppleKext ?
730                    llvm::GlobalVariable::LinkOnceODRLinkage :
731                    llvm::Function::InternalLinkage;
732 
733         return llvm::GlobalVariable::ExternalLinkage;
734 
735       case TSK_ImplicitInstantiation:
736         return !Context.getLangOpts().AppleKext ?
737                  llvm::GlobalVariable::LinkOnceODRLinkage :
738                  llvm::Function::InternalLinkage;
739 
740       case TSK_ExplicitInstantiationDefinition:
741         return !Context.getLangOpts().AppleKext ?
742                  llvm::GlobalVariable::WeakODRLinkage :
743                  llvm::Function::InternalLinkage;
744 
745       case TSK_ExplicitInstantiationDeclaration:
746         llvm_unreachable("Should not have been asked to emit this");
747     }
748   }
749 
750   // -fapple-kext mode does not support weak linkage, so we must use
751   // internal linkage.
752   if (Context.getLangOpts().AppleKext)
753     return llvm::Function::InternalLinkage;
754 
755   llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
756       llvm::GlobalValue::LinkOnceODRLinkage;
757   llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
758       llvm::GlobalValue::WeakODRLinkage;
759   if (RD->hasAttr<DLLExportAttr>()) {
760     // Cannot discard exported vtables.
761     DiscardableODRLinkage = NonDiscardableODRLinkage;
762   } else if (RD->hasAttr<DLLImportAttr>()) {
763     // Imported vtables are available externally.
764     DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
765     NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
766   }
767 
768   switch (RD->getTemplateSpecializationKind()) {
769     case TSK_Undeclared:
770     case TSK_ExplicitSpecialization:
771     case TSK_ImplicitInstantiation:
772       return DiscardableODRLinkage;
773 
774     case TSK_ExplicitInstantiationDeclaration:
775       // Explicit instantiations in MSVC do not provide vtables, so we must emit
776       // our own.
777       if (getTarget().getCXXABI().isMicrosoft())
778         return DiscardableODRLinkage;
779       return shouldEmitAvailableExternallyVTable(*this, RD)
780                  ? llvm::GlobalVariable::AvailableExternallyLinkage
781                  : llvm::GlobalVariable::ExternalLinkage;
782 
783     case TSK_ExplicitInstantiationDefinition:
784       return NonDiscardableODRLinkage;
785   }
786 
787   llvm_unreachable("Invalid TemplateSpecializationKind!");
788 }
789 
790 /// This is a callback from Sema to tell us that that a particular vtable is
791 /// required to be emitted in this translation unit.
792 ///
793 /// This is only called for vtables that _must_ be emitted (mainly due to key
794 /// functions).  For weak vtables, CodeGen tracks when they are needed and
795 /// emits them as-needed.
796 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
797   VTables.GenerateClassData(theClass);
798 }
799 
800 void
801 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
802   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
803     DI->completeClassData(RD);
804 
805   if (RD->getNumVBases())
806     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
807 
808   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
809 }
810 
811 /// At this point in the translation unit, does it appear that can we
812 /// rely on the vtable being defined elsewhere in the program?
813 ///
814 /// The response is really only definitive when called at the end of
815 /// the translation unit.
816 ///
817 /// The only semantic restriction here is that the object file should
818 /// not contain a vtable definition when that vtable is defined
819 /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
820 /// vtables when unnecessary.
821 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
822   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
823 
824   // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
825   // emit them even if there is an explicit template instantiation.
826   if (CGM.getTarget().getCXXABI().isMicrosoft())
827     return false;
828 
829   // If we have an explicit instantiation declaration (and not a
830   // definition), the vtable is defined elsewhere.
831   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
832   if (TSK == TSK_ExplicitInstantiationDeclaration)
833     return true;
834 
835   // Otherwise, if the class is an instantiated template, the
836   // vtable must be defined here.
837   if (TSK == TSK_ImplicitInstantiation ||
838       TSK == TSK_ExplicitInstantiationDefinition)
839     return false;
840 
841   // Otherwise, if the class doesn't have a key function (possibly
842   // anymore), the vtable must be defined here.
843   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
844   if (!keyFunction)
845     return false;
846 
847   // Otherwise, if we don't have a definition of the key function, the
848   // vtable must be defined somewhere else.
849   return !keyFunction->hasBody();
850 }
851 
852 /// Given that we're currently at the end of the translation unit, and
853 /// we've emitted a reference to the vtable for this class, should
854 /// we define that vtable?
855 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
856                                                    const CXXRecordDecl *RD) {
857   // If vtable is internal then it has to be done.
858   if (!CGM.getVTables().isVTableExternal(RD))
859     return true;
860 
861   // If it's external then maybe we will need it as available_externally.
862   return shouldEmitAvailableExternallyVTable(CGM, RD);
863 }
864 
865 /// Given that at some point we emitted a reference to one or more
866 /// vtables, and that we are now at the end of the translation unit,
867 /// decide whether we should emit them.
868 void CodeGenModule::EmitDeferredVTables() {
869 #ifndef NDEBUG
870   // Remember the size of DeferredVTables, because we're going to assume
871   // that this entire operation doesn't modify it.
872   size_t savedSize = DeferredVTables.size();
873 #endif
874 
875   for (const CXXRecordDecl *RD : DeferredVTables)
876     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
877       VTables.GenerateClassData(RD);
878 
879   assert(savedSize == DeferredVTables.size() &&
880          "deferred extra vtables during vtable emission?");
881   DeferredVTables.clear();
882 }
883 
884 bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
885   LinkageInfo LV = RD->getLinkageAndVisibility();
886   if (!isExternallyVisible(LV.getLinkage()))
887     return true;
888 
889   if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
890     return false;
891 
892   if (getTriple().isOSBinFormatCOFF()) {
893     if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
894       return false;
895   } else {
896     if (LV.getVisibility() != HiddenVisibility)
897       return false;
898   }
899 
900   if (getCodeGenOpts().LTOVisibilityPublicStd) {
901     const DeclContext *DC = RD;
902     while (1) {
903       auto *D = cast<Decl>(DC);
904       DC = DC->getParent();
905       if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
906         if (auto *ND = dyn_cast<NamespaceDecl>(D))
907           if (const IdentifierInfo *II = ND->getIdentifier())
908             if (II->isStr("std") || II->isStr("stdext"))
909               return false;
910         break;
911       }
912     }
913   }
914 
915   return true;
916 }
917 
918 void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
919                                            const VTableLayout &VTLayout) {
920   if (!getCodeGenOpts().PrepareForLTO)
921     return;
922 
923   CharUnits PointerWidth =
924       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
925 
926   typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
927   std::vector<BSEntry> BitsetEntries;
928   // Create a bit set entry for each address point.
929   for (auto &&AP : VTLayout.getAddressPoints())
930     BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
931 
932   // Sort the bit set entries for determinism.
933   std::sort(BitsetEntries.begin(), BitsetEntries.end(),
934             [this](const BSEntry &E1, const BSEntry &E2) {
935     if (&E1 == &E2)
936       return false;
937 
938     std::string S1;
939     llvm::raw_string_ostream O1(S1);
940     getCXXABI().getMangleContext().mangleTypeName(
941         QualType(E1.first->getTypeForDecl(), 0), O1);
942     O1.flush();
943 
944     std::string S2;
945     llvm::raw_string_ostream O2(S2);
946     getCXXABI().getMangleContext().mangleTypeName(
947         QualType(E2.first->getTypeForDecl(), 0), O2);
948     O2.flush();
949 
950     if (S1 < S2)
951       return true;
952     if (S1 != S2)
953       return false;
954 
955     return E1.second < E2.second;
956   });
957 
958   for (auto BitsetEntry : BitsetEntries)
959     AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,
960                           BitsetEntry.first);
961 }
962