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