CGCXX.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code dealing with C++ code generation.
  11. //
  12. //===----------------------------------------------------------------------===//
  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/Frontend/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 the destructor doesn't have a trivial body, we have to emit it
  37. // separately.
  38. if (!D->hasTrivialBody())
  39. return true;
  40. const CXXRecordDecl *Class = D->getParent();
  41. // We are going to instrument this destructor, so give up even if it is
  42. // currently empty.
  43. if (Class->mayInsertExtraPadding())
  44. return true;
  45. // If we need to manipulate a VTT parameter, give up.
  46. if (Class->getNumVBases()) {
  47. // Extra Credit: passing extra parameters is perfectly safe
  48. // in many calling conventions, so only bail out if the ctor's
  49. // calling convention is nonstandard.
  50. return true;
  51. }
  52. // If any field has a non-trivial destructor, we have to emit the
  53. // destructor separately.
  54. for (const auto *I : Class->fields())
  55. if (I->getType().isDestructedType())
  56. return true;
  57. // Try to find a unique base class with a non-trivial destructor.
  58. const CXXRecordDecl *UniqueBase = nullptr;
  59. for (const auto &I : Class->bases()) {
  60. // We're in the base destructor, so skip virtual bases.
  61. if (I.isVirtual()) continue;
  62. // Skip base classes with trivial destructors.
  63. const auto *Base =
  64. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  65. if (Base->hasTrivialDestructor()) continue;
  66. // If we've already found a base class with a non-trivial
  67. // destructor, give up.
  68. if (UniqueBase) return true;
  69. UniqueBase = Base;
  70. }
  71. // If we didn't find any bases with a non-trivial destructor, then
  72. // the base destructor is actually effectively trivial, which can
  73. // happen if it was needlessly user-defined or if there are virtual
  74. // bases with non-trivial destructors.
  75. if (!UniqueBase)
  76. return true;
  77. // If the base is at a non-zero offset, give up.
  78. const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
  79. if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
  80. return true;
  81. // Give up if the calling conventions don't match. We could update the call,
  82. // but it is probably not worth it.
  83. const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
  84. if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
  85. D->getType()->getAs<FunctionType>()->getCallConv())
  86. return true;
  87. return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
  88. GlobalDecl(BaseD, Dtor_Base),
  89. false);
  90. }
  91. /// Try to emit a definition as a global alias for another definition.
  92. /// If \p InEveryTU is true, we know that an equivalent alias can be produced
  93. /// in every translation unit.
  94. bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
  95. GlobalDecl TargetDecl,
  96. bool InEveryTU) {
  97. if (!getCodeGenOpts().CXXCtorDtorAliases)
  98. return true;
  99. // The alias will use the linkage of the referent. If we can't
  100. // support aliases with that linkage, fail.
  101. llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
  102. // We can't use an alias if the linkage is not valid for one.
  103. if (!llvm::GlobalAlias::isValidLinkage(Linkage))
  104. return true;
  105. // Don't create a weak alias for a dllexport'd symbol.
  106. if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
  107. llvm::GlobalValue::isWeakForLinker(Linkage))
  108. return true;
  109. llvm::GlobalValue::LinkageTypes TargetLinkage =
  110. getFunctionLinkage(TargetDecl);
  111. // Check if we have it already.
  112. StringRef MangledName = getMangledName(AliasDecl);
  113. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  114. if (Entry && !Entry->isDeclaration())
  115. return false;
  116. if (Replacements.count(MangledName))
  117. return false;
  118. // Derive the type for the alias.
  119. llvm::PointerType *AliasType
  120. = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
  121. // Find the referent. Some aliases might require a bitcast, in
  122. // which case the caller is responsible for ensuring the soundness
  123. // of these semantics.
  124. auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
  125. llvm::Constant *Aliasee = Ref;
  126. if (Ref->getType() != AliasType)
  127. Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
  128. // Instead of creating as alias to a linkonce_odr, replace all of the uses
  129. // of the aliasee.
  130. if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
  131. (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
  132. !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
  133. // FIXME: An extern template instantiation will create functions with
  134. // linkage "AvailableExternally". In libc++, some classes also define
  135. // members with attribute "AlwaysInline" and expect no reference to
  136. // be generated. It is desirable to reenable this optimisation after
  137. // corresponding LLVM changes.
  138. Replacements[MangledName] = Aliasee;
  139. return false;
  140. }
  141. if (!InEveryTU) {
  142. // If we don't have a definition for the destructor yet, don't
  143. // emit. We can't emit aliases to declarations; that's just not
  144. // how aliases work.
  145. if (Ref->isDeclaration())
  146. return true;
  147. }
  148. // Don't create an alias to a linker weak symbol. This avoids producing
  149. // different COMDATs in different TUs. Another option would be to
  150. // output the alias both for weak_odr and linkonce_odr, but that
  151. // requires explicit comdat support in the IL.
  152. if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
  153. return true;
  154. // Create the alias with no name.
  155. auto *Alias =
  156. llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee, &getModule());
  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. setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
  169. return false;
  170. }
  171. llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
  172. StructorType Type) {
  173. const CGFunctionInfo &FnInfo =
  174. getTypes().arrangeCXXStructorDeclaration(MD, Type);
  175. auto *Fn = cast<llvm::Function>(
  176. getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
  177. GlobalDecl GD;
  178. if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  179. GD = GlobalDecl(DD, toCXXDtorType(Type));
  180. } else {
  181. const auto *CD = cast<CXXConstructorDecl>(MD);
  182. GD = GlobalDecl(CD, toCXXCtorType(Type));
  183. }
  184. setFunctionLinkage(GD, Fn);
  185. setFunctionDLLStorageClass(GD, Fn);
  186. CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
  187. setFunctionDefinitionAttributes(MD, Fn);
  188. SetLLVMFunctionAttributesForDefinition(MD, Fn);
  189. return Fn;
  190. }
  191. llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
  192. const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
  193. llvm::FunctionType *FnType, bool DontDefer) {
  194. GlobalDecl GD;
  195. if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  196. GD = GlobalDecl(CD, toCXXCtorType(Type));
  197. } else {
  198. GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
  199. }
  200. StringRef Name = getMangledName(GD);
  201. if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
  202. return Existing;
  203. if (!FnType) {
  204. if (!FnInfo)
  205. FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
  206. FnType = getTypes().GetFunctionType(*FnInfo);
  207. }
  208. return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
  209. /*ForVTable=*/false,
  210. DontDefer));
  211. }
  212. static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
  213. GlobalDecl GD,
  214. llvm::Type *Ty,
  215. const CXXRecordDecl *RD) {
  216. assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
  217. "No kext in Microsoft ABI");
  218. GD = GD.getCanonicalDecl();
  219. CodeGenModule &CGM = CGF.CGM;
  220. llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
  221. Ty = Ty->getPointerTo()->getPointerTo();
  222. VTable = CGF.Builder.CreateBitCast(VTable, Ty);
  223. assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
  224. uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
  225. uint64_t AddressPoint =
  226. CGM.getItaniumVTableContext().getVTableLayout(RD)
  227. .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
  228. VTableIndex += AddressPoint;
  229. llvm::Value *VFuncPtr =
  230. CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
  231. return CGF.Builder.CreateLoad(VFuncPtr);
  232. }
  233. /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
  234. /// indirect call to virtual functions. It makes the call through indexing
  235. /// into the vtable.
  236. llvm::Value *
  237. CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  238. NestedNameSpecifier *Qual,
  239. llvm::Type *Ty) {
  240. assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
  241. "BuildAppleKextVirtualCall - bad Qual kind");
  242. const Type *QTy = Qual->getAsType();
  243. QualType T = QualType(QTy, 0);
  244. const RecordType *RT = T->getAs<RecordType>();
  245. assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
  246. const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
  247. if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
  248. return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
  249. return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
  250. }
  251. /// BuildVirtualCall - This routine makes indirect vtable call for
  252. /// call to virtual destructors. It returns 0 if it could not do it.
  253. llvm::Value *
  254. CodeGenFunction::BuildAppleKextVirtualDestructorCall(
  255. const CXXDestructorDecl *DD,
  256. CXXDtorType Type,
  257. const CXXRecordDecl *RD) {
  258. const auto *MD = cast<CXXMethodDecl>(DD);
  259. // FIXME. Dtor_Base dtor is always direct!!
  260. // It need be somehow inline expanded into the caller.
  261. // -O does that. But need to support -O0 as well.
  262. if (MD->isVirtual() && Type != Dtor_Base) {
  263. // Compute the function type we're calling.
  264. const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
  265. DD, StructorType::Complete);
  266. llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
  267. return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
  268. }
  269. return nullptr;
  270. }