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