LLVM  3.7.0
lib/Transforms/ObjCARC/ObjCARC.h
Go to the documentation of this file.
1 //===- ObjCARC.h - ObjC ARC Optimization --------------*- C++ -*-----------===//
2 //
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 
23 #ifndef LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
24 #define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
25 
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Optional.h"
29 #include "llvm/Analysis/Passes.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/InstIterator.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/Pass.h"
37 #include "ARCInstKind.h"
38 
39 namespace llvm {
40 class raw_ostream;
41 }
42 
43 namespace llvm {
44 namespace objcarc {
45 
46 /// \brief A handy option to enable/disable all ARC Optimizations.
47 extern bool EnableARCOpts;
48 
49 /// \brief Test if the given module looks interesting to run ARC optimization
50 /// on.
51 static inline bool ModuleHasARC(const Module &M) {
52  return
53  M.getNamedValue("objc_retain") ||
54  M.getNamedValue("objc_release") ||
55  M.getNamedValue("objc_autorelease") ||
56  M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
57  M.getNamedValue("objc_retainBlock") ||
58  M.getNamedValue("objc_autoreleaseReturnValue") ||
59  M.getNamedValue("objc_autoreleasePoolPush") ||
60  M.getNamedValue("objc_loadWeakRetained") ||
61  M.getNamedValue("objc_loadWeak") ||
62  M.getNamedValue("objc_destroyWeak") ||
63  M.getNamedValue("objc_storeWeak") ||
64  M.getNamedValue("objc_initWeak") ||
65  M.getNamedValue("objc_moveWeak") ||
66  M.getNamedValue("objc_copyWeak") ||
67  M.getNamedValue("objc_retainedObject") ||
68  M.getNamedValue("objc_unretainedObject") ||
69  M.getNamedValue("objc_unretainedPointer") ||
70  M.getNamedValue("clang.arc.use");
71 }
72 
73 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
74 /// look through objc_retain and objc_autorelease calls, which we know to return
75 /// their argument verbatim.
76 static inline const Value *GetUnderlyingObjCPtr(const Value *V,
77  const DataLayout &DL) {
78  for (;;) {
79  V = GetUnderlyingObject(V, DL);
81  break;
82  V = cast<CallInst>(V)->getArgOperand(0);
83  }
84 
85  return V;
86 }
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 static inline const Value *GetRCIdentityRoot(const Value *V) {
104  for (;;) {
105  V = V->stripPointerCasts();
107  break;
108  V = cast<CallInst>(V)->getArgOperand(0);
109  }
110  return V;
111 }
112 
113 /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
114 /// casts away the const of the result. For documentation about what an
115 /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
116 /// function.
117 static inline Value *GetRCIdentityRoot(Value *V) {
118  return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
119 }
120 
121 /// \brief Assuming the given instruction is one of the special calls such as
122 /// objc_retain or objc_release, return the RCIdentity root of the argument of
123 /// the call.
124 static inline Value *GetArgRCIdentityRoot(Value *Inst) {
125  return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
126 }
127 
128 static inline bool IsNullOrUndef(const Value *V) {
129  return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
130 }
131 
132 static inline bool IsNoopInstruction(const Instruction *I) {
133  return isa<BitCastInst>(I) ||
134  (isa<GetElementPtrInst>(I) &&
135  cast<GetElementPtrInst>(I)->hasAllZeroIndices());
136 }
137 
138 
139 /// \brief Erase the given instruction.
140 ///
141 /// Many ObjC calls return their argument verbatim,
142 /// so if it's such a call and the return value has users, replace them with the
143 /// argument value.
144 ///
145 static inline void EraseInstruction(Instruction *CI) {
146  Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
147 
148  bool Unused = CI->use_empty();
149 
150  if (!Unused) {
151  // Replace the return value with the argument.
152  assert((IsForwarding(GetBasicARCInstKind(CI)) ||
154  isa<ConstantPointerNull>(OldArg))) &&
155  "Can't delete non-forwarding instruction with users!");
156  CI->replaceAllUsesWith(OldArg);
157  }
158 
159  CI->eraseFromParent();
160 
161  if (Unused)
163 }
164 
165 /// \brief Test whether the given value is possible a retainable object pointer.
166 static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
167  // Pointers to static or stack storage are not valid retainable object
168  // pointers.
169  if (isa<Constant>(Op) || isa<AllocaInst>(Op))
170  return false;
171  // Special arguments can not be a valid retainable object pointer.
172  if (const Argument *Arg = dyn_cast<Argument>(Op))
173  if (Arg->hasByValAttr() ||
174  Arg->hasInAllocaAttr() ||
175  Arg->hasNestAttr() ||
176  Arg->hasStructRetAttr())
177  return false;
178  // Only consider values with pointer types.
179  //
180  // It seemes intuitive to exclude function pointer types as well, since
181  // functions are never retainable object pointers, however clang occasionally
182  // bitcasts retainable object pointers to function-pointer type temporarily.
183  PointerType *Ty = dyn_cast<PointerType>(Op->getType());
184  if (!Ty)
185  return false;
186  // Conservatively assume anything else is a potential retainable object
187  // pointer.
188  return true;
189 }
190 
191 static inline bool IsPotentialRetainableObjPtr(const Value *Op,
192  AliasAnalysis &AA) {
193  // First make the rudimentary check.
195  return false;
196 
197  // Objects in constant memory are not reference-counted.
198  if (AA.pointsToConstantMemory(Op))
199  return false;
200 
201  // Pointers in constant memory are not pointing to reference-counted objects.
202  if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
203  if (AA.pointsToConstantMemory(LI->getPointerOperand()))
204  return false;
205 
206  // Otherwise assume the worst.
207  return true;
208 }
209 
210 /// \brief Helper for GetARCInstKind. Determines what kind of construct CS
211 /// is.
213  for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
214  I != E; ++I)
217 
219 }
220 
221 /// \brief Return true if this value refers to a distinct and identifiable
222 /// object.
223 ///
224 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
225 /// special knowledge of ObjC conventions.
226 static inline bool IsObjCIdentifiedObject(const Value *V) {
227  // Assume that call results and arguments have their own "provenance".
228  // Constants (including GlobalVariables) and Allocas are never
229  // reference-counted.
230  if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
231  isa<Argument>(V) || isa<Constant>(V) ||
232  isa<AllocaInst>(V))
233  return true;
234 
235  if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
236  const Value *Pointer =
237  GetRCIdentityRoot(LI->getPointerOperand());
238  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
239  // A constant pointer can't be pointing to an object on the heap. It may
240  // be reference-counted, but it won't be deleted.
241  if (GV->isConstant())
242  return true;
243  StringRef Name = GV->getName();
244  // These special variables are known to hold values which are not
245  // reference-counted pointers.
246  if (Name.startswith("\01l_objc_msgSend_fixup_"))
247  return true;
248 
249  StringRef Section = GV->getSection();
250  if (Section.find("__message_refs") != StringRef::npos ||
251  Section.find("__objc_classrefs") != StringRef::npos ||
252  Section.find("__objc_superrefs") != StringRef::npos ||
253  Section.find("__objc_methname") != StringRef::npos ||
254  Section.find("__cstring") != StringRef::npos)
255  return true;
256  }
257  }
258 
259  return false;
260 }
261 
262 enum class ARCMDKindID {
264  CopyOnEscape,
266 };
267 
268 /// A cache of MDKinds used by various ARC optimizations.
270  Module *M;
271 
272  /// The Metadata Kind for clang.imprecise_release metadata.
273  llvm::Optional<unsigned> ImpreciseReleaseMDKind;
274 
275  /// The Metadata Kind for clang.arc.copy_on_escape metadata.
276  llvm::Optional<unsigned> CopyOnEscapeMDKind;
277 
278  /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
279  llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
280 
281 public:
282  void init(Module *Mod) {
283  M = Mod;
284  ImpreciseReleaseMDKind = NoneType::None;
285  CopyOnEscapeMDKind = NoneType::None;
286  NoObjCARCExceptionsMDKind = NoneType::None;
287  }
288 
289  unsigned get(ARCMDKindID ID) {
290  switch (ID) {
292  if (!ImpreciseReleaseMDKind)
293  ImpreciseReleaseMDKind =
294  M->getContext().getMDKindID("clang.imprecise_release");
295  return *ImpreciseReleaseMDKind;
297  if (!CopyOnEscapeMDKind)
298  CopyOnEscapeMDKind =
299  M->getContext().getMDKindID("clang.arc.copy_on_escape");
300  return *CopyOnEscapeMDKind;
302  if (!NoObjCARCExceptionsMDKind)
303  NoObjCARCExceptionsMDKind =
304  M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
305  return *NoObjCARCExceptionsMDKind;
306  }
307  llvm_unreachable("Covered switch isn't covered?!");
308  }
309 };
310 
311 } // end namespace objcarc
312 } // end namespace llvm
313 
314 #endif
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
LLVM Argument representation.
Definition: Argument.h:35
could call objc_release and/or "use" pointers
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:240
static ARCInstKind GetBasicARCInstKind(const Value *V)
Determine which objc runtime call instruction class V belongs to.
Definition: ARCInstKind.h:101
could call objc_release
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
bool IsNoopOnNull(ARCInstKind Class)
Test if the given class represents instructions which do nothing if passed a null pointer...
bool IsForwarding(ARCInstKind Class)
Test if the given class represents instructions which return their argument verbatim.
static ARCInstKind GetCallSiteClass(ImmutableCallSite CS)
Helper for GetARCInstKind.
virtual bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
pointsToConstantMemory - If the specified memory location is known to be constant, return true.
IterTy arg_end() const
Definition: CallSite.h:157
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
A Use represents the edge between a Value definition and its users.
Definition: Use.h:69
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
Definition: ObjCARC.cpp:30
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
PointerType - Class to represent pointers.
Definition: DerivedTypes.h:449
static bool IsNoopInstruction(const Instruction *I)
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
static bool IsObjCIdentifiedObject(const Value *V)
Return true if this value refers to a distinct and identifiable object.
A cache of MDKinds used by various ARC optimizations.
static const Value * GetUnderlyingObjCPtr(const Value *V, const DataLayout &DL)
This is a wrapper around getUnderlyingObject which also knows how to look through objc_retain and obj...
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a trivially dead instruction...
Definition: Local.cpp:340
anything that is inert from an ARC perspective.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
GetUnderlyingObject - This method strips off any GEP address adjustments and pointer casts from the s...
static Value * GetArgRCIdentityRoot(Value *Inst)
Assuming the given instruction is one of the special calls such as objc_retain or objc_release...
static void EraseInstruction(Instruction *CI)
Erase the given instruction.
bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:215
static bool IsNullOrUndef(const Value *V)
ARCInstKind
Equivalence classes of instructions in the ARC Model.
Definition: ARCInstKind.h:30
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:458
static bool IsPotentialRetainableObjPtr(const Value *Op)
Test whether the given value is possible a retainable object pointer.
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
could "use" a pointer
static const size_t npos
Definition: StringRef.h:44
ImmutableCallSite - establish a view to a call site for examination.
Definition: CallSite.h:418
#define I(x, y, z)
Definition: MD5.cpp:54
static const Value * GetRCIdentityRoot(const Value *V)
The RCIdentity root of a value V is a dominating value U for which retaining or releasing U is equiva...
bool use_empty() const
Definition: Value.h:275
LLVM Value Representation.
Definition: Value.h:69
IterTy arg_begin() const
arg_begin/arg_end - Return iterators corresponding to the actual argument list for a call site...
Definition: CallSite.h:151
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:88
static bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
Definition: CallSite.h:286
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:265