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