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::CreateVTableInitializer(
521     const CXXRecordDecl *RD, const VTableComponent *Components,
522     unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
523     unsigned NumVTableThunks, llvm::Constant *RTTI) {
524   SmallVector<llvm::Constant *, 64> Inits;
525 
526   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
527 
528   llvm::Type *PtrDiffTy =
529     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
530 
531   unsigned NextVTableThunkIndex = 0;
532 
533   llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
534 
535   for (unsigned I = 0; I != NumComponents; ++I) {
536     VTableComponent Component = Components[I];
537 
538     llvm::Constant *Init = nullptr;
539 
540     switch (Component.getKind()) {
541     case VTableComponent::CK_VCallOffset:
542       Init = llvm::ConstantInt::get(PtrDiffTy,
543                                     Component.getVCallOffset().getQuantity());
544       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
545       break;
546     case VTableComponent::CK_VBaseOffset:
547       Init = llvm::ConstantInt::get(PtrDiffTy,
548                                     Component.getVBaseOffset().getQuantity());
549       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
550       break;
551     case VTableComponent::CK_OffsetToTop:
552       Init = llvm::ConstantInt::get(PtrDiffTy,
553                                     Component.getOffsetToTop().getQuantity());
554       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
555       break;
556     case VTableComponent::CK_RTTI:
557       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
558       break;
559     case VTableComponent::CK_FunctionPointer:
560     case VTableComponent::CK_CompleteDtorPointer:
561     case VTableComponent::CK_DeletingDtorPointer: {
562       GlobalDecl GD;
563 
564       // Get the right global decl.
565       switch (Component.getKind()) {
566       default:
567         llvm_unreachable("Unexpected vtable component kind");
568       case VTableComponent::CK_FunctionPointer:
569         GD = Component.getFunctionDecl();
570         break;
571       case VTableComponent::CK_CompleteDtorPointer:
572         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
573         break;
574       case VTableComponent::CK_DeletingDtorPointer:
575         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
576         break;
577       }
578 
579       if (CGM.getLangOpts().CUDA) {
580         // Emit NULL for methods we can't codegen on this
581         // side. Otherwise we'd end up with vtable with unresolved
582         // references.
583         const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
584         // OK on device side: functions w/ __device__ attribute
585         // OK on host side: anything except __device__-only functions.
586         bool CanEmitMethod = CGM.getLangOpts().CUDAIsDevice
587                                  ? MD->hasAttr<CUDADeviceAttr>()
588                                  : (MD->hasAttr<CUDAHostAttr>() ||
589                                     !MD->hasAttr<CUDADeviceAttr>());
590         if (!CanEmitMethod) {
591           Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
592           break;
593         }
594         // Method is acceptable, continue processing as usual.
595       }
596 
597       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
598         // We have a pure virtual member function.
599         if (!PureVirtualFn) {
600           llvm::FunctionType *Ty =
601             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
602           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
603           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
604           if (auto *F = dyn_cast<llvm::Function>(PureVirtualFn))
605             F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
606           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
607                                                          CGM.Int8PtrTy);
608         }
609         Init = PureVirtualFn;
610       } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
611         if (!DeletedVirtualFn) {
612           llvm::FunctionType *Ty =
613             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
614           StringRef DeletedCallName =
615             CGM.getCXXABI().GetDeletedVirtualCallName();
616           DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
617           if (auto *F = dyn_cast<llvm::Function>(DeletedVirtualFn))
618             F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
619           DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
620                                                          CGM.Int8PtrTy);
621         }
622         Init = DeletedVirtualFn;
623       } else {
624         // Check if we should use a thunk.
625         if (NextVTableThunkIndex < NumVTableThunks &&
626             VTableThunks[NextVTableThunkIndex].first == I) {
627           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
628 
629           maybeEmitThunkForVTable(GD, Thunk);
630           Init = CGM.GetAddrOfThunk(GD, Thunk);
631 
632           NextVTableThunkIndex++;
633         } else {
634           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
635 
636           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
637         }
638 
639         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
640       }
641       break;
642     }
643 
644     case VTableComponent::CK_UnusedFunctionPointer:
645       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
646       break;
647     };
648 
649     Inits.push_back(Init);
650   }
651 
652   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
653   return llvm::ConstantArray::get(ArrayType, Inits);
654 }
655 
656 llvm::GlobalVariable *
657 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
658                                       const BaseSubobject &Base,
659                                       bool BaseIsVirtual,
660                                    llvm::GlobalVariable::LinkageTypes Linkage,
661                                       VTableAddressPointsMapTy& AddressPoints) {
662   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
663     DI->completeClassData(Base.getBase());
664 
665   std::unique_ptr<VTableLayout> VTLayout(
666       getItaniumVTableContext().createConstructionVTableLayout(
667           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
668 
669   // Add the address points.
670   AddressPoints = VTLayout->getAddressPoints();
671 
672   // Get the mangled construction vtable name.
673   SmallString<256> OutName;
674   llvm::raw_svector_ostream Out(OutName);
675   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
676       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
677                            Base.getBase(), Out);
678   StringRef Name = OutName.str();
679 
680   llvm::ArrayType *ArrayType =
681     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
682 
683   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
684   // guarantee that they actually will be available externally. Instead, when
685   // emitting an available_externally VTT, we provide references to an internal
686   // linkage construction vtable. The ABI only requires complete-object vtables
687   // to be the same for all instances of a type, not construction vtables.
688   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
689     Linkage = llvm::GlobalVariable::InternalLinkage;
690 
691   // Create the variable that will hold the construction vtable.
692   llvm::GlobalVariable *VTable =
693     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
694   CGM.setGlobalVisibility(VTable, RD);
695 
696   // V-tables are always unnamed_addr.
697   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
698 
699   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
700       CGM.getContext().getTagDeclType(Base.getBase()));
701 
702   // Create and set the initializer.
703   llvm::Constant *Init = CreateVTableInitializer(
704       Base.getBase(), VTLayout->vtable_component_begin(),
705       VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
706       VTLayout->getNumVTableThunks(), RTTI);
707   VTable->setInitializer(Init);
708 
709   CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
710 
711   return VTable;
712 }
713 
714 static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
715                                                 const CXXRecordDecl *RD) {
716   return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
717          CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
718 }
719 
720 /// Compute the required linkage of the vtable for the given class.
721 ///
722 /// Note that we only call this at the end of the translation unit.
723 llvm::GlobalVariable::LinkageTypes
724 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
725   if (!RD->isExternallyVisible())
726     return llvm::GlobalVariable::InternalLinkage;
727 
728   // We're at the end of the translation unit, so the current key
729   // function is fully correct.
730   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
731   if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
732     // If this class has a key function, use that to determine the
733     // linkage of the vtable.
734     const FunctionDecl *def = nullptr;
735     if (keyFunction->hasBody(def))
736       keyFunction = cast<CXXMethodDecl>(def);
737 
738     switch (keyFunction->getTemplateSpecializationKind()) {
739       case TSK_Undeclared:
740       case TSK_ExplicitSpecialization:
741         assert((def || CodeGenOpts.OptimizationLevel > 0) &&
742                "Shouldn't query vtable linkage without key function or "
743                "optimizations");
744         if (!def && CodeGenOpts.OptimizationLevel > 0)
745           return llvm::GlobalVariable::AvailableExternallyLinkage;
746 
747         if (keyFunction->isInlined())
748           return !Context.getLangOpts().AppleKext ?
749                    llvm::GlobalVariable::LinkOnceODRLinkage :
750                    llvm::Function::InternalLinkage;
751 
752         return llvm::GlobalVariable::ExternalLinkage;
753 
754       case TSK_ImplicitInstantiation:
755         return !Context.getLangOpts().AppleKext ?
756                  llvm::GlobalVariable::LinkOnceODRLinkage :
757                  llvm::Function::InternalLinkage;
758 
759       case TSK_ExplicitInstantiationDefinition:
760         return !Context.getLangOpts().AppleKext ?
761                  llvm::GlobalVariable::WeakODRLinkage :
762                  llvm::Function::InternalLinkage;
763 
764       case TSK_ExplicitInstantiationDeclaration:
765         llvm_unreachable("Should not have been asked to emit this");
766     }
767   }
768 
769   // -fapple-kext mode does not support weak linkage, so we must use
770   // internal linkage.
771   if (Context.getLangOpts().AppleKext)
772     return llvm::Function::InternalLinkage;
773 
774   llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
775       llvm::GlobalValue::LinkOnceODRLinkage;
776   llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
777       llvm::GlobalValue::WeakODRLinkage;
778   if (RD->hasAttr<DLLExportAttr>()) {
779     // Cannot discard exported vtables.
780     DiscardableODRLinkage = NonDiscardableODRLinkage;
781   } else if (RD->hasAttr<DLLImportAttr>()) {
782     // Imported vtables are available externally.
783     DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
784     NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
785   }
786 
787   switch (RD->getTemplateSpecializationKind()) {
788     case TSK_Undeclared:
789     case TSK_ExplicitSpecialization:
790     case TSK_ImplicitInstantiation:
791       return DiscardableODRLinkage;
792 
793     case TSK_ExplicitInstantiationDeclaration:
794       // Explicit instantiations in MSVC do not provide vtables, so we must emit
795       // our own.
796       if (getTarget().getCXXABI().isMicrosoft())
797         return DiscardableODRLinkage;
798       return shouldEmitAvailableExternallyVTable(*this, RD)
799                  ? llvm::GlobalVariable::AvailableExternallyLinkage
800                  : llvm::GlobalVariable::ExternalLinkage;
801 
802     case TSK_ExplicitInstantiationDefinition:
803       return NonDiscardableODRLinkage;
804   }
805 
806   llvm_unreachable("Invalid TemplateSpecializationKind!");
807 }
808 
809 /// This is a callback from Sema to tell us that that a particular vtable is
810 /// required to be emitted in this translation unit.
811 ///
812 /// This is only called for vtables that _must_ be emitted (mainly due to key
813 /// functions).  For weak vtables, CodeGen tracks when they are needed and
814 /// emits them as-needed.
815 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
816   VTables.GenerateClassData(theClass);
817 }
818 
819 void
820 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
821   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
822     DI->completeClassData(RD);
823 
824   if (RD->getNumVBases())
825     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
826 
827   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
828 }
829 
830 /// At this point in the translation unit, does it appear that can we
831 /// rely on the vtable being defined elsewhere in the program?
832 ///
833 /// The response is really only definitive when called at the end of
834 /// the translation unit.
835 ///
836 /// The only semantic restriction here is that the object file should
837 /// not contain a vtable definition when that vtable is defined
838 /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
839 /// vtables when unnecessary.
840 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
841   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
842 
843   // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
844   // emit them even if there is an explicit template instantiation.
845   if (CGM.getTarget().getCXXABI().isMicrosoft())
846     return false;
847 
848   // If we have an explicit instantiation declaration (and not a
849   // definition), the vtable is defined elsewhere.
850   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
851   if (TSK == TSK_ExplicitInstantiationDeclaration)
852     return true;
853 
854   // Otherwise, if the class is an instantiated template, the
855   // vtable must be defined here.
856   if (TSK == TSK_ImplicitInstantiation ||
857       TSK == TSK_ExplicitInstantiationDefinition)
858     return false;
859 
860   // Otherwise, if the class doesn't have a key function (possibly
861   // anymore), the vtable must be defined here.
862   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
863   if (!keyFunction)
864     return false;
865 
866   // Otherwise, if we don't have a definition of the key function, the
867   // vtable must be defined somewhere else.
868   return !keyFunction->hasBody();
869 }
870 
871 /// Given that we're currently at the end of the translation unit, and
872 /// we've emitted a reference to the vtable for this class, should
873 /// we define that vtable?
874 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
875                                                    const CXXRecordDecl *RD) {
876   // If vtable is internal then it has to be done.
877   if (!CGM.getVTables().isVTableExternal(RD))
878     return true;
879 
880   // If it's external then maybe we will need it as available_externally.
881   return shouldEmitAvailableExternallyVTable(CGM, RD);
882 }
883 
884 /// Given that at some point we emitted a reference to one or more
885 /// vtables, and that we are now at the end of the translation unit,
886 /// decide whether we should emit them.
887 void CodeGenModule::EmitDeferredVTables() {
888 #ifndef NDEBUG
889   // Remember the size of DeferredVTables, because we're going to assume
890   // that this entire operation doesn't modify it.
891   size_t savedSize = DeferredVTables.size();
892 #endif
893 
894   for (const CXXRecordDecl *RD : DeferredVTables)
895     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
896       VTables.GenerateClassData(RD);
897 
898   assert(savedSize == DeferredVTables.size() &&
899          "deferred extra vtables during vtable emission?");
900   DeferredVTables.clear();
901 }
902 
903 bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
904   LinkageInfo LV = RD->getLinkageAndVisibility();
905   if (!isExternallyVisible(LV.getLinkage()))
906     return true;
907 
908   if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
909     return false;
910 
911   if (getTriple().isOSBinFormatCOFF()) {
912     if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
913       return false;
914   } else {
915     if (LV.getVisibility() != HiddenVisibility)
916       return false;
917   }
918 
919   if (getCodeGenOpts().LTOVisibilityPublicStd) {
920     const DeclContext *DC = RD;
921     while (1) {
922       auto *D = cast<Decl>(DC);
923       DC = DC->getParent();
924       if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
925         if (auto *ND = dyn_cast<NamespaceDecl>(D))
926           if (const IdentifierInfo *II = ND->getIdentifier())
927             if (II->isStr("std") || II->isStr("stdext"))
928               return false;
929         break;
930       }
931     }
932   }
933 
934   return true;
935 }
936 
937 void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
938                                            const VTableLayout &VTLayout) {
939   if (!getCodeGenOpts().PrepareForLTO)
940     return;
941 
942   CharUnits PointerWidth =
943       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
944 
945   typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
946   std::vector<BSEntry> BitsetEntries;
947   // Create a bit set entry for each address point.
948   for (auto &&AP : VTLayout.getAddressPoints())
949     BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
950 
951   // Sort the bit set entries for determinism.
952   std::sort(BitsetEntries.begin(), BitsetEntries.end(),
953             [this](const BSEntry &E1, const BSEntry &E2) {
954     if (&E1 == &E2)
955       return false;
956 
957     std::string S1;
958     llvm::raw_string_ostream O1(S1);
959     getCXXABI().getMangleContext().mangleTypeName(
960         QualType(E1.first->getTypeForDecl(), 0), O1);
961     O1.flush();
962 
963     std::string S2;
964     llvm::raw_string_ostream O2(S2);
965     getCXXABI().getMangleContext().mangleTypeName(
966         QualType(E2.first->getTypeForDecl(), 0), O2);
967     O2.flush();
968 
969     if (S1 < S2)
970       return true;
971     if (S1 != S2)
972       return false;
973 
974     return E1.second < E2.second;
975   });
976 
977   for (auto BitsetEntry : BitsetEntries)
978     AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,
979                           BitsetEntry.first);
980 }
981