1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ code generation of virtual tables.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/CodeGen/CGFunctionInfo.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 #include "llvm/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"
29 using namespace clang;
30 using namespace CodeGen;
32 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
33 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
35 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
36 const ThunkInfo &Thunk) {
37 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
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(),
46 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
49 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
50 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
51 /*DontDefer=*/true, /*IsThunk=*/true);
54 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
55 const ThunkInfo &Thunk, llvm::Function *Fn) {
56 CGM.setGlobalVisibility(Fn, MD);
59 static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
60 llvm::Function *ThunkFn, bool ForVTable,
62 CGM.setFunctionLinkage(GD, ThunkFn);
63 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
64 !Thunk.Return.isEmpty());
66 // Set the right visibility.
67 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
68 setThunkVisibility(CGM, MD, Thunk, ThunkFn);
70 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
71 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
75 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
76 const ABIArgInfo &infoR, CanQualType typeR) {
77 return (infoL.getKind() == infoR.getKind() &&
79 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
80 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
84 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
85 QualType ResultType, RValue RV,
86 const ThunkInfo &Thunk) {
87 // Emit the return adjustment.
88 bool NullCheckValue = !ResultType->isReferenceType();
90 llvm::BasicBlock *AdjustNull = nullptr;
91 llvm::BasicBlock *AdjustNotNull = nullptr;
92 llvm::BasicBlock *AdjustEnd = nullptr;
94 llvm::Value *ReturnValue = RV.getScalarVal();
97 AdjustNull = CGF.createBasicBlock("adjust.null");
98 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
99 AdjustEnd = CGF.createBasicBlock("adjust.end");
101 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
102 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
103 CGF.EmitBlock(AdjustNotNull);
106 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
109 if (NullCheckValue) {
110 CGF.Builder.CreateBr(AdjustEnd);
111 CGF.EmitBlock(AdjustNull);
112 CGF.Builder.CreateBr(AdjustEnd);
113 CGF.EmitBlock(AdjustEnd);
115 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
116 PHI->addIncoming(ReturnValue, AdjustNotNull);
117 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
122 return RValue::get(ReturnValue);
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.
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();
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);
156 llvm::ValueToValueMapTy VMap;
157 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
158 /*ModuleLevelChanges=*/false);
159 CGM.getModule().getFunctionList().push_back(NewFn);
160 Fn->replaceAllUsesWith(NewFn);
162 Fn->eraseFromParent();
165 // "Initialize" CGF (minimally).
168 // Get the "this" value
169 llvm::Function::arg_iterator AI = Fn->arg_begin();
170 if (CGM.ReturnTypeUsesSRet(FnInfo))
173 // Find the first store of "this", which will be to the alloca associated
175 llvm::Value *ThisPtr = &*AI;
176 llvm::BasicBlock *EntryBB = Fn->begin();
177 llvm::Instruction *ThisStore =
178 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
179 return isa<llvm::StoreInst>(I) && I.getOperand(0) == ThisPtr;
181 assert(ThisStore && "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);
188 if (!Thunk.Return.isEmpty()) {
189 // Fix up the returned value, if necessary.
190 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
191 llvm::Instruction *T = I->getTerminator();
192 if (isa<llvm::ReturnInst>(T)) {
193 RValue RV = RValue::get(T->getOperand(0));
194 T->eraseFromParent();
195 Builder.SetInsertPoint(&*I);
196 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
197 Builder.CreateRet(RV.getScalarVal());
206 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
207 const CGFunctionInfo &FnInfo) {
208 assert(!CurGD.getDecl() && "CurGD was already set!");
210 CurFuncIsThunk = true;
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)
218 : CGM.getCXXABI().hasMostDerivedReturn(GD)
219 ? CGM.getContext().VoidPtrTy
220 : FPT->getReturnType();
221 FunctionArgList FunctionArgs;
223 // Create the implicit 'this' parameter declaration.
224 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
226 // Add the rest of the parameters.
227 FunctionArgs.append(MD->param_begin(), MD->param_end());
229 if (isa<CXXDestructorDecl>(MD))
230 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
232 // Start defining the function.
233 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
234 MD->getLocation(), MD->getLocation());
236 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
237 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
238 CXXThisValue = CXXABIThisValue;
241 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
242 const ThunkInfo *Thunk) {
243 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
244 "Please use a new CGF for this thunk");
245 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
247 // Adjust the 'this' pointer if necessary
248 llvm::Value *AdjustedThisPtr = Thunk ? CGM.getCXXABI().performThisAdjustment(
249 *this, LoadCXXThis(), Thunk->This)
252 if (CurFnInfo->usesInAlloca()) {
253 // We don't handle return adjusting thunks, because they require us to call
254 // the copy constructor. For now, fall through and pretend the return
255 // adjustment was empty so we don't crash.
256 if (Thunk && !Thunk->Return.isEmpty()) {
257 CGM.ErrorUnsupported(
258 MD, "non-trivial argument copy for return-adjusting thunk");
260 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
264 // Start building CallArgs.
265 CallArgList CallArgs;
266 QualType ThisType = MD->getThisType(getContext());
267 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
269 if (isa<CXXDestructorDecl>(MD))
270 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
272 // Add the rest of the arguments.
273 for (const ParmVarDecl *PD : MD->params())
274 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
276 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
279 const CGFunctionInfo &CallFnInfo =
280 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
281 RequiredArgs::forPrototypePlus(FPT, 1));
282 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
283 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
284 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
285 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
286 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
287 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
288 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
289 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
290 assert(similar(CallFnInfo.arg_begin()[i].info,
291 CallFnInfo.arg_begin()[i].type,
292 CurFnInfo->arg_begin()[i].info,
293 CurFnInfo->arg_begin()[i].type));
296 // Determine whether we have a return value slot to use.
297 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
299 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
300 ? CGM.getContext().VoidPtrTy
301 : FPT->getReturnType();
302 ReturnValueSlot Slot;
303 if (!ResultType->isVoidType() &&
304 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
305 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
306 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
308 // Now emit our call.
309 llvm::Instruction *CallOrInvoke;
310 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
312 // Consider return adjustment if we have ThunkInfo.
313 if (Thunk && !Thunk->Return.isEmpty())
314 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
317 if (!ResultType->isVoidType() && Slot.isNull())
318 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
320 // Disable the final ARC autorelease.
321 AutoreleaseResult = false;
326 void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
327 llvm::Value *AdjustedThisPtr,
328 llvm::Value *Callee) {
329 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
330 // to translate AST arguments into LLVM IR arguments. For thunks, we know
331 // that the caller prototype more or less matches the callee prototype with
332 // the exception of 'this'.
333 SmallVector<llvm::Value *, 8> Args;
334 for (llvm::Argument &A : CurFn->args())
337 // Set the adjusted 'this' pointer.
338 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
339 if (ThisAI.isDirect()) {
340 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
341 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
342 llvm::Type *ThisType = Args[ThisArgNo]->getType();
343 if (ThisType != AdjustedThisPtr->getType())
344 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
345 Args[ThisArgNo] = AdjustedThisPtr;
347 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
348 llvm::Value *ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
349 llvm::Type *ThisType =
350 cast<llvm::PointerType>(ThisAddr->getType())->getElementType();
351 if (ThisType != AdjustedThisPtr->getType())
352 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
353 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
356 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
357 // don't actually want to run them.
358 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
359 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
361 // Apply the standard set of call attributes.
362 unsigned CallingConv;
363 CodeGen::AttributeListType AttributeList;
364 CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
365 /*AttrOnCallSite=*/true);
366 llvm::AttributeSet Attrs =
367 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
368 Call->setAttributes(Attrs);
369 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
371 if (Call->getType()->isVoidTy())
372 Builder.CreateRetVoid();
374 Builder.CreateRet(Call);
376 // Finish the function to maintain CodeGenFunction invariants.
377 // FIXME: Don't emit unreachable code.
378 EmitBlock(createBasicBlock());
382 void CodeGenFunction::generateThunk(llvm::Function *Fn,
383 const CGFunctionInfo &FnInfo,
384 GlobalDecl GD, const ThunkInfo &Thunk) {
385 StartThunk(Fn, GD, FnInfo);
389 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
390 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
392 // Make the call and return the result.
393 EmitCallAndReturnForThunk(Callee, &Thunk);
396 void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
398 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
400 // FIXME: re-use FnInfo in this computation.
401 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
402 llvm::GlobalValue *Entry;
404 // Strip off a bitcast if we got one back.
405 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
406 assert(CE->getOpcode() == llvm::Instruction::BitCast);
407 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
409 Entry = cast<llvm::GlobalValue>(C);
412 // There's already a declaration with the same name, check if it has the same
413 // type or if we need to replace it.
414 if (Entry->getType()->getElementType() !=
415 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
416 llvm::GlobalValue *OldThunkFn = Entry;
418 // If the types mismatch then we have to rewrite the definition.
419 assert(OldThunkFn->isDeclaration() &&
420 "Shouldn't replace non-declaration");
422 // Remove the name from the old thunk function and get a new thunk.
423 OldThunkFn->setName(StringRef());
424 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
426 // If needed, replace the old thunk with a bitcast.
427 if (!OldThunkFn->use_empty()) {
428 llvm::Constant *NewPtrForOldDecl =
429 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
430 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
433 // Remove the old thunk.
434 OldThunkFn->eraseFromParent();
437 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
438 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
439 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
441 if (!ThunkFn->isDeclaration()) {
442 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
443 // There is already a thunk emitted for this function, do nothing.
447 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
451 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
453 if (ThunkFn->isVarArg()) {
454 // Varargs thunks are special; we can't just generate a call because
455 // we can't copy the varargs. Our implementation is rather
456 // expensive/sucky at the moment, so don't generate the thunk unless
458 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
459 if (UseAvailableExternallyLinkage)
462 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
464 // Normal thunk body generation.
465 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
468 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
471 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
472 const ThunkInfo &Thunk) {
473 // If the ABI has key functions, only the TU with the key function should emit
474 // the thunk. However, we can allow inlining of thunks if we emit them with
475 // available_externally linkage together with vtables when optimizations are
477 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
478 !CGM.getCodeGenOpts().OptimizationLevel)
481 // We can't emit thunks for member functions with incomplete types.
482 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
483 if (!CGM.getTypes().isFuncTypeConvertible(
484 MD->getType()->castAs<FunctionType>()))
487 emitThunk(GD, Thunk, /*ForVTable=*/true);
490 void CodeGenVTables::EmitThunks(GlobalDecl GD)
492 const CXXMethodDecl *MD =
493 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
495 // We don't need to generate thunks for the base destructor.
496 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
499 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
500 VTContext->getThunkInfo(GD);
502 if (!ThunkInfoVector)
505 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
506 emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
509 llvm::Constant *CodeGenVTables::CreateVTableInitializer(
510 const CXXRecordDecl *RD, const VTableComponent *Components,
511 unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
512 unsigned NumVTableThunks, llvm::Constant *RTTI) {
513 SmallVector<llvm::Constant *, 64> Inits;
515 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
517 llvm::Type *PtrDiffTy =
518 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
520 unsigned NextVTableThunkIndex = 0;
522 llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
524 for (unsigned I = 0; I != NumComponents; ++I) {
525 VTableComponent Component = Components[I];
527 llvm::Constant *Init = nullptr;
529 switch (Component.getKind()) {
530 case VTableComponent::CK_VCallOffset:
531 Init = llvm::ConstantInt::get(PtrDiffTy,
532 Component.getVCallOffset().getQuantity());
533 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
535 case VTableComponent::CK_VBaseOffset:
536 Init = llvm::ConstantInt::get(PtrDiffTy,
537 Component.getVBaseOffset().getQuantity());
538 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
540 case VTableComponent::CK_OffsetToTop:
541 Init = llvm::ConstantInt::get(PtrDiffTy,
542 Component.getOffsetToTop().getQuantity());
543 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
545 case VTableComponent::CK_RTTI:
546 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
548 case VTableComponent::CK_FunctionPointer:
549 case VTableComponent::CK_CompleteDtorPointer:
550 case VTableComponent::CK_DeletingDtorPointer: {
553 // Get the right global decl.
554 switch (Component.getKind()) {
556 llvm_unreachable("Unexpected vtable component kind");
557 case VTableComponent::CK_FunctionPointer:
558 GD = Component.getFunctionDecl();
560 case VTableComponent::CK_CompleteDtorPointer:
561 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
563 case VTableComponent::CK_DeletingDtorPointer:
564 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
568 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
569 // We have a pure virtual member function.
570 if (!PureVirtualFn) {
571 llvm::FunctionType *Ty =
572 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
573 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
574 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
575 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
578 Init = PureVirtualFn;
579 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
580 if (!DeletedVirtualFn) {
581 llvm::FunctionType *Ty =
582 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
583 StringRef DeletedCallName =
584 CGM.getCXXABI().GetDeletedVirtualCallName();
585 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
586 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
589 Init = DeletedVirtualFn;
591 // Check if we should use a thunk.
592 if (NextVTableThunkIndex < NumVTableThunks &&
593 VTableThunks[NextVTableThunkIndex].first == I) {
594 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
596 maybeEmitThunkForVTable(GD, Thunk);
597 Init = CGM.GetAddrOfThunk(GD, Thunk);
599 NextVTableThunkIndex++;
601 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
603 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
606 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
611 case VTableComponent::CK_UnusedFunctionPointer:
612 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
616 Inits.push_back(Init);
619 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
620 return llvm::ConstantArray::get(ArrayType, Inits);
623 llvm::GlobalVariable *
624 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
625 const BaseSubobject &Base,
627 llvm::GlobalVariable::LinkageTypes Linkage,
628 VTableAddressPointsMapTy& AddressPoints) {
629 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
630 DI->completeClassData(Base.getBase());
632 std::unique_ptr<VTableLayout> VTLayout(
633 getItaniumVTableContext().createConstructionVTableLayout(
634 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
636 // Add the address points.
637 AddressPoints = VTLayout->getAddressPoints();
639 // Get the mangled construction vtable name.
640 SmallString<256> OutName;
641 llvm::raw_svector_ostream Out(OutName);
642 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
643 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
644 Base.getBase(), Out);
646 StringRef Name = OutName.str();
648 llvm::ArrayType *ArrayType =
649 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
651 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
652 // guarantee that they actually will be available externally. Instead, when
653 // emitting an available_externally VTT, we provide references to an internal
654 // linkage construction vtable. The ABI only requires complete-object vtables
655 // to be the same for all instances of a type, not construction vtables.
656 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
657 Linkage = llvm::GlobalVariable::InternalLinkage;
659 // Create the variable that will hold the construction vtable.
660 llvm::GlobalVariable *VTable =
661 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
662 CGM.setGlobalVisibility(VTable, RD);
664 // V-tables are always unnamed_addr.
665 VTable->setUnnamedAddr(true);
667 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
668 CGM.getContext().getTagDeclType(Base.getBase()));
670 // Create and set the initializer.
671 llvm::Constant *Init = CreateVTableInitializer(
672 Base.getBase(), VTLayout->vtable_component_begin(),
673 VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
674 VTLayout->getNumVTableThunks(), RTTI);
675 VTable->setInitializer(Init);
677 CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
682 /// Compute the required linkage of the v-table for the given class.
684 /// Note that we only call this at the end of the translation unit.
685 llvm::GlobalVariable::LinkageTypes
686 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
687 if (!RD->isExternallyVisible())
688 return llvm::GlobalVariable::InternalLinkage;
690 // We're at the end of the translation unit, so the current key
691 // function is fully correct.
692 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
693 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
694 // If this class has a key function, use that to determine the
695 // linkage of the vtable.
696 const FunctionDecl *def = nullptr;
697 if (keyFunction->hasBody(def))
698 keyFunction = cast<CXXMethodDecl>(def);
700 switch (keyFunction->getTemplateSpecializationKind()) {
702 case TSK_ExplicitSpecialization:
703 assert(def && "Should not have been asked to emit this");
704 if (keyFunction->isInlined())
705 return !Context.getLangOpts().AppleKext ?
706 llvm::GlobalVariable::LinkOnceODRLinkage :
707 llvm::Function::InternalLinkage;
709 return llvm::GlobalVariable::ExternalLinkage;
711 case TSK_ImplicitInstantiation:
712 return !Context.getLangOpts().AppleKext ?
713 llvm::GlobalVariable::LinkOnceODRLinkage :
714 llvm::Function::InternalLinkage;
716 case TSK_ExplicitInstantiationDefinition:
717 return !Context.getLangOpts().AppleKext ?
718 llvm::GlobalVariable::WeakODRLinkage :
719 llvm::Function::InternalLinkage;
721 case TSK_ExplicitInstantiationDeclaration:
722 llvm_unreachable("Should not have been asked to emit this");
726 // -fapple-kext mode does not support weak linkage, so we must use
728 if (Context.getLangOpts().AppleKext)
729 return llvm::Function::InternalLinkage;
731 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
732 llvm::GlobalValue::LinkOnceODRLinkage;
733 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
734 llvm::GlobalValue::WeakODRLinkage;
735 if (RD->hasAttr<DLLExportAttr>()) {
736 // Cannot discard exported vtables.
737 DiscardableODRLinkage = NonDiscardableODRLinkage;
738 } else if (RD->hasAttr<DLLImportAttr>()) {
739 // Imported vtables are available externally.
740 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
741 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
744 switch (RD->getTemplateSpecializationKind()) {
746 case TSK_ExplicitSpecialization:
747 case TSK_ImplicitInstantiation:
748 return DiscardableODRLinkage;
750 case TSK_ExplicitInstantiationDeclaration:
751 return llvm::GlobalVariable::ExternalLinkage;
753 case TSK_ExplicitInstantiationDefinition:
754 return NonDiscardableODRLinkage;
757 llvm_unreachable("Invalid TemplateSpecializationKind!");
760 /// This is a callback from Sema to tell us that that a particular v-table is
761 /// required to be emitted in this translation unit.
763 /// This is only called for vtables that _must_ be emitted (mainly due to key
764 /// functions). For weak vtables, CodeGen tracks when they are needed and
765 /// emits them as-needed.
766 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
767 VTables.GenerateClassData(theClass);
771 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
772 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
773 DI->completeClassData(RD);
775 if (RD->getNumVBases())
776 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
778 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
781 /// At this point in the translation unit, does it appear that can we
782 /// rely on the vtable being defined elsewhere in the program?
784 /// The response is really only definitive when called at the end of
785 /// the translation unit.
787 /// The only semantic restriction here is that the object file should
788 /// not contain a v-table definition when that v-table is defined
789 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
790 /// v-tables when unnecessary.
791 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
792 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
794 // If we have an explicit instantiation declaration (and not a
795 // definition), the v-table is defined elsewhere.
796 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
797 if (TSK == TSK_ExplicitInstantiationDeclaration)
800 // Otherwise, if the class is an instantiated template, the
801 // v-table must be defined here.
802 if (TSK == TSK_ImplicitInstantiation ||
803 TSK == TSK_ExplicitInstantiationDefinition)
806 // Otherwise, if the class doesn't have a key function (possibly
807 // anymore), the v-table must be defined here.
808 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
812 // Otherwise, if we don't have a definition of the key function, the
813 // v-table must be defined somewhere else.
814 return !keyFunction->hasBody();
817 /// Given that we're currently at the end of the translation unit, and
818 /// we've emitted a reference to the v-table for this class, should
819 /// we define that v-table?
820 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
821 const CXXRecordDecl *RD) {
822 return !CGM.getVTables().isVTableExternal(RD);
825 /// Given that at some point we emitted a reference to one or more
826 /// v-tables, and that we are now at the end of the translation unit,
827 /// decide whether we should emit them.
828 void CodeGenModule::EmitDeferredVTables() {
830 // Remember the size of DeferredVTables, because we're going to assume
831 // that this entire operation doesn't modify it.
832 size_t savedSize = DeferredVTables.size();
835 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
836 for (const_iterator i = DeferredVTables.begin(),
837 e = DeferredVTables.end(); i != e; ++i) {
838 const CXXRecordDecl *RD = *i;
839 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
840 VTables.GenerateClassData(RD);
843 assert(savedSize == DeferredVTables.size() &&
844 "deferred extra v-tables during v-table emission?");
845 DeferredVTables.clear();
848 bool CodeGenModule::IsCFIBlacklistedRecord(const CXXRecordDecl *RD) {
849 // FIXME: Make this user configurable.
850 return RD->isInStdNamespace();
853 void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
854 const VTableLayout &VTLayout) {
855 if (!LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
856 !LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
857 !LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
858 !LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast))
861 CharUnits PointerWidth =
862 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
864 std::vector<llvm::MDTuple *> BitsetEntries;
865 // Create a bit set entry for each address point.
866 for (auto &&AP : VTLayout.getAddressPoints()) {
867 if (IsCFIBlacklistedRecord(AP.first.getBase()))
870 BitsetEntries.push_back(CreateVTableBitSetEntry(
871 VTable, PointerWidth * AP.second, AP.first.getBase()));
874 // Sort the bit set entries for determinism.
875 std::sort(BitsetEntries.begin(), BitsetEntries.end(), [](llvm::MDTuple *T1,
880 StringRef S1 = cast<llvm::MDString>(T1->getOperand(0))->getString();
881 StringRef S2 = cast<llvm::MDString>(T2->getOperand(0))->getString();
887 uint64_t Offset1 = cast<llvm::ConstantInt>(
888 cast<llvm::ConstantAsMetadata>(T1->getOperand(2))
889 ->getValue())->getZExtValue();
890 uint64_t Offset2 = cast<llvm::ConstantInt>(
891 cast<llvm::ConstantAsMetadata>(T2->getOperand(2))
892 ->getValue())->getZExtValue();
893 assert(Offset1 != Offset2);
894 return Offset1 < Offset2;
897 llvm::NamedMDNode *BitsetsMD =
898 getModule().getOrInsertNamedMetadata("llvm.bitsets");
899 for (auto BitsetEntry : BitsetEntries)
900 BitsetsMD->addOperand(BitsetEntry);