ObjCARCAnalysisUtils.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ObjCARCAnalysisUtils.h - ObjC ARC Analysis Utilities -----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. /// \file
  14. /// This file defines common analysis utilities used by the ObjC ARC Optimizer.
  15. /// ARC stands for Automatic Reference Counting and is a system for managing
  16. /// reference counts for objects in Objective C.
  17. ///
  18. /// WARNING: This file knows about certain library functions. It recognizes them
  19. /// by name, and hardwires knowledge of their semantics.
  20. ///
  21. /// WARNING: This file knows about how certain Objective-C library functions are
  22. /// used. Naive LLVM IR transformations which would otherwise be
  23. /// behavior-preserving may break these assumptions.
  24. ///
  25. //===----------------------------------------------------------------------===//
  26. #ifndef LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
  27. #define LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
  28. #include "llvm/Analysis/ObjCARCInstKind.h"
  29. #include "llvm/Analysis/ValueTracking.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/ValueHandle.h"
  33. #include <optional>
  34. namespace llvm {
  35. class AAResults;
  36. namespace objcarc {
  37. /// A handy option to enable/disable all ARC Optimizations.
  38. extern bool EnableARCOpts;
  39. /// Test if the given module looks interesting to run ARC optimization
  40. /// on.
  41. inline bool ModuleHasARC(const Module &M) {
  42. return
  43. M.getNamedValue("llvm.objc.retain") ||
  44. M.getNamedValue("llvm.objc.release") ||
  45. M.getNamedValue("llvm.objc.autorelease") ||
  46. M.getNamedValue("llvm.objc.retainAutoreleasedReturnValue") ||
  47. M.getNamedValue("llvm.objc.unsafeClaimAutoreleasedReturnValue") ||
  48. M.getNamedValue("llvm.objc.retainBlock") ||
  49. M.getNamedValue("llvm.objc.autoreleaseReturnValue") ||
  50. M.getNamedValue("llvm.objc.autoreleasePoolPush") ||
  51. M.getNamedValue("llvm.objc.loadWeakRetained") ||
  52. M.getNamedValue("llvm.objc.loadWeak") ||
  53. M.getNamedValue("llvm.objc.destroyWeak") ||
  54. M.getNamedValue("llvm.objc.storeWeak") ||
  55. M.getNamedValue("llvm.objc.initWeak") ||
  56. M.getNamedValue("llvm.objc.moveWeak") ||
  57. M.getNamedValue("llvm.objc.copyWeak") ||
  58. M.getNamedValue("llvm.objc.retainedObject") ||
  59. M.getNamedValue("llvm.objc.unretainedObject") ||
  60. M.getNamedValue("llvm.objc.unretainedPointer") ||
  61. M.getNamedValue("llvm.objc.clang.arc.use");
  62. }
  63. /// This is a wrapper around getUnderlyingObject which also knows how to
  64. /// look through objc_retain and objc_autorelease calls, which we know to return
  65. /// their argument verbatim.
  66. inline const Value *GetUnderlyingObjCPtr(const Value *V) {
  67. for (;;) {
  68. V = getUnderlyingObject(V);
  69. if (!IsForwarding(GetBasicARCInstKind(V)))
  70. break;
  71. V = cast<CallInst>(V)->getArgOperand(0);
  72. }
  73. return V;
  74. }
  75. /// A wrapper for GetUnderlyingObjCPtr used for results memoization.
  76. inline const Value *GetUnderlyingObjCPtrCached(
  77. const Value *V,
  78. DenseMap<const Value *, std::pair<WeakVH, WeakTrackingVH>> &Cache) {
  79. // The entry is invalid if either value handle is null.
  80. auto InCache = Cache.lookup(V);
  81. if (InCache.first && InCache.second)
  82. return InCache.second;
  83. const Value *Computed = GetUnderlyingObjCPtr(V);
  84. Cache[V] =
  85. std::make_pair(const_cast<Value *>(V), const_cast<Value *>(Computed));
  86. return Computed;
  87. }
  88. /// The RCIdentity root of a value \p V is a dominating value U for which
  89. /// retaining or releasing U is equivalent to retaining or releasing V. In other
  90. /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
  91. ///
  92. /// We use this in the ARC optimizer to make it easier to match up ARC
  93. /// operations by always mapping ARC operations to RCIdentityRoots instead of
  94. /// pointers themselves.
  95. ///
  96. /// The two ways that we see RCIdentical values in ObjC are via:
  97. ///
  98. /// 1. PointerCasts
  99. /// 2. Forwarding Calls that return their argument verbatim.
  100. ///
  101. /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
  102. /// This implies that two RCIdentical values must alias.
  103. inline const Value *GetRCIdentityRoot(const Value *V) {
  104. for (;;) {
  105. V = V->stripPointerCasts();
  106. if (!IsForwarding(GetBasicARCInstKind(V)))
  107. break;
  108. V = cast<CallInst>(V)->getArgOperand(0);
  109. }
  110. return V;
  111. }
  112. /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
  113. /// casts away the const of the result. For documentation about what an
  114. /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
  115. /// function.
  116. inline Value *GetRCIdentityRoot(Value *V) {
  117. return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
  118. }
  119. /// Assuming the given instruction is one of the special calls such as
  120. /// objc_retain or objc_release, return the RCIdentity root of the argument of
  121. /// the call.
  122. inline Value *GetArgRCIdentityRoot(Value *Inst) {
  123. return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
  124. }
  125. inline bool IsNullOrUndef(const Value *V) {
  126. return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
  127. }
  128. inline bool IsNoopInstruction(const Instruction *I) {
  129. return isa<BitCastInst>(I) ||
  130. (isa<GetElementPtrInst>(I) &&
  131. cast<GetElementPtrInst>(I)->hasAllZeroIndices());
  132. }
  133. /// Test whether the given value is possible a retainable object pointer.
  134. inline bool IsPotentialRetainableObjPtr(const Value *Op) {
  135. // Pointers to static or stack storage are not valid retainable object
  136. // pointers.
  137. if (isa<Constant>(Op) || isa<AllocaInst>(Op))
  138. return false;
  139. // Special arguments can not be a valid retainable object pointer.
  140. if (const Argument *Arg = dyn_cast<Argument>(Op))
  141. if (Arg->hasPassPointeeByValueCopyAttr() || Arg->hasNestAttr() ||
  142. Arg->hasStructRetAttr())
  143. return false;
  144. // Only consider values with pointer types.
  145. //
  146. // It seemes intuitive to exclude function pointer types as well, since
  147. // functions are never retainable object pointers, however clang occasionally
  148. // bitcasts retainable object pointers to function-pointer type temporarily.
  149. PointerType *Ty = dyn_cast<PointerType>(Op->getType());
  150. if (!Ty)
  151. return false;
  152. // Conservatively assume anything else is a potential retainable object
  153. // pointer.
  154. return true;
  155. }
  156. bool IsPotentialRetainableObjPtr(const Value *Op, AAResults &AA);
  157. /// Helper for GetARCInstKind. Determines what kind of construct CS
  158. /// is.
  159. inline ARCInstKind GetCallSiteClass(const CallBase &CB) {
  160. for (const Use &U : CB.args())
  161. if (IsPotentialRetainableObjPtr(U))
  162. return CB.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
  163. return CB.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
  164. }
  165. /// Return true if this value refers to a distinct and identifiable
  166. /// object.
  167. ///
  168. /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
  169. /// special knowledge of ObjC conventions.
  170. inline bool IsObjCIdentifiedObject(const Value *V) {
  171. // Assume that call results and arguments have their own "provenance".
  172. // Constants (including GlobalVariables) and Allocas are never
  173. // reference-counted.
  174. if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
  175. isa<Argument>(V) || isa<Constant>(V) ||
  176. isa<AllocaInst>(V))
  177. return true;
  178. if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
  179. const Value *Pointer =
  180. GetRCIdentityRoot(LI->getPointerOperand());
  181. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
  182. // A constant pointer can't be pointing to an object on the heap. It may
  183. // be reference-counted, but it won't be deleted.
  184. if (GV->isConstant())
  185. return true;
  186. StringRef Name = GV->getName();
  187. // These special variables are known to hold values which are not
  188. // reference-counted pointers.
  189. if (Name.startswith("\01l_objc_msgSend_fixup_"))
  190. return true;
  191. StringRef Section = GV->getSection();
  192. if (Section.contains("__message_refs") ||
  193. Section.contains("__objc_classrefs") ||
  194. Section.contains("__objc_superrefs") ||
  195. Section.contains("__objc_methname") || Section.contains("__cstring"))
  196. return true;
  197. }
  198. }
  199. return false;
  200. }
  201. enum class ARCMDKindID {
  202. ImpreciseRelease,
  203. CopyOnEscape,
  204. NoObjCARCExceptions,
  205. };
  206. /// A cache of MDKinds used by various ARC optimizations.
  207. class ARCMDKindCache {
  208. Module *M;
  209. /// The Metadata Kind for clang.imprecise_release metadata.
  210. std::optional<unsigned> ImpreciseReleaseMDKind;
  211. /// The Metadata Kind for clang.arc.copy_on_escape metadata.
  212. std::optional<unsigned> CopyOnEscapeMDKind;
  213. /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
  214. std::optional<unsigned> NoObjCARCExceptionsMDKind;
  215. public:
  216. void init(Module *Mod) {
  217. M = Mod;
  218. ImpreciseReleaseMDKind = std::nullopt;
  219. CopyOnEscapeMDKind = std::nullopt;
  220. NoObjCARCExceptionsMDKind = std::nullopt;
  221. }
  222. unsigned get(ARCMDKindID ID) {
  223. switch (ID) {
  224. case ARCMDKindID::ImpreciseRelease:
  225. if (!ImpreciseReleaseMDKind)
  226. ImpreciseReleaseMDKind =
  227. M->getContext().getMDKindID("clang.imprecise_release");
  228. return *ImpreciseReleaseMDKind;
  229. case ARCMDKindID::CopyOnEscape:
  230. if (!CopyOnEscapeMDKind)
  231. CopyOnEscapeMDKind =
  232. M->getContext().getMDKindID("clang.arc.copy_on_escape");
  233. return *CopyOnEscapeMDKind;
  234. case ARCMDKindID::NoObjCARCExceptions:
  235. if (!NoObjCARCExceptionsMDKind)
  236. NoObjCARCExceptionsMDKind =
  237. M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
  238. return *NoObjCARCExceptionsMDKind;
  239. }
  240. llvm_unreachable("Covered switch isn't covered?!");
  241. }
  242. };
  243. } // end namespace objcarc
  244. } // end namespace llvm
  245. #endif
  246. #ifdef __GNUC__
  247. #pragma GCC diagnostic pop
  248. #endif