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