blob: 1b31e744a3d2dbacda54d4a4dd7596ea03b61506 [file] [log] [blame]
Michael Gottesman6eb95dc2013-07-10 18:49:00 +00001//===- ObjCARC.h - ObjC ARC Optimization --------------*- C++ -*-----------===//
Michael Gottesman08904e32013-01-28 03:28:38 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file defines common definitions/declarations used by the ObjC ARC
11/// Optimizer. ARC stands for Automatic Reference Counting and is a system for
12/// managing reference counts for objects in Objective C.
13///
14/// WARNING: This file knows about certain library functions. It recognizes them
15/// by name, and hardwires knowledge of their semantics.
16///
17/// WARNING: This file knows about how certain Objective-C library functions are
18/// used. Naive LLVM IR transformations which would otherwise be
19/// behavior-preserving may break these assumptions.
20///
21//===----------------------------------------------------------------------===//
22
Benjamin Kramera7c40ef2014-08-13 16:26:38 +000023#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
24#define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
Michael Gottesman08904e32013-01-28 03:28:38 +000025
26#include "llvm/ADT/StringSwitch.h"
27#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Analysis/Passes.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000029#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth83948572014-03-04 10:30:26 +000031#include "llvm/IR/InstIterator.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000032#include "llvm/IR/Module.h"
33#include "llvm/Pass.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000034#include "llvm/Transforms/ObjCARC.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "llvm/Transforms/Utils/Local.h"
Michael Gottesman6f729fa2015-02-19 19:51:32 +000036#include "ARCInstKind.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000037
38namespace llvm {
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000039class raw_ostream;
40}
41
42namespace llvm {
Michael Gottesman08904e32013-01-28 03:28:38 +000043namespace objcarc {
44
45/// \brief A handy option to enable/disable all ARC Optimizations.
46extern bool EnableARCOpts;
47
48/// \brief Test if the given module looks interesting to run ARC optimization
49/// on.
50static inline bool ModuleHasARC(const Module &M) {
51 return
52 M.getNamedValue("objc_retain") ||
53 M.getNamedValue("objc_release") ||
54 M.getNamedValue("objc_autorelease") ||
55 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
56 M.getNamedValue("objc_retainBlock") ||
57 M.getNamedValue("objc_autoreleaseReturnValue") ||
58 M.getNamedValue("objc_autoreleasePoolPush") ||
59 M.getNamedValue("objc_loadWeakRetained") ||
60 M.getNamedValue("objc_loadWeak") ||
61 M.getNamedValue("objc_destroyWeak") ||
62 M.getNamedValue("objc_storeWeak") ||
63 M.getNamedValue("objc_initWeak") ||
64 M.getNamedValue("objc_moveWeak") ||
65 M.getNamedValue("objc_copyWeak") ||
66 M.getNamedValue("objc_retainedObject") ||
67 M.getNamedValue("objc_unretainedObject") ||
Michael Gottesman3b8f8772013-03-29 21:15:23 +000068 M.getNamedValue("objc_unretainedPointer") ||
69 M.getNamedValue("clang.arc.use");
Michael Gottesman08904e32013-01-28 03:28:38 +000070}
71
Michael Gottesman294e7da2013-01-28 05:51:54 +000072/// \brief This is a wrapper around getUnderlyingObject which also knows how to
73/// look through objc_retain and objc_autorelease calls, which we know to return
74/// their argument verbatim.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000075static inline const Value *GetUnderlyingObjCPtr(const Value *V,
76 const DataLayout &DL) {
Michael Gottesman294e7da2013-01-28 05:51:54 +000077 for (;;) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000078 V = GetUnderlyingObject(V, DL);
Michael Gottesman6f729fa2015-02-19 19:51:32 +000079 if (!IsForwarding(GetBasicARCInstKind(V)))
Michael Gottesman294e7da2013-01-28 05:51:54 +000080 break;
81 V = cast<CallInst>(V)->getArgOperand(0);
82 }
83
84 return V;
85}
86
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000087/// The RCIdentity root of a value \p V is a dominating value U for which
88/// retaining or releasing U is equivalent to retaining or releasing V. In other
89/// words, ARC operations on \p V are equivalent to ARC operations on \p U.
90///
91/// We use this in the ARC optimizer to make it easier to match up ARC
92/// operations by always mapping ARC operations to RCIdentityRoots instead of
93/// pointers themselves.
94///
95/// The two ways that we see RCIdentical values in ObjC are via:
96///
97/// 1. PointerCasts
98/// 2. Forwarding Calls that return their argument verbatim.
99///
100/// Thus this function strips off pointer casts and forwarding calls. *NOTE*
101/// This implies that two RCIdentical values must alias.
102static inline const Value *GetRCIdentityRoot(const Value *V) {
Michael Gottesman294e7da2013-01-28 05:51:54 +0000103 for (;;) {
104 V = V->stripPointerCasts();
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000105 if (!IsForwarding(GetBasicARCInstKind(V)))
Michael Gottesman294e7da2013-01-28 05:51:54 +0000106 break;
107 V = cast<CallInst>(V)->getArgOperand(0);
108 }
109 return V;
110}
111
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000112/// 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.
116static inline Value *GetRCIdentityRoot(Value *V) {
117 return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
Michael Gottesman294e7da2013-01-28 05:51:54 +0000118}
119
Michael Gottesman778138e2013-01-29 03:03:03 +0000120/// \brief Assuming the given instruction is one of the special calls such as
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000121/// objc_retain or objc_release, return the RCIdentity root of the argument of
122/// the call.
123static inline Value *GetArgRCIdentityRoot(Value *Inst) {
124 return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
Michael Gottesman778138e2013-01-29 03:03:03 +0000125}
126
Michael Gottesman65c24812013-03-25 09:27:43 +0000127static inline bool IsNullOrUndef(const Value *V) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000128 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
129}
130
Michael Gottesman65c24812013-03-25 09:27:43 +0000131static inline bool IsNoopInstruction(const Instruction *I) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000132 return isa<BitCastInst>(I) ||
133 (isa<GetElementPtrInst>(I) &&
134 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
135}
136
137
138/// \brief Erase the given instruction.
139///
140/// Many ObjC calls return their argument verbatim,
141/// so if it's such a call and the return value has users, replace them with the
142/// argument value.
143///
144static inline void EraseInstruction(Instruction *CI) {
145 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
146
147 bool Unused = CI->use_empty();
148
149 if (!Unused) {
150 // Replace the return value with the argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000151 assert((IsForwarding(GetBasicARCInstKind(CI)) ||
152 (IsNoopOnNull(GetBasicARCInstKind(CI)) &&
Michael Gottesmanc1b648f2013-07-08 23:30:23 +0000153 isa<ConstantPointerNull>(OldArg))) &&
Michael Gottesman778138e2013-01-29 03:03:03 +0000154 "Can't delete non-forwarding instruction with users!");
155 CI->replaceAllUsesWith(OldArg);
156 }
157
158 CI->eraseFromParent();
159
160 if (Unused)
161 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
162}
163
164/// \brief Test whether the given value is possible a retainable object pointer.
165static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
Michael Gottesman23a1ee52013-01-29 04:58:30 +0000166 // Pointers to static or stack storage are not valid retainable object
167 // pointers.
Michael Gottesman778138e2013-01-29 03:03:03 +0000168 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
169 return false;
170 // Special arguments can not be a valid retainable object pointer.
171 if (const Argument *Arg = dyn_cast<Argument>(Op))
172 if (Arg->hasByValAttr() ||
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000173 Arg->hasInAllocaAttr() ||
Michael Gottesman778138e2013-01-29 03:03:03 +0000174 Arg->hasNestAttr() ||
175 Arg->hasStructRetAttr())
176 return false;
177 // Only consider values with pointer types.
178 //
179 // It seemes intuitive to exclude function pointer types as well, since
180 // functions are never retainable object pointers, however clang occasionally
181 // bitcasts retainable object pointers to function-pointer type temporarily.
182 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
183 if (!Ty)
184 return false;
Michael Gottesman23a1ee52013-01-29 04:58:30 +0000185 // Conservatively assume anything else is a potential retainable object
186 // pointer.
Michael Gottesman778138e2013-01-29 03:03:03 +0000187 return true;
188}
189
190static inline bool IsPotentialRetainableObjPtr(const Value *Op,
191 AliasAnalysis &AA) {
192 // First make the rudimentary check.
193 if (!IsPotentialRetainableObjPtr(Op))
194 return false;
195
196 // Objects in constant memory are not reference-counted.
197 if (AA.pointsToConstantMemory(Op))
198 return false;
199
200 // Pointers in constant memory are not pointing to reference-counted objects.
201 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
202 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
203 return false;
204
205 // Otherwise assume the worst.
206 return true;
207}
208
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000209/// \brief Helper for GetARCInstKind. Determines what kind of construct CS
Michael Gottesman778138e2013-01-29 03:03:03 +0000210/// is.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000211static inline ARCInstKind GetCallSiteClass(ImmutableCallSite CS) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000212 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
213 I != E; ++I)
214 if (IsPotentialRetainableObjPtr(*I))
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000215 return CS.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
Michael Gottesman778138e2013-01-29 03:03:03 +0000216
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000217 return CS.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
Michael Gottesman778138e2013-01-29 03:03:03 +0000218}
219
220/// \brief Return true if this value refers to a distinct and identifiable
221/// object.
222///
223/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
224/// special knowledge of ObjC conventions.
225static inline bool IsObjCIdentifiedObject(const Value *V) {
226 // Assume that call results and arguments have their own "provenance".
227 // Constants (including GlobalVariables) and Allocas are never
228 // reference-counted.
229 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
230 isa<Argument>(V) || isa<Constant>(V) ||
231 isa<AllocaInst>(V))
232 return true;
233
234 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
235 const Value *Pointer =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000236 GetRCIdentityRoot(LI->getPointerOperand());
Michael Gottesman778138e2013-01-29 03:03:03 +0000237 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
238 // A constant pointer can't be pointing to an object on the heap. It may
239 // be reference-counted, but it won't be deleted.
240 if (GV->isConstant())
241 return true;
242 StringRef Name = GV->getName();
243 // These special variables are known to hold values which are not
244 // reference-counted pointers.
Rafael Espindolaa3b5b602014-11-17 02:28:27 +0000245 if (Name.startswith("\01l_objc_msgSend_fixup_"))
246 return true;
247
248 StringRef Section = GV->getSection();
249 if (Section.find("__message_refs") != StringRef::npos ||
250 Section.find("__objc_classrefs") != StringRef::npos ||
251 Section.find("__objc_superrefs") != StringRef::npos ||
252 Section.find("__objc_methname") != StringRef::npos ||
253 Section.find("__cstring") != StringRef::npos)
Michael Gottesman778138e2013-01-29 03:03:03 +0000254 return true;
255 }
256 }
257
258 return false;
259}
Michael Gottesman294e7da2013-01-28 05:51:54 +0000260
Michael Gottesman41c01002015-03-06 00:34:33 +0000261/// A cache of MDKinds used by various ARC optimizations.
262struct ARCMDKindCache {
263 /// The Metadata Kind for clang.imprecise_release metadata.
264 unsigned ImpreciseReleaseMDKind;
265
266 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
267 unsigned CopyOnEscapeMDKind;
268
269 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
270 unsigned NoObjCARCExceptionsMDKind;
271};
272
Michael Gottesman08904e32013-01-28 03:28:38 +0000273} // end namespace objcarc
274} // end namespace llvm
275
Benjamin Kramera7c40ef2014-08-13 16:26:38 +0000276#endif