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