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