llvm-project
314 строк · 12.0 Кб
1//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation.
10//
11//===----------------------------------------------------------------------===//
12
13// We might split this into multiple files if it gets too unwieldy
14
15#include "CGCXXABI.h"16#include "CodeGenFunction.h"17#include "CodeGenModule.h"18#include "clang/AST/ASTContext.h"19#include "clang/AST/Attr.h"20#include "clang/AST/Decl.h"21#include "clang/AST/DeclCXX.h"22#include "clang/AST/DeclObjC.h"23#include "clang/AST/Mangle.h"24#include "clang/AST/RecordLayout.h"25#include "clang/AST/StmtCXX.h"26#include "clang/Basic/CodeGenOptions.h"27#include "llvm/ADT/StringExtras.h"28using namespace clang;29using namespace CodeGen;30
31
32/// Try to emit a base destructor as an alias to its primary
33/// base-class destructor.
34bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {35if (!getCodeGenOpts().CXXCtorDtorAliases)36return true;37
38// Producing an alias to a base class ctor/dtor can degrade debug quality39// as the debugger cannot tell them apart.40if (getCodeGenOpts().OptimizationLevel == 0)41return true;42
43// Disable this optimization for ARM64EC. FIXME: This probably should work,44// but getting the symbol table correct is complicated.45if (getTarget().getTriple().isWindowsArm64EC())46return true;47
48// If sanitizing memory to check for use-after-dtor, do not emit as49// an alias, unless this class owns no members.50if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&51!D->getParent()->field_empty())52return true;53
54// If the destructor doesn't have a trivial body, we have to emit it55// separately.56if (!D->hasTrivialBody())57return true;58
59const CXXRecordDecl *Class = D->getParent();60
61// We are going to instrument this destructor, so give up even if it is62// currently empty.63if (Class->mayInsertExtraPadding())64return true;65
66// If we need to manipulate a VTT parameter, give up.67if (Class->getNumVBases()) {68// Extra Credit: passing extra parameters is perfectly safe69// in many calling conventions, so only bail out if the ctor's70// calling convention is nonstandard.71return true;72}73
74// If any field has a non-trivial destructor, we have to emit the75// destructor separately.76for (const auto *I : Class->fields())77if (I->getType().isDestructedType())78return true;79
80// Try to find a unique base class with a non-trivial destructor.81const CXXRecordDecl *UniqueBase = nullptr;82for (const auto &I : Class->bases()) {83
84// We're in the base destructor, so skip virtual bases.85if (I.isVirtual()) continue;86
87// Skip base classes with trivial destructors.88const auto *Base =89cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());90if (Base->hasTrivialDestructor()) continue;91
92// If we've already found a base class with a non-trivial93// destructor, give up.94if (UniqueBase) return true;95UniqueBase = Base;96}97
98// If we didn't find any bases with a non-trivial destructor, then99// the base destructor is actually effectively trivial, which can100// happen if it was needlessly user-defined or if there are virtual101// bases with non-trivial destructors.102if (!UniqueBase)103return true;104
105// If the base is at a non-zero offset, give up.106const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);107if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())108return true;109
110// Give up if the calling conventions don't match. We could update the call,111// but it is probably not worth it.112const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();113if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=114D->getType()->castAs<FunctionType>()->getCallConv())115return true;116
117GlobalDecl AliasDecl(D, Dtor_Base);118GlobalDecl TargetDecl(BaseD, Dtor_Base);119
120// The alias will use the linkage of the referent. If we can't121// support aliases with that linkage, fail.122llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);123
124// We can't use an alias if the linkage is not valid for one.125if (!llvm::GlobalAlias::isValidLinkage(Linkage))126return true;127
128llvm::GlobalValue::LinkageTypes TargetLinkage =129getFunctionLinkage(TargetDecl);130
131// Check if we have it already.132StringRef MangledName = getMangledName(AliasDecl);133llvm::GlobalValue *Entry = GetGlobalValue(MangledName);134if (Entry && !Entry->isDeclaration())135return false;136if (Replacements.count(MangledName))137return false;138
139llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);140
141// Find the referent.142auto *Aliasee = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));143
144// Instead of creating as alias to a linkonce_odr, replace all of the uses145// of the aliasee.146if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&147!(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&148TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {149// FIXME: An extern template instantiation will create functions with150// linkage "AvailableExternally". In libc++, some classes also define151// members with attribute "AlwaysInline" and expect no reference to152// be generated. It is desirable to reenable this optimisation after153// corresponding LLVM changes.154addReplacement(MangledName, Aliasee);155return false;156}157
158// If we have a weak, non-discardable alias (weak, weak_odr), like an extern159// template instantiation or a dllexported class, avoid forming it on COFF.160// A COFF weak external alias cannot satisfy a normal undefined symbol161// reference from another TU. The other TU must also mark the referenced162// symbol as weak, which we cannot rely on.163if (llvm::GlobalValue::isWeakForLinker(Linkage) &&164getTriple().isOSBinFormatCOFF()) {165return true;166}167
168// If we don't have a definition for the destructor yet or the definition is169// avaialable_externally, don't emit an alias. We can't emit aliases to170// declarations; that's just not how aliases work.171if (Aliasee->isDeclarationForLinker())172return true;173
174// Don't create an alias to a linker weak symbol. This avoids producing175// different COMDATs in different TUs. Another option would be to176// output the alias both for weak_odr and linkonce_odr, but that177// requires explicit comdat support in the IL.178if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))179return true;180
181// Create the alias with no name.182auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",183Aliasee, &getModule());184
185// Destructors are always unnamed_addr.186Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);187
188// Switch any previous uses to the alias.189if (Entry) {190assert(Entry->getValueType() == AliasValueType &&191Entry->getAddressSpace() == Alias->getAddressSpace() &&192"declaration exists with different type");193Alias->takeName(Entry);194Entry->replaceAllUsesWith(Alias);195Entry->eraseFromParent();196} else {197Alias->setName(MangledName);198}199
200// Finally, set up the alias with its proper name and attributes.201SetCommonAttributes(AliasDecl, Alias);202
203return false;204}
205
206llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {207const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);208auto *Fn = cast<llvm::Function>(209getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,210/*DontDefer=*/true, ForDefinition));211
212setFunctionLinkage(GD, Fn);213
214CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);215setNonAliasAttributes(GD, Fn);216SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);217return Fn;218}
219
220llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(221GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,222bool DontDefer, ForDefinition_t IsForDefinition) {223auto *MD = cast<CXXMethodDecl>(GD.getDecl());224
225if (isa<CXXDestructorDecl>(MD)) {226// Always alias equivalent complete destructors to base destructors in the227// MS ABI.228if (getTarget().getCXXABI().isMicrosoft() &&229GD.getDtorType() == Dtor_Complete &&230MD->getParent()->getNumVBases() == 0)231GD = GD.getWithDtorType(Dtor_Base);232}233
234if (!FnType) {235if (!FnInfo)236FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);237FnType = getTypes().GetFunctionType(*FnInfo);238}239
240llvm::Constant *Ptr = GetOrCreateLLVMFunction(241getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,242/*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);243return {FnType, Ptr};244}
245
246static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,247GlobalDecl GD,248llvm::Type *Ty,249const CXXRecordDecl *RD) {250assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&251"No kext in Microsoft ABI");252CodeGenModule &CGM = CGF.CGM;253llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());254Ty = llvm::PointerType::getUnqual(CGM.getLLVMContext());255assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");256uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);257const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);258VTableLayout::AddressPointLocation AddressPoint =259VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));260VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +261AddressPoint.AddressPointIndex;262llvm::Value *VFuncPtr =263CGF.Builder.CreateConstInBoundsGEP1_64(Ty, VTable, VTableIndex, "vfnkxt");264llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(265Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));266
267CGPointerAuthInfo PointerAuth;268if (auto &Schema =269CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers) {270GlobalDecl OrigMD =271CGM.getItaniumVTableContext().findOriginalMethod(GD.getCanonicalDecl());272PointerAuth = CGF.EmitPointerAuthInfo(Schema, VFuncPtr, OrigMD, QualType());273}274
275CGCallee Callee(GD, VFunc, PointerAuth);276return Callee;277}
278
279/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
280/// indirect call to virtual functions. It makes the call through indexing
281/// into the vtable.
282CGCallee
283CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,284NestedNameSpecifier *Qual,285llvm::Type *Ty) {286assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&287"BuildAppleKextVirtualCall - bad Qual kind");288
289const Type *QTy = Qual->getAsType();290QualType T = QualType(QTy, 0);291const RecordType *RT = T->getAs<RecordType>();292assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");293const auto *RD = cast<CXXRecordDecl>(RT->getDecl());294
295if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))296return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);297
298return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);299}
300
301/// BuildVirtualCall - This routine makes indirect vtable call for
302/// call to virtual destructors. It returns 0 if it could not do it.
303CGCallee
304CodeGenFunction::BuildAppleKextVirtualDestructorCall(305const CXXDestructorDecl *DD,306CXXDtorType Type,307const CXXRecordDecl *RD) {308assert(DD->isVirtual() && Type != Dtor_Base);309// Compute the function type we're calling.310const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(311GlobalDecl(DD, Dtor_Complete));312llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);313return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);314}
315