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