1 //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ code generation.
12 //===----------------------------------------------------------------------===//
14 // We might split this into multiple files if it gets too unwieldy
16 #include "CodeGenModule.h"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/ASTContext.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/Frontend/CodeGenOptions.h"
27 #include "llvm/ADT/StringExtras.h"
28 using namespace clang;
29 using namespace CodeGen;
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)
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)
42 // If the destructor doesn't have a trivial body, we have to emit it
44 if (!D->hasTrivialBody())
47 const CXXRecordDecl *Class = D->getParent();
49 // We are going to instrument this destructor, so give up even if it is
51 if (Class->mayInsertExtraPadding())
54 // If we need to manipulate a VTT parameter, give up.
55 if (Class->getNumVBases()) {
56 // Extra Credit: passing extra parameters is perfectly safe
57 // in many calling conventions, so only bail out if the ctor's
58 // calling convention is nonstandard.
62 // If any field has a non-trivial destructor, we have to emit the
63 // destructor separately.
64 for (const auto *I : Class->fields())
65 if (I->getType().isDestructedType())
68 // Try to find a unique base class with a non-trivial destructor.
69 const CXXRecordDecl *UniqueBase = nullptr;
70 for (const auto &I : Class->bases()) {
72 // We're in the base destructor, so skip virtual bases.
73 if (I.isVirtual()) continue;
75 // Skip base classes with trivial destructors.
77 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
78 if (Base->hasTrivialDestructor()) continue;
80 // If we've already found a base class with a non-trivial
81 // destructor, give up.
82 if (UniqueBase) return true;
86 // If we didn't find any bases with a non-trivial destructor, then
87 // the base destructor is actually effectively trivial, which can
88 // happen if it was needlessly user-defined or if there are virtual
89 // bases with non-trivial destructors.
93 // If the base is at a non-zero offset, give up.
94 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
95 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
98 // Give up if the calling conventions don't match. We could update the call,
99 // but it is probably not worth it.
100 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
101 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
102 D->getType()->getAs<FunctionType>()->getCallConv())
105 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
106 GlobalDecl(BaseD, Dtor_Base),
110 /// Try to emit a definition as a global alias for another definition.
111 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
112 /// in every translation unit.
113 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
114 GlobalDecl TargetDecl,
116 if (!getCodeGenOpts().CXXCtorDtorAliases)
119 // The alias will use the linkage of the referent. If we can't
120 // support aliases with that linkage, fail.
121 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
123 // We can't use an alias if the linkage is not valid for one.
124 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
127 // Don't create a weak alias for a dllexport'd symbol.
128 if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
129 llvm::GlobalValue::isWeakForLinker(Linkage))
132 llvm::GlobalValue::LinkageTypes TargetLinkage =
133 getFunctionLinkage(TargetDecl);
135 // Check if we have it already.
136 StringRef MangledName = getMangledName(AliasDecl);
137 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
138 if (Entry && !Entry->isDeclaration())
140 if (Replacements.count(MangledName))
143 // Derive the type for the alias.
144 llvm::PointerType *AliasType
145 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
147 // Find the referent. Some aliases might require a bitcast, in
148 // which case the caller is responsible for ensuring the soundness
149 // of these semantics.
150 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
151 llvm::Constant *Aliasee = Ref;
152 if (Ref->getType() != AliasType)
153 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
155 // Instead of creating as alias to a linkonce_odr, replace all of the uses
157 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
158 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
159 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
160 // FIXME: An extern template instantiation will create functions with
161 // linkage "AvailableExternally". In libc++, some classes also define
162 // members with attribute "AlwaysInline" and expect no reference to
163 // be generated. It is desirable to reenable this optimisation after
164 // corresponding LLVM changes.
165 Replacements[MangledName] = Aliasee;
170 // If we don't have a definition for the destructor yet, don't
171 // emit. We can't emit aliases to declarations; that's just not
173 if (Ref->isDeclaration())
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))
184 // Create the alias with no name.
186 llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee, &getModule());
188 // Switch any previous uses to the alias.
190 assert(Entry->getType() == AliasType &&
191 "declaration exists with different type");
192 Alias->takeName(Entry);
193 Entry->replaceAllUsesWith(Alias);
194 Entry->eraseFromParent();
196 Alias->setName(MangledName);
199 // Finally, set up the alias with its proper name and attributes.
200 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
205 llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
207 const CGFunctionInfo &FnInfo =
208 getTypes().arrangeCXXStructorDeclaration(MD, Type);
209 auto *Fn = cast<llvm::Function>(
210 getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
213 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
214 GD = GlobalDecl(DD, toCXXDtorType(Type));
216 const auto *CD = cast<CXXConstructorDecl>(MD);
217 GD = GlobalDecl(CD, toCXXCtorType(Type));
220 setFunctionLinkage(GD, Fn);
221 setFunctionDLLStorageClass(GD, Fn);
223 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
224 setFunctionDefinitionAttributes(MD, Fn);
225 SetLLVMFunctionAttributesForDefinition(MD, Fn);
229 llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
230 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
231 llvm::FunctionType *FnType, bool DontDefer) {
233 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
234 GD = GlobalDecl(CD, toCXXCtorType(Type));
236 GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
239 StringRef Name = getMangledName(GD);
240 if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
245 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
246 FnType = getTypes().GetFunctionType(*FnInfo);
249 return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
254 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
257 const CXXRecordDecl *RD) {
258 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
259 "No kext in Microsoft ABI");
260 GD = GD.getCanonicalDecl();
261 CodeGenModule &CGM = CGF.CGM;
262 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
263 Ty = Ty->getPointerTo()->getPointerTo();
264 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
265 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
266 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
267 uint64_t AddressPoint =
268 CGM.getItaniumVTableContext().getVTableLayout(RD)
269 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
270 VTableIndex += AddressPoint;
271 llvm::Value *VFuncPtr =
272 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
273 return CGF.Builder.CreateLoad(VFuncPtr);
276 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
277 /// indirect call to virtual functions. It makes the call through indexing
280 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
281 NestedNameSpecifier *Qual,
283 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
284 "BuildAppleKextVirtualCall - bad Qual kind");
286 const Type *QTy = Qual->getAsType();
287 QualType T = QualType(QTy, 0);
288 const RecordType *RT = T->getAs<RecordType>();
289 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
290 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
292 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
293 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
295 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
298 /// BuildVirtualCall - This routine makes indirect vtable call for
299 /// call to virtual destructors. It returns 0 if it could not do it.
301 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
302 const CXXDestructorDecl *DD,
304 const CXXRecordDecl *RD) {
305 const auto *MD = cast<CXXMethodDecl>(DD);
306 // FIXME. Dtor_Base dtor is always direct!!
307 // It need be somehow inline expanded into the caller.
308 // -O does that. But need to support -O0 as well.
309 if (MD->isVirtual() && Type != Dtor_Base) {
310 // Compute the function type we're calling.
311 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
312 DD, StructorType::Complete);
313 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
314 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);