LLVM  mainline
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_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
00024 #define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
00025 
00026 #include "llvm/ADT/StringSwitch.h"
00027 #include "llvm/ADT/Optional.h"
00028 #include "llvm/Analysis/AliasAnalysis.h"
00029 #include "llvm/Analysis/Passes.h"
00030 #include "llvm/Analysis/ValueTracking.h"
00031 #include "llvm/IR/CallSite.h"
00032 #include "llvm/IR/InstIterator.h"
00033 #include "llvm/IR/Module.h"
00034 #include "llvm/Pass.h"
00035 #include "llvm/Transforms/ObjCARC.h"
00036 #include "llvm/Transforms/Utils/Local.h"
00037 #include "ARCInstKind.h"
00038 
00039 namespace llvm {
00040 class raw_ostream;
00041 }
00042 
00043 namespace llvm {
00044 namespace objcarc {
00045 
00046 /// \brief A handy option to enable/disable all ARC Optimizations.
00047 extern bool EnableARCOpts;
00048 
00049 /// \brief Test if the given module looks interesting to run ARC optimization
00050 /// on.
00051 static inline bool ModuleHasARC(const Module &M) {
00052   return
00053     M.getNamedValue("objc_retain") ||
00054     M.getNamedValue("objc_release") ||
00055     M.getNamedValue("objc_autorelease") ||
00056     M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
00057     M.getNamedValue("objc_retainBlock") ||
00058     M.getNamedValue("objc_autoreleaseReturnValue") ||
00059     M.getNamedValue("objc_autoreleasePoolPush") ||
00060     M.getNamedValue("objc_loadWeakRetained") ||
00061     M.getNamedValue("objc_loadWeak") ||
00062     M.getNamedValue("objc_destroyWeak") ||
00063     M.getNamedValue("objc_storeWeak") ||
00064     M.getNamedValue("objc_initWeak") ||
00065     M.getNamedValue("objc_moveWeak") ||
00066     M.getNamedValue("objc_copyWeak") ||
00067     M.getNamedValue("objc_retainedObject") ||
00068     M.getNamedValue("objc_unretainedObject") ||
00069     M.getNamedValue("objc_unretainedPointer") ||
00070     M.getNamedValue("clang.arc.use");
00071 }
00072 
00073 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
00074 /// look through objc_retain and objc_autorelease calls, which we know to return
00075 /// their argument verbatim.
00076 static inline const Value *GetUnderlyingObjCPtr(const Value *V,
00077                                                 const DataLayout &DL) {
00078   for (;;) {
00079     V = GetUnderlyingObject(V, DL);
00080     if (!IsForwarding(GetBasicARCInstKind(V)))
00081       break;
00082     V = cast<CallInst>(V)->getArgOperand(0);
00083   }
00084 
00085   return V;
00086 }
00087 
00088 /// The RCIdentity root of a value \p V is a dominating value U for which
00089 /// retaining or releasing U is equivalent to retaining or releasing V. In other
00090 /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
00091 ///
00092 /// We use this in the ARC optimizer to make it easier to match up ARC
00093 /// operations by always mapping ARC operations to RCIdentityRoots instead of
00094 /// pointers themselves.
00095 ///
00096 /// The two ways that we see RCIdentical values in ObjC are via:
00097 ///
00098 ///   1. PointerCasts
00099 ///   2. Forwarding Calls that return their argument verbatim.
00100 ///
00101 /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
00102 /// This implies that two RCIdentical values must alias.
00103 static inline const Value *GetRCIdentityRoot(const Value *V) {
00104   for (;;) {
00105     V = V->stripPointerCasts();
00106     if (!IsForwarding(GetBasicARCInstKind(V)))
00107       break;
00108     V = cast<CallInst>(V)->getArgOperand(0);
00109   }
00110   return V;
00111 }
00112 
00113 /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
00114 /// casts away the const of the result. For documentation about what an
00115 /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
00116 /// function.
00117 static inline Value *GetRCIdentityRoot(Value *V) {
00118   return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
00119 }
00120 
00121 /// \brief Assuming the given instruction is one of the special calls such as
00122 /// objc_retain or objc_release, return the RCIdentity root of the argument of
00123 /// the call.
00124 static inline Value *GetArgRCIdentityRoot(Value *Inst) {
00125   return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
00126 }
00127 
00128 static inline bool IsNullOrUndef(const Value *V) {
00129   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
00130 }
00131 
00132 static inline bool IsNoopInstruction(const Instruction *I) {
00133   return isa<BitCastInst>(I) ||
00134     (isa<GetElementPtrInst>(I) &&
00135      cast<GetElementPtrInst>(I)->hasAllZeroIndices());
00136 }
00137 
00138 
00139 /// \brief Erase the given instruction.
00140 ///
00141 /// Many ObjC calls return their argument verbatim,
00142 /// so if it's such a call and the return value has users, replace them with the
00143 /// argument value.
00144 ///
00145 static inline void EraseInstruction(Instruction *CI) {
00146   Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
00147 
00148   bool Unused = CI->use_empty();
00149 
00150   if (!Unused) {
00151     // Replace the return value with the argument.
00152     assert((IsForwarding(GetBasicARCInstKind(CI)) ||
00153             (IsNoopOnNull(GetBasicARCInstKind(CI)) &&
00154              isa<ConstantPointerNull>(OldArg))) &&
00155            "Can't delete non-forwarding instruction with users!");
00156     CI->replaceAllUsesWith(OldArg);
00157   }
00158 
00159   CI->eraseFromParent();
00160 
00161   if (Unused)
00162     RecursivelyDeleteTriviallyDeadInstructions(OldArg);
00163 }
00164 
00165 /// \brief Test whether the given value is possible a retainable object pointer.
00166 static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
00167   // Pointers to static or stack storage are not valid retainable object
00168   // pointers.
00169   if (isa<Constant>(Op) || isa<AllocaInst>(Op))
00170     return false;
00171   // Special arguments can not be a valid retainable object pointer.
00172   if (const Argument *Arg = dyn_cast<Argument>(Op))
00173     if (Arg->hasByValAttr() ||
00174         Arg->hasInAllocaAttr() ||
00175         Arg->hasNestAttr() ||
00176         Arg->hasStructRetAttr())
00177       return false;
00178   // Only consider values with pointer types.
00179   //
00180   // It seemes intuitive to exclude function pointer types as well, since
00181   // functions are never retainable object pointers, however clang occasionally
00182   // bitcasts retainable object pointers to function-pointer type temporarily.
00183   PointerType *Ty = dyn_cast<PointerType>(Op->getType());
00184   if (!Ty)
00185     return false;
00186   // Conservatively assume anything else is a potential retainable object
00187   // pointer.
00188   return true;
00189 }
00190 
00191 static inline bool IsPotentialRetainableObjPtr(const Value *Op,
00192                                                AliasAnalysis &AA) {
00193   // First make the rudimentary check.
00194   if (!IsPotentialRetainableObjPtr(Op))
00195     return false;
00196 
00197   // Objects in constant memory are not reference-counted.
00198   if (AA.pointsToConstantMemory(Op))
00199     return false;
00200 
00201   // Pointers in constant memory are not pointing to reference-counted objects.
00202   if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
00203     if (AA.pointsToConstantMemory(LI->getPointerOperand()))
00204       return false;
00205 
00206   // Otherwise assume the worst.
00207   return true;
00208 }
00209 
00210 /// \brief Helper for GetARCInstKind. Determines what kind of construct CS
00211 /// is.
00212 static inline ARCInstKind GetCallSiteClass(ImmutableCallSite CS) {
00213   for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
00214        I != E; ++I)
00215     if (IsPotentialRetainableObjPtr(*I))
00216       return CS.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
00217 
00218   return CS.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
00219 }
00220 
00221 /// \brief Return true if this value refers to a distinct and identifiable
00222 /// object.
00223 ///
00224 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
00225 /// special knowledge of ObjC conventions.
00226 static inline bool IsObjCIdentifiedObject(const Value *V) {
00227   // Assume that call results and arguments have their own "provenance".
00228   // Constants (including GlobalVariables) and Allocas are never
00229   // reference-counted.
00230   if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
00231       isa<Argument>(V) || isa<Constant>(V) ||
00232       isa<AllocaInst>(V))
00233     return true;
00234 
00235   if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
00236     const Value *Pointer =
00237       GetRCIdentityRoot(LI->getPointerOperand());
00238     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
00239       // A constant pointer can't be pointing to an object on the heap. It may
00240       // be reference-counted, but it won't be deleted.
00241       if (GV->isConstant())
00242         return true;
00243       StringRef Name = GV->getName();
00244       // These special variables are known to hold values which are not
00245       // reference-counted pointers.
00246       if (Name.startswith("\01l_objc_msgSend_fixup_"))
00247         return true;
00248 
00249       StringRef Section = GV->getSection();
00250       if (Section.find("__message_refs") != StringRef::npos ||
00251           Section.find("__objc_classrefs") != StringRef::npos ||
00252           Section.find("__objc_superrefs") != StringRef::npos ||
00253           Section.find("__objc_methname") != StringRef::npos ||
00254           Section.find("__cstring") != StringRef::npos)
00255         return true;
00256     }
00257   }
00258 
00259   return false;
00260 }
00261 
00262 enum class ARCMDKindID {
00263   ImpreciseRelease,
00264   CopyOnEscape,
00265   NoObjCARCExceptions,
00266 };
00267 
00268 /// A cache of MDKinds used by various ARC optimizations.
00269 class ARCMDKindCache {
00270   Module *M;
00271 
00272   /// The Metadata Kind for clang.imprecise_release metadata.
00273   llvm::Optional<unsigned> ImpreciseReleaseMDKind;
00274 
00275   /// The Metadata Kind for clang.arc.copy_on_escape metadata.
00276   llvm::Optional<unsigned> CopyOnEscapeMDKind;
00277 
00278   /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
00279   llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
00280 
00281 public:
00282   void init(Module *Mod) {
00283     M = Mod;
00284     ImpreciseReleaseMDKind = NoneType::None;
00285     CopyOnEscapeMDKind = NoneType::None;
00286     NoObjCARCExceptionsMDKind = NoneType::None;
00287   }
00288 
00289   unsigned get(ARCMDKindID ID) {
00290     switch (ID) {
00291     case ARCMDKindID::ImpreciseRelease:
00292       if (!ImpreciseReleaseMDKind)
00293         ImpreciseReleaseMDKind =
00294             M->getContext().getMDKindID("clang.imprecise_release");
00295       return *ImpreciseReleaseMDKind;
00296     case ARCMDKindID::CopyOnEscape:
00297       if (!CopyOnEscapeMDKind)
00298         CopyOnEscapeMDKind =
00299             M->getContext().getMDKindID("clang.arc.copy_on_escape");
00300       return *CopyOnEscapeMDKind;
00301     case ARCMDKindID::NoObjCARCExceptions:
00302       if (!NoObjCARCExceptionsMDKind)
00303         NoObjCARCExceptionsMDKind =
00304             M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
00305       return *NoObjCARCExceptionsMDKind;
00306     }
00307     llvm_unreachable("Covered switch isn't covered?!");
00308   }
00309 };
00310 
00311 } // end namespace objcarc
00312 } // end namespace llvm
00313 
00314 #endif