ObjCARCAnalysisUtils.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
  27. #define LLVM_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
  28. #include "llvm/ADT/Optional.h"
  29. #include "llvm/Analysis/ObjCARCInstKind.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/ValueHandle.h"
  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 *
  77. GetUnderlyingObjCPtrCached(const Value *V,
  78. DenseMap<const Value *, WeakTrackingVH> &Cache) {
  79. if (auto InCache = Cache.lookup(V))
  80. return InCache;
  81. const Value *Computed = GetUnderlyingObjCPtr(V);
  82. Cache[V] = const_cast<Value *>(Computed);
  83. return Computed;
  84. }
  85. /// The RCIdentity root of a value \p V is a dominating value U for which
  86. /// retaining or releasing U is equivalent to retaining or releasing V. In other
  87. /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
  88. ///
  89. /// We use this in the ARC optimizer to make it easier to match up ARC
  90. /// operations by always mapping ARC operations to RCIdentityRoots instead of
  91. /// pointers themselves.
  92. ///
  93. /// The two ways that we see RCIdentical values in ObjC are via:
  94. ///
  95. /// 1. PointerCasts
  96. /// 2. Forwarding Calls that return their argument verbatim.
  97. ///
  98. /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
  99. /// This implies that two RCIdentical values must alias.
  100. inline const Value *GetRCIdentityRoot(const Value *V) {
  101. for (;;) {
  102. V = V->stripPointerCasts();
  103. if (!IsForwarding(GetBasicARCInstKind(V)))
  104. break;
  105. V = cast<CallInst>(V)->getArgOperand(0);
  106. }
  107. return V;
  108. }
  109. /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
  110. /// casts away the const of the result. For documentation about what an
  111. /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
  112. /// function.
  113. inline Value *GetRCIdentityRoot(Value *V) {
  114. return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
  115. }
  116. /// Assuming the given instruction is one of the special calls such as
  117. /// objc_retain or objc_release, return the RCIdentity root of the argument of
  118. /// the call.
  119. inline Value *GetArgRCIdentityRoot(Value *Inst) {
  120. return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
  121. }
  122. inline bool IsNullOrUndef(const Value *V) {
  123. return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
  124. }
  125. inline bool IsNoopInstruction(const Instruction *I) {
  126. return isa<BitCastInst>(I) ||
  127. (isa<GetElementPtrInst>(I) &&
  128. cast<GetElementPtrInst>(I)->hasAllZeroIndices());
  129. }
  130. /// Test whether the given value is possible a retainable object pointer.
  131. inline bool IsPotentialRetainableObjPtr(const Value *Op) {
  132. // Pointers to static or stack storage are not valid retainable object
  133. // pointers.
  134. if (isa<Constant>(Op) || isa<AllocaInst>(Op))
  135. return false;
  136. // Special arguments can not be a valid retainable object pointer.
  137. if (const Argument *Arg = dyn_cast<Argument>(Op))
  138. if (Arg->hasPassPointeeByValueCopyAttr() || Arg->hasNestAttr() ||
  139. Arg->hasStructRetAttr())
  140. return false;
  141. // Only consider values with pointer types.
  142. //
  143. // It seemes intuitive to exclude function pointer types as well, since
  144. // functions are never retainable object pointers, however clang occasionally
  145. // bitcasts retainable object pointers to function-pointer type temporarily.
  146. PointerType *Ty = dyn_cast<PointerType>(Op->getType());
  147. if (!Ty)
  148. return false;
  149. // Conservatively assume anything else is a potential retainable object
  150. // pointer.
  151. return true;
  152. }
  153. bool IsPotentialRetainableObjPtr(const Value *Op, AAResults &AA);
  154. /// Helper for GetARCInstKind. Determines what kind of construct CS
  155. /// is.
  156. inline ARCInstKind GetCallSiteClass(const CallBase &CB) {
  157. for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I)
  158. if (IsPotentialRetainableObjPtr(*I))
  159. return CB.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
  160. return CB.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
  161. }
  162. /// Return true if this value refers to a distinct and identifiable
  163. /// object.
  164. ///
  165. /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
  166. /// special knowledge of ObjC conventions.
  167. inline bool IsObjCIdentifiedObject(const Value *V) {
  168. // Assume that call results and arguments have their own "provenance".
  169. // Constants (including GlobalVariables) and Allocas are never
  170. // reference-counted.
  171. if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
  172. isa<Argument>(V) || isa<Constant>(V) ||
  173. isa<AllocaInst>(V))
  174. return true;
  175. if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
  176. const Value *Pointer =
  177. GetRCIdentityRoot(LI->getPointerOperand());
  178. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
  179. // A constant pointer can't be pointing to an object on the heap. It may
  180. // be reference-counted, but it won't be deleted.
  181. if (GV->isConstant())
  182. return true;
  183. StringRef Name = GV->getName();
  184. // These special variables are known to hold values which are not
  185. // reference-counted pointers.
  186. if (Name.startswith("\01l_objc_msgSend_fixup_"))
  187. return true;
  188. StringRef Section = GV->getSection();
  189. if (Section.find("__message_refs") != StringRef::npos ||
  190. Section.find("__objc_classrefs") != StringRef::npos ||
  191. Section.find("__objc_superrefs") != StringRef::npos ||
  192. Section.find("__objc_methname") != StringRef::npos ||
  193. Section.find("__cstring") != StringRef::npos)
  194. return true;
  195. }
  196. }
  197. return false;
  198. }
  199. enum class ARCMDKindID {
  200. ImpreciseRelease,
  201. CopyOnEscape,
  202. NoObjCARCExceptions,
  203. };
  204. /// A cache of MDKinds used by various ARC optimizations.
  205. class ARCMDKindCache {
  206. Module *M;
  207. /// The Metadata Kind for clang.imprecise_release metadata.
  208. llvm::Optional<unsigned> ImpreciseReleaseMDKind;
  209. /// The Metadata Kind for clang.arc.copy_on_escape metadata.
  210. llvm::Optional<unsigned> CopyOnEscapeMDKind;
  211. /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
  212. llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
  213. public:
  214. void init(Module *Mod) {
  215. M = Mod;
  216. ImpreciseReleaseMDKind = NoneType::None;
  217. CopyOnEscapeMDKind = NoneType::None;
  218. NoObjCARCExceptionsMDKind = NoneType::None;
  219. }
  220. unsigned get(ARCMDKindID ID) {
  221. switch (ID) {
  222. case ARCMDKindID::ImpreciseRelease:
  223. if (!ImpreciseReleaseMDKind)
  224. ImpreciseReleaseMDKind =
  225. M->getContext().getMDKindID("clang.imprecise_release");
  226. return *ImpreciseReleaseMDKind;
  227. case ARCMDKindID::CopyOnEscape:
  228. if (!CopyOnEscapeMDKind)
  229. CopyOnEscapeMDKind =
  230. M->getContext().getMDKindID("clang.arc.copy_on_escape");
  231. return *CopyOnEscapeMDKind;
  232. case ARCMDKindID::NoObjCARCExceptions:
  233. if (!NoObjCARCExceptionsMDKind)
  234. NoObjCARCExceptionsMDKind =
  235. M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
  236. return *NoObjCARCExceptionsMDKind;
  237. }
  238. llvm_unreachable("Covered switch isn't covered?!");
  239. }
  240. };
  241. } // end namespace objcarc
  242. } // end namespace llvm
  243. #endif
  244. #ifdef __GNUC__
  245. #pragma GCC diagnostic pop
  246. #endif