CGCXXABI.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. //===----- CGCXXABI.cpp - Interface to C++ ABIs ---------------------------===//
  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 provides an abstract class for C++ code generation. Concrete subclasses
  10. // of this implement code generation for specific C++ ABIs.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGCXXABI.h"
  14. #include "CGCleanup.h"
  15. #include "clang/AST/Attr.h"
  16. using namespace clang;
  17. using namespace CodeGen;
  18. CGCXXABI::~CGCXXABI() { }
  19. void CGCXXABI::ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S) {
  20. DiagnosticsEngine &Diags = CGF.CGM.getDiags();
  21. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  22. "cannot yet compile %0 in this ABI");
  23. Diags.Report(CGF.getContext().getFullLoc(CGF.CurCodeDecl->getLocation()),
  24. DiagID)
  25. << S;
  26. }
  27. llvm::Constant *CGCXXABI::GetBogusMemberPointer(QualType T) {
  28. return llvm::Constant::getNullValue(CGM.getTypes().ConvertType(T));
  29. }
  30. llvm::Type *
  31. CGCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
  32. return CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  33. }
  34. CGCallee CGCXXABI::EmitLoadOfMemberFunctionPointer(
  35. CodeGenFunction &CGF, const Expr *E, Address This,
  36. llvm::Value *&ThisPtrForCall,
  37. llvm::Value *MemPtr, const MemberPointerType *MPT) {
  38. ErrorUnsupportedABI(CGF, "calls through member pointers");
  39. ThisPtrForCall = This.getPointer();
  40. const FunctionProtoType *FPT =
  41. MPT->getPointeeType()->getAs<FunctionProtoType>();
  42. const auto *RD =
  43. cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
  44. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
  45. CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
  46. llvm::Constant *FnPtr = llvm::Constant::getNullValue(FTy->getPointerTo());
  47. return CGCallee::forDirect(FnPtr, FPT);
  48. }
  49. llvm::Value *
  50. CGCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
  51. Address Base, llvm::Value *MemPtr,
  52. const MemberPointerType *MPT) {
  53. ErrorUnsupportedABI(CGF, "loads of member pointers");
  54. llvm::Type *Ty = CGF.ConvertType(MPT->getPointeeType())
  55. ->getPointerTo(Base.getAddressSpace());
  56. return llvm::Constant::getNullValue(Ty);
  57. }
  58. llvm::Value *CGCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
  59. const CastExpr *E,
  60. llvm::Value *Src) {
  61. ErrorUnsupportedABI(CGF, "member function pointer conversions");
  62. return GetBogusMemberPointer(E->getType());
  63. }
  64. llvm::Constant *CGCXXABI::EmitMemberPointerConversion(const CastExpr *E,
  65. llvm::Constant *Src) {
  66. return GetBogusMemberPointer(E->getType());
  67. }
  68. llvm::Value *
  69. CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
  70. llvm::Value *L,
  71. llvm::Value *R,
  72. const MemberPointerType *MPT,
  73. bool Inequality) {
  74. ErrorUnsupportedABI(CGF, "member function pointer comparison");
  75. return CGF.Builder.getFalse();
  76. }
  77. llvm::Value *
  78. CGCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  79. llvm::Value *MemPtr,
  80. const MemberPointerType *MPT) {
  81. ErrorUnsupportedABI(CGF, "member function pointer null testing");
  82. return CGF.Builder.getFalse();
  83. }
  84. llvm::Constant *
  85. CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
  86. return GetBogusMemberPointer(QualType(MPT, 0));
  87. }
  88. llvm::Constant *CGCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
  89. return GetBogusMemberPointer(CGM.getContext().getMemberPointerType(
  90. MD->getType(), MD->getParent()->getTypeForDecl()));
  91. }
  92. llvm::Constant *CGCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
  93. CharUnits offset) {
  94. return GetBogusMemberPointer(QualType(MPT, 0));
  95. }
  96. llvm::Constant *CGCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) {
  97. return GetBogusMemberPointer(MPT);
  98. }
  99. bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
  100. // Fake answer.
  101. return true;
  102. }
  103. void CGCXXABI::buildThisParam(CodeGenFunction &CGF, FunctionArgList &params) {
  104. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  105. // FIXME: I'm not entirely sure I like using a fake decl just for code
  106. // generation. Maybe we can come up with a better way?
  107. auto *ThisDecl = ImplicitParamDecl::Create(
  108. CGM.getContext(), nullptr, MD->getLocation(),
  109. &CGM.getContext().Idents.get("this"), MD->getThisType(),
  110. ImplicitParamDecl::CXXThis);
  111. params.push_back(ThisDecl);
  112. CGF.CXXABIThisDecl = ThisDecl;
  113. // Compute the presumed alignment of 'this', which basically comes
  114. // down to whether we know it's a complete object or not.
  115. auto &Layout = CGF.getContext().getASTRecordLayout(MD->getParent());
  116. if (MD->getParent()->getNumVBases() == 0 || // avoid vcall in common case
  117. MD->getParent()->isEffectivelyFinal() ||
  118. isThisCompleteObject(CGF.CurGD)) {
  119. CGF.CXXABIThisAlignment = Layout.getAlignment();
  120. } else {
  121. CGF.CXXABIThisAlignment = Layout.getNonVirtualAlignment();
  122. }
  123. }
  124. llvm::Value *CGCXXABI::loadIncomingCXXThis(CodeGenFunction &CGF) {
  125. return CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)),
  126. "this");
  127. }
  128. void CGCXXABI::setCXXABIThisValue(CodeGenFunction &CGF, llvm::Value *ThisPtr) {
  129. /// Initialize the 'this' slot.
  130. assert(getThisDecl(CGF) && "no 'this' variable for function");
  131. CGF.CXXABIThisValue = ThisPtr;
  132. }
  133. bool CGCXXABI::mayNeedDestruction(const VarDecl *VD) const {
  134. if (VD->needsDestruction(getContext()))
  135. return true;
  136. // If the variable has an incomplete class type (or array thereof), it
  137. // might need destruction.
  138. const Type *T = VD->getType()->getBaseElementTypeUnsafe();
  139. if (T->getAs<RecordType>() && T->isIncompleteType())
  140. return true;
  141. return false;
  142. }
  143. bool CGCXXABI::isEmittedWithConstantInitializer(
  144. const VarDecl *VD, bool InspectInitForWeakDef) const {
  145. VD = VD->getMostRecentDecl();
  146. if (VD->hasAttr<ConstInitAttr>())
  147. return true;
  148. // All later checks examine the initializer specified on the variable. If
  149. // the variable is weak, such examination would not be correct.
  150. if (!InspectInitForWeakDef && (VD->isWeak() || VD->hasAttr<SelectAnyAttr>()))
  151. return false;
  152. const VarDecl *InitDecl = VD->getInitializingDeclaration();
  153. if (!InitDecl)
  154. return false;
  155. // If there's no initializer to run, this is constant initialization.
  156. if (!InitDecl->hasInit())
  157. return true;
  158. // If we have the only definition, we don't need a thread wrapper if we
  159. // will emit the value as a constant.
  160. if (isUniqueGVALinkage(getContext().GetGVALinkageForVariable(VD)))
  161. return !mayNeedDestruction(VD) && InitDecl->evaluateValue();
  162. // Otherwise, we need a thread wrapper unless we know that every
  163. // translation unit will emit the value as a constant. We rely on the
  164. // variable being constant-initialized in every translation unit if it's
  165. // constant-initialized in any translation unit, which isn't actually
  166. // guaranteed by the standard but is necessary for sanity.
  167. return InitDecl->hasConstantInitialization();
  168. }
  169. void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
  170. RValue RV, QualType ResultType) {
  171. assert(!CGF.hasAggregateEvaluationKind(ResultType) &&
  172. "cannot handle aggregates");
  173. CGF.EmitReturnOfRValue(RV, ResultType);
  174. }
  175. CharUnits CGCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
  176. if (!requiresArrayCookie(expr))
  177. return CharUnits::Zero();
  178. return getArrayCookieSizeImpl(expr->getAllocatedType());
  179. }
  180. CharUnits CGCXXABI::getArrayCookieSizeImpl(QualType elementType) {
  181. // BOGUS
  182. return CharUnits::Zero();
  183. }
  184. Address CGCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  185. Address NewPtr,
  186. llvm::Value *NumElements,
  187. const CXXNewExpr *expr,
  188. QualType ElementType) {
  189. // Should never be called.
  190. ErrorUnsupportedABI(CGF, "array cookie initialization");
  191. return Address::invalid();
  192. }
  193. bool CGCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
  194. QualType elementType) {
  195. // If the class's usual deallocation function takes two arguments,
  196. // it needs a cookie.
  197. if (expr->doesUsualArrayDeleteWantSize())
  198. return true;
  199. return elementType.isDestructedType();
  200. }
  201. bool CGCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
  202. // If the class's usual deallocation function takes two arguments,
  203. // it needs a cookie.
  204. if (expr->doesUsualArrayDeleteWantSize())
  205. return true;
  206. return expr->getAllocatedType().isDestructedType();
  207. }
  208. void CGCXXABI::ReadArrayCookie(CodeGenFunction &CGF, Address ptr,
  209. const CXXDeleteExpr *expr, QualType eltTy,
  210. llvm::Value *&numElements,
  211. llvm::Value *&allocPtr, CharUnits &cookieSize) {
  212. // Derive a char* in the same address space as the pointer.
  213. ptr = CGF.Builder.CreateElementBitCast(ptr, CGF.Int8Ty);
  214. // If we don't need an array cookie, bail out early.
  215. if (!requiresArrayCookie(expr, eltTy)) {
  216. allocPtr = ptr.getPointer();
  217. numElements = nullptr;
  218. cookieSize = CharUnits::Zero();
  219. return;
  220. }
  221. cookieSize = getArrayCookieSizeImpl(eltTy);
  222. Address allocAddr =
  223. CGF.Builder.CreateConstInBoundsByteGEP(ptr, -cookieSize);
  224. allocPtr = allocAddr.getPointer();
  225. numElements = readArrayCookieImpl(CGF, allocAddr, cookieSize);
  226. }
  227. llvm::Value *CGCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
  228. Address ptr,
  229. CharUnits cookieSize) {
  230. ErrorUnsupportedABI(CGF, "reading a new[] cookie");
  231. return llvm::ConstantInt::get(CGF.SizeTy, 0);
  232. }
  233. /// Returns the adjustment, in bytes, required for the given
  234. /// member-pointer operation. Returns null if no adjustment is
  235. /// required.
  236. llvm::Constant *CGCXXABI::getMemberPointerAdjustment(const CastExpr *E) {
  237. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  238. E->getCastKind() == CK_BaseToDerivedMemberPointer);
  239. QualType derivedType;
  240. if (E->getCastKind() == CK_DerivedToBaseMemberPointer)
  241. derivedType = E->getSubExpr()->getType();
  242. else
  243. derivedType = E->getType();
  244. const CXXRecordDecl *derivedClass =
  245. derivedType->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDecl();
  246. return CGM.GetNonVirtualBaseClassOffset(derivedClass,
  247. E->path_begin(),
  248. E->path_end());
  249. }
  250. llvm::BasicBlock *
  251. CGCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
  252. const CXXRecordDecl *RD) {
  253. if (CGM.getTarget().getCXXABI().hasConstructorVariants())
  254. llvm_unreachable("shouldn't be called in this ABI");
  255. ErrorUnsupportedABI(CGF, "complete object detection in ctor");
  256. return nullptr;
  257. }
  258. void CGCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
  259. const CXXDestructorDecl *Dtor,
  260. CXXDtorType DT) const {
  261. // Assume the base C++ ABI has no special rules for destructor variants.
  262. CGM.setDLLImportDLLExport(GV, Dtor);
  263. }
  264. llvm::GlobalValue::LinkageTypes CGCXXABI::getCXXDestructorLinkage(
  265. GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
  266. // Delegate back to CGM by default.
  267. return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
  268. /*IsConstantVariable=*/false);
  269. }
  270. bool CGCXXABI::NeedsVTTParameter(GlobalDecl GD) {
  271. return false;
  272. }
  273. llvm::CallInst *
  274. CGCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
  275. llvm::Value *Exn) {
  276. // Just call std::terminate and ignore the violating exception.
  277. return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
  278. }
  279. CatchTypeInfo CGCXXABI::getCatchAllTypeInfo() {
  280. return CatchTypeInfo{nullptr, 0};
  281. }
  282. std::vector<CharUnits> CGCXXABI::getVBPtrOffsets(const CXXRecordDecl *RD) {
  283. return std::vector<CharUnits>();
  284. }
  285. CGCXXABI::AddedStructorArgCounts CGCXXABI::addImplicitConstructorArgs(
  286. CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
  287. bool ForVirtualBase, bool Delegating, CallArgList &Args) {
  288. AddedStructorArgs AddedArgs =
  289. getImplicitConstructorArgs(CGF, D, Type, ForVirtualBase, Delegating);
  290. for (size_t i = 0; i < AddedArgs.Prefix.size(); ++i) {
  291. Args.insert(Args.begin() + 1 + i,
  292. CallArg(RValue::get(AddedArgs.Prefix[i].Value),
  293. AddedArgs.Prefix[i].Type));
  294. }
  295. for (const auto &arg : AddedArgs.Suffix) {
  296. Args.add(RValue::get(arg.Value), arg.Type);
  297. }
  298. return AddedStructorArgCounts(AddedArgs.Prefix.size(),
  299. AddedArgs.Suffix.size());
  300. }