Changed isNullOrUndef => IsNullOrUndef and isNoopInstruction => IsNoopInstruction...
[oota-llvm.git] / lib / Transforms / ObjCARC / ObjCARC.h
1 //===- ObjCARC.h - ObjC ARC Optimization --------------*- mode: 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_TRANSFORMS_SCALAR_OBJCARC_H
24 #define LLVM_TRANSFORMS_SCALAR_OBJCARC_H
25
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/Passes.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/InstIterator.h"
34 #include "llvm/Transforms/ObjCARC.h"
35 #include "llvm/Transforms/Utils/Local.h"
36
37 namespace llvm {
38 class raw_ostream;
39 }
40
41 namespace llvm {
42 namespace objcarc {
43
44 /// \brief A handy option to enable/disable all ARC Optimizations.
45 extern bool EnableARCOpts;
46
47 /// \brief Test if the given module looks interesting to run ARC optimization
48 /// on.
49 static inline bool ModuleHasARC(const Module &M) {
50   return
51     M.getNamedValue("objc_retain") ||
52     M.getNamedValue("objc_release") ||
53     M.getNamedValue("objc_autorelease") ||
54     M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
55     M.getNamedValue("objc_retainBlock") ||
56     M.getNamedValue("objc_autoreleaseReturnValue") ||
57     M.getNamedValue("objc_autoreleasePoolPush") ||
58     M.getNamedValue("objc_loadWeakRetained") ||
59     M.getNamedValue("objc_loadWeak") ||
60     M.getNamedValue("objc_destroyWeak") ||
61     M.getNamedValue("objc_storeWeak") ||
62     M.getNamedValue("objc_initWeak") ||
63     M.getNamedValue("objc_moveWeak") ||
64     M.getNamedValue("objc_copyWeak") ||
65     M.getNamedValue("objc_retainedObject") ||
66     M.getNamedValue("objc_unretainedObject") ||
67     M.getNamedValue("objc_unretainedPointer");
68 }
69
70 /// \enum InstructionClass
71 /// \brief A simple classification for instructions.
72 enum InstructionClass {
73   IC_Retain,              ///< objc_retain
74   IC_RetainRV,            ///< objc_retainAutoreleasedReturnValue
75   IC_RetainBlock,         ///< objc_retainBlock
76   IC_Release,             ///< objc_release
77   IC_Autorelease,         ///< objc_autorelease
78   IC_AutoreleaseRV,       ///< objc_autoreleaseReturnValue
79   IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
80   IC_AutoreleasepoolPop,  ///< objc_autoreleasePoolPop
81   IC_NoopCast,            ///< objc_retainedObject, etc.
82   IC_FusedRetainAutorelease, ///< objc_retainAutorelease
83   IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
84   IC_LoadWeakRetained,    ///< objc_loadWeakRetained (primitive)
85   IC_StoreWeak,           ///< objc_storeWeak (primitive)
86   IC_InitWeak,            ///< objc_initWeak (derived)
87   IC_LoadWeak,            ///< objc_loadWeak (derived)
88   IC_MoveWeak,            ///< objc_moveWeak (derived)
89   IC_CopyWeak,            ///< objc_copyWeak (derived)
90   IC_DestroyWeak,         ///< objc_destroyWeak (derived)
91   IC_StoreStrong,         ///< objc_storeStrong (derived)
92   IC_IntrinsicUser,       ///< clang.arc.use
93   IC_CallOrUser,          ///< could call objc_release and/or "use" pointers
94   IC_Call,                ///< could call objc_release
95   IC_User,                ///< could "use" a pointer
96   IC_None                 ///< anything else
97 };
98
99 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class);
100
101 /// \brief Test if the given class is a kind of user.
102 inline static bool IsUser(InstructionClass Class) {
103   return Class == IC_User ||
104          Class == IC_CallOrUser ||
105          Class == IC_IntrinsicUser;
106 }
107
108 /// \brief Test if the given class is objc_retain or equivalent.
109 static inline bool IsRetain(InstructionClass Class) {
110   return Class == IC_Retain ||
111          Class == IC_RetainRV;
112 }
113
114 /// \brief Test if the given class is objc_autorelease or equivalent.
115 static inline bool IsAutorelease(InstructionClass Class) {
116   return Class == IC_Autorelease ||
117          Class == IC_AutoreleaseRV;
118 }
119
120 /// \brief Test if the given class represents instructions which return their
121 /// argument verbatim.
122 static inline bool IsForwarding(InstructionClass Class) {
123   // objc_retainBlock technically doesn't always return its argument
124   // verbatim, but it doesn't matter for our purposes here.
125   return Class == IC_Retain ||
126          Class == IC_RetainRV ||
127          Class == IC_Autorelease ||
128          Class == IC_AutoreleaseRV ||
129          Class == IC_RetainBlock ||
130          Class == IC_NoopCast;
131 }
132
133 /// \brief Test if the given class represents instructions which do nothing if
134 /// passed a null pointer.
135 static inline bool IsNoopOnNull(InstructionClass Class) {
136   return Class == IC_Retain ||
137          Class == IC_RetainRV ||
138          Class == IC_Release ||
139          Class == IC_Autorelease ||
140          Class == IC_AutoreleaseRV ||
141          Class == IC_RetainBlock;
142 }
143
144 /// \brief Test if the given class represents instructions which are always safe
145 /// to mark with the "tail" keyword.
146 static inline bool IsAlwaysTail(InstructionClass Class) {
147   // IC_RetainBlock may be given a stack argument.
148   return Class == IC_Retain ||
149          Class == IC_RetainRV ||
150          Class == IC_AutoreleaseRV;
151 }
152
153 /// \brief Test if the given class represents instructions which are never safe
154 /// to mark with the "tail" keyword.
155 static inline bool IsNeverTail(InstructionClass Class) {
156   /// It is never safe to tail call objc_autorelease since by tail calling
157   /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
158   /// fast autoreleasing causing our object to be potentially reclaimed from the
159   /// autorelease pool which violates the semantics of __autoreleasing types in
160   /// ARC.
161   return Class == IC_Autorelease;
162 }
163
164 /// \brief Test if the given class represents instructions which are always safe
165 /// to mark with the nounwind attribute.
166 static inline bool IsNoThrow(InstructionClass Class) {
167   // objc_retainBlock is not nounwind because it calls user copy constructors
168   // which could theoretically throw.
169   return Class == IC_Retain ||
170          Class == IC_RetainRV ||
171          Class == IC_Release ||
172          Class == IC_Autorelease ||
173          Class == IC_AutoreleaseRV ||
174          Class == IC_AutoreleasepoolPush ||
175          Class == IC_AutoreleasepoolPop;
176 }
177
178 /// Test whether the given instruction can autorelease any pointer or cause an
179 /// autoreleasepool pop.
180 static inline bool
181 CanInterruptRV(InstructionClass Class) {
182   switch (Class) {
183   case IC_AutoreleasepoolPop:
184   case IC_CallOrUser:
185   case IC_Call:
186   case IC_Autorelease:
187   case IC_AutoreleaseRV:
188   case IC_FusedRetainAutorelease:
189   case IC_FusedRetainAutoreleaseRV:
190     return true;
191   default:
192     return false;
193   }
194 }
195
196 /// \brief Determine if F is one of the special known Functions.  If it isn't,
197 /// return IC_CallOrUser.
198 InstructionClass GetFunctionClass(const Function *F);
199
200 /// \brief Determine which objc runtime call instruction class V belongs to.
201 ///
202 /// This is similar to GetInstructionClass except that it only detects objc
203 /// runtime calls. This allows it to be faster.
204 ///
205 static inline InstructionClass GetBasicInstructionClass(const Value *V) {
206   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
207     if (const Function *F = CI->getCalledFunction())
208       return GetFunctionClass(F);
209     // Otherwise, be conservative.
210     return IC_CallOrUser;
211   }
212
213   // Otherwise, be conservative.
214   return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
215 }
216
217 /// \brief Determine what kind of construct V is.
218 InstructionClass GetInstructionClass(const Value *V);
219
220 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
221 /// look through objc_retain and objc_autorelease calls, which we know to return
222 /// their argument verbatim.
223 static inline const Value *GetUnderlyingObjCPtr(const Value *V) {
224   for (;;) {
225     V = GetUnderlyingObject(V);
226     if (!IsForwarding(GetBasicInstructionClass(V)))
227       break;
228     V = cast<CallInst>(V)->getArgOperand(0);
229   }
230
231   return V;
232 }
233
234 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
235 /// how to look through objc_retain and objc_autorelease calls, which we know to
236 /// return their argument verbatim.
237 static inline const Value *StripPointerCastsAndObjCCalls(const Value *V) {
238   for (;;) {
239     V = V->stripPointerCasts();
240     if (!IsForwarding(GetBasicInstructionClass(V)))
241       break;
242     V = cast<CallInst>(V)->getArgOperand(0);
243   }
244   return V;
245 }
246
247 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
248 /// how to look through objc_retain and objc_autorelease calls, which we know to
249 /// return their argument verbatim.
250 static inline Value *StripPointerCastsAndObjCCalls(Value *V) {
251   for (;;) {
252     V = V->stripPointerCasts();
253     if (!IsForwarding(GetBasicInstructionClass(V)))
254       break;
255     V = cast<CallInst>(V)->getArgOperand(0);
256   }
257   return V;
258 }
259
260 /// \brief Assuming the given instruction is one of the special calls such as
261 /// objc_retain or objc_release, return the argument value, stripped of no-op
262 /// casts and forwarding calls.
263 static inline Value *GetObjCArg(Value *Inst) {
264   return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
265 }
266
267 static inline bool IsNullOrUndef(const Value *V) {
268   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
269 }
270
271 static inline bool IsNoopInstruction(const Instruction *I) {
272   return isa<BitCastInst>(I) ||
273     (isa<GetElementPtrInst>(I) &&
274      cast<GetElementPtrInst>(I)->hasAllZeroIndices());
275 }
276
277
278 /// \brief Erase the given instruction.
279 ///
280 /// Many ObjC calls return their argument verbatim,
281 /// so if it's such a call and the return value has users, replace them with the
282 /// argument value.
283 ///
284 static inline void EraseInstruction(Instruction *CI) {
285   Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
286
287   bool Unused = CI->use_empty();
288
289   if (!Unused) {
290     // Replace the return value with the argument.
291     assert(IsForwarding(GetBasicInstructionClass(CI)) &&
292            "Can't delete non-forwarding instruction with users!");
293     CI->replaceAllUsesWith(OldArg);
294   }
295
296   CI->eraseFromParent();
297
298   if (Unused)
299     RecursivelyDeleteTriviallyDeadInstructions(OldArg);
300 }
301
302 /// \brief Test whether the given value is possible a retainable object pointer.
303 static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
304   // Pointers to static or stack storage are not valid retainable object
305   // pointers.
306   if (isa<Constant>(Op) || isa<AllocaInst>(Op))
307     return false;
308   // Special arguments can not be a valid retainable object pointer.
309   if (const Argument *Arg = dyn_cast<Argument>(Op))
310     if (Arg->hasByValAttr() ||
311         Arg->hasNestAttr() ||
312         Arg->hasStructRetAttr())
313       return false;
314   // Only consider values with pointer types.
315   //
316   // It seemes intuitive to exclude function pointer types as well, since
317   // functions are never retainable object pointers, however clang occasionally
318   // bitcasts retainable object pointers to function-pointer type temporarily.
319   PointerType *Ty = dyn_cast<PointerType>(Op->getType());
320   if (!Ty)
321     return false;
322   // Conservatively assume anything else is a potential retainable object
323   // pointer.
324   return true;
325 }
326
327 static inline bool IsPotentialRetainableObjPtr(const Value *Op,
328                                                AliasAnalysis &AA) {
329   // First make the rudimentary check.
330   if (!IsPotentialRetainableObjPtr(Op))
331     return false;
332
333   // Objects in constant memory are not reference-counted.
334   if (AA.pointsToConstantMemory(Op))
335     return false;
336
337   // Pointers in constant memory are not pointing to reference-counted objects.
338   if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
339     if (AA.pointsToConstantMemory(LI->getPointerOperand()))
340       return false;
341
342   // Otherwise assume the worst.
343   return true;
344 }
345
346 /// \brief Helper for GetInstructionClass. Determines what kind of construct CS
347 /// is.
348 static inline InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
349   for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
350        I != E; ++I)
351     if (IsPotentialRetainableObjPtr(*I))
352       return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
353
354   return CS.onlyReadsMemory() ? IC_None : IC_Call;
355 }
356
357 /// \brief Return true if this value refers to a distinct and identifiable
358 /// object.
359 ///
360 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
361 /// special knowledge of ObjC conventions.
362 static inline bool IsObjCIdentifiedObject(const Value *V) {
363   // Assume that call results and arguments have their own "provenance".
364   // Constants (including GlobalVariables) and Allocas are never
365   // reference-counted.
366   if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
367       isa<Argument>(V) || isa<Constant>(V) ||
368       isa<AllocaInst>(V))
369     return true;
370
371   if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
372     const Value *Pointer =
373       StripPointerCastsAndObjCCalls(LI->getPointerOperand());
374     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
375       // A constant pointer can't be pointing to an object on the heap. It may
376       // be reference-counted, but it won't be deleted.
377       if (GV->isConstant())
378         return true;
379       StringRef Name = GV->getName();
380       // These special variables are known to hold values which are not
381       // reference-counted pointers.
382       if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
383           Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
384           Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
385           Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
386           Name.startswith("\01l_objc_msgSend_fixup_"))
387         return true;
388     }
389   }
390
391   return false;
392 }
393
394 } // end namespace objcarc
395 } // end namespace llvm
396
397 #endif // LLVM_TRANSFORMS_SCALAR_OBJCARC_H