clang 23.0.0git
CGCXX.cpp
Go to the documentation of this file.
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"
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"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Intrinsics.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.
35 if (!getCodeGenOpts().CXXCtorDtorAliases)
36 return true;
37
38 // Producing an alias to a base class ctor/dtor can degrade debug quality
39 // as the debugger cannot tell them apart.
40 if (getCodeGenOpts().OptimizationLevel == 0)
41 return true;
42
43 // Disable this optimization for ARM64EC. FIXME: This probably should work,
44 // but getting the symbol table correct is complicated.
45 if (getTarget().getTriple().isWindowsArm64EC())
46 return true;
47
48 // If sanitizing memory to check for use-after-dtor, do not emit as
49 // an alias, unless this class owns no members.
50 if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
51 !D->getParent()->field_empty())
52 return true;
53
54 // If the destructor doesn't have a trivial body, we have to emit it
55 // separately.
56 if (!D->hasTrivialBody())
57 return true;
58
59 const CXXRecordDecl *Class = D->getParent();
60
61 // We are going to instrument this destructor, so give up even if it is
62 // currently empty.
63 if (Class->mayInsertExtraPadding())
64 return true;
65
66 // If we need to manipulate a VTT parameter, give up.
67 if (Class->getNumVBases()) {
68 // Extra Credit: passing extra parameters is perfectly safe
69 // in many calling conventions, so only bail out if the ctor's
70 // calling convention is nonstandard.
71 return true;
72 }
73
74 // If any field has a non-trivial destructor, we have to emit the
75 // destructor separately.
76 for (const auto *I : Class->fields())
77 if (I->getType().isDestructedType())
78 return true;
79
80 // Try to find a unique base class with a non-trivial destructor.
81 const CXXRecordDecl *UniqueBase = nullptr;
82 for (const auto &I : Class->bases()) {
83
84 // We're in the base destructor, so skip virtual bases.
85 if (I.isVirtual()) continue;
86
87 // Skip base classes with trivial destructors.
88 const auto *Base = I.getType()->castAsCXXRecordDecl();
89 if (Base->hasTrivialDestructor()) continue;
90
91 // If we've already found a base class with a non-trivial
92 // destructor, give up.
93 if (UniqueBase) return true;
94 UniqueBase = Base;
95 }
96
97 // If we didn't find any bases with a non-trivial destructor, then
98 // the base destructor is actually effectively trivial, which can
99 // happen if it was needlessly user-defined or if there are virtual
100 // bases with non-trivial destructors.
101 if (!UniqueBase)
102 return true;
103
104 // If the base is at a non-zero offset, give up.
105 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
106 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
107 return true;
108
109 // Give up if the calling conventions don't match. We could update the call,
110 // but it is probably not worth it.
111 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
112 if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=
114 return true;
115
117 GlobalDecl TargetDecl(BaseD, Dtor_Base);
118
119 // The alias will use the linkage of the referent. If we can't
120 // support aliases with that linkage, fail.
121 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
122
123 // We can't use an alias if the linkage is not valid for one.
124 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
125 return true;
126
127 llvm::GlobalValue::LinkageTypes TargetLinkage =
128 getFunctionLinkage(TargetDecl);
129
130 // Check if we have it already.
131 StringRef MangledName = getMangledName(AliasDecl);
132 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
133 if (Entry && !Entry->isDeclaration())
134 return false;
135 if (Replacements.count(MangledName))
136 return false;
137
138 llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
139
140 // Find the referent.
141 auto *Aliasee = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
142
143 // Instead of creating as alias to a linkonce_odr, replace all of the uses
144 // of the aliasee.
145 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
146 !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
147 TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
148 // FIXME: An extern template instantiation will create functions with
149 // linkage "AvailableExternally". In libc++, some classes also define
150 // members with attribute "AlwaysInline" and expect no reference to
151 // be generated. It is desirable to reenable this optimisation after
152 // corresponding LLVM changes.
153 addReplacement(MangledName, Aliasee);
154 return false;
155 }
156
157 // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
158 // template instantiation or a dllexported class, avoid forming it on COFF.
159 // A COFF weak external alias cannot satisfy a normal undefined symbol
160 // reference from another TU. The other TU must also mark the referenced
161 // symbol as weak, which we cannot rely on.
162 if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
163 getTriple().isOSBinFormatCOFF()) {
164 return true;
165 }
166
167 // If we don't have a definition for the destructor yet or the definition is
168 // avaialable_externally, don't emit an alias. We can't emit aliases to
169 // declarations; that's just not how aliases work.
170 if (Aliasee->isDeclarationForLinker())
171 return true;
172
173 // Don't create an alias to a linker weak symbol. This avoids producing
174 // different COMDATs in different TUs. Another option would be to
175 // output the alias both for weak_odr and linkonce_odr, but that
176 // requires explicit comdat support in the IL.
177 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
178 return true;
179 // Create the alias with no name.
180 auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
181 Aliasee, &getModule());
182
183 // Destructors are always unnamed_addr.
184 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
185
186 // Switch any previous uses to the alias.
187 if (Entry) {
188 assert(Entry->getValueType() == AliasValueType &&
189 Entry->getAddressSpace() == Alias->getAddressSpace() &&
190 "declaration exists with different type");
191 Alias->takeName(Entry);
192 Entry->replaceAllUsesWith(Alias);
193 Entry->eraseFromParent();
194 } else {
195 Alias->setName(MangledName);
196 }
197
198 // Finally, set up the alias with its proper name and attributes.
200
201 return false;
202}
203
204/// Emit a definition as a global alias for another definition, unconditionally.
206 GlobalDecl TargetDecl) {
207
208 llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
209
210 StringRef MangledName = getMangledName(AliasDecl);
211 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
212 if (Entry && !Entry->isDeclaration())
213 return;
214 auto *Aliasee = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
215
216 // Determine the linkage type for the alias.
217 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
218
219 // Create the alias with no name.
220 auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
221 Aliasee, &getModule());
222 // Destructors are always unnamed_addr.
223 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
224
225 if (Entry) {
226 assert(Entry->getValueType() == AliasValueType &&
227 Entry->getAddressSpace() == Alias->getAddressSpace() &&
228 "declaration exists with different type");
229 Alias->takeName(Entry);
230 Entry->replaceAllUsesWith(Alias);
231 Entry->eraseFromParent();
232 } else {
233 Alias->setName(MangledName);
234 }
235
236 // Set any additional necessary attributes for the alias.
238}
239
240// For an implicit __host__ __device__ destructor, this trap body is reachable
241// only when a host-allocated object is destroyed on the device through the
242// vtable. HIP documents that pattern as invalid: an object with virtual
243// member functions constructed on the host cannot be destroyed on the device.
244// Device-side construction either pulls the dtor in as an organic device
245// caller (errors surface in Sema) or compiles cleanly (the real body is
246// emitted, no trap).
248 llvm::Function *Fn) {
249 if (!getLangOpts().CUDAIsDevice)
250 return false;
251 const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
252 if (!FD || !getContext().CUDADeviceInvalidFuncs.count(FD->getCanonicalDecl()))
253 return false;
254 llvm::BasicBlock *BB =
255 llvm::BasicBlock::Create(getLLVMContext(), "entry", Fn);
256 llvm::IRBuilder<> Builder(BB);
257 Builder.CreateIntrinsic(llvm::Intrinsic::trap, {});
258 llvm::Type *RetTy = Fn->getReturnType();
259 if (RetTy->isVoidTy())
260 Builder.CreateRetVoid();
261 else
262 Builder.CreateRet(llvm::PoisonValue::get(RetTy));
263 return true;
264}
265
268 auto *Fn = cast<llvm::Function>(
269 getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
270 /*DontDefer=*/true, ForDefinition));
271
272 setFunctionLinkage(GD, Fn);
273
275 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
276 setNonAliasAttributes(GD, Fn);
278 return Fn;
279}
280
282 GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
283 bool DontDefer, ForDefinition_t IsForDefinition) {
284 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
285
286 if (isa<CXXDestructorDecl>(MD)) {
287 // Always alias equivalent complete destructors to base destructors in the
288 // MS ABI.
289 if (getTarget().getCXXABI().isMicrosoft() &&
290 GD.getDtorType() == Dtor_Complete &&
291 MD->getParent()->getNumVBases() == 0)
292 GD = GD.getWithDtorType(Dtor_Base);
293 }
294
295 if (!FnType) {
296 if (!FnInfo)
298 FnType = getTypes().GetFunctionType(*FnInfo);
299 }
300
301 llvm::Constant *Ptr = GetOrCreateLLVMFunction(
302 getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
303 /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
304 return {FnType, Ptr};
305}
306
308 GlobalDecl GD,
309 llvm::Type *Ty,
310 const CXXRecordDecl *RD) {
311 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
312 "No kext in Microsoft ABI");
313 CodeGenModule &CGM = CGF.CGM;
314 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
315 Ty = llvm::PointerType::getUnqual(CGM.getLLVMContext());
316 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
317 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
318 const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
321 VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
322 AddressPoint.AddressPointIndex;
323 llvm::Value *VFuncPtr =
324 CGF.Builder.CreateConstInBoundsGEP1_64(Ty, VTable, VTableIndex, "vfnkxt");
325 llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(
326 Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));
327
328 CGPointerAuthInfo PointerAuth;
329 if (auto &Schema =
331 GlobalDecl OrigMD =
333 PointerAuth = CGF.EmitPointerAuthInfo(Schema, VFuncPtr, OrigMD, QualType());
334 }
335
336 CGCallee Callee(GD, VFunc, PointerAuth);
337 return Callee;
338}
339
340/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
341/// indirect call to virtual functions. It makes the call through indexing
342/// into the vtable.
345 llvm::Type *Ty) {
346 const CXXRecordDecl *RD = Qual.getAsRecordDecl();
347 assert(RD && "BuildAppleKextVirtualCall - Qual must be record");
348 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
350
351 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
352}
353
354/// BuildVirtualCall - This routine makes indirect vtable call for
355/// call to virtual destructors. It returns 0 if it could not do it.
358 const CXXDestructorDecl *DD,
360 const CXXRecordDecl *RD) {
361 assert(DD->isVirtual() && Type != Dtor_Base);
362 // Compute the function type we're calling.
363 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
365 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
366 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
367}
Defines the clang::ASTContext interface.
static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF, GlobalDecl GD, llvm::Type *Ty, const CXXRecordDecl *RD)
Definition CGCXX.cpp:307
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
bool isVirtual() const
Definition DeclCXX.h:2187
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2127
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition CGBuilder.h:138
virtual llvm::GlobalVariable * getAddrOfVTable(const CXXRecordDecl *RD, CharUnits VPtrOffset)=0
Get the address of the vtable for the given record decl which should be used for the vptr at the give...
All available information about a concrete callee.
Definition CGCall.h:64
CGFunctionInfo - Class to encapsulate the information about a function definition.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, CXXDtorType Type, const CXXRecordDecl *RD)
BuildVirtualCall - This routine makes indirect vtable call for call to virtual destructors.
Definition CGCXX.cpp:357
CGPointerAuthInfo EmitPointerAuthInfo(const PointerAuthSchema &Schema, llvm::Value *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Emit the concrete pointer authentication informaton for the given authentication schema.
CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier Qual, llvm::Type *Ty)
BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making indirect call to virtual...
Definition CGCXX.cpp:343
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition CGCXX.cpp:281
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
bool tryEmitCUDADeviceInvalidFunctionBody(GlobalDecl GD, llvm::Function *Fn)
Emit a trap stub body for functions in ASTContext::CUDADeviceInvalidFuncs.
Definition CGCXX.cpp:247
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Try to emit a base destructor as an alias to its primary base-class destructor.
Definition CGCXX.cpp:34
void EmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target)
Emit a definition as a global alias for another definition, unconditionally.
Definition CGCXX.cpp:205
llvm::Function * codegenCXXStructor(GlobalDecl GD)
Definition CGCXX.cpp:266
const llvm::Triple & getTriple() const
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ItaniumVTableContext & getItaniumVTableContext()
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void addReplacement(StringRef Name, llvm::Constant *C)
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1873
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition CGCall.cpp:409
bool hasAttr() const
Definition DeclBase.h:585
bool hasTrivialBody() const
Returns whether the function has a trivial body that does not require any specific codegen.
Definition Decl.cpp:3184
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
CallingConv getCallConv() const
Definition TypeBase.h:4920
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
GlobalDecl getCanonicalDecl() const
Definition GlobalDecl.h:97
GlobalDecl getWithDtorType(CXXDtorType Type)
Definition GlobalDecl.h:185
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
const VTableLayout & getVTableLayout(const CXXRecordDecl *RD)
GlobalDecl findOriginalMethod(GlobalDecl GD)
Return the method that added the v-table slot that will be used to call the given method.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool field_empty() const
Definition Decl.h:4558
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
size_t getVTableOffset(size_t i) const
AddressPointLocation getAddressPoint(BaseSubobject Base) const
QualType getType() const
Definition Decl.h:723
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
CXXDtorType
C++ destructor types.
Definition ABI.h:34
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5979
PointerAuthSchema CXXVirtualFunctionPointers
The ABI for most C++ virtual function pointers, i.e. v-table entries.