LLVM API Documentation

lib/Transforms/ObjCARC/ObjCARC.h
Go to the documentation of this file.
00001 //===- ObjCARC.h - ObjC ARC Optimization --------------*- C++ -*-----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 /// This file defines common definitions/declarations used by the ObjC ARC
00011 /// Optimizer. ARC stands for Automatic Reference Counting and is a system for
00012 /// managing reference counts for objects in Objective C.
00013 ///
00014 /// WARNING: This file knows about certain library functions. It recognizes them
00015 /// by name, and hardwires knowledge of their semantics.
00016 ///
00017 /// WARNING: This file knows about how certain Objective-C library functions are
00018 /// used. Naive LLVM IR transformations which would otherwise be
00019 /// behavior-preserving may break these assumptions.
00020 ///
00021 //===----------------------------------------------------------------------===//
00022 
00023 #ifndef LLVM_TRANSFORMS_SCALAR_OBJCARC_H
00024 #define LLVM_TRANSFORMS_SCALAR_OBJCARC_H
00025 
00026 #include "llvm/ADT/StringSwitch.h"
00027 #include "llvm/Analysis/AliasAnalysis.h"
00028 #include "llvm/Analysis/Passes.h"
00029 #include "llvm/Analysis/ValueTracking.h"
00030 #include "llvm/IR/CallSite.h"
00031 #include "llvm/IR/InstIterator.h"
00032 #include "llvm/IR/Module.h"
00033 #include "llvm/Pass.h"
00034 #include "llvm/Transforms/ObjCARC.h"
00035 #include "llvm/Transforms/Utils/Local.h"
00036 
00037 namespace llvm {
00038 class raw_ostream;
00039 }
00040 
00041 namespace llvm {
00042 namespace objcarc {
00043 
00044 /// \brief A handy option to enable/disable all ARC Optimizations.
00045 extern bool EnableARCOpts;
00046 
00047 /// \brief Test if the given module looks interesting to run ARC optimization
00048 /// on.
00049 static inline bool ModuleHasARC(const Module &M) {
00050   return
00051     M.getNamedValue("objc_retain") ||
00052     M.getNamedValue("objc_release") ||
00053     M.getNamedValue("objc_autorelease") ||
00054     M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
00055     M.getNamedValue("objc_retainBlock") ||
00056     M.getNamedValue("objc_autoreleaseReturnValue") ||
00057     M.getNamedValue("objc_autoreleasePoolPush") ||
00058     M.getNamedValue("objc_loadWeakRetained") ||
00059     M.getNamedValue("objc_loadWeak") ||
00060     M.getNamedValue("objc_destroyWeak") ||
00061     M.getNamedValue("objc_storeWeak") ||
00062     M.getNamedValue("objc_initWeak") ||
00063     M.getNamedValue("objc_moveWeak") ||
00064     M.getNamedValue("objc_copyWeak") ||
00065     M.getNamedValue("objc_retainedObject") ||
00066     M.getNamedValue("objc_unretainedObject") ||
00067     M.getNamedValue("objc_unretainedPointer") ||
00068     M.getNamedValue("clang.arc.use");
00069 }
00070 
00071 /// \enum InstructionClass
00072 /// \brief A simple classification for instructions.
00073 enum InstructionClass {
00074   IC_Retain,              ///< objc_retain
00075   IC_RetainRV,            ///< objc_retainAutoreleasedReturnValue
00076   IC_RetainBlock,         ///< objc_retainBlock
00077   IC_Release,             ///< objc_release
00078   IC_Autorelease,         ///< objc_autorelease
00079   IC_AutoreleaseRV,       ///< objc_autoreleaseReturnValue
00080   IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
00081   IC_AutoreleasepoolPop,  ///< objc_autoreleasePoolPop
00082   IC_NoopCast,            ///< objc_retainedObject, etc.
00083   IC_FusedRetainAutorelease, ///< objc_retainAutorelease
00084   IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
00085   IC_LoadWeakRetained,    ///< objc_loadWeakRetained (primitive)
00086   IC_StoreWeak,           ///< objc_storeWeak (primitive)
00087   IC_InitWeak,            ///< objc_initWeak (derived)
00088   IC_LoadWeak,            ///< objc_loadWeak (derived)
00089   IC_MoveWeak,            ///< objc_moveWeak (derived)
00090   IC_CopyWeak,            ///< objc_copyWeak (derived)
00091   IC_DestroyWeak,         ///< objc_destroyWeak (derived)
00092   IC_StoreStrong,         ///< objc_storeStrong (derived)
00093   IC_IntrinsicUser,       ///< clang.arc.use
00094   IC_CallOrUser,          ///< could call objc_release and/or "use" pointers
00095   IC_Call,                ///< could call objc_release
00096   IC_User,                ///< could "use" a pointer
00097   IC_None                 ///< anything else
00098 };
00099 
00100 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class);
00101 
00102 /// \brief Test if the given class is a kind of user.
00103 inline static bool IsUser(InstructionClass Class) {
00104   return Class == IC_User ||
00105          Class == IC_CallOrUser ||
00106          Class == IC_IntrinsicUser;
00107 }
00108 
00109 /// \brief Test if the given class is objc_retain or equivalent.
00110 static inline bool IsRetain(InstructionClass Class) {
00111   return Class == IC_Retain ||
00112          Class == IC_RetainRV;
00113 }
00114 
00115 /// \brief Test if the given class is objc_autorelease or equivalent.
00116 static inline bool IsAutorelease(InstructionClass Class) {
00117   return Class == IC_Autorelease ||
00118          Class == IC_AutoreleaseRV;
00119 }
00120 
00121 /// \brief Test if the given class represents instructions which return their
00122 /// argument verbatim.
00123 static inline bool IsForwarding(InstructionClass Class) {
00124   return Class == IC_Retain ||
00125          Class == IC_RetainRV ||
00126          Class == IC_Autorelease ||
00127          Class == IC_AutoreleaseRV ||
00128          Class == IC_NoopCast;
00129 }
00130 
00131 /// \brief Test if the given class represents instructions which do nothing if
00132 /// passed a null pointer.
00133 static inline bool IsNoopOnNull(InstructionClass Class) {
00134   return Class == IC_Retain ||
00135          Class == IC_RetainRV ||
00136          Class == IC_Release ||
00137          Class == IC_Autorelease ||
00138          Class == IC_AutoreleaseRV ||
00139          Class == IC_RetainBlock;
00140 }
00141 
00142 /// \brief Test if the given class represents instructions which are always safe
00143 /// to mark with the "tail" keyword.
00144 static inline bool IsAlwaysTail(InstructionClass Class) {
00145   // IC_RetainBlock may be given a stack argument.
00146   return Class == IC_Retain ||
00147          Class == IC_RetainRV ||
00148          Class == IC_AutoreleaseRV;
00149 }
00150 
00151 /// \brief Test if the given class represents instructions which are never safe
00152 /// to mark with the "tail" keyword.
00153 static inline bool IsNeverTail(InstructionClass Class) {
00154   /// It is never safe to tail call objc_autorelease since by tail calling
00155   /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
00156   /// fast autoreleasing causing our object to be potentially reclaimed from the
00157   /// autorelease pool which violates the semantics of __autoreleasing types in
00158   /// ARC.
00159   return Class == IC_Autorelease;
00160 }
00161 
00162 /// \brief Test if the given class represents instructions which are always safe
00163 /// to mark with the nounwind attribute.
00164 static inline bool IsNoThrow(InstructionClass Class) {
00165   // objc_retainBlock is not nounwind because it calls user copy constructors
00166   // which could theoretically throw.
00167   return Class == IC_Retain ||
00168          Class == IC_RetainRV ||
00169          Class == IC_Release ||
00170          Class == IC_Autorelease ||
00171          Class == IC_AutoreleaseRV ||
00172          Class == IC_AutoreleasepoolPush ||
00173          Class == IC_AutoreleasepoolPop;
00174 }
00175 
00176 /// Test whether the given instruction can autorelease any pointer or cause an
00177 /// autoreleasepool pop.
00178 static inline bool
00179 CanInterruptRV(InstructionClass Class) {
00180   switch (Class) {
00181   case IC_AutoreleasepoolPop:
00182   case IC_CallOrUser:
00183   case IC_Call:
00184   case IC_Autorelease:
00185   case IC_AutoreleaseRV:
00186   case IC_FusedRetainAutorelease:
00187   case IC_FusedRetainAutoreleaseRV:
00188     return true;
00189   default:
00190     return false;
00191   }
00192 }
00193 
00194 /// \brief Determine if F is one of the special known Functions.  If it isn't,
00195 /// return IC_CallOrUser.
00196 InstructionClass GetFunctionClass(const Function *F);
00197 
00198 /// \brief Determine which objc runtime call instruction class V belongs to.
00199 ///
00200 /// This is similar to GetInstructionClass except that it only detects objc
00201 /// runtime calls. This allows it to be faster.
00202 ///
00203 static inline InstructionClass GetBasicInstructionClass(const Value *V) {
00204   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
00205     if (const Function *F = CI->getCalledFunction())
00206       return GetFunctionClass(F);
00207     // Otherwise, be conservative.
00208     return IC_CallOrUser;
00209   }
00210 
00211   // Otherwise, be conservative.
00212   return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
00213 }
00214 
00215 /// \brief Determine what kind of construct V is.
00216 InstructionClass GetInstructionClass(const Value *V);
00217 
00218 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
00219 /// look through objc_retain and objc_autorelease calls, which we know to return
00220 /// their argument verbatim.
00221 static inline const Value *GetUnderlyingObjCPtr(const Value *V) {
00222   for (;;) {
00223     V = GetUnderlyingObject(V);
00224     if (!IsForwarding(GetBasicInstructionClass(V)))
00225       break;
00226     V = cast<CallInst>(V)->getArgOperand(0);
00227   }
00228 
00229   return V;
00230 }
00231 
00232 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
00233 /// how to look through objc_retain and objc_autorelease calls, which we know to
00234 /// return their argument verbatim.
00235 static inline const Value *StripPointerCastsAndObjCCalls(const Value *V) {
00236   for (;;) {
00237     V = V->stripPointerCasts();
00238     if (!IsForwarding(GetBasicInstructionClass(V)))
00239       break;
00240     V = cast<CallInst>(V)->getArgOperand(0);
00241   }
00242   return V;
00243 }
00244 
00245 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
00246 /// how to look through objc_retain and objc_autorelease calls, which we know to
00247 /// return their argument verbatim.
00248 static inline Value *StripPointerCastsAndObjCCalls(Value *V) {
00249   for (;;) {
00250     V = V->stripPointerCasts();
00251     if (!IsForwarding(GetBasicInstructionClass(V)))
00252       break;
00253     V = cast<CallInst>(V)->getArgOperand(0);
00254   }
00255   return V;
00256 }
00257 
00258 /// \brief Assuming the given instruction is one of the special calls such as
00259 /// objc_retain or objc_release, return the argument value, stripped of no-op
00260 /// casts and forwarding calls.
00261 static inline Value *GetObjCArg(Value *Inst) {
00262   return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
00263 }
00264 
00265 static inline bool IsNullOrUndef(const Value *V) {
00266   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
00267 }
00268 
00269 static inline bool IsNoopInstruction(const Instruction *I) {
00270   return isa<BitCastInst>(I) ||
00271     (isa<GetElementPtrInst>(I) &&
00272      cast<GetElementPtrInst>(I)->hasAllZeroIndices());
00273 }
00274 
00275 
00276 /// \brief Erase the given instruction.
00277 ///
00278 /// Many ObjC calls return their argument verbatim,
00279 /// so if it's such a call and the return value has users, replace them with the
00280 /// argument value.
00281 ///
00282 static inline void EraseInstruction(Instruction *CI) {
00283   Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
00284 
00285   bool Unused = CI->use_empty();
00286 
00287   if (!Unused) {
00288     // Replace the return value with the argument.
00289     assert((IsForwarding(GetBasicInstructionClass(CI)) ||
00290             (IsNoopOnNull(GetBasicInstructionClass(CI)) &&
00291              isa<ConstantPointerNull>(OldArg))) &&
00292            "Can't delete non-forwarding instruction with users!");
00293     CI->replaceAllUsesWith(OldArg);
00294   }
00295 
00296   CI->eraseFromParent();
00297 
00298   if (Unused)
00299     RecursivelyDeleteTriviallyDeadInstructions(OldArg);
00300 }
00301 
00302 /// \brief Test whether the given value is possible a retainable object pointer.
00303 static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
00304   // Pointers to static or stack storage are not valid retainable object
00305   // pointers.
00306   if (isa<Constant>(Op) || isa<AllocaInst>(Op))
00307     return false;
00308   // Special arguments can not be a valid retainable object pointer.
00309   if (const Argument *Arg = dyn_cast<Argument>(Op))
00310     if (Arg->hasByValAttr() ||
00311         Arg->hasInAllocaAttr() ||
00312         Arg->hasNestAttr() ||
00313         Arg->hasStructRetAttr())
00314       return false;
00315   // Only consider values with pointer types.
00316   //
00317   // It seemes intuitive to exclude function pointer types as well, since
00318   // functions are never retainable object pointers, however clang occasionally
00319   // bitcasts retainable object pointers to function-pointer type temporarily.
00320   PointerType *Ty = dyn_cast<PointerType>(Op->getType());
00321   if (!Ty)
00322     return false;
00323   // Conservatively assume anything else is a potential retainable object
00324   // pointer.
00325   return true;
00326 }
00327 
00328 static inline bool IsPotentialRetainableObjPtr(const Value *Op,
00329                                                AliasAnalysis &AA) {
00330   // First make the rudimentary check.
00331   if (!IsPotentialRetainableObjPtr(Op))
00332     return false;
00333 
00334   // Objects in constant memory are not reference-counted.
00335   if (AA.pointsToConstantMemory(Op))
00336     return false;
00337 
00338   // Pointers in constant memory are not pointing to reference-counted objects.
00339   if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
00340     if (AA.pointsToConstantMemory(LI->getPointerOperand()))
00341       return false;
00342 
00343   // Otherwise assume the worst.
00344   return true;
00345 }
00346 
00347 /// \brief Helper for GetInstructionClass. Determines what kind of construct CS
00348 /// is.
00349 static inline InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
00350   for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
00351        I != E; ++I)
00352     if (IsPotentialRetainableObjPtr(*I))
00353       return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
00354 
00355   return CS.onlyReadsMemory() ? IC_None : IC_Call;
00356 }
00357 
00358 /// \brief Return true if this value refers to a distinct and identifiable
00359 /// object.
00360 ///
00361 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
00362 /// special knowledge of ObjC conventions.
00363 static inline bool IsObjCIdentifiedObject(const Value *V) {
00364   // Assume that call results and arguments have their own "provenance".
00365   // Constants (including GlobalVariables) and Allocas are never
00366   // reference-counted.
00367   if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
00368       isa<Argument>(V) || isa<Constant>(V) ||
00369       isa<AllocaInst>(V))
00370     return true;
00371 
00372   if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
00373     const Value *Pointer =
00374       StripPointerCastsAndObjCCalls(LI->getPointerOperand());
00375     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
00376       // A constant pointer can't be pointing to an object on the heap. It may
00377       // be reference-counted, but it won't be deleted.
00378       if (GV->isConstant())
00379         return true;
00380       StringRef Name = GV->getName();
00381       // These special variables are known to hold values which are not
00382       // reference-counted pointers.
00383       if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
00384           Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
00385           Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
00386           Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
00387           Name.startswith("\01l_objc_msgSend_fixup_"))
00388         return true;
00389     }
00390   }
00391 
00392   return false;
00393 }
00394 
00395 } // end namespace objcarc
00396 } // end namespace llvm
00397 
00398 #endif // LLVM_TRANSFORMS_SCALAR_OBJCARC_H