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