CGCXX.cpp 12 KB

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