blob: 614fa29e3e60ffdd13b20ecbaadfdd19005bdfc5 [file] [log] [blame]
Michael Gottesman08904e32013-01-28 03:28:38 +00001//===- 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"
Michael Gottesman294e7da2013-01-28 05:51:54 +000029#include "llvm/Analysis/ValueTracking.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000030#include "llvm/IR/Module.h"
31#include "llvm/Pass.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000032#include "llvm/Support/CallSite.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000033#include "llvm/Support/InstIterator.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 Gottesman08904e32013-01-28 03:28:38 +000036
37namespace llvm {
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000038class raw_ostream;
39}
40
41namespace llvm {
Michael Gottesman08904e32013-01-28 03:28:38 +000042namespace objcarc {
43
44/// \brief A handy option to enable/disable all ARC Optimizations.
45extern bool EnableARCOpts;
46
47/// \brief Test if the given module looks interesting to run ARC optimization
48/// on.
49static 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.
72enum 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)
John McCall20182ac2013-03-22 21:38:36 +000092 IC_IntrinsicUser, ///< clang.arc.use
Michael Gottesman08904e32013-01-28 03:28:38 +000093 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
Michael Gottesman5ed40af2013-01-28 06:39:31 +000099raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class);
Michael Gottesman08904e32013-01-28 03:28:38 +0000100
John McCall20182ac2013-03-22 21:38:36 +0000101/// \brief Test if the given class is a kind of user.
102inline static bool IsUser(InstructionClass Class) {
103 return Class == IC_User ||
104 Class == IC_CallOrUser ||
105 Class == IC_IntrinsicUser;
106}
107
Michael Gottesman294e7da2013-01-28 05:51:54 +0000108/// \brief Test if the given class is objc_retain or equivalent.
109static 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.
115static 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.
122static inline bool IsForwarding(InstructionClass Class) {
Michael Gottesman294e7da2013-01-28 05:51:54 +0000123 return Class == IC_Retain ||
124 Class == IC_RetainRV ||
125 Class == IC_Autorelease ||
126 Class == IC_AutoreleaseRV ||
Michael Gottesman294e7da2013-01-28 05:51:54 +0000127 Class == IC_NoopCast;
128}
129
130/// \brief Test if the given class represents instructions which do nothing if
131/// passed a null pointer.
132static inline bool IsNoopOnNull(InstructionClass Class) {
133 return Class == IC_Retain ||
134 Class == IC_RetainRV ||
135 Class == IC_Release ||
136 Class == IC_Autorelease ||
137 Class == IC_AutoreleaseRV ||
138 Class == IC_RetainBlock;
139}
140
141/// \brief Test if the given class represents instructions which are always safe
142/// to mark with the "tail" keyword.
143static inline bool IsAlwaysTail(InstructionClass Class) {
144 // IC_RetainBlock may be given a stack argument.
145 return Class == IC_Retain ||
146 Class == IC_RetainRV ||
147 Class == IC_AutoreleaseRV;
148}
149
150/// \brief Test if the given class represents instructions which are never safe
151/// to mark with the "tail" keyword.
152static inline bool IsNeverTail(InstructionClass Class) {
153 /// It is never safe to tail call objc_autorelease since by tail calling
154 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
155 /// fast autoreleasing causing our object to be potentially reclaimed from the
156 /// autorelease pool which violates the semantics of __autoreleasing types in
157 /// ARC.
158 return Class == IC_Autorelease;
159}
160
161/// \brief Test if the given class represents instructions which are always safe
162/// to mark with the nounwind attribute.
163static inline bool IsNoThrow(InstructionClass Class) {
164 // objc_retainBlock is not nounwind because it calls user copy constructors
165 // which could theoretically throw.
166 return Class == IC_Retain ||
167 Class == IC_RetainRV ||
168 Class == IC_Release ||
169 Class == IC_Autorelease ||
170 Class == IC_AutoreleaseRV ||
171 Class == IC_AutoreleasepoolPush ||
172 Class == IC_AutoreleasepoolPop;
173}
Michael Gottesman08904e32013-01-28 03:28:38 +0000174
Michael Gottesman778138e2013-01-29 03:03:03 +0000175/// Test whether the given instruction can autorelease any pointer or cause an
176/// autoreleasepool pop.
177static inline bool
178CanInterruptRV(InstructionClass Class) {
179 switch (Class) {
180 case IC_AutoreleasepoolPop:
181 case IC_CallOrUser:
182 case IC_Call:
183 case IC_Autorelease:
184 case IC_AutoreleaseRV:
185 case IC_FusedRetainAutorelease:
186 case IC_FusedRetainAutoreleaseRV:
187 return true;
188 default:
189 return false;
190 }
191}
192
Michael Gottesman08904e32013-01-28 03:28:38 +0000193/// \brief Determine if F is one of the special known Functions. If it isn't,
194/// return IC_CallOrUser.
Michael Gottesman5ed40af2013-01-28 06:39:31 +0000195InstructionClass GetFunctionClass(const Function *F);
Michael Gottesman08904e32013-01-28 03:28:38 +0000196
197/// \brief Determine which objc runtime call instruction class V belongs to.
198///
199/// This is similar to GetInstructionClass except that it only detects objc
200/// runtime calls. This allows it to be faster.
201///
202static inline InstructionClass GetBasicInstructionClass(const Value *V) {
203 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
204 if (const Function *F = CI->getCalledFunction())
205 return GetFunctionClass(F);
206 // Otherwise, be conservative.
207 return IC_CallOrUser;
208 }
209
210 // Otherwise, be conservative.
211 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
212}
213
Michael Gottesman778138e2013-01-29 03:03:03 +0000214/// \brief Determine what kind of construct V is.
215InstructionClass GetInstructionClass(const Value *V);
Michael Gottesman294e7da2013-01-28 05:51:54 +0000216
217/// \brief This is a wrapper around getUnderlyingObject which also knows how to
218/// look through objc_retain and objc_autorelease calls, which we know to return
219/// their argument verbatim.
220static inline const Value *GetUnderlyingObjCPtr(const Value *V) {
221 for (;;) {
222 V = GetUnderlyingObject(V);
223 if (!IsForwarding(GetBasicInstructionClass(V)))
224 break;
225 V = cast<CallInst>(V)->getArgOperand(0);
226 }
227
228 return V;
229}
230
231/// \brief This is a wrapper around Value::stripPointerCasts which also knows
232/// how to look through objc_retain and objc_autorelease calls, which we know to
233/// return their argument verbatim.
234static inline const Value *StripPointerCastsAndObjCCalls(const Value *V) {
235 for (;;) {
236 V = V->stripPointerCasts();
237 if (!IsForwarding(GetBasicInstructionClass(V)))
238 break;
239 V = cast<CallInst>(V)->getArgOperand(0);
240 }
241 return V;
242}
243
244/// \brief This is a wrapper around Value::stripPointerCasts which also knows
245/// how to look through objc_retain and objc_autorelease calls, which we know to
246/// return their argument verbatim.
247static inline Value *StripPointerCastsAndObjCCalls(Value *V) {
248 for (;;) {
249 V = V->stripPointerCasts();
250 if (!IsForwarding(GetBasicInstructionClass(V)))
251 break;
252 V = cast<CallInst>(V)->getArgOperand(0);
253 }
254 return V;
255}
256
Michael Gottesman778138e2013-01-29 03:03:03 +0000257/// \brief Assuming the given instruction is one of the special calls such as
258/// objc_retain or objc_release, return the argument value, stripped of no-op
259/// casts and forwarding calls.
260static inline Value *GetObjCArg(Value *Inst) {
261 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
262}
263
Michael Gottesman65c24812013-03-25 09:27:43 +0000264static inline bool IsNullOrUndef(const Value *V) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000265 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
266}
267
Michael Gottesman65c24812013-03-25 09:27:43 +0000268static inline bool IsNoopInstruction(const Instruction *I) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000269 return isa<BitCastInst>(I) ||
270 (isa<GetElementPtrInst>(I) &&
271 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
272}
273
274
275/// \brief Erase the given instruction.
276///
277/// Many ObjC calls return their argument verbatim,
278/// so if it's such a call and the return value has users, replace them with the
279/// argument value.
280///
281static inline void EraseInstruction(Instruction *CI) {
282 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
283
284 bool Unused = CI->use_empty();
285
286 if (!Unused) {
287 // Replace the return value with the argument.
288 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
289 "Can't delete non-forwarding instruction with users!");
290 CI->replaceAllUsesWith(OldArg);
291 }
292
293 CI->eraseFromParent();
294
295 if (Unused)
296 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
297}
298
299/// \brief Test whether the given value is possible a retainable object pointer.
300static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
Michael Gottesman23a1ee52013-01-29 04:58:30 +0000301 // Pointers to static or stack storage are not valid retainable object
302 // pointers.
Michael Gottesman778138e2013-01-29 03:03:03 +0000303 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
304 return false;
305 // Special arguments can not be a valid retainable object pointer.
306 if (const Argument *Arg = dyn_cast<Argument>(Op))
307 if (Arg->hasByValAttr() ||
308 Arg->hasNestAttr() ||
309 Arg->hasStructRetAttr())
310 return false;
311 // Only consider values with pointer types.
312 //
313 // It seemes intuitive to exclude function pointer types as well, since
314 // functions are never retainable object pointers, however clang occasionally
315 // bitcasts retainable object pointers to function-pointer type temporarily.
316 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
317 if (!Ty)
318 return false;
Michael Gottesman23a1ee52013-01-29 04:58:30 +0000319 // Conservatively assume anything else is a potential retainable object
320 // pointer.
Michael Gottesman778138e2013-01-29 03:03:03 +0000321 return true;
322}
323
324static inline bool IsPotentialRetainableObjPtr(const Value *Op,
325 AliasAnalysis &AA) {
326 // First make the rudimentary check.
327 if (!IsPotentialRetainableObjPtr(Op))
328 return false;
329
330 // Objects in constant memory are not reference-counted.
331 if (AA.pointsToConstantMemory(Op))
332 return false;
333
334 // Pointers in constant memory are not pointing to reference-counted objects.
335 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
336 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
337 return false;
338
339 // Otherwise assume the worst.
340 return true;
341}
342
343/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
344/// is.
345static inline InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
346 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
347 I != E; ++I)
348 if (IsPotentialRetainableObjPtr(*I))
349 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
350
351 return CS.onlyReadsMemory() ? IC_None : IC_Call;
352}
353
354/// \brief Return true if this value refers to a distinct and identifiable
355/// object.
356///
357/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
358/// special knowledge of ObjC conventions.
359static inline bool IsObjCIdentifiedObject(const Value *V) {
360 // Assume that call results and arguments have their own "provenance".
361 // Constants (including GlobalVariables) and Allocas are never
362 // reference-counted.
363 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
364 isa<Argument>(V) || isa<Constant>(V) ||
365 isa<AllocaInst>(V))
366 return true;
367
368 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
369 const Value *Pointer =
370 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
371 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
372 // A constant pointer can't be pointing to an object on the heap. It may
373 // be reference-counted, but it won't be deleted.
374 if (GV->isConstant())
375 return true;
376 StringRef Name = GV->getName();
377 // These special variables are known to hold values which are not
378 // reference-counted pointers.
379 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
380 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
381 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
382 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
383 Name.startswith("\01l_objc_msgSend_fixup_"))
384 return true;
385 }
386 }
387
388 return false;
389}
Michael Gottesman294e7da2013-01-28 05:51:54 +0000390
Michael Gottesman08904e32013-01-28 03:28:38 +0000391} // end namespace objcarc
392} // end namespace llvm
393
394#endif // LLVM_TRANSFORMS_SCALAR_OBJCARC_H