Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGCXX.cpp
35234 views
//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code dealing with C++ code generation.9//10//===----------------------------------------------------------------------===//1112// We might split this into multiple files if it gets too unwieldy1314#include "CGCXXABI.h"15#include "CodeGenFunction.h"16#include "CodeGenModule.h"17#include "clang/AST/ASTContext.h"18#include "clang/AST/Attr.h"19#include "clang/AST/Decl.h"20#include "clang/AST/DeclCXX.h"21#include "clang/AST/DeclObjC.h"22#include "clang/AST/Mangle.h"23#include "clang/AST/RecordLayout.h"24#include "clang/AST/StmtCXX.h"25#include "clang/Basic/CodeGenOptions.h"26#include "llvm/ADT/StringExtras.h"27using namespace clang;28using namespace CodeGen;293031/// Try to emit a base destructor as an alias to its primary32/// base-class destructor.33bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {34if (!getCodeGenOpts().CXXCtorDtorAliases)35return true;3637// Producing an alias to a base class ctor/dtor can degrade debug quality38// as the debugger cannot tell them apart.39if (getCodeGenOpts().OptimizationLevel == 0)40return true;4142// Disable this optimization for ARM64EC. FIXME: This probably should work,43// but getting the symbol table correct is complicated.44if (getTarget().getTriple().isWindowsArm64EC())45return true;4647// If sanitizing memory to check for use-after-dtor, do not emit as48// an alias, unless this class owns no members.49if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&50!D->getParent()->field_empty())51return true;5253// If the destructor doesn't have a trivial body, we have to emit it54// separately.55if (!D->hasTrivialBody())56return true;5758const CXXRecordDecl *Class = D->getParent();5960// We are going to instrument this destructor, so give up even if it is61// currently empty.62if (Class->mayInsertExtraPadding())63return true;6465// If we need to manipulate a VTT parameter, give up.66if (Class->getNumVBases()) {67// Extra Credit: passing extra parameters is perfectly safe68// in many calling conventions, so only bail out if the ctor's69// calling convention is nonstandard.70return true;71}7273// If any field has a non-trivial destructor, we have to emit the74// destructor separately.75for (const auto *I : Class->fields())76if (I->getType().isDestructedType())77return true;7879// Try to find a unique base class with a non-trivial destructor.80const CXXRecordDecl *UniqueBase = nullptr;81for (const auto &I : Class->bases()) {8283// We're in the base destructor, so skip virtual bases.84if (I.isVirtual()) continue;8586// Skip base classes with trivial destructors.87const auto *Base =88cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());89if (Base->hasTrivialDestructor()) continue;9091// If we've already found a base class with a non-trivial92// destructor, give up.93if (UniqueBase) return true;94UniqueBase = Base;95}9697// If we didn't find any bases with a non-trivial destructor, then98// the base destructor is actually effectively trivial, which can99// happen if it was needlessly user-defined or if there are virtual100// bases with non-trivial destructors.101if (!UniqueBase)102return true;103104// If the base is at a non-zero offset, give up.105const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);106if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())107return true;108109// Give up if the calling conventions don't match. We could update the call,110// but it is probably not worth it.111const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();112if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=113D->getType()->castAs<FunctionType>()->getCallConv())114return true;115116GlobalDecl AliasDecl(D, Dtor_Base);117GlobalDecl TargetDecl(BaseD, Dtor_Base);118119// The alias will use the linkage of the referent. If we can't120// support aliases with that linkage, fail.121llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);122123// We can't use an alias if the linkage is not valid for one.124if (!llvm::GlobalAlias::isValidLinkage(Linkage))125return true;126127llvm::GlobalValue::LinkageTypes TargetLinkage =128getFunctionLinkage(TargetDecl);129130// Check if we have it already.131StringRef MangledName = getMangledName(AliasDecl);132llvm::GlobalValue *Entry = GetGlobalValue(MangledName);133if (Entry && !Entry->isDeclaration())134return false;135if (Replacements.count(MangledName))136return false;137138llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);139140// Find the referent.141auto *Aliasee = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));142143// Instead of creating as alias to a linkonce_odr, replace all of the uses144// of the aliasee.145if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&146!(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&147TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {148// FIXME: An extern template instantiation will create functions with149// linkage "AvailableExternally". In libc++, some classes also define150// members with attribute "AlwaysInline" and expect no reference to151// be generated. It is desirable to reenable this optimisation after152// corresponding LLVM changes.153addReplacement(MangledName, Aliasee);154return false;155}156157// If we have a weak, non-discardable alias (weak, weak_odr), like an extern158// template instantiation or a dllexported class, avoid forming it on COFF.159// A COFF weak external alias cannot satisfy a normal undefined symbol160// reference from another TU. The other TU must also mark the referenced161// symbol as weak, which we cannot rely on.162if (llvm::GlobalValue::isWeakForLinker(Linkage) &&163getTriple().isOSBinFormatCOFF()) {164return true;165}166167// If we don't have a definition for the destructor yet or the definition is168// avaialable_externally, don't emit an alias. We can't emit aliases to169// declarations; that's just not how aliases work.170if (Aliasee->isDeclarationForLinker())171return true;172173// Don't create an alias to a linker weak symbol. This avoids producing174// different COMDATs in different TUs. Another option would be to175// output the alias both for weak_odr and linkonce_odr, but that176// requires explicit comdat support in the IL.177if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))178return true;179180// Create the alias with no name.181auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",182Aliasee, &getModule());183184// Destructors are always unnamed_addr.185Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);186187// Switch any previous uses to the alias.188if (Entry) {189assert(Entry->getValueType() == AliasValueType &&190Entry->getAddressSpace() == Alias->getAddressSpace() &&191"declaration exists with different type");192Alias->takeName(Entry);193Entry->replaceAllUsesWith(Alias);194Entry->eraseFromParent();195} else {196Alias->setName(MangledName);197}198199// Finally, set up the alias with its proper name and attributes.200SetCommonAttributes(AliasDecl, Alias);201202return false;203}204205llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {206const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);207auto *Fn = cast<llvm::Function>(208getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,209/*DontDefer=*/true, ForDefinition));210211setFunctionLinkage(GD, Fn);212213CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);214setNonAliasAttributes(GD, Fn);215SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);216return Fn;217}218219llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(220GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,221bool DontDefer, ForDefinition_t IsForDefinition) {222auto *MD = cast<CXXMethodDecl>(GD.getDecl());223224if (isa<CXXDestructorDecl>(MD)) {225// Always alias equivalent complete destructors to base destructors in the226// MS ABI.227if (getTarget().getCXXABI().isMicrosoft() &&228GD.getDtorType() == Dtor_Complete &&229MD->getParent()->getNumVBases() == 0)230GD = GD.getWithDtorType(Dtor_Base);231}232233if (!FnType) {234if (!FnInfo)235FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);236FnType = getTypes().GetFunctionType(*FnInfo);237}238239llvm::Constant *Ptr = GetOrCreateLLVMFunction(240getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,241/*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);242return {FnType, Ptr};243}244245static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,246GlobalDecl GD,247llvm::Type *Ty,248const CXXRecordDecl *RD) {249assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&250"No kext in Microsoft ABI");251CodeGenModule &CGM = CGF.CGM;252llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());253Ty = llvm::PointerType::getUnqual(CGM.getLLVMContext());254assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");255uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);256const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);257VTableLayout::AddressPointLocation AddressPoint =258VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));259VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +260AddressPoint.AddressPointIndex;261llvm::Value *VFuncPtr =262CGF.Builder.CreateConstInBoundsGEP1_64(Ty, VTable, VTableIndex, "vfnkxt");263llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(264Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));265266CGPointerAuthInfo PointerAuth;267if (auto &Schema =268CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers) {269GlobalDecl OrigMD =270CGM.getItaniumVTableContext().findOriginalMethod(GD.getCanonicalDecl());271PointerAuth = CGF.EmitPointerAuthInfo(Schema, VFuncPtr, OrigMD, QualType());272}273274CGCallee Callee(GD, VFunc, PointerAuth);275return Callee;276}277278/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making279/// indirect call to virtual functions. It makes the call through indexing280/// into the vtable.281CGCallee282CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,283NestedNameSpecifier *Qual,284llvm::Type *Ty) {285assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&286"BuildAppleKextVirtualCall - bad Qual kind");287288const Type *QTy = Qual->getAsType();289QualType T = QualType(QTy, 0);290const RecordType *RT = T->getAs<RecordType>();291assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");292const auto *RD = cast<CXXRecordDecl>(RT->getDecl());293294if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))295return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);296297return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);298}299300/// BuildVirtualCall - This routine makes indirect vtable call for301/// call to virtual destructors. It returns 0 if it could not do it.302CGCallee303CodeGenFunction::BuildAppleKextVirtualDestructorCall(304const CXXDestructorDecl *DD,305CXXDtorType Type,306const CXXRecordDecl *RD) {307assert(DD->isVirtual() && Type != Dtor_Base);308// Compute the function type we're calling.309const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(310GlobalDecl(DD, Dtor_Complete));311llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);312return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);313}314315316