LLVM API Documentation

ObjCARCAPElim.cpp
Go to the documentation of this file.
00001 //===- ObjCARCAPElim.cpp - ObjC ARC Optimization --------------------------===//
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 ///
00011 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
00012 /// Reference Counting and is a system for managing reference counts for objects
00013 /// in Objective C.
00014 ///
00015 /// This specific file implements optimizations which remove extraneous
00016 /// autorelease pools.
00017 ///
00018 /// WARNING: This file knows about certain library functions. It recognizes them
00019 /// by name, and hardwires knowledge of their semantics.
00020 ///
00021 /// WARNING: This file knows about how certain Objective-C library functions are
00022 /// used. Naive LLVM IR transformations which would otherwise be
00023 /// behavior-preserving may break these assumptions.
00024 ///
00025 //===----------------------------------------------------------------------===//
00026 
00027 #define DEBUG_TYPE "objc-arc-ap-elim"
00028 #include "ObjCARC.h"
00029 #include "llvm/ADT/STLExtras.h"
00030 #include "llvm/IR/Constants.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 
00034 using namespace llvm;
00035 using namespace llvm::objcarc;
00036 
00037 namespace {
00038   /// \brief Autorelease pool elimination.
00039   class ObjCARCAPElim : public ModulePass {
00040     void getAnalysisUsage(AnalysisUsage &AU) const override;
00041     bool runOnModule(Module &M) override;
00042 
00043     static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
00044     static bool OptimizeBB(BasicBlock *BB);
00045 
00046   public:
00047     static char ID;
00048     ObjCARCAPElim() : ModulePass(ID) {
00049       initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
00050     }
00051   };
00052 }
00053 
00054 char ObjCARCAPElim::ID = 0;
00055 INITIALIZE_PASS(ObjCARCAPElim,
00056                 "objc-arc-apelim",
00057                 "ObjC ARC autorelease pool elimination",
00058                 false, false)
00059 
00060 Pass *llvm::createObjCARCAPElimPass() {
00061   return new ObjCARCAPElim();
00062 }
00063 
00064 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
00065   AU.setPreservesCFG();
00066 }
00067 
00068 /// Interprocedurally determine if calls made by the given call site can
00069 /// possibly produce autoreleases.
00070 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
00071   if (const Function *Callee = CS.getCalledFunction()) {
00072     if (Callee->isDeclaration() || Callee->mayBeOverridden())
00073       return true;
00074     for (Function::const_iterator I = Callee->begin(), E = Callee->end();
00075          I != E; ++I) {
00076       const BasicBlock *BB = I;
00077       for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
00078            J != F; ++J)
00079         if (ImmutableCallSite JCS = ImmutableCallSite(J))
00080           // This recursion depth limit is arbitrary. It's just great
00081           // enough to cover known interesting testcases.
00082           if (Depth < 3 &&
00083               !JCS.onlyReadsMemory() &&
00084               MayAutorelease(JCS, Depth + 1))
00085             return true;
00086     }
00087     return false;
00088   }
00089 
00090   return true;
00091 }
00092 
00093 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
00094   bool Changed = false;
00095 
00096   Instruction *Push = 0;
00097   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
00098     Instruction *Inst = I++;
00099     switch (GetBasicInstructionClass(Inst)) {
00100     case IC_AutoreleasepoolPush:
00101       Push = Inst;
00102       break;
00103     case IC_AutoreleasepoolPop:
00104       // If this pop matches a push and nothing in between can autorelease,
00105       // zap the pair.
00106       if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
00107         Changed = true;
00108         DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
00109                         "autorelease pair:\n"
00110                         "                           Pop: " << *Inst << "\n"
00111                      << "                           Push: " << *Push << "\n");
00112         Inst->eraseFromParent();
00113         Push->eraseFromParent();
00114       }
00115       Push = 0;
00116       break;
00117     case IC_CallOrUser:
00118       if (MayAutorelease(ImmutableCallSite(Inst)))
00119         Push = 0;
00120       break;
00121     default:
00122       break;
00123     }
00124   }
00125 
00126   return Changed;
00127 }
00128 
00129 bool ObjCARCAPElim::runOnModule(Module &M) {
00130   if (!EnableARCOpts)
00131     return false;
00132 
00133   // If nothing in the Module uses ARC, don't do anything.
00134   if (!ModuleHasARC(M))
00135     return false;
00136 
00137   // Find the llvm.global_ctors variable, as the first step in
00138   // identifying the global constructors. In theory, unnecessary autorelease
00139   // pools could occur anywhere, but in practice it's pretty rare. Global
00140   // ctors are a place where autorelease pools get inserted automatically,
00141   // so it's pretty common for them to be unnecessary, and it's pretty
00142   // profitable to eliminate them.
00143   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
00144   if (!GV)
00145     return false;
00146 
00147   assert(GV->hasDefinitiveInitializer() &&
00148          "llvm.global_ctors is uncooperative!");
00149 
00150   bool Changed = false;
00151 
00152   // Dig the constructor functions out of GV's initializer.
00153   ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
00154   for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
00155        OI != OE; ++OI) {
00156     Value *Op = *OI;
00157     // llvm.global_ctors is an array of pairs where the second members
00158     // are constructor functions.
00159     Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
00160     // If the user used a constructor function with the wrong signature and
00161     // it got bitcasted or whatever, look the other way.
00162     if (!F)
00163       continue;
00164     // Only look at function definitions.
00165     if (F->isDeclaration())
00166       continue;
00167     // Only look at functions with one basic block.
00168     if (std::next(F->begin()) != F->end())
00169       continue;
00170     // Ok, a single-block constructor function definition. Try to optimize it.
00171     Changed |= OptimizeBB(F->begin());
00172   }
00173 
00174   return Changed;
00175 }