blob: 16c5f6701da0cd17d097290a5053d0ef05e3d06f [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- ObjCARCAnalysisUtils.h - ObjC ARC Analysis Utilities -----*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
23#define LLVM_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
24
25#include "llvm/ADT/Optional.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010026#include "llvm/Analysis/ObjCARCInstKind.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010027#include "llvm/Analysis/ValueTracking.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010028#include "llvm/IR/Constants.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010029#include "llvm/IR/Module.h"
Andrew Scullcdfcccc2018-10-05 20:58:37 +010030#include "llvm/IR/ValueHandle.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010031
32namespace llvm {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010033
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020034class AAResults;
35
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010036namespace objcarc {
37
Andrew Scullcdfcccc2018-10-05 20:58:37 +010038/// A handy option to enable/disable all ARC Optimizations.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010039extern bool EnableARCOpts;
40
Andrew Scullcdfcccc2018-10-05 20:58:37 +010041/// Test if the given module looks interesting to run ARC optimization
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010042/// on.
43inline bool ModuleHasARC(const Module &M) {
44 return
Andrew Walbran16937d02019-10-22 13:54:20 +010045 M.getNamedValue("llvm.objc.retain") ||
46 M.getNamedValue("llvm.objc.release") ||
47 M.getNamedValue("llvm.objc.autorelease") ||
48 M.getNamedValue("llvm.objc.retainAutoreleasedReturnValue") ||
49 M.getNamedValue("llvm.objc.unsafeClaimAutoreleasedReturnValue") ||
50 M.getNamedValue("llvm.objc.retainBlock") ||
51 M.getNamedValue("llvm.objc.autoreleaseReturnValue") ||
52 M.getNamedValue("llvm.objc.autoreleasePoolPush") ||
53 M.getNamedValue("llvm.objc.loadWeakRetained") ||
54 M.getNamedValue("llvm.objc.loadWeak") ||
55 M.getNamedValue("llvm.objc.destroyWeak") ||
56 M.getNamedValue("llvm.objc.storeWeak") ||
57 M.getNamedValue("llvm.objc.initWeak") ||
58 M.getNamedValue("llvm.objc.moveWeak") ||
59 M.getNamedValue("llvm.objc.copyWeak") ||
60 M.getNamedValue("llvm.objc.retainedObject") ||
61 M.getNamedValue("llvm.objc.unretainedObject") ||
62 M.getNamedValue("llvm.objc.unretainedPointer") ||
63 M.getNamedValue("llvm.objc.clang.arc.use");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010064}
65
Andrew Scullcdfcccc2018-10-05 20:58:37 +010066/// This is a wrapper around getUnderlyingObject which also knows how to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010067/// look through objc_retain and objc_autorelease calls, which we know to return
68/// their argument verbatim.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020069inline const Value *GetUnderlyingObjCPtr(const Value *V) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010070 for (;;) {
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020071 V = getUnderlyingObject(V);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010072 if (!IsForwarding(GetBasicARCInstKind(V)))
73 break;
74 V = cast<CallInst>(V)->getArgOperand(0);
75 }
76
77 return V;
78}
79
80/// A wrapper for GetUnderlyingObjCPtr used for results memoization.
81inline const Value *
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020082GetUnderlyingObjCPtrCached(const Value *V,
Andrew Scullcdfcccc2018-10-05 20:58:37 +010083 DenseMap<const Value *, WeakTrackingVH> &Cache) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010084 if (auto InCache = Cache.lookup(V))
85 return InCache;
86
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020087 const Value *Computed = GetUnderlyingObjCPtr(V);
Andrew Scullcdfcccc2018-10-05 20:58:37 +010088 Cache[V] = const_cast<Value *>(Computed);
89 return Computed;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010090}
91
92/// The RCIdentity root of a value \p V is a dominating value U for which
93/// retaining or releasing U is equivalent to retaining or releasing V. In other
94/// words, ARC operations on \p V are equivalent to ARC operations on \p U.
95///
96/// We use this in the ARC optimizer to make it easier to match up ARC
97/// operations by always mapping ARC operations to RCIdentityRoots instead of
98/// pointers themselves.
99///
100/// The two ways that we see RCIdentical values in ObjC are via:
101///
102/// 1. PointerCasts
103/// 2. Forwarding Calls that return their argument verbatim.
104///
105/// Thus this function strips off pointer casts and forwarding calls. *NOTE*
106/// This implies that two RCIdentical values must alias.
107inline const Value *GetRCIdentityRoot(const Value *V) {
108 for (;;) {
109 V = V->stripPointerCasts();
110 if (!IsForwarding(GetBasicARCInstKind(V)))
111 break;
112 V = cast<CallInst>(V)->getArgOperand(0);
113 }
114 return V;
115}
116
117/// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
118/// casts away the const of the result. For documentation about what an
119/// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
120/// function.
121inline Value *GetRCIdentityRoot(Value *V) {
122 return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
123}
124
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100125/// Assuming the given instruction is one of the special calls such as
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100126/// objc_retain or objc_release, return the RCIdentity root of the argument of
127/// the call.
128inline Value *GetArgRCIdentityRoot(Value *Inst) {
129 return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
130}
131
132inline bool IsNullOrUndef(const Value *V) {
133 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
134}
135
136inline bool IsNoopInstruction(const Instruction *I) {
137 return isa<BitCastInst>(I) ||
138 (isa<GetElementPtrInst>(I) &&
139 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
140}
141
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100142/// Test whether the given value is possible a retainable object pointer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100143inline bool IsPotentialRetainableObjPtr(const Value *Op) {
144 // Pointers to static or stack storage are not valid retainable object
145 // pointers.
146 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
147 return false;
148 // Special arguments can not be a valid retainable object pointer.
149 if (const Argument *Arg = dyn_cast<Argument>(Op))
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200150 if (Arg->hasPassPointeeByValueCopyAttr() || Arg->hasNestAttr() ||
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100151 Arg->hasStructRetAttr())
152 return false;
153 // Only consider values with pointer types.
154 //
155 // It seemes intuitive to exclude function pointer types as well, since
156 // functions are never retainable object pointers, however clang occasionally
157 // bitcasts retainable object pointers to function-pointer type temporarily.
158 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
159 if (!Ty)
160 return false;
161 // Conservatively assume anything else is a potential retainable object
162 // pointer.
163 return true;
164}
165
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200166bool IsPotentialRetainableObjPtr(const Value *Op, AAResults &AA);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100167
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100168/// Helper for GetARCInstKind. Determines what kind of construct CS
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100169/// is.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200170inline ARCInstKind GetCallSiteClass(const CallBase &CB) {
171 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100172 if (IsPotentialRetainableObjPtr(*I))
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200173 return CB.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100174
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200175 return CB.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100176}
177
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100178/// Return true if this value refers to a distinct and identifiable
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100179/// object.
180///
181/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
182/// special knowledge of ObjC conventions.
183inline bool IsObjCIdentifiedObject(const Value *V) {
184 // Assume that call results and arguments have their own "provenance".
185 // Constants (including GlobalVariables) and Allocas are never
186 // reference-counted.
187 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
188 isa<Argument>(V) || isa<Constant>(V) ||
189 isa<AllocaInst>(V))
190 return true;
191
192 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
193 const Value *Pointer =
194 GetRCIdentityRoot(LI->getPointerOperand());
195 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
196 // A constant pointer can't be pointing to an object on the heap. It may
197 // be reference-counted, but it won't be deleted.
198 if (GV->isConstant())
199 return true;
200 StringRef Name = GV->getName();
201 // These special variables are known to hold values which are not
202 // reference-counted pointers.
203 if (Name.startswith("\01l_objc_msgSend_fixup_"))
204 return true;
205
206 StringRef Section = GV->getSection();
207 if (Section.find("__message_refs") != StringRef::npos ||
208 Section.find("__objc_classrefs") != StringRef::npos ||
209 Section.find("__objc_superrefs") != StringRef::npos ||
210 Section.find("__objc_methname") != StringRef::npos ||
211 Section.find("__cstring") != StringRef::npos)
212 return true;
213 }
214 }
215
216 return false;
217}
218
219enum class ARCMDKindID {
220 ImpreciseRelease,
221 CopyOnEscape,
222 NoObjCARCExceptions,
223};
224
225/// A cache of MDKinds used by various ARC optimizations.
226class ARCMDKindCache {
227 Module *M;
228
229 /// The Metadata Kind for clang.imprecise_release metadata.
230 llvm::Optional<unsigned> ImpreciseReleaseMDKind;
231
232 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
233 llvm::Optional<unsigned> CopyOnEscapeMDKind;
234
235 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
236 llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
237
238public:
239 void init(Module *Mod) {
240 M = Mod;
241 ImpreciseReleaseMDKind = NoneType::None;
242 CopyOnEscapeMDKind = NoneType::None;
243 NoObjCARCExceptionsMDKind = NoneType::None;
244 }
245
246 unsigned get(ARCMDKindID ID) {
247 switch (ID) {
248 case ARCMDKindID::ImpreciseRelease:
249 if (!ImpreciseReleaseMDKind)
250 ImpreciseReleaseMDKind =
251 M->getContext().getMDKindID("clang.imprecise_release");
252 return *ImpreciseReleaseMDKind;
253 case ARCMDKindID::CopyOnEscape:
254 if (!CopyOnEscapeMDKind)
255 CopyOnEscapeMDKind =
256 M->getContext().getMDKindID("clang.arc.copy_on_escape");
257 return *CopyOnEscapeMDKind;
258 case ARCMDKindID::NoObjCARCExceptions:
259 if (!NoObjCARCExceptionsMDKind)
260 NoObjCARCExceptionsMDKind =
261 M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
262 return *NoObjCARCExceptionsMDKind;
263 }
264 llvm_unreachable("Covered switch isn't covered?!");
265 }
266};
267
268} // end namespace objcarc
269} // end namespace llvm
270
271#endif