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