LCOV - code coverage report
Current view: top level - include/llvm/Analysis - ObjCARCAnalysisUtils.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 79 86 91.9 %
Date: 2018-05-20 00:06:23 Functions: 9 9 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- ObjCARCAnalysisUtils.h - ObjC ARC Analysis Utilities -----*- 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 analysis utilities used by the ObjC ARC Optimizer.
      11             : /// ARC stands for Automatic Reference Counting and is a system for managing
      12             : /// 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_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
      24             : #define LLVM_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
      25             : 
      26             : #include "llvm/ADT/Optional.h"
      27             : #include "llvm/ADT/StringSwitch.h"
      28             : #include "llvm/Analysis/AliasAnalysis.h"
      29             : #include "llvm/Analysis/ObjCARCInstKind.h"
      30             : #include "llvm/Analysis/Passes.h"
      31             : #include "llvm/Analysis/ValueTracking.h"
      32             : #include "llvm/IR/CallSite.h"
      33             : #include "llvm/IR/Constants.h"
      34             : #include "llvm/IR/InstIterator.h"
      35             : #include "llvm/IR/LLVMContext.h"
      36             : #include "llvm/IR/Module.h"
      37             : #include "llvm/Pass.h"
      38             : 
      39             : namespace llvm {
      40             : class raw_ostream;
      41             : }
      42             : 
      43             : namespace llvm {
      44             : namespace objcarc {
      45             : 
      46             : /// A handy option to enable/disable all ARC Optimizations.
      47             : extern bool EnableARCOpts;
      48             : 
      49             : /// Test if the given module looks interesting to run ARC optimization
      50             : /// on.
      51         282 : inline bool ModuleHasARC(const Module &M) {
      52             :   return
      53         811 :     M.getNamedValue("objc_retain") ||
      54         762 :     M.getNamedValue("objc_release") ||
      55         748 :     M.getNamedValue("objc_autorelease") ||
      56         747 :     M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
      57         746 :     M.getNamedValue("objc_unsafeClaimAutoreleasedReturnValue") ||
      58         746 :     M.getNamedValue("objc_retainBlock") ||
      59         745 :     M.getNamedValue("objc_autoreleaseReturnValue") ||
      60         742 :     M.getNamedValue("objc_autoreleasePoolPush") ||
      61         737 :     M.getNamedValue("objc_loadWeakRetained") ||
      62         734 :     M.getNamedValue("objc_loadWeak") ||
      63         734 :     M.getNamedValue("objc_destroyWeak") ||
      64         734 :     M.getNamedValue("objc_storeWeak") ||
      65         733 :     M.getNamedValue("objc_initWeak") ||
      66         732 :     M.getNamedValue("objc_moveWeak") ||
      67         732 :     M.getNamedValue("objc_copyWeak") ||
      68         732 :     M.getNamedValue("objc_retainedObject") ||
      69         732 :     M.getNamedValue("objc_unretainedObject") ||
      70        1014 :     M.getNamedValue("objc_unretainedPointer") ||
      71         789 :     M.getNamedValue("clang.arc.use");
      72             : }
      73             : 
      74             : /// This is a wrapper around getUnderlyingObject which also knows how to
      75             : /// look through objc_retain and objc_autorelease calls, which we know to return
      76             : /// their argument verbatim.
      77        4457 : inline const Value *GetUnderlyingObjCPtr(const Value *V,
      78             :                                                 const DataLayout &DL) {
      79             :   for (;;) {
      80             :     V = GetUnderlyingObject(V, DL);
      81        4516 :     if (!IsForwarding(GetBasicARCInstKind(V)))
      82             :       break;
      83          59 :     V = cast<CallInst>(V)->getArgOperand(0);
      84             :   }
      85             : 
      86        4457 :   return V;
      87             : }
      88             : 
      89             : /// A wrapper for GetUnderlyingObjCPtr used for results memoization.
      90             : inline const Value *
      91        2770 : GetUnderlyingObjCPtrCached(const Value *V, const DataLayout &DL,
      92             :                            DenseMap<const Value *, const Value *> &Cache) {
      93        5018 :   if (auto InCache = Cache.lookup(V))
      94             :     return InCache;
      95             : 
      96        1044 :   return Cache[V] = GetUnderlyingObjCPtr(V, DL);
      97             : }
      98             : 
      99             : /// The RCIdentity root of a value \p V is a dominating value U for which
     100             : /// retaining or releasing U is equivalent to retaining or releasing V. In other
     101             : /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
     102             : ///
     103             : /// We use this in the ARC optimizer to make it easier to match up ARC
     104             : /// operations by always mapping ARC operations to RCIdentityRoots instead of
     105             : /// pointers themselves.
     106             : ///
     107             : /// The two ways that we see RCIdentical values in ObjC are via:
     108             : ///
     109             : ///   1. PointerCasts
     110             : ///   2. Forwarding Calls that return their argument verbatim.
     111             : ///
     112             : /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
     113             : /// This implies that two RCIdentical values must alias.
     114        6825 : inline const Value *GetRCIdentityRoot(const Value *V) {
     115             :   for (;;) {
     116        7299 :     V = V->stripPointerCasts();
     117        7299 :     if (!IsForwarding(GetBasicARCInstKind(V)))
     118             :       break;
     119         474 :     V = cast<CallInst>(V)->getArgOperand(0);
     120             :   }
     121        6825 :   return V;
     122             : }
     123             : 
     124             : /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
     125             : /// casts away the const of the result. For documentation about what an
     126             : /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
     127             : /// function.
     128             : inline Value *GetRCIdentityRoot(Value *V) {
     129        2522 :   return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
     130             : }
     131             : 
     132             : /// Assuming the given instruction is one of the special calls such as
     133             : /// objc_retain or objc_release, return the RCIdentity root of the argument of
     134             : /// the call.
     135             : inline Value *GetArgRCIdentityRoot(Value *Inst) {
     136        2408 :   return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
     137             : }
     138             : 
     139             : inline bool IsNullOrUndef(const Value *V) {
     140         857 :   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
     141             : }
     142             : 
     143             : inline bool IsNoopInstruction(const Instruction *I) {
     144          70 :   return isa<BitCastInst>(I) ||
     145           0 :     (isa<GetElementPtrInst>(I) &&
     146           0 :      cast<GetElementPtrInst>(I)->hasAllZeroIndices());
     147             : }
     148             : 
     149             : /// Test whether the given value is possible a retainable object pointer.
     150        4168 : inline bool IsPotentialRetainableObjPtr(const Value *Op) {
     151             :   // Pointers to static or stack storage are not valid retainable object
     152             :   // pointers.
     153        4168 :   if (isa<Constant>(Op) || isa<AllocaInst>(Op))
     154             :     return false;
     155             :   // Special arguments can not be a valid retainable object pointer.
     156             :   if (const Argument *Arg = dyn_cast<Argument>(Op))
     157        1150 :     if (Arg->hasByValAttr() ||
     158        1150 :         Arg->hasInAllocaAttr() ||
     159        1725 :         Arg->hasNestAttr() ||
     160         575 :         Arg->hasStructRetAttr())
     161             :       return false;
     162             :   // Only consider values with pointer types.
     163             :   //
     164             :   // It seemes intuitive to exclude function pointer types as well, since
     165             :   // functions are never retainable object pointers, however clang occasionally
     166             :   // bitcasts retainable object pointers to function-pointer type temporarily.
     167        2322 :   PointerType *Ty = dyn_cast<PointerType>(Op->getType());
     168             :   if (!Ty)
     169             :     return false;
     170             :   // Conservatively assume anything else is a potential retainable object
     171             :   // pointer.
     172        2188 :   return true;
     173             : }
     174             : 
     175        1059 : inline bool IsPotentialRetainableObjPtr(const Value *Op,
     176             :                                                AliasAnalysis &AA) {
     177             :   // First make the rudimentary check.
     178        1059 :   if (!IsPotentialRetainableObjPtr(Op))
     179             :     return false;
     180             : 
     181             :   // Objects in constant memory are not reference-counted.
     182         934 :   if (AA.pointsToConstantMemory(Op))
     183             :     return false;
     184             : 
     185             :   // Pointers in constant memory are not pointing to reference-counted objects.
     186             :   if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
     187         206 :     if (AA.pointsToConstantMemory(LI->getPointerOperand()))
     188             :       return false;
     189             : 
     190             :   // Otherwise assume the worst.
     191             :   return true;
     192             : }
     193             : 
     194             : /// Helper for GetARCInstKind. Determines what kind of construct CS
     195             : /// is.
     196        1105 : inline ARCInstKind GetCallSiteClass(ImmutableCallSite CS) {
     197        2120 :   for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
     198        2120 :        I != E; ++I)
     199        1535 :     if (IsPotentialRetainableObjPtr(*I))
     200         520 :       return CS.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
     201             : 
     202         585 :   return CS.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
     203             : }
     204             : 
     205             : /// Return true if this value refers to a distinct and identifiable
     206             : /// object.
     207             : ///
     208             : /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
     209             : /// special knowledge of ObjC conventions.
     210        1293 : inline bool IsObjCIdentifiedObject(const Value *V) {
     211             :   // Assume that call results and arguments have their own "provenance".
     212             :   // Constants (including GlobalVariables) and Allocas are never
     213             :   // reference-counted.
     214         974 :   if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
     215         744 :       isa<Argument>(V) || isa<Constant>(V) ||
     216             :       isa<AllocaInst>(V))
     217             :     return true;
     218             : 
     219             :   if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
     220             :     const Value *Pointer =
     221         420 :       GetRCIdentityRoot(LI->getPointerOperand());
     222             :     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
     223             :       // A constant pointer can't be pointing to an object on the heap. It may
     224             :       // be reference-counted, but it won't be deleted.
     225         264 :       if (GV->isConstant())
     226         159 :         return true;
     227         260 :       StringRef Name = GV->getName();
     228             :       // These special variables are known to hold values which are not
     229             :       // reference-counted pointers.
     230             :       if (Name.startswith("\01l_objc_msgSend_fixup_"))
     231             :         return true;
     232             : 
     233         484 :       StringRef Section = GV->getSection();
     234         708 :       if (Section.find("__message_refs") != StringRef::npos ||
     235         625 :           Section.find("__objc_classrefs") != StringRef::npos ||
     236         542 :           Section.find("__objc_superrefs") != StringRef::npos ||
     237         748 :           Section.find("__objc_methname") != StringRef::npos ||
     238         365 :           Section.find("__cstring") != StringRef::npos)
     239             :         return true;
     240             :     }
     241             :   }
     242             : 
     243             :   return false;
     244             : }
     245             : 
     246             : enum class ARCMDKindID {
     247             :   ImpreciseRelease,
     248             :   CopyOnEscape,
     249             :   NoObjCARCExceptions,
     250             : };
     251             : 
     252             : /// A cache of MDKinds used by various ARC optimizations.
     253          30 : class ARCMDKindCache {
     254             :   Module *M;
     255             : 
     256             :   /// The Metadata Kind for clang.imprecise_release metadata.
     257             :   llvm::Optional<unsigned> ImpreciseReleaseMDKind;
     258             : 
     259             :   /// The Metadata Kind for clang.arc.copy_on_escape metadata.
     260             :   llvm::Optional<unsigned> CopyOnEscapeMDKind;
     261             : 
     262             :   /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
     263             :   llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
     264             : 
     265             : public:
     266             :   void init(Module *Mod) {
     267          30 :     M = Mod;
     268             :     ImpreciseReleaseMDKind = NoneType::None;
     269             :     CopyOnEscapeMDKind = NoneType::None;
     270             :     NoObjCARCExceptionsMDKind = NoneType::None;
     271             :   }
     272             : 
     273        1168 :   unsigned get(ARCMDKindID ID) {
     274        1168 :     switch (ID) {
     275         973 :     case ARCMDKindID::ImpreciseRelease:
     276         973 :       if (!ImpreciseReleaseMDKind)
     277             :         ImpreciseReleaseMDKind =
     278          81 :             M->getContext().getMDKindID("clang.imprecise_release");
     279         973 :       return *ImpreciseReleaseMDKind;
     280           0 :     case ARCMDKindID::CopyOnEscape:
     281           0 :       if (!CopyOnEscapeMDKind)
     282             :         CopyOnEscapeMDKind =
     283           0 :             M->getContext().getMDKindID("clang.arc.copy_on_escape");
     284           0 :       return *CopyOnEscapeMDKind;
     285         195 :     case ARCMDKindID::NoObjCARCExceptions:
     286         195 :       if (!NoObjCARCExceptionsMDKind)
     287             :         NoObjCARCExceptionsMDKind =
     288          72 :             M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
     289         195 :       return *NoObjCARCExceptionsMDKind;
     290             :     }
     291           0 :     llvm_unreachable("Covered switch isn't covered?!");
     292             :   }
     293             : };
     294             : 
     295             : } // end namespace objcarc
     296             : } // end namespace llvm
     297             : 
     298             : #endif

Generated by: LCOV version 1.13