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 //===----------------------------------------------------------------------===//
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "ConstantBuilder.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "clang/Frontend/CodeGenOptions.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Transforms/Utils/Cloning.h"
27 using namespace clang;
28 using namespace CodeGen;
30 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
31 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
33 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
34 const ThunkInfo &Thunk) {
35 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
37 // Compute the mangled name.
38 SmallString<256> Name;
39 llvm::raw_svector_ostream Out(Name);
40 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
41 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
44 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
46 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
47 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
48 /*DontDefer=*/true, /*IsThunk=*/true);
51 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
52 const ThunkInfo &Thunk, llvm::Function *Fn) {
53 CGM.setGlobalVisibility(Fn, MD);
56 static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
57 llvm::Function *ThunkFn, bool ForVTable,
59 CGM.setFunctionLinkage(GD, ThunkFn);
60 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
61 !Thunk.Return.isEmpty());
63 // Set the right visibility.
64 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
65 setThunkVisibility(CGM, MD, Thunk, ThunkFn);
67 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
68 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
72 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
73 const ABIArgInfo &infoR, CanQualType typeR) {
74 return (infoL.getKind() == infoR.getKind() &&
76 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
77 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
81 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
82 QualType ResultType, RValue RV,
83 const ThunkInfo &Thunk) {
84 // Emit the return adjustment.
85 bool NullCheckValue = !ResultType->isReferenceType();
87 llvm::BasicBlock *AdjustNull = nullptr;
88 llvm::BasicBlock *AdjustNotNull = nullptr;
89 llvm::BasicBlock *AdjustEnd = nullptr;
91 llvm::Value *ReturnValue = RV.getScalarVal();
94 AdjustNull = CGF.createBasicBlock("adjust.null");
95 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
96 AdjustEnd = CGF.createBasicBlock("adjust.end");
98 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
99 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
100 CGF.EmitBlock(AdjustNotNull);
103 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
104 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
105 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
106 Address(ReturnValue, ClassAlign),
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 Fn->replaceAllUsesWith(NewFn);
160 Fn->eraseFromParent();
163 // "Initialize" CGF (minimally).
166 // Get the "this" value
167 llvm::Function::arg_iterator AI = Fn->arg_begin();
168 if (CGM.ReturnTypeUsesSRet(FnInfo))
171 // Find the first store of "this", which will be to the alloca associated
173 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
174 llvm::BasicBlock *EntryBB = &Fn->front();
175 llvm::BasicBlock::iterator ThisStore =
176 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
177 return isa<llvm::StoreInst>(I) &&
178 I.getOperand(0) == ThisPtr.getPointer();
180 assert(ThisStore != EntryBB->end() &&
181 "Store of this should be in entry block?");
182 // Adjust "this", if necessary.
183 Builder.SetInsertPoint(&*ThisStore);
184 llvm::Value *AdjustedThisPtr =
185 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
186 ThisStore->setOperand(0, AdjustedThisPtr);
188 if (!Thunk.Return.isEmpty()) {
189 // Fix up the returned value, if necessary.
190 for (llvm::BasicBlock &BB : *Fn) {
191 llvm::Instruction *T = BB.getTerminator();
192 if (isa<llvm::ReturnInst>(T)) {
193 RValue RV = RValue::get(T->getOperand(0));
194 T->eraseFromParent();
195 Builder.SetInsertPoint(&BB);
196 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
197 Builder.CreateRet(RV.getScalarVal());
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 auto NL = ApplyDebugLocation::CreateEmpty(*this);
234 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
236 // Create a scope with an artificial location for the body of this function.
237 auto AL = ApplyDebugLocation::CreateArtificial(*this);
239 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
240 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
241 CXXThisValue = CXXABIThisValue;
246 void CodeGenFunction::FinishThunk() {
247 // Clear these to restore the invariants expected by
248 // StartFunction/FinishFunction.
249 CurCodeDecl = nullptr;
250 CurFuncDecl = nullptr;
255 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Constant *CalleePtr,
256 const ThunkInfo *Thunk) {
257 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
258 "Please use a new CGF for this thunk");
259 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
261 // Adjust the 'this' pointer if necessary
262 llvm::Value *AdjustedThisPtr =
263 Thunk ? CGM.getCXXABI().performThisAdjustment(
264 *this, LoadCXXThisAddress(), Thunk->This)
267 if (CurFnInfo->usesInAlloca()) {
268 // We don't handle return adjusting thunks, because they require us to call
269 // the copy constructor. For now, fall through and pretend the return
270 // adjustment was empty so we don't crash.
271 if (Thunk && !Thunk->Return.isEmpty()) {
272 CGM.ErrorUnsupported(
273 MD, "non-trivial argument copy for return-adjusting thunk");
275 EmitMustTailThunk(MD, AdjustedThisPtr, CalleePtr);
279 // Start building CallArgs.
280 CallArgList CallArgs;
281 QualType ThisType = MD->getThisType(getContext());
282 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
284 if (isa<CXXDestructorDecl>(MD))
285 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
287 // Add the rest of the arguments.
288 for (const ParmVarDecl *PD : MD->parameters())
289 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
291 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
294 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
295 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD));
296 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
297 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
298 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
299 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
300 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
301 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
302 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
303 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
304 assert(similar(CallFnInfo.arg_begin()[i].info,
305 CallFnInfo.arg_begin()[i].type,
306 CurFnInfo->arg_begin()[i].info,
307 CurFnInfo->arg_begin()[i].type));
310 // Determine whether we have a return value slot to use.
311 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
313 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
314 ? CGM.getContext().VoidPtrTy
315 : FPT->getReturnType();
316 ReturnValueSlot Slot;
317 if (!ResultType->isVoidType() &&
318 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
319 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
320 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
322 // Now emit our call.
323 llvm::Instruction *CallOrInvoke;
324 CGCallee Callee = CGCallee::forDirect(CalleePtr, MD);
325 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, &CallOrInvoke);
327 // Consider return adjustment if we have ThunkInfo.
328 if (Thunk && !Thunk->Return.isEmpty())
329 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
330 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
331 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
334 if (!ResultType->isVoidType() && Slot.isNull())
335 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
337 // Disable the final ARC autorelease.
338 AutoreleaseResult = false;
343 void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
344 llvm::Value *AdjustedThisPtr,
345 llvm::Value *CalleePtr) {
346 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
347 // to translate AST arguments into LLVM IR arguments. For thunks, we know
348 // that the caller prototype more or less matches the callee prototype with
349 // the exception of 'this'.
350 SmallVector<llvm::Value *, 8> Args;
351 for (llvm::Argument &A : CurFn->args())
354 // Set the adjusted 'this' pointer.
355 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
356 if (ThisAI.isDirect()) {
357 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
358 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
359 llvm::Type *ThisType = Args[ThisArgNo]->getType();
360 if (ThisType != AdjustedThisPtr->getType())
361 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
362 Args[ThisArgNo] = AdjustedThisPtr;
364 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
365 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
366 llvm::Type *ThisType = ThisAddr.getElementType();
367 if (ThisType != AdjustedThisPtr->getType())
368 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
369 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
372 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
373 // don't actually want to run them.
374 llvm::CallInst *Call = Builder.CreateCall(CalleePtr, Args);
375 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
377 // Apply the standard set of call attributes.
378 unsigned CallingConv;
379 CodeGen::AttributeListType AttributeList;
380 CGM.ConstructAttributeList(CalleePtr->getName(),
381 *CurFnInfo, MD, AttributeList,
382 CallingConv, /*AttrOnCallSite=*/true);
383 llvm::AttributeSet Attrs =
384 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
385 Call->setAttributes(Attrs);
386 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
388 if (Call->getType()->isVoidTy())
389 Builder.CreateRetVoid();
391 Builder.CreateRet(Call);
393 // Finish the function to maintain CodeGenFunction invariants.
394 // FIXME: Don't emit unreachable code.
395 EmitBlock(createBasicBlock());
399 void CodeGenFunction::generateThunk(llvm::Function *Fn,
400 const CGFunctionInfo &FnInfo,
401 GlobalDecl GD, const ThunkInfo &Thunk) {
402 StartThunk(Fn, GD, FnInfo);
403 // Create a scope with an artificial location for the body of this function.
404 auto AL = ApplyDebugLocation::CreateArtificial(*this);
408 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
409 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
411 // Make the call and return the result.
412 EmitCallAndReturnForThunk(Callee, &Thunk);
415 void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
417 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
419 // FIXME: re-use FnInfo in this computation.
420 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
421 llvm::GlobalValue *Entry;
423 // Strip off a bitcast if we got one back.
424 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
425 assert(CE->getOpcode() == llvm::Instruction::BitCast);
426 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
428 Entry = cast<llvm::GlobalValue>(C);
431 // There's already a declaration with the same name, check if it has the same
432 // type or if we need to replace it.
433 if (Entry->getType()->getElementType() !=
434 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
435 llvm::GlobalValue *OldThunkFn = Entry;
437 // If the types mismatch then we have to rewrite the definition.
438 assert(OldThunkFn->isDeclaration() &&
439 "Shouldn't replace non-declaration");
441 // Remove the name from the old thunk function and get a new thunk.
442 OldThunkFn->setName(StringRef());
443 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
445 // If needed, replace the old thunk with a bitcast.
446 if (!OldThunkFn->use_empty()) {
447 llvm::Constant *NewPtrForOldDecl =
448 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
449 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
452 // Remove the old thunk.
453 OldThunkFn->eraseFromParent();
456 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
457 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
458 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
460 if (!ThunkFn->isDeclaration()) {
461 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
462 // There is already a thunk emitted for this function, do nothing.
466 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
470 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
472 if (ThunkFn->isVarArg()) {
473 // Varargs thunks are special; we can't just generate a call because
474 // we can't copy the varargs. Our implementation is rather
475 // expensive/sucky at the moment, so don't generate the thunk unless
477 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
478 if (UseAvailableExternallyLinkage)
481 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
483 // Normal thunk body generation.
484 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
487 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
490 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
491 const ThunkInfo &Thunk) {
492 // If the ABI has key functions, only the TU with the key function should emit
493 // the thunk. However, we can allow inlining of thunks if we emit them with
494 // available_externally linkage together with vtables when optimizations are
496 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
497 !CGM.getCodeGenOpts().OptimizationLevel)
500 // We can't emit thunks for member functions with incomplete types.
501 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
502 if (!CGM.getTypes().isFuncTypeConvertible(
503 MD->getType()->castAs<FunctionType>()))
506 emitThunk(GD, Thunk, /*ForVTable=*/true);
509 void CodeGenVTables::EmitThunks(GlobalDecl GD)
511 const CXXMethodDecl *MD =
512 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
514 // We don't need to generate thunks for the base destructor.
515 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
518 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
519 VTContext->getThunkInfo(GD);
521 if (!ThunkInfoVector)
524 for (const ThunkInfo& Thunk : *ThunkInfoVector)
525 emitThunk(GD, Thunk, /*ForVTable=*/false);
528 void CodeGenVTables::addVTableComponent(
529 ConstantArrayBuilder &builder, const VTableLayout &layout,
530 unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
531 auto &component = layout.vtable_components()[idx];
533 auto addOffsetConstant = [&](CharUnits offset) {
534 builder.add(llvm::ConstantExpr::getIntToPtr(
535 llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
539 switch (component.getKind()) {
540 case VTableComponent::CK_VCallOffset:
541 return addOffsetConstant(component.getVCallOffset());
543 case VTableComponent::CK_VBaseOffset:
544 return addOffsetConstant(component.getVBaseOffset());
546 case VTableComponent::CK_OffsetToTop:
547 return addOffsetConstant(component.getOffsetToTop());
549 case VTableComponent::CK_RTTI:
550 return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
552 case VTableComponent::CK_FunctionPointer:
553 case VTableComponent::CK_CompleteDtorPointer:
554 case VTableComponent::CK_DeletingDtorPointer: {
557 // Get the right global decl.
558 switch (component.getKind()) {
560 llvm_unreachable("Unexpected vtable component kind");
561 case VTableComponent::CK_FunctionPointer:
562 GD = component.getFunctionDecl();
564 case VTableComponent::CK_CompleteDtorPointer:
565 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
567 case VTableComponent::CK_DeletingDtorPointer:
568 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
572 if (CGM.getLangOpts().CUDA) {
573 // Emit NULL for methods we can't codegen on this
574 // side. Otherwise we'd end up with vtable with unresolved
576 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
577 // OK on device side: functions w/ __device__ attribute
578 // OK on host side: anything except __device__-only functions.
580 CGM.getLangOpts().CUDAIsDevice
581 ? MD->hasAttr<CUDADeviceAttr>()
582 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
584 return builder.addNullPointer(CGM.Int8PtrTy);
585 // Method is acceptable, continue processing as usual.
588 auto getSpecialVirtualFn = [&](StringRef name) {
589 llvm::FunctionType *fnTy =
590 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
591 llvm::Constant *fn = CGM.CreateRuntimeFunction(fnTy, name);
592 if (auto f = dyn_cast<llvm::Function>(fn))
593 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
594 return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
597 llvm::Constant *fnPtr;
599 // Pure virtual member functions.
600 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
603 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
604 fnPtr = PureVirtualFn;
606 // Deleted virtual member functions.
607 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
608 if (!DeletedVirtualFn)
610 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
611 fnPtr = DeletedVirtualFn;
614 } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
615 layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
616 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
618 maybeEmitThunkForVTable(GD, thunkInfo);
619 nextVTableThunkIndex++;
620 fnPtr = CGM.GetAddrOfThunk(GD, thunkInfo);
622 // Otherwise we can use the method definition directly.
624 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
625 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
628 fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
633 case VTableComponent::CK_UnusedFunctionPointer:
634 return builder.addNullPointer(CGM.Int8PtrTy);
637 llvm_unreachable("Unexpected vtable component kind");
640 llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
641 SmallVector<llvm::Type *, 4> tys;
642 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
643 tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
646 return llvm::StructType::get(CGM.getLLVMContext(), tys);
649 void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
650 const VTableLayout &layout,
651 llvm::Constant *rtti) {
652 unsigned nextVTableThunkIndex = 0;
653 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
654 auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
655 size_t thisIndex = layout.getVTableOffset(i);
656 size_t nextIndex = thisIndex + layout.getVTableSize(i);
657 for (unsigned i = thisIndex; i != nextIndex; ++i) {
658 addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
660 vtableElem.finishAndAddTo(builder);
664 llvm::GlobalVariable *
665 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
666 const BaseSubobject &Base,
668 llvm::GlobalVariable::LinkageTypes Linkage,
669 VTableAddressPointsMapTy& AddressPoints) {
670 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
671 DI->completeClassData(Base.getBase());
673 std::unique_ptr<VTableLayout> VTLayout(
674 getItaniumVTableContext().createConstructionVTableLayout(
675 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
677 // Add the address points.
678 AddressPoints = VTLayout->getAddressPoints();
680 // Get the mangled construction vtable name.
681 SmallString<256> OutName;
682 llvm::raw_svector_ostream Out(OutName);
683 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
684 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
685 Base.getBase(), Out);
686 StringRef Name = OutName.str();
688 llvm::Type *VTType = getVTableType(*VTLayout);
690 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
691 // guarantee that they actually will be available externally. Instead, when
692 // emitting an available_externally VTT, we provide references to an internal
693 // linkage construction vtable. The ABI only requires complete-object vtables
694 // to be the same for all instances of a type, not construction vtables.
695 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
696 Linkage = llvm::GlobalVariable::InternalLinkage;
698 // Create the variable that will hold the construction vtable.
699 llvm::GlobalVariable *VTable =
700 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage);
701 CGM.setGlobalVisibility(VTable, RD);
703 // V-tables are always unnamed_addr.
704 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
706 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
707 CGM.getContext().getTagDeclType(Base.getBase()));
709 // Create and set the initializer.
710 ConstantInitBuilder builder(CGM);
711 auto components = builder.beginStruct();
712 createVTableInitializer(components, *VTLayout, RTTI);
713 components.finishAndSetAsInitializer(VTable);
715 CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
720 static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
721 const CXXRecordDecl *RD) {
722 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
723 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
726 /// Compute the required linkage of the vtable for the given class.
728 /// Note that we only call this at the end of the translation unit.
729 llvm::GlobalVariable::LinkageTypes
730 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
731 if (!RD->isExternallyVisible())
732 return llvm::GlobalVariable::InternalLinkage;
734 // We're at the end of the translation unit, so the current key
735 // function is fully correct.
736 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
737 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
738 // If this class has a key function, use that to determine the
739 // linkage of the vtable.
740 const FunctionDecl *def = nullptr;
741 if (keyFunction->hasBody(def))
742 keyFunction = cast<CXXMethodDecl>(def);
744 switch (keyFunction->getTemplateSpecializationKind()) {
746 case TSK_ExplicitSpecialization:
747 assert((def || CodeGenOpts.OptimizationLevel > 0) &&
748 "Shouldn't query vtable linkage without key function or "
750 if (!def && CodeGenOpts.OptimizationLevel > 0)
751 return llvm::GlobalVariable::AvailableExternallyLinkage;
753 if (keyFunction->isInlined())
754 return !Context.getLangOpts().AppleKext ?
755 llvm::GlobalVariable::LinkOnceODRLinkage :
756 llvm::Function::InternalLinkage;
758 return llvm::GlobalVariable::ExternalLinkage;
760 case TSK_ImplicitInstantiation:
761 return !Context.getLangOpts().AppleKext ?
762 llvm::GlobalVariable::LinkOnceODRLinkage :
763 llvm::Function::InternalLinkage;
765 case TSK_ExplicitInstantiationDefinition:
766 return !Context.getLangOpts().AppleKext ?
767 llvm::GlobalVariable::WeakODRLinkage :
768 llvm::Function::InternalLinkage;
770 case TSK_ExplicitInstantiationDeclaration:
771 llvm_unreachable("Should not have been asked to emit this");
775 // -fapple-kext mode does not support weak linkage, so we must use
777 if (Context.getLangOpts().AppleKext)
778 return llvm::Function::InternalLinkage;
780 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
781 llvm::GlobalValue::LinkOnceODRLinkage;
782 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
783 llvm::GlobalValue::WeakODRLinkage;
784 if (RD->hasAttr<DLLExportAttr>()) {
785 // Cannot discard exported vtables.
786 DiscardableODRLinkage = NonDiscardableODRLinkage;
787 } else if (RD->hasAttr<DLLImportAttr>()) {
788 // Imported vtables are available externally.
789 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
790 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
793 switch (RD->getTemplateSpecializationKind()) {
795 case TSK_ExplicitSpecialization:
796 case TSK_ImplicitInstantiation:
797 return DiscardableODRLinkage;
799 case TSK_ExplicitInstantiationDeclaration:
800 // Explicit instantiations in MSVC do not provide vtables, so we must emit
802 if (getTarget().getCXXABI().isMicrosoft())
803 return DiscardableODRLinkage;
804 return shouldEmitAvailableExternallyVTable(*this, RD)
805 ? llvm::GlobalVariable::AvailableExternallyLinkage
806 : llvm::GlobalVariable::ExternalLinkage;
808 case TSK_ExplicitInstantiationDefinition:
809 return NonDiscardableODRLinkage;
812 llvm_unreachable("Invalid TemplateSpecializationKind!");
815 /// This is a callback from Sema to tell us that that a particular vtable is
816 /// required to be emitted in this translation unit.
818 /// This is only called for vtables that _must_ be emitted (mainly due to key
819 /// functions). For weak vtables, CodeGen tracks when they are needed and
820 /// emits them as-needed.
821 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
822 VTables.GenerateClassData(theClass);
826 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
827 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
828 DI->completeClassData(RD);
830 if (RD->getNumVBases())
831 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
833 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
836 /// At this point in the translation unit, does it appear that can we
837 /// rely on the vtable being defined elsewhere in the program?
839 /// The response is really only definitive when called at the end of
840 /// the translation unit.
842 /// The only semantic restriction here is that the object file should
843 /// not contain a vtable definition when that vtable is defined
844 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
845 /// vtables when unnecessary.
846 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
847 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
849 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
850 // emit them even if there is an explicit template instantiation.
851 if (CGM.getTarget().getCXXABI().isMicrosoft())
854 // If we have an explicit instantiation declaration (and not a
855 // definition), the vtable is defined elsewhere.
856 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
857 if (TSK == TSK_ExplicitInstantiationDeclaration)
860 // Otherwise, if the class is an instantiated template, the
861 // vtable must be defined here.
862 if (TSK == TSK_ImplicitInstantiation ||
863 TSK == TSK_ExplicitInstantiationDefinition)
866 // Otherwise, if the class doesn't have a key function (possibly
867 // anymore), the vtable must be defined here.
868 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
872 // Otherwise, if we don't have a definition of the key function, the
873 // vtable must be defined somewhere else.
874 return !keyFunction->hasBody();
877 /// Given that we're currently at the end of the translation unit, and
878 /// we've emitted a reference to the vtable for this class, should
879 /// we define that vtable?
880 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
881 const CXXRecordDecl *RD) {
882 // If vtable is internal then it has to be done.
883 if (!CGM.getVTables().isVTableExternal(RD))
886 // If it's external then maybe we will need it as available_externally.
887 return shouldEmitAvailableExternallyVTable(CGM, RD);
890 /// Given that at some point we emitted a reference to one or more
891 /// vtables, and that we are now at the end of the translation unit,
892 /// decide whether we should emit them.
893 void CodeGenModule::EmitDeferredVTables() {
895 // Remember the size of DeferredVTables, because we're going to assume
896 // that this entire operation doesn't modify it.
897 size_t savedSize = DeferredVTables.size();
900 for (const CXXRecordDecl *RD : DeferredVTables)
901 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
902 VTables.GenerateClassData(RD);
904 assert(savedSize == DeferredVTables.size() &&
905 "deferred extra vtables during vtable emission?");
906 DeferredVTables.clear();
909 bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
910 LinkageInfo LV = RD->getLinkageAndVisibility();
911 if (!isExternallyVisible(LV.getLinkage()))
914 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
917 if (getTriple().isOSBinFormatCOFF()) {
918 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
921 if (LV.getVisibility() != HiddenVisibility)
925 if (getCodeGenOpts().LTOVisibilityPublicStd) {
926 const DeclContext *DC = RD;
928 auto *D = cast<Decl>(DC);
929 DC = DC->getParent();
930 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
931 if (auto *ND = dyn_cast<NamespaceDecl>(D))
932 if (const IdentifierInfo *II = ND->getIdentifier())
933 if (II->isStr("std") || II->isStr("stdext"))
943 void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
944 const VTableLayout &VTLayout) {
945 if (!getCodeGenOpts().PrepareForLTO)
948 CharUnits PointerWidth =
949 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
951 typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
952 std::vector<BSEntry> BitsetEntries;
953 // Create a bit set entry for each address point.
954 for (auto &&AP : VTLayout.getAddressPoints())
955 BitsetEntries.push_back(
956 std::make_pair(AP.first.getBase(),
957 VTLayout.getVTableOffset(AP.second.VTableIndex) +
958 AP.second.AddressPointIndex));
960 // Sort the bit set entries for determinism.
961 std::sort(BitsetEntries.begin(), BitsetEntries.end(),
962 [this](const BSEntry &E1, const BSEntry &E2) {
967 llvm::raw_string_ostream O1(S1);
968 getCXXABI().getMangleContext().mangleTypeName(
969 QualType(E1.first->getTypeForDecl(), 0), O1);
973 llvm::raw_string_ostream O2(S2);
974 getCXXABI().getMangleContext().mangleTypeName(
975 QualType(E2.first->getTypeForDecl(), 0), O2);
983 return E1.second < E2.second;
986 for (auto BitsetEntry : BitsetEntries)
987 AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,