1cbc7bc94SDevang Patel //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
287fc5a5eSAnders Carlsson //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
687fc5a5eSAnders Carlsson //
787fc5a5eSAnders Carlsson //===----------------------------------------------------------------------===//
887fc5a5eSAnders Carlsson //
987fc5a5eSAnders Carlsson // This contains code dealing with C++ code generation.
1087fc5a5eSAnders Carlsson //
1187fc5a5eSAnders Carlsson //===----------------------------------------------------------------------===//
1287fc5a5eSAnders Carlsson
1387fc5a5eSAnders Carlsson // We might split this into multiple files if it gets too unwieldy
1487fc5a5eSAnders Carlsson
154e786ddcSCharles Davis #include "CGCXXABI.h"
1687fc5a5eSAnders Carlsson #include "CodeGenFunction.h"
179803178aSReid Kleckner #include "CodeGenModule.h"
1887fc5a5eSAnders Carlsson #include "clang/AST/ASTContext.h"
199803178aSReid Kleckner #include "clang/AST/Attr.h"
2087fc5a5eSAnders Carlsson #include "clang/AST/Decl.h"
21e5fd6f22SAnders Carlsson #include "clang/AST/DeclCXX.h"
22131be8b4SAnders Carlsson #include "clang/AST/DeclObjC.h"
230ff0b376SPeter Collingbourne #include "clang/AST/Mangle.h"
243a02247dSChandler Carruth #include "clang/AST/RecordLayout.h"
2552d78a51SAnders Carlsson #include "clang/AST/StmtCXX.h"
266368818fSRichard Trieu #include "clang/Basic/CodeGenOptions.h"
2787fc5a5eSAnders Carlsson #include "llvm/ADT/StringExtras.h"
2887fc5a5eSAnders Carlsson using namespace clang;
2987fc5a5eSAnders Carlsson using namespace CodeGen;
3087fc5a5eSAnders Carlsson
317f416cc4SJohn McCall
32f8ff7b9fSJohn McCall /// Try to emit a base destructor as an alias to its primary
33f8ff7b9fSJohn McCall /// base-class destructor.
TryEmitBaseDestructorAsAlias(const CXXDestructorDecl * D)34f8ff7b9fSJohn McCall bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
35f8ff7b9fSJohn McCall if (!getCodeGenOpts().CXXCtorDtorAliases)
36f8ff7b9fSJohn McCall return true;
37f8ff7b9fSJohn McCall
38d967badcSRafael Espindola // Producing an alias to a base class ctor/dtor can degrade debug quality
39f6a24ce4SAlp Toker // as the debugger cannot tell them apart.
40d967badcSRafael Espindola if (getCodeGenOpts().OptimizationLevel == 0)
41d967badcSRafael Espindola return true;
42d967badcSRafael Espindola
43866af2d6SNaomi Musgrave // If sanitizing memory to check for use-after-dtor, do not emit as
44866af2d6SNaomi Musgrave // an alias, unless this class owns no members.
45866af2d6SNaomi Musgrave if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
46866af2d6SNaomi Musgrave !D->getParent()->field_empty())
47866af2d6SNaomi Musgrave return true;
48866af2d6SNaomi Musgrave
49f8ff7b9fSJohn McCall // If the destructor doesn't have a trivial body, we have to emit it
50f8ff7b9fSJohn McCall // separately.
519bd7d164SAnders Carlsson if (!D->hasTrivialBody())
52f8ff7b9fSJohn McCall return true;
53f8ff7b9fSJohn McCall
54f8ff7b9fSJohn McCall const CXXRecordDecl *Class = D->getParent();
55f8ff7b9fSJohn McCall
565f1b4e8fSKostya Serebryany // We are going to instrument this destructor, so give up even if it is
575f1b4e8fSKostya Serebryany // currently empty.
585f1b4e8fSKostya Serebryany if (Class->mayInsertExtraPadding())
595f1b4e8fSKostya Serebryany return true;
605f1b4e8fSKostya Serebryany
61f8ff7b9fSJohn McCall // If we need to manipulate a VTT parameter, give up.
62f8ff7b9fSJohn McCall if (Class->getNumVBases()) {
63f8ff7b9fSJohn McCall // Extra Credit: passing extra parameters is perfectly safe
64f8ff7b9fSJohn McCall // in many calling conventions, so only bail out if the ctor's
65f8ff7b9fSJohn McCall // calling convention is nonstandard.
66f8ff7b9fSJohn McCall return true;
67f8ff7b9fSJohn McCall }
68f8ff7b9fSJohn McCall
692b3c5538SJohn McCall // If any field has a non-trivial destructor, we have to emit the
702b3c5538SJohn McCall // destructor separately.
71e8a8baefSAaron Ballman for (const auto *I : Class->fields())
722d7c57ecSDavid Blaikie if (I->getType().isDestructedType())
73f8ff7b9fSJohn McCall return true;
74f8ff7b9fSJohn McCall
75f8ff7b9fSJohn McCall // Try to find a unique base class with a non-trivial destructor.
768a13c418SCraig Topper const CXXRecordDecl *UniqueBase = nullptr;
77574705edSAaron Ballman for (const auto &I : Class->bases()) {
78f8ff7b9fSJohn McCall
79f8ff7b9fSJohn McCall // We're in the base destructor, so skip virtual bases.
80574705edSAaron Ballman if (I.isVirtual()) continue;
81f8ff7b9fSJohn McCall
82f8ff7b9fSJohn McCall // Skip base classes with trivial destructors.
832ae250c3SRafael Espindola const auto *Base =
841cd399c9SSimon Pilgrim cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
85f8ff7b9fSJohn McCall if (Base->hasTrivialDestructor()) continue;
86f8ff7b9fSJohn McCall
87f8ff7b9fSJohn McCall // If we've already found a base class with a non-trivial
88f8ff7b9fSJohn McCall // destructor, give up.
89f8ff7b9fSJohn McCall if (UniqueBase) return true;
90f8ff7b9fSJohn McCall UniqueBase = Base;
91f8ff7b9fSJohn McCall }
92f8ff7b9fSJohn McCall
93f8ff7b9fSJohn McCall // If we didn't find any bases with a non-trivial destructor, then
94f8ff7b9fSJohn McCall // the base destructor is actually effectively trivial, which can
95f8ff7b9fSJohn McCall // happen if it was needlessly user-defined or if there are virtual
96f8ff7b9fSJohn McCall // bases with non-trivial destructors.
97f8ff7b9fSJohn McCall if (!UniqueBase)
98f8ff7b9fSJohn McCall return true;
99f8ff7b9fSJohn McCall
100f8ff7b9fSJohn McCall // If the base is at a non-zero offset, give up.
101f8ff7b9fSJohn McCall const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
1022ef30314SBenjamin Kramer if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
103f8ff7b9fSJohn McCall return true;
104f8ff7b9fSJohn McCall
105191b9512SRafael Espindola // Give up if the calling conventions don't match. We could update the call,
106191b9512SRafael Espindola // but it is probably not worth it.
107961ba21aSRafael Espindola const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
1087e38f0c4SSimon Pilgrim if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=
1097e38f0c4SSimon Pilgrim D->getType()->castAs<FunctionType>()->getCallConv())
110191b9512SRafael Espindola return true;
111191b9512SRafael Espindola
112d914fd21SPeter Collingbourne GlobalDecl AliasDecl(D, Dtor_Base);
113d914fd21SPeter Collingbourne GlobalDecl TargetDecl(BaseD, Dtor_Base);
114d4324148SJohn McCall
115f6a24ce4SAlp Toker // The alias will use the linkage of the referent. If we can't
116d4324148SJohn McCall // support aliases with that linkage, fail.
1174d90dba7SPeter Collingbourne llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
118d4324148SJohn McCall
1193f643bd1SRafael Espindola // We can't use an alias if the linkage is not valid for one.
1203f643bd1SRafael Espindola if (!llvm::GlobalAlias::isValidLinkage(Linkage))
1213f643bd1SRafael Espindola return true;
1223f643bd1SRafael Espindola
1232e2995bfSRafael Espindola llvm::GlobalValue::LinkageTypes TargetLinkage =
1242e2995bfSRafael Espindola getFunctionLinkage(TargetDecl);
1252e2995bfSRafael Espindola
1263f643bd1SRafael Espindola // Check if we have it already.
1273f643bd1SRafael Espindola StringRef MangledName = getMangledName(AliasDecl);
1283f643bd1SRafael Espindola llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1293f643bd1SRafael Espindola if (Entry && !Entry->isDeclaration())
1303f643bd1SRafael Espindola return false;
1312e2995bfSRafael Espindola if (Replacements.count(MangledName))
1322e2995bfSRafael Espindola return false;
1333f643bd1SRafael Espindola
134f8ff7b9fSJohn McCall // Derive the type for the alias.
1352a791d7dSDavid Blaikie llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
1362a791d7dSDavid Blaikie llvm::PointerType *AliasType = AliasValueType->getPointerTo();
137f8ff7b9fSJohn McCall
138f6a24ce4SAlp Toker // Find the referent. Some aliases might require a bitcast, in
139f8ff7b9fSJohn McCall // which case the caller is responsible for ensuring the soundness
140f8ff7b9fSJohn McCall // of these semantics.
1412ae250c3SRafael Espindola auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
14227c60b51SRafael Espindola llvm::Constant *Aliasee = Ref;
14327c60b51SRafael Espindola if (Ref->getType() != AliasType)
14427c60b51SRafael Espindola Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
145f8ff7b9fSJohn McCall
146e2ec6faaSRafael Espindola // Instead of creating as alias to a linkonce_odr, replace all of the uses
147b2633b97SRafael Espindola // of the aliasee.
1483da37e05SReid Kleckner if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
1493da37e05SReid Kleckner !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
1503da37e05SReid Kleckner TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
1513da37e05SReid Kleckner // FIXME: An extern template instantiation will create functions with
1523da37e05SReid Kleckner // linkage "AvailableExternally". In libc++, some classes also define
1533da37e05SReid Kleckner // members with attribute "AlwaysInline" and expect no reference to
1543da37e05SReid Kleckner // be generated. It is desirable to reenable this optimisation after
1553da37e05SReid Kleckner // corresponding LLVM changes.
156f8adb381SYaron Keren addReplacement(MangledName, Aliasee);
157e2ec6faaSRafael Espindola return false;
158e2ec6faaSRafael Espindola }
159e2ec6faaSRafael Espindola
160489cfe14SReid Kleckner // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
161489cfe14SReid Kleckner // template instantiation or a dllexported class, avoid forming it on COFF.
162489cfe14SReid Kleckner // A COFF weak external alias cannot satisfy a normal undefined symbol
163489cfe14SReid Kleckner // reference from another TU. The other TU must also mark the referenced
164489cfe14SReid Kleckner // symbol as weak, which we cannot rely on.
165489cfe14SReid Kleckner if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
166489cfe14SReid Kleckner getTriple().isOSBinFormatCOFF()) {
167489cfe14SReid Kleckner return true;
168489cfe14SReid Kleckner }
169489cfe14SReid Kleckner
1703da37e05SReid Kleckner // If we don't have a definition for the destructor yet or the definition is
1713da37e05SReid Kleckner // avaialable_externally, don't emit an alias. We can't emit aliases to
1723da37e05SReid Kleckner // declarations; that's just not how aliases work.
1733da37e05SReid Kleckner if (Ref->isDeclarationForLinker())
174961ba21aSRafael Espindola return true;
175961ba21aSRafael Espindola
176129d313cSRafael Espindola // Don't create an alias to a linker weak symbol. This avoids producing
177129d313cSRafael Espindola // different COMDATs in different TUs. Another option would be to
178129d313cSRafael Espindola // output the alias both for weak_odr and linkonce_odr, but that
179129d313cSRafael Espindola // requires explicit comdat support in the IL.
180b15683e6SRafael Espindola if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
181961ba21aSRafael Espindola return true;
1822e2995bfSRafael Espindola
183d4324148SJohn McCall // Create the alias with no name.
1842a791d7dSDavid Blaikie auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
1852a791d7dSDavid Blaikie Aliasee, &getModule());
186d4324148SJohn McCall
187d914fd21SPeter Collingbourne // Destructors are always unnamed_addr.
188d914fd21SPeter Collingbourne Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
189d914fd21SPeter Collingbourne
190aea181deSJohn McCall // Switch any previous uses to the alias.
191d4324148SJohn McCall if (Entry) {
192aea181deSJohn McCall assert(Entry->getType() == AliasType &&
193aea181deSJohn McCall "declaration exists with different type");
1947ec5043cSJohn McCall Alias->takeName(Entry);
195d4324148SJohn McCall Entry->replaceAllUsesWith(Alias);
196d4324148SJohn McCall Entry->eraseFromParent();
1977ec5043cSJohn McCall } else {
198ea836bc4SAnders Carlsson Alias->setName(MangledName);
199d4324148SJohn McCall }
200d4324148SJohn McCall
201d4324148SJohn McCall // Finally, set up the alias with its proper name and attributes.
202b7350046SRafael Espindola SetCommonAttributes(AliasDecl, Alias);
203d4324148SJohn McCall
204d4324148SJohn McCall return false;
205d4324148SJohn McCall }
206bd7d11f7SAnders Carlsson
codegenCXXStructor(GlobalDecl GD)207d1c5b28cSPeter Collingbourne llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {
208d1c5b28cSPeter Collingbourne const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);
2095368618dSRafael Espindola auto *Fn = cast<llvm::Function>(
210d1c5b28cSPeter Collingbourne getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
211d195d4c5SJohn McCall /*DontDefer=*/true, ForDefinition));
2125368618dSRafael Espindola
2135368618dSRafael Espindola setFunctionLinkage(GD, Fn);
214bb4f962aSHans Wennborg
2155368618dSRafael Espindola CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
216e4e78135SRafael Espindola setNonAliasAttributes(GD, Fn);
217d1c5b28cSPeter Collingbourne SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
2185368618dSRafael Espindola return Fn;
2195368618dSRafael Espindola }
2205368618dSRafael Espindola
getAddrAndTypeOfCXXStructor(GlobalDecl GD,const CGFunctionInfo * FnInfo,llvm::FunctionType * FnType,bool DontDefer,ForDefinition_t IsForDefinition)221f7321540SJames Y Knight llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(
222d1c5b28cSPeter Collingbourne GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
223d1c5b28cSPeter Collingbourne bool DontDefer, ForDefinition_t IsForDefinition) {
224d1c5b28cSPeter Collingbourne auto *MD = cast<CXXMethodDecl>(GD.getDecl());
225f7321540SJames Y Knight
2261ba406c9SSimon Pilgrim if (isa<CXXDestructorDecl>(MD)) {
227ae9b0701SReid Kleckner // Always alias equivalent complete destructors to base destructors in the
228ae9b0701SReid Kleckner // MS ABI.
229ae9b0701SReid Kleckner if (getTarget().getCXXABI().isMicrosoft() &&
230d1c5b28cSPeter Collingbourne GD.getDtorType() == Dtor_Complete &&
231d1c5b28cSPeter Collingbourne MD->getParent()->getNumVBases() == 0)
232d1c5b28cSPeter Collingbourne GD = GD.getWithDtorType(Dtor_Base);
2338d2a19b4SRafael Espindola }
23409b5fe68SAnders Carlsson
2358d2a19b4SRafael Espindola if (!FnType) {
2368d2a19b4SRafael Espindola if (!FnInfo)
237d1c5b28cSPeter Collingbourne FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
2388d2a19b4SRafael Espindola FnType = getTypes().GetFunctionType(*FnInfo);
2398d2a19b4SRafael Espindola }
24046288effSJohn McCall
241f7321540SJames Y Knight llvm::Constant *Ptr = GetOrCreateLLVMFunction(
242cab5858eSAndrey Bokhanko getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
24349a3ad21SRui Ueyama /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
244f7321540SJames Y Knight return {FnType, Ptr};
245e8eeffdfSAnders Carlsson }
246eaa28f7eSAnders Carlsson
BuildAppleKextVirtualCall(CodeGenFunction & CGF,GlobalDecl GD,llvm::Type * Ty,const CXXRecordDecl * RD)247b92ab1afSJohn McCall static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
24803e8746fSTimur Iskhodzhanov GlobalDecl GD,
24903e8746fSTimur Iskhodzhanov llvm::Type *Ty,
25003e8746fSTimur Iskhodzhanov const CXXRecordDecl *RD) {
25188fd439aSTimur Iskhodzhanov assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
25288fd439aSTimur Iskhodzhanov "No kext in Microsoft ABI");
25303e8746fSTimur Iskhodzhanov CodeGenModule &CGM = CGF.CGM;
2548b5987ebSTimur Iskhodzhanov llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
25546354bacSNikita Popov Ty = Ty->getPointerTo();
25646354bacSNikita Popov VTable = CGF.Builder.CreateBitCast(VTable, Ty->getPointerTo());
25703e8746fSTimur Iskhodzhanov assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
25858776636STimur Iskhodzhanov uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
2592849c4e8SPeter Collingbourne const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
2602849c4e8SPeter Collingbourne VTableLayout::AddressPointLocation AddressPoint =
2612849c4e8SPeter Collingbourne VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
2622849c4e8SPeter Collingbourne VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
2632849c4e8SPeter Collingbourne AddressPoint.AddressPointIndex;
26403e8746fSTimur Iskhodzhanov llvm::Value *VFuncPtr =
265*5071360eSNikita Popov CGF.Builder.CreateConstInBoundsGEP1_64(Ty, VTable, VTableIndex, "vfnkxt");
26607c9d532SGuillaume Chatelet llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(
26746354bacSNikita Popov Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));
268de6480a3SErich Keane CGCallee Callee(GD, VFunc);
269b92ab1afSJohn McCall return Callee;
270e828c369SAnders Carlsson }
271e828c369SAnders Carlsson
27203e8746fSTimur Iskhodzhanov /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
27347609b08SFariborz Jahanian /// indirect call to virtual functions. It makes the call through indexing
27447609b08SFariborz Jahanian /// into the vtable.
275b92ab1afSJohn McCall CGCallee
BuildAppleKextVirtualCall(const CXXMethodDecl * MD,NestedNameSpecifier * Qual,llvm::Type * Ty)27647609b08SFariborz Jahanian CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
27747609b08SFariborz Jahanian NestedNameSpecifier *Qual,
2782192fe50SChris Lattner llvm::Type *Ty) {
27947609b08SFariborz Jahanian assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
28047609b08SFariborz Jahanian "BuildAppleKextVirtualCall - bad Qual kind");
28147609b08SFariborz Jahanian
28247609b08SFariborz Jahanian const Type *QTy = Qual->getAsType();
28347609b08SFariborz Jahanian QualType T = QualType(QTy, 0);
28447609b08SFariborz Jahanian const RecordType *RT = T->getAs<RecordType>();
28547609b08SFariborz Jahanian assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
2862ae250c3SRafael Espindola const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
287265c325eSFariborz Jahanian
2882ae250c3SRafael Espindola if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
289265c325eSFariborz Jahanian return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
290265c325eSFariborz Jahanian
29103e8746fSTimur Iskhodzhanov return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
29247609b08SFariborz Jahanian }
29347609b08SFariborz Jahanian
294265c325eSFariborz Jahanian /// BuildVirtualCall - This routine makes indirect vtable call for
295265c325eSFariborz Jahanian /// call to virtual destructors. It returns 0 if it could not do it.
296b92ab1afSJohn McCall CGCallee
BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl * DD,CXXDtorType Type,const CXXRecordDecl * RD)297265c325eSFariborz Jahanian CodeGenFunction::BuildAppleKextVirtualDestructorCall(
298265c325eSFariborz Jahanian const CXXDestructorDecl *DD,
299265c325eSFariborz Jahanian CXXDtorType Type,
300265c325eSFariborz Jahanian const CXXRecordDecl *RD) {
301b92ab1afSJohn McCall assert(DD->isVirtual() && Type != Dtor_Base);
302265c325eSFariborz Jahanian // Compute the function type we're calling.
3038d2a19b4SRafael Espindola const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
304d1c5b28cSPeter Collingbourne GlobalDecl(DD, Dtor_Complete));
305a729c62bSJohn McCall llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
30603e8746fSTimur Iskhodzhanov return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
307265c325eSFariborz Jahanian }
308