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