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