ObjCARC.cpp revision 1dae3e965cc0b113b437c2c836f6e3c28a5cdb53
1ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===// 2ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// 3ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// The LLVM Compiler Infrastructure 4ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// 5ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// This file is distributed under the University of Illinois Open Source 6ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// License. See LICENSE.TXT for details. 7ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// 8ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao//===----------------------------------------------------------------------===// 9ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// 10ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// This file defines ObjC ARC optimizations. ARC stands for 11ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// Automatic Reference Counting and is a system for managing reference counts 12ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// for objects in Objective C. 13ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// 14ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// The optimizations performed include elimination of redundant, partially 15ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// redundant, and inconsequential reference count operations, elimination of 16ee6cdb95525abc8c7766798148302306a100b774Shih-wei Liao// redundant weak pointer operations, pattern-matching and replacement of 17a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// low-level operations into higher-level operations, and numerous minor 18a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// simplifications. 19a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// 20a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// This file also defines a simple ARC-aware AliasAnalysis. 21a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// 22a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// WARNING: This file knows about certain library functions. It recognizes them 23a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// by name, and hardwires knowedge of their semantics. 24a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// 25a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// WARNING: This file knows about how certain Objective-C library functions are 26a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// used. Naive LLVM IR transformations which would otherwise be 27a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// behavior-preserving may break these assumptions. 28a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// 29a839a76142ae481e578a85218008043dc52c5cf3Logan Chien//===----------------------------------------------------------------------===// 30a839a76142ae481e578a85218008043dc52c5cf3Logan Chien 31a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#define DEBUG_TYPE "objc-arc" 32a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/Function.h" 33a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/Intrinsics.h" 34a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/GlobalVariable.h" 3558611fc8193e7386698178f167a2e0cbdd6a4f6fLogan Chien#include "llvm/DerivedTypes.h" 3658611fc8193e7386698178f167a2e0cbdd6a4f6fLogan Chien#include "llvm/Module.h" 37a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/Analysis/ValueTracking.h" 38a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/Transforms/Utils/Local.h" 3971e5a4a2fa18ff55b1e04e73b70b2938150a143cLogan Chien#include "llvm/Support/CallSite.h" 40a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/Support/CommandLine.h" 41a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/ADT/StringSwitch.h" 422061b057e0922ac33b9314c1ccaa50eb7286b847Logan Chien#include "llvm/ADT/DenseMap.h" 43a839a76142ae481e578a85218008043dc52c5cf3Logan Chien#include "llvm/ADT/STLExtras.h" 44a839a76142ae481e578a85218008043dc52c5cf3Logan Chienusing namespace llvm; 45a839a76142ae481e578a85218008043dc52c5cf3Logan Chien 4658611fc8193e7386698178f167a2e0cbdd6a4f6fLogan Chien// A handy option to enable/disable all optimizations in this file. 47a839a76142ae481e578a85218008043dc52c5cf3Logan Chienstatic cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true)); 48a839a76142ae481e578a85218008043dc52c5cf3Logan Chien 4958611fc8193e7386698178f167a2e0cbdd6a4f6fLogan Chien//===----------------------------------------------------------------------===// 50a839a76142ae481e578a85218008043dc52c5cf3Logan Chien// Misc. Utilities 51a839a76142ae481e578a85218008043dc52c5cf3Logan Chien//===----------------------------------------------------------------------===// 5274f7a939f44d926babd52f59978e6b093e4bb2d0Logan Chien 53a839a76142ae481e578a85218008043dc52c5cf3Logan Chiennamespace { 54a839a76142ae481e578a85218008043dc52c5cf3Logan Chien /// MapVector - An associative container with fast insertion-order 5558611fc8193e7386698178f167a2e0cbdd6a4f6fLogan Chien /// (deterministic) iteration over its elements. Plus the special 56a839a76142ae481e578a85218008043dc52c5cf3Logan Chien /// blot operation. 57a839a76142ae481e578a85218008043dc52c5cf3Logan Chien template<class KeyT, class ValueT> 58a839a76142ae481e578a85218008043dc52c5cf3Logan Chien class MapVector { 5958611fc8193e7386698178f167a2e0cbdd6a4f6fLogan Chien /// Map - Map keys to indices in Vector. 60a839a76142ae481e578a85218008043dc52c5cf3Logan Chien typedef DenseMap<KeyT, size_t> MapTy; 61a839a76142ae481e578a85218008043dc52c5cf3Logan Chien MapTy Map; 62a839a76142ae481e578a85218008043dc52c5cf3Logan Chien 63a839a76142ae481e578a85218008043dc52c5cf3Logan Chien /// Vector - Keys and values. 64a839a76142ae481e578a85218008043dc52c5cf3Logan Chien typedef std::vector<std::pair<KeyT, ValueT> > VectorTy; 65a839a76142ae481e578a85218008043dc52c5cf3Logan Chien VectorTy Vector; 66a839a76142ae481e578a85218008043dc52c5cf3Logan Chien 67a839a76142ae481e578a85218008043dc52c5cf3Logan Chien public: 68 typedef typename VectorTy::iterator iterator; 69 typedef typename VectorTy::const_iterator const_iterator; 70 iterator begin() { return Vector.begin(); } 71 iterator end() { return Vector.end(); } 72 const_iterator begin() const { return Vector.begin(); } 73 const_iterator end() const { return Vector.end(); } 74 75#ifdef XDEBUG 76 ~MapVector() { 77 assert(Vector.size() >= Map.size()); // May differ due to blotting. 78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end(); 79 I != E; ++I) { 80 assert(I->second < Vector.size()); 81 assert(Vector[I->second].first == I->first); 82 } 83 for (typename VectorTy::const_iterator I = Vector.begin(), 84 E = Vector.end(); I != E; ++I) 85 assert(!I->first || 86 (Map.count(I->first) && 87 Map[I->first] == size_t(I - Vector.begin()))); 88 } 89#endif 90 91 ValueT &operator[](KeyT Arg) { 92 std::pair<typename MapTy::iterator, bool> Pair = 93 Map.insert(std::make_pair(Arg, size_t(0))); 94 if (Pair.second) { 95 Pair.first->second = Vector.size(); 96 Vector.push_back(std::make_pair(Arg, ValueT())); 97 return Vector.back().second; 98 } 99 return Vector[Pair.first->second].second; 100 } 101 102 std::pair<iterator, bool> 103 insert(const std::pair<KeyT, ValueT> &InsertPair) { 104 std::pair<typename MapTy::iterator, bool> Pair = 105 Map.insert(std::make_pair(InsertPair.first, size_t(0))); 106 if (Pair.second) { 107 Pair.first->second = Vector.size(); 108 Vector.push_back(InsertPair); 109 return std::make_pair(llvm::prior(Vector.end()), true); 110 } 111 return std::make_pair(Vector.begin() + Pair.first->second, false); 112 } 113 114 const_iterator find(KeyT Key) const { 115 typename MapTy::const_iterator It = Map.find(Key); 116 if (It == Map.end()) return Vector.end(); 117 return Vector.begin() + It->second; 118 } 119 120 /// blot - This is similar to erase, but instead of removing the element 121 /// from the vector, it just zeros out the key in the vector. This leaves 122 /// iterators intact, but clients must be prepared for zeroed-out keys when 123 /// iterating. 124 void blot(KeyT Key) { 125 typename MapTy::iterator It = Map.find(Key); 126 if (It == Map.end()) return; 127 Vector[It->second].first = KeyT(); 128 Map.erase(It); 129 } 130 131 void clear() { 132 Map.clear(); 133 Vector.clear(); 134 } 135 }; 136} 137 138//===----------------------------------------------------------------------===// 139// ARC Utilities. 140//===----------------------------------------------------------------------===// 141 142namespace { 143 /// InstructionClass - A simple classification for instructions. 144 enum InstructionClass { 145 IC_Retain, ///< objc_retain 146 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue 147 IC_RetainBlock, ///< objc_retainBlock 148 IC_Release, ///< objc_release 149 IC_Autorelease, ///< objc_autorelease 150 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue 151 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush 152 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop 153 IC_NoopCast, ///< objc_retainedObject, etc. 154 IC_FusedRetainAutorelease, ///< objc_retainAutorelease 155 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue 156 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive) 157 IC_StoreWeak, ///< objc_storeWeak (primitive) 158 IC_InitWeak, ///< objc_initWeak (derived) 159 IC_LoadWeak, ///< objc_loadWeak (derived) 160 IC_MoveWeak, ///< objc_moveWeak (derived) 161 IC_CopyWeak, ///< objc_copyWeak (derived) 162 IC_DestroyWeak, ///< objc_destroyWeak (derived) 163 IC_CallOrUser, ///< could call objc_release and/or "use" pointers 164 IC_Call, ///< could call objc_release 165 IC_User, ///< could "use" a pointer 166 IC_None ///< anything else 167 }; 168} 169 170/// IsPotentialUse - Test whether the given value is possible a 171/// reference-counted pointer. 172static bool IsPotentialUse(const Value *Op) { 173 // Pointers to static or stack storage are not reference-counted pointers. 174 if (isa<Constant>(Op) || isa<AllocaInst>(Op)) 175 return false; 176 // Special arguments are not reference-counted. 177 if (const Argument *Arg = dyn_cast<Argument>(Op)) 178 if (Arg->hasByValAttr() || 179 Arg->hasNestAttr() || 180 Arg->hasStructRetAttr()) 181 return false; 182 // Only consider values with pointer types. 183 // It seemes intuitive to exclude function pointer types as well, since 184 // functions are never reference-counted, however clang occasionally 185 // bitcasts reference-counted pointers to function-pointer type 186 // temporarily. 187 PointerType *Ty = dyn_cast<PointerType>(Op->getType()); 188 if (!Ty) 189 return false; 190 // Conservatively assume anything else is a potential use. 191 return true; 192} 193 194/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind 195/// of construct CS is. 196static InstructionClass GetCallSiteClass(ImmutableCallSite CS) { 197 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 198 I != E; ++I) 199 if (IsPotentialUse(*I)) 200 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser; 201 202 return CS.onlyReadsMemory() ? IC_None : IC_Call; 203} 204 205/// GetFunctionClass - Determine if F is one of the special known Functions. 206/// If it isn't, return IC_CallOrUser. 207static InstructionClass GetFunctionClass(const Function *F) { 208 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 209 210 // No arguments. 211 if (AI == AE) 212 return StringSwitch<InstructionClass>(F->getName()) 213 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush) 214 .Default(IC_CallOrUser); 215 216 // One argument. 217 const Argument *A0 = AI++; 218 if (AI == AE) 219 // Argument is a pointer. 220 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) { 221 Type *ETy = PTy->getElementType(); 222 // Argument is i8*. 223 if (ETy->isIntegerTy(8)) 224 return StringSwitch<InstructionClass>(F->getName()) 225 .Case("objc_retain", IC_Retain) 226 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV) 227 .Case("objc_retainBlock", IC_RetainBlock) 228 .Case("objc_release", IC_Release) 229 .Case("objc_autorelease", IC_Autorelease) 230 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV) 231 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop) 232 .Case("objc_retainedObject", IC_NoopCast) 233 .Case("objc_unretainedObject", IC_NoopCast) 234 .Case("objc_unretainedPointer", IC_NoopCast) 235 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease) 236 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease) 237 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV) 238 .Default(IC_CallOrUser); 239 240 // Argument is i8** 241 if (PointerType *Pte = dyn_cast<PointerType>(ETy)) 242 if (Pte->getElementType()->isIntegerTy(8)) 243 return StringSwitch<InstructionClass>(F->getName()) 244 .Case("objc_loadWeakRetained", IC_LoadWeakRetained) 245 .Case("objc_loadWeak", IC_LoadWeak) 246 .Case("objc_destroyWeak", IC_DestroyWeak) 247 .Default(IC_CallOrUser); 248 } 249 250 // Two arguments, first is i8**. 251 const Argument *A1 = AI++; 252 if (AI == AE) 253 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) 254 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType())) 255 if (Pte->getElementType()->isIntegerTy(8)) 256 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) { 257 Type *ETy1 = PTy1->getElementType(); 258 // Second argument is i8* 259 if (ETy1->isIntegerTy(8)) 260 return StringSwitch<InstructionClass>(F->getName()) 261 .Case("objc_storeWeak", IC_StoreWeak) 262 .Case("objc_initWeak", IC_InitWeak) 263 .Default(IC_CallOrUser); 264 // Second argument is i8**. 265 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1)) 266 if (Pte1->getElementType()->isIntegerTy(8)) 267 return StringSwitch<InstructionClass>(F->getName()) 268 .Case("objc_moveWeak", IC_MoveWeak) 269 .Case("objc_copyWeak", IC_CopyWeak) 270 .Default(IC_CallOrUser); 271 } 272 273 // Anything else. 274 return IC_CallOrUser; 275} 276 277/// GetInstructionClass - Determine what kind of construct V is. 278static InstructionClass GetInstructionClass(const Value *V) { 279 if (const Instruction *I = dyn_cast<Instruction>(V)) { 280 // Any instruction other than bitcast and gep with a pointer operand have a 281 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer 282 // to a subsequent use, rather than using it themselves, in this sense. 283 // As a short cut, several other opcodes are known to have no pointer 284 // operands of interest. And ret is never followed by a release, so it's 285 // not interesting to examine. 286 switch (I->getOpcode()) { 287 case Instruction::Call: { 288 const CallInst *CI = cast<CallInst>(I); 289 // Check for calls to special functions. 290 if (const Function *F = CI->getCalledFunction()) { 291 InstructionClass Class = GetFunctionClass(F); 292 if (Class != IC_CallOrUser) 293 return Class; 294 295 // None of the intrinsic functions do objc_release. For intrinsics, the 296 // only question is whether or not they may be users. 297 switch (F->getIntrinsicID()) { 298 case 0: break; 299 case Intrinsic::bswap: case Intrinsic::ctpop: 300 case Intrinsic::ctlz: case Intrinsic::cttz: 301 case Intrinsic::returnaddress: case Intrinsic::frameaddress: 302 case Intrinsic::stacksave: case Intrinsic::stackrestore: 303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend: 304 // Don't let dbg info affect our results. 305 case Intrinsic::dbg_declare: case Intrinsic::dbg_value: 306 // Short cut: Some intrinsics obviously don't use ObjC pointers. 307 return IC_None; 308 default: 309 for (Function::const_arg_iterator AI = F->arg_begin(), 310 AE = F->arg_end(); AI != AE; ++AI) 311 if (IsPotentialUse(AI)) 312 return IC_User; 313 return IC_None; 314 } 315 } 316 return GetCallSiteClass(CI); 317 } 318 case Instruction::Invoke: 319 return GetCallSiteClass(cast<InvokeInst>(I)); 320 case Instruction::BitCast: 321 case Instruction::GetElementPtr: 322 case Instruction::Select: case Instruction::PHI: 323 case Instruction::Ret: case Instruction::Br: 324 case Instruction::Switch: case Instruction::IndirectBr: 325 case Instruction::Alloca: case Instruction::VAArg: 326 case Instruction::Add: case Instruction::FAdd: 327 case Instruction::Sub: case Instruction::FSub: 328 case Instruction::Mul: case Instruction::FMul: 329 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv: 330 case Instruction::SRem: case Instruction::URem: case Instruction::FRem: 331 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: 332 case Instruction::And: case Instruction::Or: case Instruction::Xor: 333 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc: 334 case Instruction::IntToPtr: case Instruction::FCmp: 335 case Instruction::FPTrunc: case Instruction::FPExt: 336 case Instruction::FPToUI: case Instruction::FPToSI: 337 case Instruction::UIToFP: case Instruction::SIToFP: 338 case Instruction::InsertElement: case Instruction::ExtractElement: 339 case Instruction::ShuffleVector: 340 case Instruction::ExtractValue: 341 break; 342 case Instruction::ICmp: 343 // Comparing a pointer with null, or any other constant, isn't an 344 // interesting use, because we don't care what the pointer points to, or 345 // about the values of any other dynamic reference-counted pointers. 346 if (IsPotentialUse(I->getOperand(1))) 347 return IC_User; 348 break; 349 default: 350 // For anything else, check all the operands. 351 // Note that this includes both operands of a Store: while the first 352 // operand isn't actually being dereferenced, it is being stored to 353 // memory where we can no longer track who might read it and dereference 354 // it, so we have to consider it potentially used. 355 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end(); 356 OI != OE; ++OI) 357 if (IsPotentialUse(*OI)) 358 return IC_User; 359 } 360 } 361 362 // Otherwise, it's totally inert for ARC purposes. 363 return IC_None; 364} 365 366/// GetBasicInstructionClass - Determine what kind of construct V is. This is 367/// similar to GetInstructionClass except that it only detects objc runtine 368/// calls. This allows it to be faster. 369static InstructionClass GetBasicInstructionClass(const Value *V) { 370 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 371 if (const Function *F = CI->getCalledFunction()) 372 return GetFunctionClass(F); 373 // Otherwise, be conservative. 374 return IC_CallOrUser; 375 } 376 377 // Otherwise, be conservative. 378 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User; 379} 380 381/// IsRetain - Test if the the given class is objc_retain or 382/// equivalent. 383static bool IsRetain(InstructionClass Class) { 384 return Class == IC_Retain || 385 Class == IC_RetainRV; 386} 387 388/// IsAutorelease - Test if the the given class is objc_autorelease or 389/// equivalent. 390static bool IsAutorelease(InstructionClass Class) { 391 return Class == IC_Autorelease || 392 Class == IC_AutoreleaseRV; 393} 394 395/// IsForwarding - Test if the given class represents instructions which return 396/// their argument verbatim. 397static bool IsForwarding(InstructionClass Class) { 398 // objc_retainBlock technically doesn't always return its argument 399 // verbatim, but it doesn't matter for our purposes here. 400 return Class == IC_Retain || 401 Class == IC_RetainRV || 402 Class == IC_Autorelease || 403 Class == IC_AutoreleaseRV || 404 Class == IC_RetainBlock || 405 Class == IC_NoopCast; 406} 407 408/// IsNoopOnNull - Test if the given class represents instructions which do 409/// nothing if passed a null pointer. 410static bool IsNoopOnNull(InstructionClass Class) { 411 return Class == IC_Retain || 412 Class == IC_RetainRV || 413 Class == IC_Release || 414 Class == IC_Autorelease || 415 Class == IC_AutoreleaseRV || 416 Class == IC_RetainBlock; 417} 418 419/// IsAlwaysTail - Test if the given class represents instructions which are 420/// always safe to mark with the "tail" keyword. 421static bool IsAlwaysTail(InstructionClass Class) { 422 // IC_RetainBlock may be given a stack argument. 423 return Class == IC_Retain || 424 Class == IC_RetainRV || 425 Class == IC_Autorelease || 426 Class == IC_AutoreleaseRV; 427} 428 429/// IsNoThrow - Test if the given class represents instructions which are always 430/// safe to mark with the nounwind attribute.. 431static bool IsNoThrow(InstructionClass Class) { 432 // objc_retainBlock is not nounwind because it calls user copy constructors 433 // which could theoretically throw. 434 return Class == IC_Retain || 435 Class == IC_RetainRV || 436 Class == IC_Release || 437 Class == IC_Autorelease || 438 Class == IC_AutoreleaseRV || 439 Class == IC_AutoreleasepoolPush || 440 Class == IC_AutoreleasepoolPop; 441} 442 443/// EraseInstruction - Erase the given instruction. ObjC calls return their 444/// argument verbatim, so if it's such a call and the return value has users, 445/// replace them with the argument value. 446static void EraseInstruction(Instruction *CI) { 447 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0); 448 449 bool Unused = CI->use_empty(); 450 451 if (!Unused) { 452 // Replace the return value with the argument. 453 assert(IsForwarding(GetBasicInstructionClass(CI)) && 454 "Can't delete non-forwarding instruction with users!"); 455 CI->replaceAllUsesWith(OldArg); 456 } 457 458 CI->eraseFromParent(); 459 460 if (Unused) 461 RecursivelyDeleteTriviallyDeadInstructions(OldArg); 462} 463 464/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which 465/// also knows how to look through objc_retain and objc_autorelease calls, which 466/// we know to return their argument verbatim. 467static const Value *GetUnderlyingObjCPtr(const Value *V) { 468 for (;;) { 469 V = GetUnderlyingObject(V); 470 if (!IsForwarding(GetBasicInstructionClass(V))) 471 break; 472 V = cast<CallInst>(V)->getArgOperand(0); 473 } 474 475 return V; 476} 477 478/// StripPointerCastsAndObjCCalls - This is a wrapper around 479/// Value::stripPointerCasts which also knows how to look through objc_retain 480/// and objc_autorelease calls, which we know to return their argument verbatim. 481static const Value *StripPointerCastsAndObjCCalls(const Value *V) { 482 for (;;) { 483 V = V->stripPointerCasts(); 484 if (!IsForwarding(GetBasicInstructionClass(V))) 485 break; 486 V = cast<CallInst>(V)->getArgOperand(0); 487 } 488 return V; 489} 490 491/// StripPointerCastsAndObjCCalls - This is a wrapper around 492/// Value::stripPointerCasts which also knows how to look through objc_retain 493/// and objc_autorelease calls, which we know to return their argument verbatim. 494static Value *StripPointerCastsAndObjCCalls(Value *V) { 495 for (;;) { 496 V = V->stripPointerCasts(); 497 if (!IsForwarding(GetBasicInstructionClass(V))) 498 break; 499 V = cast<CallInst>(V)->getArgOperand(0); 500 } 501 return V; 502} 503 504/// GetObjCArg - Assuming the given instruction is one of the special calls such 505/// as objc_retain or objc_release, return the argument value, stripped of no-op 506/// casts and forwarding calls. 507static Value *GetObjCArg(Value *Inst) { 508 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0)); 509} 510 511/// IsObjCIdentifiedObject - This is similar to AliasAnalysis' 512/// isObjCIdentifiedObject, except that it uses special knowledge of 513/// ObjC conventions... 514static bool IsObjCIdentifiedObject(const Value *V) { 515 // Assume that call results and arguments have their own "provenance". 516 // Constants (including GlobalVariables) and Allocas are never 517 // reference-counted. 518 if (isa<CallInst>(V) || isa<InvokeInst>(V) || 519 isa<Argument>(V) || isa<Constant>(V) || 520 isa<AllocaInst>(V)) 521 return true; 522 523 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) { 524 const Value *Pointer = 525 StripPointerCastsAndObjCCalls(LI->getPointerOperand()); 526 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) { 527 // A constant pointer can't be pointing to an object on the heap. It may 528 // be reference-counted, but it won't be deleted. 529 if (GV->isConstant()) 530 return true; 531 StringRef Name = GV->getName(); 532 // These special variables are known to hold values which are not 533 // reference-counted pointers. 534 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") || 535 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") || 536 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") || 537 Name.startswith("\01L_OBJC_METH_VAR_NAME_") || 538 Name.startswith("\01l_objc_msgSend_fixup_")) 539 return true; 540 } 541 } 542 543 return false; 544} 545 546/// FindSingleUseIdentifiedObject - This is similar to 547/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value 548/// with multiple uses. 549static const Value *FindSingleUseIdentifiedObject(const Value *Arg) { 550 if (Arg->hasOneUse()) { 551 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg)) 552 return FindSingleUseIdentifiedObject(BC->getOperand(0)); 553 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg)) 554 if (GEP->hasAllZeroIndices()) 555 return FindSingleUseIdentifiedObject(GEP->getPointerOperand()); 556 if (IsForwarding(GetBasicInstructionClass(Arg))) 557 return FindSingleUseIdentifiedObject( 558 cast<CallInst>(Arg)->getArgOperand(0)); 559 if (!IsObjCIdentifiedObject(Arg)) 560 return 0; 561 return Arg; 562 } 563 564 // If we found an identifiable object but it has multiple uses, but they 565 // are trivial uses, we can still consider this to be a single-use 566 // value. 567 if (IsObjCIdentifiedObject(Arg)) { 568 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); 569 UI != UE; ++UI) { 570 const User *U = *UI; 571 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg) 572 return 0; 573 } 574 575 return Arg; 576 } 577 578 return 0; 579} 580 581/// ModuleHasARC - Test if the given module looks interesting to run ARC 582/// optimization on. 583static bool ModuleHasARC(const Module &M) { 584 return 585 M.getNamedValue("objc_retain") || 586 M.getNamedValue("objc_release") || 587 M.getNamedValue("objc_autorelease") || 588 M.getNamedValue("objc_retainAutoreleasedReturnValue") || 589 M.getNamedValue("objc_retainBlock") || 590 M.getNamedValue("objc_autoreleaseReturnValue") || 591 M.getNamedValue("objc_autoreleasePoolPush") || 592 M.getNamedValue("objc_loadWeakRetained") || 593 M.getNamedValue("objc_loadWeak") || 594 M.getNamedValue("objc_destroyWeak") || 595 M.getNamedValue("objc_storeWeak") || 596 M.getNamedValue("objc_initWeak") || 597 M.getNamedValue("objc_moveWeak") || 598 M.getNamedValue("objc_copyWeak") || 599 M.getNamedValue("objc_retainedObject") || 600 M.getNamedValue("objc_unretainedObject") || 601 M.getNamedValue("objc_unretainedPointer"); 602} 603 604/// DoesObjCBlockEscape - Test whether the given pointer, which is an 605/// Objective C block pointer, does not "escape". This differs from regular 606/// escape analysis in that a use as an argument to a call is not considered 607/// an escape. 608static bool DoesObjCBlockEscape(const Value *BlockPtr) { 609 // Walk the def-use chains. 610 SmallVector<const Value *, 4> Worklist; 611 Worklist.push_back(BlockPtr); 612 do { 613 const Value *V = Worklist.pop_back_val(); 614 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end(); 615 UI != UE; ++UI) { 616 const User *UUser = *UI; 617 // Special - Use by a call (callee or argument) is not considered 618 // to be an escape. 619 if (isa<CallInst>(UUser) || isa<InvokeInst>(UUser)) 620 continue; 621 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) || 622 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) { 623 Worklist.push_back(UUser); 624 continue; 625 } 626 return true; 627 } 628 } while (!Worklist.empty()); 629 630 // No escapes found. 631 return false; 632} 633 634//===----------------------------------------------------------------------===// 635// ARC AliasAnalysis. 636//===----------------------------------------------------------------------===// 637 638#include "llvm/Pass.h" 639#include "llvm/Analysis/AliasAnalysis.h" 640#include "llvm/Analysis/Passes.h" 641 642namespace { 643 /// ObjCARCAliasAnalysis - This is a simple alias analysis 644 /// implementation that uses knowledge of ARC constructs to answer queries. 645 /// 646 /// TODO: This class could be generalized to know about other ObjC-specific 647 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing 648 /// even though their offsets are dynamic. 649 class ObjCARCAliasAnalysis : public ImmutablePass, 650 public AliasAnalysis { 651 public: 652 static char ID; // Class identification, replacement for typeinfo 653 ObjCARCAliasAnalysis() : ImmutablePass(ID) { 654 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry()); 655 } 656 657 private: 658 virtual void initializePass() { 659 InitializeAliasAnalysis(this); 660 } 661 662 /// getAdjustedAnalysisPointer - This method is used when a pass implements 663 /// an analysis interface through multiple inheritance. If needed, it 664 /// should override this to adjust the this pointer as needed for the 665 /// specified pass info. 666 virtual void *getAdjustedAnalysisPointer(const void *PI) { 667 if (PI == &AliasAnalysis::ID) 668 return (AliasAnalysis*)this; 669 return this; 670 } 671 672 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 673 virtual AliasResult alias(const Location &LocA, const Location &LocB); 674 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal); 675 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS); 676 virtual ModRefBehavior getModRefBehavior(const Function *F); 677 virtual ModRefResult getModRefInfo(ImmutableCallSite CS, 678 const Location &Loc); 679 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1, 680 ImmutableCallSite CS2); 681 }; 682} // End of anonymous namespace 683 684// Register this pass... 685char ObjCARCAliasAnalysis::ID = 0; 686INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa", 687 "ObjC-ARC-Based Alias Analysis", false, true, false) 688 689ImmutablePass *llvm::createObjCARCAliasAnalysisPass() { 690 return new ObjCARCAliasAnalysis(); 691} 692 693void 694ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { 695 AU.setPreservesAll(); 696 AliasAnalysis::getAnalysisUsage(AU); 697} 698 699AliasAnalysis::AliasResult 700ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) { 701 if (!EnableARCOpts) 702 return AliasAnalysis::alias(LocA, LocB); 703 704 // First, strip off no-ops, including ObjC-specific no-ops, and try making a 705 // precise alias query. 706 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr); 707 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr); 708 AliasResult Result = 709 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag), 710 Location(SB, LocB.Size, LocB.TBAATag)); 711 if (Result != MayAlias) 712 return Result; 713 714 // If that failed, climb to the underlying object, including climbing through 715 // ObjC-specific no-ops, and try making an imprecise alias query. 716 const Value *UA = GetUnderlyingObjCPtr(SA); 717 const Value *UB = GetUnderlyingObjCPtr(SB); 718 if (UA != SA || UB != SB) { 719 Result = AliasAnalysis::alias(Location(UA), Location(UB)); 720 // We can't use MustAlias or PartialAlias results here because 721 // GetUnderlyingObjCPtr may return an offsetted pointer value. 722 if (Result == NoAlias) 723 return NoAlias; 724 } 725 726 // If that failed, fail. We don't need to chain here, since that's covered 727 // by the earlier precise query. 728 return MayAlias; 729} 730 731bool 732ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc, 733 bool OrLocal) { 734 if (!EnableARCOpts) 735 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); 736 737 // First, strip off no-ops, including ObjC-specific no-ops, and try making 738 // a precise alias query. 739 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr); 740 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag), 741 OrLocal)) 742 return true; 743 744 // If that failed, climb to the underlying object, including climbing through 745 // ObjC-specific no-ops, and try making an imprecise alias query. 746 const Value *U = GetUnderlyingObjCPtr(S); 747 if (U != S) 748 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal); 749 750 // If that failed, fail. We don't need to chain here, since that's covered 751 // by the earlier precise query. 752 return false; 753} 754 755AliasAnalysis::ModRefBehavior 756ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) { 757 // We have nothing to do. Just chain to the next AliasAnalysis. 758 return AliasAnalysis::getModRefBehavior(CS); 759} 760 761AliasAnalysis::ModRefBehavior 762ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) { 763 if (!EnableARCOpts) 764 return AliasAnalysis::getModRefBehavior(F); 765 766 switch (GetFunctionClass(F)) { 767 case IC_NoopCast: 768 return DoesNotAccessMemory; 769 default: 770 break; 771 } 772 773 return AliasAnalysis::getModRefBehavior(F); 774} 775 776AliasAnalysis::ModRefResult 777ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) { 778 if (!EnableARCOpts) 779 return AliasAnalysis::getModRefInfo(CS, Loc); 780 781 switch (GetBasicInstructionClass(CS.getInstruction())) { 782 case IC_Retain: 783 case IC_RetainRV: 784 case IC_Autorelease: 785 case IC_AutoreleaseRV: 786 case IC_NoopCast: 787 case IC_AutoreleasepoolPush: 788 case IC_FusedRetainAutorelease: 789 case IC_FusedRetainAutoreleaseRV: 790 // These functions don't access any memory visible to the compiler. 791 // Note that this doesn't include objc_retainBlock, becuase it updates 792 // pointers when it copies block data. 793 return NoModRef; 794 default: 795 break; 796 } 797 798 return AliasAnalysis::getModRefInfo(CS, Loc); 799} 800 801AliasAnalysis::ModRefResult 802ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1, 803 ImmutableCallSite CS2) { 804 // TODO: Theoretically we could check for dependencies between objc_* calls 805 // and OnlyAccessesArgumentPointees calls or other well-behaved calls. 806 return AliasAnalysis::getModRefInfo(CS1, CS2); 807} 808 809//===----------------------------------------------------------------------===// 810// ARC expansion. 811//===----------------------------------------------------------------------===// 812 813#include "llvm/Support/InstIterator.h" 814#include "llvm/Transforms/Scalar.h" 815 816namespace { 817 /// ObjCARCExpand - Early ARC transformations. 818 class ObjCARCExpand : public FunctionPass { 819 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 820 virtual bool doInitialization(Module &M); 821 virtual bool runOnFunction(Function &F); 822 823 /// Run - A flag indicating whether this optimization pass should run. 824 bool Run; 825 826 public: 827 static char ID; 828 ObjCARCExpand() : FunctionPass(ID) { 829 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry()); 830 } 831 }; 832} 833 834char ObjCARCExpand::ID = 0; 835INITIALIZE_PASS(ObjCARCExpand, 836 "objc-arc-expand", "ObjC ARC expansion", false, false) 837 838Pass *llvm::createObjCARCExpandPass() { 839 return new ObjCARCExpand(); 840} 841 842void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const { 843 AU.setPreservesCFG(); 844} 845 846bool ObjCARCExpand::doInitialization(Module &M) { 847 Run = ModuleHasARC(M); 848 return false; 849} 850 851bool ObjCARCExpand::runOnFunction(Function &F) { 852 if (!EnableARCOpts) 853 return false; 854 855 // If nothing in the Module uses ARC, don't do anything. 856 if (!Run) 857 return false; 858 859 bool Changed = false; 860 861 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) { 862 Instruction *Inst = &*I; 863 864 switch (GetBasicInstructionClass(Inst)) { 865 case IC_Retain: 866 case IC_RetainRV: 867 case IC_Autorelease: 868 case IC_AutoreleaseRV: 869 case IC_FusedRetainAutorelease: 870 case IC_FusedRetainAutoreleaseRV: 871 // These calls return their argument verbatim, as a low-level 872 // optimization. However, this makes high-level optimizations 873 // harder. Undo any uses of this optimization that the front-end 874 // emitted here. We'll redo them in a later pass. 875 Changed = true; 876 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0)); 877 break; 878 default: 879 break; 880 } 881 } 882 883 return Changed; 884} 885 886//===----------------------------------------------------------------------===// 887// ARC autorelease pool elimination. 888//===----------------------------------------------------------------------===// 889 890#include "llvm/Constants.h" 891 892namespace { 893 /// ObjCARCAPElim - Autorelease pool elimination. 894 class ObjCARCAPElim : public ModulePass { 895 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 896 virtual bool runOnModule(Module &M); 897 898 bool MayAutorelease(CallSite CS); 899 bool OptimizeBB(BasicBlock *BB); 900 901 public: 902 static char ID; 903 ObjCARCAPElim() : ModulePass(ID) { 904 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry()); 905 } 906 }; 907} 908 909char ObjCARCAPElim::ID = 0; 910INITIALIZE_PASS(ObjCARCAPElim, 911 "objc-arc-apelim", 912 "ObjC ARC autorelease pool elimination", 913 false, false) 914 915Pass *llvm::createObjCARCAPElimPass() { 916 return new ObjCARCAPElim(); 917} 918 919void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const { 920 AU.setPreservesCFG(); 921} 922 923/// MayAutorelease - Interprocedurally determine if calls made by the 924/// given call site can possibly produce autoreleases. 925bool ObjCARCAPElim::MayAutorelease(CallSite CS) { 926 if (Function *Callee = CS.getCalledFunction()) { 927 if (Callee->isDeclaration() || Callee->mayBeOverridden()) 928 return true; 929 for (Function::iterator I = Callee->begin(), E = Callee->end(); 930 I != E; ++I) { 931 BasicBlock *BB = I; 932 for (BasicBlock::iterator J = BB->begin(), F = BB->end(); J != F; ++J) 933 if (CallSite JCS = CallSite(J)) 934 if (!JCS.onlyReadsMemory() && MayAutorelease(JCS)) 935 return true; 936 } 937 return false; 938 } 939 940 return true; 941} 942 943bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) { 944 bool Changed = false; 945 946 Instruction *Push = 0; 947 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { 948 Instruction *Inst = I++; 949 switch (GetBasicInstructionClass(Inst)) { 950 case IC_AutoreleasepoolPush: 951 Push = Inst; 952 break; 953 case IC_AutoreleasepoolPop: 954 // If this pop matches a push and nothing in between can autorelease, 955 // zap the pair. 956 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) { 957 Changed = true; 958 Inst->eraseFromParent(); 959 Push->eraseFromParent(); 960 } 961 Push = 0; 962 break; 963 case IC_CallOrUser: 964 if (MayAutorelease(CallSite(Inst))) 965 Push = 0; 966 break; 967 default: 968 break; 969 } 970 } 971 972 return Changed; 973} 974 975bool ObjCARCAPElim::runOnModule(Module &M) { 976 if (!EnableARCOpts) 977 return false; 978 979 // If nothing in the Module uses ARC, don't do anything. 980 if (!ModuleHasARC(M)) 981 return false; 982 983 // Find the llvm.global_ctors variable, as the first step in 984 // identifying the global constructors. 985 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors"); 986 if (!GV) 987 return false; 988 989 assert(GV->hasDefinitiveInitializer() && 990 "llvm.global_ctors is uncooperative!"); 991 992 bool Changed = false; 993 994 // Dig the constructor functions out of GV's initializer. 995 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 996 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end(); 997 OI != OE; ++OI) { 998 Value *Op = *OI; 999 // llvm.global_ctors is an array of pairs where the second members 1000 // are constructor functions. 1001 Function *F = cast<Function>(cast<ConstantStruct>(Op)->getOperand(1)); 1002 // Only look at function definitions. 1003 if (F->isDeclaration()) 1004 continue; 1005 // Only look at functions with one basic block. 1006 if (llvm::next(F->begin()) != F->end()) 1007 continue; 1008 // Ok, a single-block constructor function definition. Try to optimize it. 1009 Changed |= OptimizeBB(F->begin()); 1010 } 1011 1012 return Changed; 1013} 1014 1015//===----------------------------------------------------------------------===// 1016// ARC optimization. 1017//===----------------------------------------------------------------------===// 1018 1019// TODO: On code like this: 1020// 1021// objc_retain(%x) 1022// stuff_that_cannot_release() 1023// objc_autorelease(%x) 1024// stuff_that_cannot_release() 1025// objc_retain(%x) 1026// stuff_that_cannot_release() 1027// objc_autorelease(%x) 1028// 1029// The second retain and autorelease can be deleted. 1030 1031// TODO: It should be possible to delete 1032// objc_autoreleasePoolPush and objc_autoreleasePoolPop 1033// pairs if nothing is actually autoreleased between them. Also, autorelease 1034// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code 1035// after inlining) can be turned into plain release calls. 1036 1037// TODO: Critical-edge splitting. If the optimial insertion point is 1038// a critical edge, the current algorithm has to fail, because it doesn't 1039// know how to split edges. It should be possible to make the optimizer 1040// think in terms of edges, rather than blocks, and then split critical 1041// edges on demand. 1042 1043// TODO: OptimizeSequences could generalized to be Interprocedural. 1044 1045// TODO: Recognize that a bunch of other objc runtime calls have 1046// non-escaping arguments and non-releasing arguments, and may be 1047// non-autoreleasing. 1048 1049// TODO: Sink autorelease calls as far as possible. Unfortunately we 1050// usually can't sink them past other calls, which would be the main 1051// case where it would be useful. 1052 1053// TODO: The pointer returned from objc_loadWeakRetained is retained. 1054 1055// TODO: Delete release+retain pairs (rare). 1056 1057#include "llvm/GlobalAlias.h" 1058#include "llvm/Constants.h" 1059#include "llvm/LLVMContext.h" 1060#include "llvm/Support/ErrorHandling.h" 1061#include "llvm/Support/CFG.h" 1062#include "llvm/ADT/Statistic.h" 1063#include "llvm/ADT/SmallPtrSet.h" 1064#include "llvm/ADT/DenseSet.h" 1065 1066STATISTIC(NumNoops, "Number of no-op objc calls eliminated"); 1067STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated"); 1068STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases"); 1069STATISTIC(NumRets, "Number of return value forwarding " 1070 "retain+autoreleaes eliminated"); 1071STATISTIC(NumRRs, "Number of retain+release paths eliminated"); 1072STATISTIC(NumPeeps, "Number of calls peephole-optimized"); 1073 1074namespace { 1075 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it 1076 /// uses many of the same techniques, except it uses special ObjC-specific 1077 /// reasoning about pointer relationships. 1078 class ProvenanceAnalysis { 1079 AliasAnalysis *AA; 1080 1081 typedef std::pair<const Value *, const Value *> ValuePairTy; 1082 typedef DenseMap<ValuePairTy, bool> CachedResultsTy; 1083 CachedResultsTy CachedResults; 1084 1085 bool relatedCheck(const Value *A, const Value *B); 1086 bool relatedSelect(const SelectInst *A, const Value *B); 1087 bool relatedPHI(const PHINode *A, const Value *B); 1088 1089 // Do not implement. 1090 void operator=(const ProvenanceAnalysis &); 1091 ProvenanceAnalysis(const ProvenanceAnalysis &); 1092 1093 public: 1094 ProvenanceAnalysis() {} 1095 1096 void setAA(AliasAnalysis *aa) { AA = aa; } 1097 1098 AliasAnalysis *getAA() const { return AA; } 1099 1100 bool related(const Value *A, const Value *B); 1101 1102 void clear() { 1103 CachedResults.clear(); 1104 } 1105 }; 1106} 1107 1108bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) { 1109 // If the values are Selects with the same condition, we can do a more precise 1110 // check: just check for relations between the values on corresponding arms. 1111 if (const SelectInst *SB = dyn_cast<SelectInst>(B)) 1112 if (A->getCondition() == SB->getCondition()) { 1113 if (related(A->getTrueValue(), SB->getTrueValue())) 1114 return true; 1115 if (related(A->getFalseValue(), SB->getFalseValue())) 1116 return true; 1117 return false; 1118 } 1119 1120 // Check both arms of the Select node individually. 1121 if (related(A->getTrueValue(), B)) 1122 return true; 1123 if (related(A->getFalseValue(), B)) 1124 return true; 1125 1126 // The arms both checked out. 1127 return false; 1128} 1129 1130bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) { 1131 // If the values are PHIs in the same block, we can do a more precise as well 1132 // as efficient check: just check for relations between the values on 1133 // corresponding edges. 1134 if (const PHINode *PNB = dyn_cast<PHINode>(B)) 1135 if (PNB->getParent() == A->getParent()) { 1136 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) 1137 if (related(A->getIncomingValue(i), 1138 PNB->getIncomingValueForBlock(A->getIncomingBlock(i)))) 1139 return true; 1140 return false; 1141 } 1142 1143 // Check each unique source of the PHI node against B. 1144 SmallPtrSet<const Value *, 4> UniqueSrc; 1145 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) { 1146 const Value *PV1 = A->getIncomingValue(i); 1147 if (UniqueSrc.insert(PV1) && related(PV1, B)) 1148 return true; 1149 } 1150 1151 // All of the arms checked out. 1152 return false; 1153} 1154 1155/// isStoredObjCPointer - Test if the value of P, or any value covered by its 1156/// provenance, is ever stored within the function (not counting callees). 1157static bool isStoredObjCPointer(const Value *P) { 1158 SmallPtrSet<const Value *, 8> Visited; 1159 SmallVector<const Value *, 8> Worklist; 1160 Worklist.push_back(P); 1161 Visited.insert(P); 1162 do { 1163 P = Worklist.pop_back_val(); 1164 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end(); 1165 UI != UE; ++UI) { 1166 const User *Ur = *UI; 1167 if (isa<StoreInst>(Ur)) { 1168 if (UI.getOperandNo() == 0) 1169 // The pointer is stored. 1170 return true; 1171 // The pointed is stored through. 1172 continue; 1173 } 1174 if (isa<CallInst>(Ur)) 1175 // The pointer is passed as an argument, ignore this. 1176 continue; 1177 if (isa<PtrToIntInst>(P)) 1178 // Assume the worst. 1179 return true; 1180 if (Visited.insert(Ur)) 1181 Worklist.push_back(Ur); 1182 } 1183 } while (!Worklist.empty()); 1184 1185 // Everything checked out. 1186 return false; 1187} 1188 1189bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) { 1190 // Skip past provenance pass-throughs. 1191 A = GetUnderlyingObjCPtr(A); 1192 B = GetUnderlyingObjCPtr(B); 1193 1194 // Quick check. 1195 if (A == B) 1196 return true; 1197 1198 // Ask regular AliasAnalysis, for a first approximation. 1199 switch (AA->alias(A, B)) { 1200 case AliasAnalysis::NoAlias: 1201 return false; 1202 case AliasAnalysis::MustAlias: 1203 case AliasAnalysis::PartialAlias: 1204 return true; 1205 case AliasAnalysis::MayAlias: 1206 break; 1207 } 1208 1209 bool AIsIdentified = IsObjCIdentifiedObject(A); 1210 bool BIsIdentified = IsObjCIdentifiedObject(B); 1211 1212 // An ObjC-Identified object can't alias a load if it is never locally stored. 1213 if (AIsIdentified) { 1214 if (BIsIdentified) { 1215 // If both pointers have provenance, they can be directly compared. 1216 if (A != B) 1217 return false; 1218 } else { 1219 if (isa<LoadInst>(B)) 1220 return isStoredObjCPointer(A); 1221 } 1222 } else { 1223 if (BIsIdentified && isa<LoadInst>(A)) 1224 return isStoredObjCPointer(B); 1225 } 1226 1227 // Special handling for PHI and Select. 1228 if (const PHINode *PN = dyn_cast<PHINode>(A)) 1229 return relatedPHI(PN, B); 1230 if (const PHINode *PN = dyn_cast<PHINode>(B)) 1231 return relatedPHI(PN, A); 1232 if (const SelectInst *S = dyn_cast<SelectInst>(A)) 1233 return relatedSelect(S, B); 1234 if (const SelectInst *S = dyn_cast<SelectInst>(B)) 1235 return relatedSelect(S, A); 1236 1237 // Conservative. 1238 return true; 1239} 1240 1241bool ProvenanceAnalysis::related(const Value *A, const Value *B) { 1242 // Begin by inserting a conservative value into the map. If the insertion 1243 // fails, we have the answer already. If it succeeds, leave it there until we 1244 // compute the real answer to guard against recursive queries. 1245 if (A > B) std::swap(A, B); 1246 std::pair<CachedResultsTy::iterator, bool> Pair = 1247 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true)); 1248 if (!Pair.second) 1249 return Pair.first->second; 1250 1251 bool Result = relatedCheck(A, B); 1252 CachedResults[ValuePairTy(A, B)] = Result; 1253 return Result; 1254} 1255 1256namespace { 1257 // Sequence - A sequence of states that a pointer may go through in which an 1258 // objc_retain and objc_release are actually needed. 1259 enum Sequence { 1260 S_None, 1261 S_Retain, ///< objc_retain(x) 1262 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement 1263 S_Use, ///< any use of x 1264 S_Stop, ///< like S_Release, but code motion is stopped 1265 S_Release, ///< objc_release(x) 1266 S_MovableRelease ///< objc_release(x), !clang.imprecise_release 1267 }; 1268} 1269 1270static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) { 1271 // The easy cases. 1272 if (A == B) 1273 return A; 1274 if (A == S_None || B == S_None) 1275 return S_None; 1276 1277 if (A > B) std::swap(A, B); 1278 if (TopDown) { 1279 // Choose the side which is further along in the sequence. 1280 if ((A == S_Retain || A == S_CanRelease) && 1281 (B == S_CanRelease || B == S_Use)) 1282 return B; 1283 } else { 1284 // Choose the side which is further along in the sequence. 1285 if ((A == S_Use || A == S_CanRelease) && 1286 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease)) 1287 return A; 1288 // If both sides are releases, choose the more conservative one. 1289 if (A == S_Stop && (B == S_Release || B == S_MovableRelease)) 1290 return A; 1291 if (A == S_Release && B == S_MovableRelease) 1292 return A; 1293 } 1294 1295 return S_None; 1296} 1297 1298namespace { 1299 /// RRInfo - Unidirectional information about either a 1300 /// retain-decrement-use-release sequence or release-use-decrement-retain 1301 /// reverese sequence. 1302 struct RRInfo { 1303 /// KnownSafe - After an objc_retain, the reference count of the referenced 1304 /// object is known to be positive. Similarly, before an objc_release, the 1305 /// reference count of the referenced object is known to be positive. If 1306 /// there are retain-release pairs in code regions where the retain count 1307 /// is known to be positive, they can be eliminated, regardless of any side 1308 /// effects between them. 1309 /// 1310 /// Also, a retain+release pair nested within another retain+release 1311 /// pair all on the known same pointer value can be eliminated, regardless 1312 /// of any intervening side effects. 1313 /// 1314 /// KnownSafe is true when either of these conditions is satisfied. 1315 bool KnownSafe; 1316 1317 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as 1318 /// opposed to objc_retain calls). 1319 bool IsRetainBlock; 1320 1321 /// IsTailCallRelease - True of the objc_release calls are all marked 1322 /// with the "tail" keyword. 1323 bool IsTailCallRelease; 1324 1325 /// Partial - True of we've seen an opportunity for partial RR elimination, 1326 /// such as pushing calls into a CFG triangle or into one side of a 1327 /// CFG diamond. 1328 /// TODO: Consider moving this to PtrState. 1329 bool Partial; 1330 1331 /// ReleaseMetadata - If the Calls are objc_release calls and they all have 1332 /// a clang.imprecise_release tag, this is the metadata tag. 1333 MDNode *ReleaseMetadata; 1334 1335 /// Calls - For a top-down sequence, the set of objc_retains or 1336 /// objc_retainBlocks. For bottom-up, the set of objc_releases. 1337 SmallPtrSet<Instruction *, 2> Calls; 1338 1339 /// ReverseInsertPts - The set of optimal insert positions for 1340 /// moving calls in the opposite sequence. 1341 SmallPtrSet<Instruction *, 2> ReverseInsertPts; 1342 1343 RRInfo() : 1344 KnownSafe(false), IsRetainBlock(false), 1345 IsTailCallRelease(false), Partial(false), 1346 ReleaseMetadata(0) {} 1347 1348 void clear(); 1349 }; 1350} 1351 1352void RRInfo::clear() { 1353 KnownSafe = false; 1354 IsRetainBlock = false; 1355 IsTailCallRelease = false; 1356 Partial = false; 1357 ReleaseMetadata = 0; 1358 Calls.clear(); 1359 ReverseInsertPts.clear(); 1360} 1361 1362namespace { 1363 /// PtrState - This class summarizes several per-pointer runtime properties 1364 /// which are propogated through the flow graph. 1365 class PtrState { 1366 /// RefCount - The known minimum number of reference count increments. 1367 unsigned RefCount; 1368 1369 /// NestCount - The known minimum level of retain+release nesting. 1370 unsigned NestCount; 1371 1372 /// Seq - The current position in the sequence. 1373 Sequence Seq; 1374 1375 public: 1376 /// RRI - Unidirectional information about the current sequence. 1377 /// TODO: Encapsulate this better. 1378 RRInfo RRI; 1379 1380 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {} 1381 1382 void SetAtLeastOneRefCount() { 1383 if (RefCount == 0) RefCount = 1; 1384 } 1385 1386 void IncrementRefCount() { 1387 if (RefCount != UINT_MAX) ++RefCount; 1388 } 1389 1390 void DecrementRefCount() { 1391 if (RefCount != 0) --RefCount; 1392 } 1393 1394 bool IsKnownIncremented() const { 1395 return RefCount > 0; 1396 } 1397 1398 void IncrementNestCount() { 1399 if (NestCount != UINT_MAX) ++NestCount; 1400 } 1401 1402 void DecrementNestCount() { 1403 if (NestCount != 0) --NestCount; 1404 } 1405 1406 bool IsKnownNested() const { 1407 return NestCount > 0; 1408 } 1409 1410 void SetSeq(Sequence NewSeq) { 1411 Seq = NewSeq; 1412 } 1413 1414 Sequence GetSeq() const { 1415 return Seq; 1416 } 1417 1418 void ClearSequenceProgress() { 1419 Seq = S_None; 1420 RRI.clear(); 1421 } 1422 1423 void Merge(const PtrState &Other, bool TopDown); 1424 }; 1425} 1426 1427void 1428PtrState::Merge(const PtrState &Other, bool TopDown) { 1429 Seq = MergeSeqs(Seq, Other.Seq, TopDown); 1430 RefCount = std::min(RefCount, Other.RefCount); 1431 NestCount = std::min(NestCount, Other.NestCount); 1432 1433 // We can't merge a plain objc_retain with an objc_retainBlock. 1434 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock) 1435 Seq = S_None; 1436 1437 // If we're not in a sequence (anymore), drop all associated state. 1438 if (Seq == S_None) { 1439 RRI.clear(); 1440 } else if (RRI.Partial || Other.RRI.Partial) { 1441 // If we're doing a merge on a path that's previously seen a partial 1442 // merge, conservatively drop the sequence, to avoid doing partial 1443 // RR elimination. If the branch predicates for the two merge differ, 1444 // mixing them is unsafe. 1445 Seq = S_None; 1446 RRI.clear(); 1447 } else { 1448 // Conservatively merge the ReleaseMetadata information. 1449 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata) 1450 RRI.ReleaseMetadata = 0; 1451 1452 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe; 1453 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease; 1454 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end()); 1455 1456 // Merge the insert point sets. If there are any differences, 1457 // that makes this a partial merge. 1458 RRI.Partial = RRI.ReverseInsertPts.size() != 1459 Other.RRI.ReverseInsertPts.size(); 1460 for (SmallPtrSet<Instruction *, 2>::const_iterator 1461 I = Other.RRI.ReverseInsertPts.begin(), 1462 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I) 1463 RRI.Partial |= RRI.ReverseInsertPts.insert(*I); 1464 } 1465} 1466 1467namespace { 1468 /// BBState - Per-BasicBlock state. 1469 class BBState { 1470 /// TopDownPathCount - The number of unique control paths from the entry 1471 /// which can reach this block. 1472 unsigned TopDownPathCount; 1473 1474 /// BottomUpPathCount - The number of unique control paths to exits 1475 /// from this block. 1476 unsigned BottomUpPathCount; 1477 1478 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp. 1479 typedef MapVector<const Value *, PtrState> MapTy; 1480 1481 /// PerPtrTopDown - The top-down traversal uses this to record information 1482 /// known about a pointer at the bottom of each block. 1483 MapTy PerPtrTopDown; 1484 1485 /// PerPtrBottomUp - The bottom-up traversal uses this to record information 1486 /// known about a pointer at the top of each block. 1487 MapTy PerPtrBottomUp; 1488 1489 public: 1490 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {} 1491 1492 typedef MapTy::iterator ptr_iterator; 1493 typedef MapTy::const_iterator ptr_const_iterator; 1494 1495 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); } 1496 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); } 1497 ptr_const_iterator top_down_ptr_begin() const { 1498 return PerPtrTopDown.begin(); 1499 } 1500 ptr_const_iterator top_down_ptr_end() const { 1501 return PerPtrTopDown.end(); 1502 } 1503 1504 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); } 1505 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); } 1506 ptr_const_iterator bottom_up_ptr_begin() const { 1507 return PerPtrBottomUp.begin(); 1508 } 1509 ptr_const_iterator bottom_up_ptr_end() const { 1510 return PerPtrBottomUp.end(); 1511 } 1512 1513 /// SetAsEntry - Mark this block as being an entry block, which has one 1514 /// path from the entry by definition. 1515 void SetAsEntry() { TopDownPathCount = 1; } 1516 1517 /// SetAsExit - Mark this block as being an exit block, which has one 1518 /// path to an exit by definition. 1519 void SetAsExit() { BottomUpPathCount = 1; } 1520 1521 PtrState &getPtrTopDownState(const Value *Arg) { 1522 return PerPtrTopDown[Arg]; 1523 } 1524 1525 PtrState &getPtrBottomUpState(const Value *Arg) { 1526 return PerPtrBottomUp[Arg]; 1527 } 1528 1529 void clearBottomUpPointers() { 1530 PerPtrBottomUp.clear(); 1531 } 1532 1533 void clearTopDownPointers() { 1534 PerPtrTopDown.clear(); 1535 } 1536 1537 void InitFromPred(const BBState &Other); 1538 void InitFromSucc(const BBState &Other); 1539 void MergePred(const BBState &Other); 1540 void MergeSucc(const BBState &Other); 1541 1542 /// GetAllPathCount - Return the number of possible unique paths from an 1543 /// entry to an exit which pass through this block. This is only valid 1544 /// after both the top-down and bottom-up traversals are complete. 1545 unsigned GetAllPathCount() const { 1546 return TopDownPathCount * BottomUpPathCount; 1547 } 1548 1549 /// IsVisitedTopDown - Test whether the block for this BBState has been 1550 /// visited by the top-down portion of the algorithm. 1551 bool isVisitedTopDown() const { 1552 return TopDownPathCount != 0; 1553 } 1554 }; 1555} 1556 1557void BBState::InitFromPred(const BBState &Other) { 1558 PerPtrTopDown = Other.PerPtrTopDown; 1559 TopDownPathCount = Other.TopDownPathCount; 1560} 1561 1562void BBState::InitFromSucc(const BBState &Other) { 1563 PerPtrBottomUp = Other.PerPtrBottomUp; 1564 BottomUpPathCount = Other.BottomUpPathCount; 1565} 1566 1567/// MergePred - The top-down traversal uses this to merge information about 1568/// predecessors to form the initial state for a new block. 1569void BBState::MergePred(const BBState &Other) { 1570 // Other.TopDownPathCount can be 0, in which case it is either dead or a 1571 // loop backedge. Loop backedges are special. 1572 TopDownPathCount += Other.TopDownPathCount; 1573 1574 // For each entry in the other set, if our set has an entry with the same key, 1575 // merge the entries. Otherwise, copy the entry and merge it with an empty 1576 // entry. 1577 for (ptr_const_iterator MI = Other.top_down_ptr_begin(), 1578 ME = Other.top_down_ptr_end(); MI != ME; ++MI) { 1579 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI); 1580 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, 1581 /*TopDown=*/true); 1582 } 1583 1584 // For each entry in our set, if the other set doesn't have an entry with the 1585 // same key, force it to merge with an empty entry. 1586 for (ptr_iterator MI = top_down_ptr_begin(), 1587 ME = top_down_ptr_end(); MI != ME; ++MI) 1588 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end()) 1589 MI->second.Merge(PtrState(), /*TopDown=*/true); 1590} 1591 1592/// MergeSucc - The bottom-up traversal uses this to merge information about 1593/// successors to form the initial state for a new block. 1594void BBState::MergeSucc(const BBState &Other) { 1595 // Other.BottomUpPathCount can be 0, in which case it is either dead or a 1596 // loop backedge. Loop backedges are special. 1597 BottomUpPathCount += Other.BottomUpPathCount; 1598 1599 // For each entry in the other set, if our set has an entry with the 1600 // same key, merge the entries. Otherwise, copy the entry and merge 1601 // it with an empty entry. 1602 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(), 1603 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) { 1604 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI); 1605 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second, 1606 /*TopDown=*/false); 1607 } 1608 1609 // For each entry in our set, if the other set doesn't have an entry 1610 // with the same key, force it to merge with an empty entry. 1611 for (ptr_iterator MI = bottom_up_ptr_begin(), 1612 ME = bottom_up_ptr_end(); MI != ME; ++MI) 1613 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end()) 1614 MI->second.Merge(PtrState(), /*TopDown=*/false); 1615} 1616 1617namespace { 1618 /// ObjCARCOpt - The main ARC optimization pass. 1619 class ObjCARCOpt : public FunctionPass { 1620 bool Changed; 1621 ProvenanceAnalysis PA; 1622 1623 /// Run - A flag indicating whether this optimization pass should run. 1624 bool Run; 1625 1626 /// RetainRVCallee, etc. - Declarations for ObjC runtime 1627 /// functions, for use in creating calls to them. These are initialized 1628 /// lazily to avoid cluttering up the Module with unused declarations. 1629 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee, 1630 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee; 1631 1632 /// UsedInThisFunciton - Flags which determine whether each of the 1633 /// interesting runtine functions is in fact used in the current function. 1634 unsigned UsedInThisFunction; 1635 1636 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release 1637 /// metadata. 1638 unsigned ImpreciseReleaseMDKind; 1639 1640 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape 1641 /// metadata. 1642 unsigned CopyOnEscapeMDKind; 1643 1644 Constant *getRetainRVCallee(Module *M); 1645 Constant *getAutoreleaseRVCallee(Module *M); 1646 Constant *getReleaseCallee(Module *M); 1647 Constant *getRetainCallee(Module *M); 1648 Constant *getRetainBlockCallee(Module *M); 1649 Constant *getAutoreleaseCallee(Module *M); 1650 1651 bool IsRetainBlockOptimizable(const Instruction *Inst); 1652 1653 void OptimizeRetainCall(Function &F, Instruction *Retain); 1654 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV); 1655 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV); 1656 void OptimizeIndividualCalls(Function &F); 1657 1658 void CheckForCFGHazards(const BasicBlock *BB, 1659 DenseMap<const BasicBlock *, BBState> &BBStates, 1660 BBState &MyStates) const; 1661 bool VisitBottomUp(BasicBlock *BB, 1662 DenseMap<const BasicBlock *, BBState> &BBStates, 1663 MapVector<Value *, RRInfo> &Retains); 1664 bool VisitTopDown(BasicBlock *BB, 1665 DenseMap<const BasicBlock *, BBState> &BBStates, 1666 DenseMap<Value *, RRInfo> &Releases); 1667 bool Visit(Function &F, 1668 DenseMap<const BasicBlock *, BBState> &BBStates, 1669 MapVector<Value *, RRInfo> &Retains, 1670 DenseMap<Value *, RRInfo> &Releases); 1671 1672 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove, 1673 MapVector<Value *, RRInfo> &Retains, 1674 DenseMap<Value *, RRInfo> &Releases, 1675 SmallVectorImpl<Instruction *> &DeadInsts, 1676 Module *M); 1677 1678 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates, 1679 MapVector<Value *, RRInfo> &Retains, 1680 DenseMap<Value *, RRInfo> &Releases, 1681 Module *M); 1682 1683 void OptimizeWeakCalls(Function &F); 1684 1685 bool OptimizeSequences(Function &F); 1686 1687 void OptimizeReturns(Function &F); 1688 1689 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 1690 virtual bool doInitialization(Module &M); 1691 virtual bool runOnFunction(Function &F); 1692 virtual void releaseMemory(); 1693 1694 public: 1695 static char ID; 1696 ObjCARCOpt() : FunctionPass(ID) { 1697 initializeObjCARCOptPass(*PassRegistry::getPassRegistry()); 1698 } 1699 }; 1700} 1701 1702char ObjCARCOpt::ID = 0; 1703INITIALIZE_PASS_BEGIN(ObjCARCOpt, 1704 "objc-arc", "ObjC ARC optimization", false, false) 1705INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis) 1706INITIALIZE_PASS_END(ObjCARCOpt, 1707 "objc-arc", "ObjC ARC optimization", false, false) 1708 1709Pass *llvm::createObjCARCOptPass() { 1710 return new ObjCARCOpt(); 1711} 1712 1713void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const { 1714 AU.addRequired<ObjCARCAliasAnalysis>(); 1715 AU.addRequired<AliasAnalysis>(); 1716 // ARC optimization doesn't currently split critical edges. 1717 AU.setPreservesCFG(); 1718} 1719 1720bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) { 1721 // Without the magic metadata tag, we have to assume this might be an 1722 // objc_retainBlock call inserted to convert a block pointer to an id, 1723 // in which case it really is needed. 1724 if (!Inst->getMetadata(CopyOnEscapeMDKind)) 1725 return false; 1726 1727 // If the pointer "escapes" (not including being used in a call), 1728 // the copy may be needed. 1729 if (DoesObjCBlockEscape(Inst)) 1730 return false; 1731 1732 // Otherwise, it's not needed. 1733 return true; 1734} 1735 1736Constant *ObjCARCOpt::getRetainRVCallee(Module *M) { 1737 if (!RetainRVCallee) { 1738 LLVMContext &C = M->getContext(); 1739 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); 1740 std::vector<Type *> Params; 1741 Params.push_back(I8X); 1742 FunctionType *FTy = 1743 FunctionType::get(I8X, Params, /*isVarArg=*/false); 1744 AttrListPtr Attributes; 1745 Attributes.addAttr(~0u, Attribute::NoUnwind); 1746 RetainRVCallee = 1747 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy, 1748 Attributes); 1749 } 1750 return RetainRVCallee; 1751} 1752 1753Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) { 1754 if (!AutoreleaseRVCallee) { 1755 LLVMContext &C = M->getContext(); 1756 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); 1757 std::vector<Type *> Params; 1758 Params.push_back(I8X); 1759 FunctionType *FTy = 1760 FunctionType::get(I8X, Params, /*isVarArg=*/false); 1761 AttrListPtr Attributes; 1762 Attributes.addAttr(~0u, Attribute::NoUnwind); 1763 AutoreleaseRVCallee = 1764 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy, 1765 Attributes); 1766 } 1767 return AutoreleaseRVCallee; 1768} 1769 1770Constant *ObjCARCOpt::getReleaseCallee(Module *M) { 1771 if (!ReleaseCallee) { 1772 LLVMContext &C = M->getContext(); 1773 std::vector<Type *> Params; 1774 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C))); 1775 AttrListPtr Attributes; 1776 Attributes.addAttr(~0u, Attribute::NoUnwind); 1777 ReleaseCallee = 1778 M->getOrInsertFunction( 1779 "objc_release", 1780 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), 1781 Attributes); 1782 } 1783 return ReleaseCallee; 1784} 1785 1786Constant *ObjCARCOpt::getRetainCallee(Module *M) { 1787 if (!RetainCallee) { 1788 LLVMContext &C = M->getContext(); 1789 std::vector<Type *> Params; 1790 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C))); 1791 AttrListPtr Attributes; 1792 Attributes.addAttr(~0u, Attribute::NoUnwind); 1793 RetainCallee = 1794 M->getOrInsertFunction( 1795 "objc_retain", 1796 FunctionType::get(Params[0], Params, /*isVarArg=*/false), 1797 Attributes); 1798 } 1799 return RetainCallee; 1800} 1801 1802Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) { 1803 if (!RetainBlockCallee) { 1804 LLVMContext &C = M->getContext(); 1805 std::vector<Type *> Params; 1806 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C))); 1807 AttrListPtr Attributes; 1808 // objc_retainBlock is not nounwind because it calls user copy constructors 1809 // which could theoretically throw. 1810 RetainBlockCallee = 1811 M->getOrInsertFunction( 1812 "objc_retainBlock", 1813 FunctionType::get(Params[0], Params, /*isVarArg=*/false), 1814 Attributes); 1815 } 1816 return RetainBlockCallee; 1817} 1818 1819Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) { 1820 if (!AutoreleaseCallee) { 1821 LLVMContext &C = M->getContext(); 1822 std::vector<Type *> Params; 1823 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C))); 1824 AttrListPtr Attributes; 1825 Attributes.addAttr(~0u, Attribute::NoUnwind); 1826 AutoreleaseCallee = 1827 M->getOrInsertFunction( 1828 "objc_autorelease", 1829 FunctionType::get(Params[0], Params, /*isVarArg=*/false), 1830 Attributes); 1831 } 1832 return AutoreleaseCallee; 1833} 1834 1835/// CanAlterRefCount - Test whether the given instruction can result in a 1836/// reference count modification (positive or negative) for the pointer's 1837/// object. 1838static bool 1839CanAlterRefCount(const Instruction *Inst, const Value *Ptr, 1840 ProvenanceAnalysis &PA, InstructionClass Class) { 1841 switch (Class) { 1842 case IC_Autorelease: 1843 case IC_AutoreleaseRV: 1844 case IC_User: 1845 // These operations never directly modify a reference count. 1846 return false; 1847 default: break; 1848 } 1849 1850 ImmutableCallSite CS = static_cast<const Value *>(Inst); 1851 assert(CS && "Only calls can alter reference counts!"); 1852 1853 // See if AliasAnalysis can help us with the call. 1854 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS); 1855 if (AliasAnalysis::onlyReadsMemory(MRB)) 1856 return false; 1857 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) { 1858 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 1859 I != E; ++I) { 1860 const Value *Op = *I; 1861 if (IsPotentialUse(Op) && PA.related(Ptr, Op)) 1862 return true; 1863 } 1864 return false; 1865 } 1866 1867 // Assume the worst. 1868 return true; 1869} 1870 1871/// CanUse - Test whether the given instruction can "use" the given pointer's 1872/// object in a way that requires the reference count to be positive. 1873static bool 1874CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, 1875 InstructionClass Class) { 1876 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers. 1877 if (Class == IC_Call) 1878 return false; 1879 1880 // Consider various instructions which may have pointer arguments which are 1881 // not "uses". 1882 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) { 1883 // Comparing a pointer with null, or any other constant, isn't really a use, 1884 // because we don't care what the pointer points to, or about the values 1885 // of any other dynamic reference-counted pointers. 1886 if (!IsPotentialUse(ICI->getOperand(1))) 1887 return false; 1888 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) { 1889 // For calls, just check the arguments (and not the callee operand). 1890 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(), 1891 OE = CS.arg_end(); OI != OE; ++OI) { 1892 const Value *Op = *OI; 1893 if (IsPotentialUse(Op) && PA.related(Ptr, Op)) 1894 return true; 1895 } 1896 return false; 1897 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 1898 // Special-case stores, because we don't care about the stored value, just 1899 // the store address. 1900 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand()); 1901 // If we can't tell what the underlying object was, assume there is a 1902 // dependence. 1903 return IsPotentialUse(Op) && PA.related(Op, Ptr); 1904 } 1905 1906 // Check each operand for a match. 1907 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end(); 1908 OI != OE; ++OI) { 1909 const Value *Op = *OI; 1910 if (IsPotentialUse(Op) && PA.related(Ptr, Op)) 1911 return true; 1912 } 1913 return false; 1914} 1915 1916/// CanInterruptRV - Test whether the given instruction can autorelease 1917/// any pointer or cause an autoreleasepool pop. 1918static bool 1919CanInterruptRV(InstructionClass Class) { 1920 switch (Class) { 1921 case IC_AutoreleasepoolPop: 1922 case IC_CallOrUser: 1923 case IC_Call: 1924 case IC_Autorelease: 1925 case IC_AutoreleaseRV: 1926 case IC_FusedRetainAutorelease: 1927 case IC_FusedRetainAutoreleaseRV: 1928 return true; 1929 default: 1930 return false; 1931 } 1932} 1933 1934namespace { 1935 /// DependenceKind - There are several kinds of dependence-like concepts in 1936 /// use here. 1937 enum DependenceKind { 1938 NeedsPositiveRetainCount, 1939 CanChangeRetainCount, 1940 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease. 1941 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue. 1942 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue. 1943 }; 1944} 1945 1946/// Depends - Test if there can be dependencies on Inst through Arg. This 1947/// function only tests dependencies relevant for removing pairs of calls. 1948static bool 1949Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg, 1950 ProvenanceAnalysis &PA) { 1951 // If we've reached the definition of Arg, stop. 1952 if (Inst == Arg) 1953 return true; 1954 1955 switch (Flavor) { 1956 case NeedsPositiveRetainCount: { 1957 InstructionClass Class = GetInstructionClass(Inst); 1958 switch (Class) { 1959 case IC_AutoreleasepoolPop: 1960 case IC_AutoreleasepoolPush: 1961 case IC_None: 1962 return false; 1963 default: 1964 return CanUse(Inst, Arg, PA, Class); 1965 } 1966 } 1967 1968 case CanChangeRetainCount: { 1969 InstructionClass Class = GetInstructionClass(Inst); 1970 switch (Class) { 1971 case IC_AutoreleasepoolPop: 1972 // Conservatively assume this can decrement any count. 1973 return true; 1974 case IC_AutoreleasepoolPush: 1975 case IC_None: 1976 return false; 1977 default: 1978 return CanAlterRefCount(Inst, Arg, PA, Class); 1979 } 1980 } 1981 1982 case RetainAutoreleaseDep: 1983 switch (GetBasicInstructionClass(Inst)) { 1984 case IC_AutoreleasepoolPop: 1985 // Don't merge an objc_autorelease with an objc_retain inside a different 1986 // autoreleasepool scope. 1987 return true; 1988 case IC_Retain: 1989 case IC_RetainRV: 1990 // Check for a retain of the same pointer for merging. 1991 return GetObjCArg(Inst) == Arg; 1992 default: 1993 // Nothing else matters for objc_retainAutorelease formation. 1994 return false; 1995 } 1996 break; 1997 1998 case RetainAutoreleaseRVDep: { 1999 InstructionClass Class = GetBasicInstructionClass(Inst); 2000 switch (Class) { 2001 case IC_Retain: 2002 case IC_RetainRV: 2003 // Check for a retain of the same pointer for merging. 2004 return GetObjCArg(Inst) == Arg; 2005 default: 2006 // Anything that can autorelease interrupts 2007 // retainAutoreleaseReturnValue formation. 2008 return CanInterruptRV(Class); 2009 } 2010 break; 2011 } 2012 2013 case RetainRVDep: 2014 return CanInterruptRV(GetBasicInstructionClass(Inst)); 2015 } 2016 2017 llvm_unreachable("Invalid dependence flavor"); 2018} 2019 2020/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and 2021/// find local and non-local dependencies on Arg. 2022/// TODO: Cache results? 2023static void 2024FindDependencies(DependenceKind Flavor, 2025 const Value *Arg, 2026 BasicBlock *StartBB, Instruction *StartInst, 2027 SmallPtrSet<Instruction *, 4> &DependingInstructions, 2028 SmallPtrSet<const BasicBlock *, 4> &Visited, 2029 ProvenanceAnalysis &PA) { 2030 BasicBlock::iterator StartPos = StartInst; 2031 2032 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist; 2033 Worklist.push_back(std::make_pair(StartBB, StartPos)); 2034 do { 2035 std::pair<BasicBlock *, BasicBlock::iterator> Pair = 2036 Worklist.pop_back_val(); 2037 BasicBlock *LocalStartBB = Pair.first; 2038 BasicBlock::iterator LocalStartPos = Pair.second; 2039 BasicBlock::iterator StartBBBegin = LocalStartBB->begin(); 2040 for (;;) { 2041 if (LocalStartPos == StartBBBegin) { 2042 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false); 2043 if (PI == PE) 2044 // If we've reached the function entry, produce a null dependence. 2045 DependingInstructions.insert(0); 2046 else 2047 // Add the predecessors to the worklist. 2048 do { 2049 BasicBlock *PredBB = *PI; 2050 if (Visited.insert(PredBB)) 2051 Worklist.push_back(std::make_pair(PredBB, PredBB->end())); 2052 } while (++PI != PE); 2053 break; 2054 } 2055 2056 Instruction *Inst = --LocalStartPos; 2057 if (Depends(Flavor, Inst, Arg, PA)) { 2058 DependingInstructions.insert(Inst); 2059 break; 2060 } 2061 } 2062 } while (!Worklist.empty()); 2063 2064 // Determine whether the original StartBB post-dominates all of the blocks we 2065 // visited. If not, insert a sentinal indicating that most optimizations are 2066 // not safe. 2067 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(), 2068 E = Visited.end(); I != E; ++I) { 2069 const BasicBlock *BB = *I; 2070 if (BB == StartBB) 2071 continue; 2072 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); 2073 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) { 2074 const BasicBlock *Succ = *SI; 2075 if (Succ != StartBB && !Visited.count(Succ)) { 2076 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1)); 2077 return; 2078 } 2079 } 2080 } 2081} 2082 2083static bool isNullOrUndef(const Value *V) { 2084 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V); 2085} 2086 2087static bool isNoopInstruction(const Instruction *I) { 2088 return isa<BitCastInst>(I) || 2089 (isa<GetElementPtrInst>(I) && 2090 cast<GetElementPtrInst>(I)->hasAllZeroIndices()); 2091} 2092 2093/// OptimizeRetainCall - Turn objc_retain into 2094/// objc_retainAutoreleasedReturnValue if the operand is a return value. 2095void 2096ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) { 2097 CallSite CS(GetObjCArg(Retain)); 2098 Instruction *Call = CS.getInstruction(); 2099 if (!Call) return; 2100 if (Call->getParent() != Retain->getParent()) return; 2101 2102 // Check that the call is next to the retain. 2103 BasicBlock::iterator I = Call; 2104 ++I; 2105 while (isNoopInstruction(I)) ++I; 2106 if (&*I != Retain) 2107 return; 2108 2109 // Turn it to an objc_retainAutoreleasedReturnValue.. 2110 Changed = true; 2111 ++NumPeeps; 2112 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent())); 2113} 2114 2115/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into 2116/// objc_retain if the operand is not a return value. Or, if it can be 2117/// paired with an objc_autoreleaseReturnValue, delete the pair and 2118/// return true. 2119bool 2120ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) { 2121 // Check for the argument being from an immediately preceding call. 2122 Value *Arg = GetObjCArg(RetainRV); 2123 CallSite CS(Arg); 2124 if (Instruction *Call = CS.getInstruction()) 2125 if (Call->getParent() == RetainRV->getParent()) { 2126 BasicBlock::iterator I = Call; 2127 ++I; 2128 while (isNoopInstruction(I)) ++I; 2129 if (&*I == RetainRV) 2130 return false; 2131 } 2132 2133 // Check for being preceded by an objc_autoreleaseReturnValue on the same 2134 // pointer. In this case, we can delete the pair. 2135 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin(); 2136 if (I != Begin) { 2137 do --I; while (I != Begin && isNoopInstruction(I)); 2138 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV && 2139 GetObjCArg(I) == Arg) { 2140 Changed = true; 2141 ++NumPeeps; 2142 EraseInstruction(I); 2143 EraseInstruction(RetainRV); 2144 return true; 2145 } 2146 } 2147 2148 // Turn it to a plain objc_retain. 2149 Changed = true; 2150 ++NumPeeps; 2151 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent())); 2152 return false; 2153} 2154 2155/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into 2156/// objc_autorelease if the result is not used as a return value. 2157void 2158ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) { 2159 // Check for a return of the pointer value. 2160 const Value *Ptr = GetObjCArg(AutoreleaseRV); 2161 SmallVector<const Value *, 2> Users; 2162 Users.push_back(Ptr); 2163 do { 2164 Ptr = Users.pop_back_val(); 2165 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); 2166 UI != UE; ++UI) { 2167 const User *I = *UI; 2168 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV) 2169 return; 2170 if (isa<BitCastInst>(I)) 2171 Users.push_back(I); 2172 } 2173 } while (!Users.empty()); 2174 2175 Changed = true; 2176 ++NumPeeps; 2177 cast<CallInst>(AutoreleaseRV)-> 2178 setCalledFunction(getAutoreleaseCallee(F.getParent())); 2179} 2180 2181/// OptimizeIndividualCalls - Visit each call, one at a time, and make 2182/// simplifications without doing any additional analysis. 2183void ObjCARCOpt::OptimizeIndividualCalls(Function &F) { 2184 // Reset all the flags in preparation for recomputing them. 2185 UsedInThisFunction = 0; 2186 2187 // Visit all objc_* calls in F. 2188 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 2189 Instruction *Inst = &*I++; 2190 InstructionClass Class = GetBasicInstructionClass(Inst); 2191 2192 switch (Class) { 2193 default: break; 2194 2195 // Delete no-op casts. These function calls have special semantics, but 2196 // the semantics are entirely implemented via lowering in the front-end, 2197 // so by the time they reach the optimizer, they are just no-op calls 2198 // which return their argument. 2199 // 2200 // There are gray areas here, as the ability to cast reference-counted 2201 // pointers to raw void* and back allows code to break ARC assumptions, 2202 // however these are currently considered to be unimportant. 2203 case IC_NoopCast: 2204 Changed = true; 2205 ++NumNoops; 2206 EraseInstruction(Inst); 2207 continue; 2208 2209 // If the pointer-to-weak-pointer is null, it's undefined behavior. 2210 case IC_StoreWeak: 2211 case IC_LoadWeak: 2212 case IC_LoadWeakRetained: 2213 case IC_InitWeak: 2214 case IC_DestroyWeak: { 2215 CallInst *CI = cast<CallInst>(Inst); 2216 if (isNullOrUndef(CI->getArgOperand(0))) { 2217 Type *Ty = CI->getArgOperand(0)->getType(); 2218 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), 2219 Constant::getNullValue(Ty), 2220 CI); 2221 CI->replaceAllUsesWith(UndefValue::get(CI->getType())); 2222 CI->eraseFromParent(); 2223 continue; 2224 } 2225 break; 2226 } 2227 case IC_CopyWeak: 2228 case IC_MoveWeak: { 2229 CallInst *CI = cast<CallInst>(Inst); 2230 if (isNullOrUndef(CI->getArgOperand(0)) || 2231 isNullOrUndef(CI->getArgOperand(1))) { 2232 Type *Ty = CI->getArgOperand(0)->getType(); 2233 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), 2234 Constant::getNullValue(Ty), 2235 CI); 2236 CI->replaceAllUsesWith(UndefValue::get(CI->getType())); 2237 CI->eraseFromParent(); 2238 continue; 2239 } 2240 break; 2241 } 2242 case IC_Retain: 2243 OptimizeRetainCall(F, Inst); 2244 break; 2245 case IC_RetainRV: 2246 if (OptimizeRetainRVCall(F, Inst)) 2247 continue; 2248 break; 2249 case IC_AutoreleaseRV: 2250 OptimizeAutoreleaseRVCall(F, Inst); 2251 break; 2252 } 2253 2254 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused. 2255 if (IsAutorelease(Class) && Inst->use_empty()) { 2256 CallInst *Call = cast<CallInst>(Inst); 2257 const Value *Arg = Call->getArgOperand(0); 2258 Arg = FindSingleUseIdentifiedObject(Arg); 2259 if (Arg) { 2260 Changed = true; 2261 ++NumAutoreleases; 2262 2263 // Create the declaration lazily. 2264 LLVMContext &C = Inst->getContext(); 2265 CallInst *NewCall = 2266 CallInst::Create(getReleaseCallee(F.getParent()), 2267 Call->getArgOperand(0), "", Call); 2268 NewCall->setMetadata(ImpreciseReleaseMDKind, 2269 MDNode::get(C, ArrayRef<Value *>())); 2270 EraseInstruction(Call); 2271 Inst = NewCall; 2272 Class = IC_Release; 2273 } 2274 } 2275 2276 // For functions which can never be passed stack arguments, add 2277 // a tail keyword. 2278 if (IsAlwaysTail(Class)) { 2279 Changed = true; 2280 cast<CallInst>(Inst)->setTailCall(); 2281 } 2282 2283 // Set nounwind as needed. 2284 if (IsNoThrow(Class)) { 2285 Changed = true; 2286 cast<CallInst>(Inst)->setDoesNotThrow(); 2287 } 2288 2289 if (!IsNoopOnNull(Class)) { 2290 UsedInThisFunction |= 1 << Class; 2291 continue; 2292 } 2293 2294 const Value *Arg = GetObjCArg(Inst); 2295 2296 // ARC calls with null are no-ops. Delete them. 2297 if (isNullOrUndef(Arg)) { 2298 Changed = true; 2299 ++NumNoops; 2300 EraseInstruction(Inst); 2301 continue; 2302 } 2303 2304 // Keep track of which of retain, release, autorelease, and retain_block 2305 // are actually present in this function. 2306 UsedInThisFunction |= 1 << Class; 2307 2308 // If Arg is a PHI, and one or more incoming values to the 2309 // PHI are null, and the call is control-equivalent to the PHI, and there 2310 // are no relevant side effects between the PHI and the call, the call 2311 // could be pushed up to just those paths with non-null incoming values. 2312 // For now, don't bother splitting critical edges for this. 2313 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist; 2314 Worklist.push_back(std::make_pair(Inst, Arg)); 2315 do { 2316 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val(); 2317 Inst = Pair.first; 2318 Arg = Pair.second; 2319 2320 const PHINode *PN = dyn_cast<PHINode>(Arg); 2321 if (!PN) continue; 2322 2323 // Determine if the PHI has any null operands, or any incoming 2324 // critical edges. 2325 bool HasNull = false; 2326 bool HasCriticalEdges = false; 2327 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2328 Value *Incoming = 2329 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); 2330 if (isNullOrUndef(Incoming)) 2331 HasNull = true; 2332 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back()) 2333 .getNumSuccessors() != 1) { 2334 HasCriticalEdges = true; 2335 break; 2336 } 2337 } 2338 // If we have null operands and no critical edges, optimize. 2339 if (!HasCriticalEdges && HasNull) { 2340 SmallPtrSet<Instruction *, 4> DependingInstructions; 2341 SmallPtrSet<const BasicBlock *, 4> Visited; 2342 2343 // Check that there is nothing that cares about the reference 2344 // count between the call and the phi. 2345 FindDependencies(NeedsPositiveRetainCount, Arg, 2346 Inst->getParent(), Inst, 2347 DependingInstructions, Visited, PA); 2348 if (DependingInstructions.size() == 1 && 2349 *DependingInstructions.begin() == PN) { 2350 Changed = true; 2351 ++NumPartialNoops; 2352 // Clone the call into each predecessor that has a non-null value. 2353 CallInst *CInst = cast<CallInst>(Inst); 2354 Type *ParamTy = CInst->getArgOperand(0)->getType(); 2355 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2356 Value *Incoming = 2357 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i)); 2358 if (!isNullOrUndef(Incoming)) { 2359 CallInst *Clone = cast<CallInst>(CInst->clone()); 2360 Value *Op = PN->getIncomingValue(i); 2361 Instruction *InsertPos = &PN->getIncomingBlock(i)->back(); 2362 if (Op->getType() != ParamTy) 2363 Op = new BitCastInst(Op, ParamTy, "", InsertPos); 2364 Clone->setArgOperand(0, Op); 2365 Clone->insertBefore(InsertPos); 2366 Worklist.push_back(std::make_pair(Clone, Incoming)); 2367 } 2368 } 2369 // Erase the original call. 2370 EraseInstruction(CInst); 2371 continue; 2372 } 2373 } 2374 } while (!Worklist.empty()); 2375 } 2376} 2377 2378/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible 2379/// control flow, or other CFG structures where moving code across the edge 2380/// would result in it being executed more. 2381void 2382ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB, 2383 DenseMap<const BasicBlock *, BBState> &BBStates, 2384 BBState &MyStates) const { 2385 // If any top-down local-use or possible-dec has a succ which is earlier in 2386 // the sequence, forget it. 2387 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(), 2388 E = MyStates.top_down_ptr_end(); I != E; ++I) 2389 switch (I->second.GetSeq()) { 2390 default: break; 2391 case S_Use: { 2392 const Value *Arg = I->first; 2393 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); 2394 bool SomeSuccHasSame = false; 2395 bool AllSuccsHaveSame = true; 2396 PtrState &S = MyStates.getPtrTopDownState(Arg); 2397 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) { 2398 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg); 2399 switch (SuccS.GetSeq()) { 2400 case S_None: 2401 case S_CanRelease: { 2402 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe) 2403 S.ClearSequenceProgress(); 2404 continue; 2405 } 2406 case S_Use: 2407 SomeSuccHasSame = true; 2408 break; 2409 case S_Stop: 2410 case S_Release: 2411 case S_MovableRelease: 2412 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe) 2413 AllSuccsHaveSame = false; 2414 break; 2415 case S_Retain: 2416 llvm_unreachable("bottom-up pointer in retain state!"); 2417 } 2418 } 2419 // If the state at the other end of any of the successor edges 2420 // matches the current state, require all edges to match. This 2421 // guards against loops in the middle of a sequence. 2422 if (SomeSuccHasSame && !AllSuccsHaveSame) 2423 S.ClearSequenceProgress(); 2424 break; 2425 } 2426 case S_CanRelease: { 2427 const Value *Arg = I->first; 2428 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); 2429 bool SomeSuccHasSame = false; 2430 bool AllSuccsHaveSame = true; 2431 PtrState &S = MyStates.getPtrTopDownState(Arg); 2432 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) { 2433 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg); 2434 switch (SuccS.GetSeq()) { 2435 case S_None: { 2436 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe) 2437 S.ClearSequenceProgress(); 2438 continue; 2439 } 2440 case S_CanRelease: 2441 SomeSuccHasSame = true; 2442 break; 2443 case S_Stop: 2444 case S_Release: 2445 case S_MovableRelease: 2446 case S_Use: 2447 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe) 2448 AllSuccsHaveSame = false; 2449 break; 2450 case S_Retain: 2451 llvm_unreachable("bottom-up pointer in retain state!"); 2452 } 2453 } 2454 // If the state at the other end of any of the successor edges 2455 // matches the current state, require all edges to match. This 2456 // guards against loops in the middle of a sequence. 2457 if (SomeSuccHasSame && !AllSuccsHaveSame) 2458 S.ClearSequenceProgress(); 2459 break; 2460 } 2461 } 2462} 2463 2464bool 2465ObjCARCOpt::VisitBottomUp(BasicBlock *BB, 2466 DenseMap<const BasicBlock *, BBState> &BBStates, 2467 MapVector<Value *, RRInfo> &Retains) { 2468 bool NestingDetected = false; 2469 BBState &MyStates = BBStates[BB]; 2470 2471 // Merge the states from each successor to compute the initial state 2472 // for the current block. 2473 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back()); 2474 succ_const_iterator SI(TI), SE(TI, false); 2475 if (SI == SE) 2476 MyStates.SetAsExit(); 2477 else 2478 do { 2479 const BasicBlock *Succ = *SI++; 2480 if (Succ == BB) 2481 continue; 2482 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ); 2483 // If we haven't seen this node yet, then we've found a CFG cycle. 2484 // Be optimistic here; it's CheckForCFGHazards' job detect trouble. 2485 if (I == BBStates.end()) 2486 continue; 2487 MyStates.InitFromSucc(I->second); 2488 while (SI != SE) { 2489 Succ = *SI++; 2490 if (Succ != BB) { 2491 I = BBStates.find(Succ); 2492 if (I != BBStates.end()) 2493 MyStates.MergeSucc(I->second); 2494 } 2495 } 2496 break; 2497 } while (SI != SE); 2498 2499 // Visit all the instructions, bottom-up. 2500 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) { 2501 Instruction *Inst = llvm::prior(I); 2502 InstructionClass Class = GetInstructionClass(Inst); 2503 const Value *Arg = 0; 2504 2505 switch (Class) { 2506 case IC_Release: { 2507 Arg = GetObjCArg(Inst); 2508 2509 PtrState &S = MyStates.getPtrBottomUpState(Arg); 2510 2511 // If we see two releases in a row on the same pointer. If so, make 2512 // a note, and we'll cicle back to revisit it after we've 2513 // hopefully eliminated the second release, which may allow us to 2514 // eliminate the first release too. 2515 // Theoretically we could implement removal of nested retain+release 2516 // pairs by making PtrState hold a stack of states, but this is 2517 // simple and avoids adding overhead for the non-nested case. 2518 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) 2519 NestingDetected = true; 2520 2521 S.RRI.clear(); 2522 2523 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); 2524 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release); 2525 S.RRI.ReleaseMetadata = ReleaseMetadata; 2526 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented(); 2527 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); 2528 S.RRI.Calls.insert(Inst); 2529 2530 S.IncrementRefCount(); 2531 S.IncrementNestCount(); 2532 break; 2533 } 2534 case IC_RetainBlock: 2535 // An objc_retainBlock call with just a use may need to be kept, 2536 // because it may be copying a block from the stack to the heap. 2537 if (!IsRetainBlockOptimizable(Inst)) 2538 break; 2539 // FALLTHROUGH 2540 case IC_Retain: 2541 case IC_RetainRV: { 2542 Arg = GetObjCArg(Inst); 2543 2544 PtrState &S = MyStates.getPtrBottomUpState(Arg); 2545 S.DecrementRefCount(); 2546 S.SetAtLeastOneRefCount(); 2547 S.DecrementNestCount(); 2548 2549 switch (S.GetSeq()) { 2550 case S_Stop: 2551 case S_Release: 2552 case S_MovableRelease: 2553 case S_Use: 2554 S.RRI.ReverseInsertPts.clear(); 2555 // FALL THROUGH 2556 case S_CanRelease: 2557 // Don't do retain+release tracking for IC_RetainRV, because it's 2558 // better to let it remain as the first instruction after a call. 2559 if (Class != IC_RetainRV) { 2560 S.RRI.IsRetainBlock = Class == IC_RetainBlock; 2561 Retains[Inst] = S.RRI; 2562 } 2563 S.ClearSequenceProgress(); 2564 break; 2565 case S_None: 2566 break; 2567 case S_Retain: 2568 llvm_unreachable("bottom-up pointer in retain state!"); 2569 } 2570 continue; 2571 } 2572 case IC_AutoreleasepoolPop: 2573 // Conservatively, clear MyStates for all known pointers. 2574 MyStates.clearBottomUpPointers(); 2575 continue; 2576 case IC_AutoreleasepoolPush: 2577 case IC_None: 2578 // These are irrelevant. 2579 continue; 2580 default: 2581 break; 2582 } 2583 2584 // Consider any other possible effects of this instruction on each 2585 // pointer being tracked. 2586 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(), 2587 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) { 2588 const Value *Ptr = MI->first; 2589 if (Ptr == Arg) 2590 continue; // Handled above. 2591 PtrState &S = MI->second; 2592 Sequence Seq = S.GetSeq(); 2593 2594 // Check for possible releases. 2595 if (CanAlterRefCount(Inst, Ptr, PA, Class)) { 2596 S.DecrementRefCount(); 2597 switch (Seq) { 2598 case S_Use: 2599 S.SetSeq(S_CanRelease); 2600 continue; 2601 case S_CanRelease: 2602 case S_Release: 2603 case S_MovableRelease: 2604 case S_Stop: 2605 case S_None: 2606 break; 2607 case S_Retain: 2608 llvm_unreachable("bottom-up pointer in retain state!"); 2609 } 2610 } 2611 2612 // Check for possible direct uses. 2613 switch (Seq) { 2614 case S_Release: 2615 case S_MovableRelease: 2616 if (CanUse(Inst, Ptr, PA, Class)) { 2617 assert(S.RRI.ReverseInsertPts.empty()); 2618 S.RRI.ReverseInsertPts.insert(Inst); 2619 S.SetSeq(S_Use); 2620 } else if (Seq == S_Release && 2621 (Class == IC_User || Class == IC_CallOrUser)) { 2622 // Non-movable releases depend on any possible objc pointer use. 2623 S.SetSeq(S_Stop); 2624 assert(S.RRI.ReverseInsertPts.empty()); 2625 S.RRI.ReverseInsertPts.insert(Inst); 2626 } 2627 break; 2628 case S_Stop: 2629 if (CanUse(Inst, Ptr, PA, Class)) 2630 S.SetSeq(S_Use); 2631 break; 2632 case S_CanRelease: 2633 case S_Use: 2634 case S_None: 2635 break; 2636 case S_Retain: 2637 llvm_unreachable("bottom-up pointer in retain state!"); 2638 } 2639 } 2640 } 2641 2642 return NestingDetected; 2643} 2644 2645bool 2646ObjCARCOpt::VisitTopDown(BasicBlock *BB, 2647 DenseMap<const BasicBlock *, BBState> &BBStates, 2648 DenseMap<Value *, RRInfo> &Releases) { 2649 bool NestingDetected = false; 2650 BBState &MyStates = BBStates[BB]; 2651 2652 // Merge the states from each predecessor to compute the initial state 2653 // for the current block. 2654 const_pred_iterator PI(BB), PE(BB, false); 2655 if (PI == PE) 2656 MyStates.SetAsEntry(); 2657 else 2658 do { 2659 const BasicBlock *Pred = *PI++; 2660 if (Pred == BB) 2661 continue; 2662 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred); 2663 // If we haven't seen this node yet, then we've found a CFG cycle. 2664 // Be optimistic here; it's CheckForCFGHazards' job detect trouble. 2665 if (I == BBStates.end() || !I->second.isVisitedTopDown()) 2666 continue; 2667 MyStates.InitFromPred(I->second); 2668 while (PI != PE) { 2669 Pred = *PI++; 2670 if (Pred != BB) { 2671 I = BBStates.find(Pred); 2672 if (I != BBStates.end() && I->second.isVisitedTopDown()) 2673 MyStates.MergePred(I->second); 2674 } 2675 } 2676 break; 2677 } while (PI != PE); 2678 2679 // Visit all the instructions, top-down. 2680 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 2681 Instruction *Inst = I; 2682 InstructionClass Class = GetInstructionClass(Inst); 2683 const Value *Arg = 0; 2684 2685 switch (Class) { 2686 case IC_RetainBlock: 2687 // An objc_retainBlock call with just a use may need to be kept, 2688 // because it may be copying a block from the stack to the heap. 2689 if (!IsRetainBlockOptimizable(Inst)) 2690 break; 2691 // FALLTHROUGH 2692 case IC_Retain: 2693 case IC_RetainRV: { 2694 Arg = GetObjCArg(Inst); 2695 2696 PtrState &S = MyStates.getPtrTopDownState(Arg); 2697 2698 // Don't do retain+release tracking for IC_RetainRV, because it's 2699 // better to let it remain as the first instruction after a call. 2700 if (Class != IC_RetainRV) { 2701 // If we see two retains in a row on the same pointer. If so, make 2702 // a note, and we'll cicle back to revisit it after we've 2703 // hopefully eliminated the second retain, which may allow us to 2704 // eliminate the first retain too. 2705 // Theoretically we could implement removal of nested retain+release 2706 // pairs by making PtrState hold a stack of states, but this is 2707 // simple and avoids adding overhead for the non-nested case. 2708 if (S.GetSeq() == S_Retain) 2709 NestingDetected = true; 2710 2711 S.SetSeq(S_Retain); 2712 S.RRI.clear(); 2713 S.RRI.IsRetainBlock = Class == IC_RetainBlock; 2714 // Don't check S.IsKnownIncremented() here because it's not 2715 // sufficient. 2716 S.RRI.KnownSafe = S.IsKnownNested(); 2717 S.RRI.Calls.insert(Inst); 2718 } 2719 2720 S.SetAtLeastOneRefCount(); 2721 S.IncrementRefCount(); 2722 S.IncrementNestCount(); 2723 continue; 2724 } 2725 case IC_Release: { 2726 Arg = GetObjCArg(Inst); 2727 2728 PtrState &S = MyStates.getPtrTopDownState(Arg); 2729 S.DecrementRefCount(); 2730 S.DecrementNestCount(); 2731 2732 switch (S.GetSeq()) { 2733 case S_Retain: 2734 case S_CanRelease: 2735 S.RRI.ReverseInsertPts.clear(); 2736 // FALL THROUGH 2737 case S_Use: 2738 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind); 2739 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall(); 2740 Releases[Inst] = S.RRI; 2741 S.ClearSequenceProgress(); 2742 break; 2743 case S_None: 2744 break; 2745 case S_Stop: 2746 case S_Release: 2747 case S_MovableRelease: 2748 llvm_unreachable("top-down pointer in release state!"); 2749 } 2750 break; 2751 } 2752 case IC_AutoreleasepoolPop: 2753 // Conservatively, clear MyStates for all known pointers. 2754 MyStates.clearTopDownPointers(); 2755 continue; 2756 case IC_AutoreleasepoolPush: 2757 case IC_None: 2758 // These are irrelevant. 2759 continue; 2760 default: 2761 break; 2762 } 2763 2764 // Consider any other possible effects of this instruction on each 2765 // pointer being tracked. 2766 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(), 2767 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) { 2768 const Value *Ptr = MI->first; 2769 if (Ptr == Arg) 2770 continue; // Handled above. 2771 PtrState &S = MI->second; 2772 Sequence Seq = S.GetSeq(); 2773 2774 // Check for possible releases. 2775 if (CanAlterRefCount(Inst, Ptr, PA, Class)) { 2776 S.DecrementRefCount(); 2777 switch (Seq) { 2778 case S_Retain: 2779 S.SetSeq(S_CanRelease); 2780 assert(S.RRI.ReverseInsertPts.empty()); 2781 S.RRI.ReverseInsertPts.insert(Inst); 2782 2783 // One call can't cause a transition from S_Retain to S_CanRelease 2784 // and S_CanRelease to S_Use. If we've made the first transition, 2785 // we're done. 2786 continue; 2787 case S_Use: 2788 case S_CanRelease: 2789 case S_None: 2790 break; 2791 case S_Stop: 2792 case S_Release: 2793 case S_MovableRelease: 2794 llvm_unreachable("top-down pointer in release state!"); 2795 } 2796 } 2797 2798 // Check for possible direct uses. 2799 switch (Seq) { 2800 case S_CanRelease: 2801 if (CanUse(Inst, Ptr, PA, Class)) 2802 S.SetSeq(S_Use); 2803 break; 2804 case S_Retain: 2805 case S_Use: 2806 case S_None: 2807 break; 2808 case S_Stop: 2809 case S_Release: 2810 case S_MovableRelease: 2811 llvm_unreachable("top-down pointer in release state!"); 2812 } 2813 } 2814 } 2815 2816 CheckForCFGHazards(BB, BBStates, MyStates); 2817 return NestingDetected; 2818} 2819 2820static void 2821ComputePostOrders(Function &F, 2822 SmallVectorImpl<BasicBlock *> &PostOrder, 2823 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) { 2824 /// Backedges - Backedges detected in the DFS. These edges will be 2825 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be 2826 /// traversed in the desired order. 2827 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges; 2828 2829 /// Visited - The visited set, for doing DFS walks. 2830 SmallPtrSet<BasicBlock *, 16> Visited; 2831 2832 // Do DFS, computing the PostOrder. 2833 SmallPtrSet<BasicBlock *, 16> OnStack; 2834 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack; 2835 BasicBlock *EntryBB = &F.getEntryBlock(); 2836 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB))); 2837 Visited.insert(EntryBB); 2838 OnStack.insert(EntryBB); 2839 do { 2840 dfs_next_succ: 2841 succ_iterator End = succ_end(SuccStack.back().first); 2842 while (SuccStack.back().second != End) { 2843 BasicBlock *BB = *SuccStack.back().second++; 2844 if (Visited.insert(BB)) { 2845 SuccStack.push_back(std::make_pair(BB, succ_begin(BB))); 2846 OnStack.insert(BB); 2847 goto dfs_next_succ; 2848 } 2849 if (OnStack.count(BB)) 2850 Backedges.insert(std::make_pair(SuccStack.back().first, BB)); 2851 } 2852 OnStack.erase(SuccStack.back().first); 2853 PostOrder.push_back(SuccStack.pop_back_val().first); 2854 } while (!SuccStack.empty()); 2855 2856 Visited.clear(); 2857 2858 // Compute the exits, which are the starting points for reverse-CFG DFS. 2859 SmallVector<BasicBlock *, 4> Exits; 2860 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { 2861 BasicBlock *BB = I; 2862 if (BB->getTerminator()->getNumSuccessors() == 0) 2863 Exits.push_back(BB); 2864 } 2865 2866 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder. 2867 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack; 2868 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end(); 2869 I != E; ++I) { 2870 BasicBlock *ExitBB = *I; 2871 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB))); 2872 Visited.insert(ExitBB); 2873 while (!PredStack.empty()) { 2874 reverse_dfs_next_succ: 2875 pred_iterator End = pred_end(PredStack.back().first); 2876 while (PredStack.back().second != End) { 2877 BasicBlock *BB = *PredStack.back().second++; 2878 // Skip backedges detected in the forward-CFG DFS. 2879 if (Backedges.count(std::make_pair(BB, PredStack.back().first))) 2880 continue; 2881 if (Visited.insert(BB)) { 2882 PredStack.push_back(std::make_pair(BB, pred_begin(BB))); 2883 goto reverse_dfs_next_succ; 2884 } 2885 } 2886 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first); 2887 } 2888 } 2889} 2890 2891// Visit - Visit the function both top-down and bottom-up. 2892bool 2893ObjCARCOpt::Visit(Function &F, 2894 DenseMap<const BasicBlock *, BBState> &BBStates, 2895 MapVector<Value *, RRInfo> &Retains, 2896 DenseMap<Value *, RRInfo> &Releases) { 2897 2898 // Use reverse-postorder traversals, because we magically know that loops 2899 // will be well behaved, i.e. they won't repeatedly call retain on a single 2900 // pointer without doing a release. We can't use the ReversePostOrderTraversal 2901 // class here because we want the reverse-CFG postorder to consider each 2902 // function exit point, and we want to ignore selected cycle edges. 2903 SmallVector<BasicBlock *, 16> PostOrder; 2904 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder; 2905 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder); 2906 2907 // Use reverse-postorder on the reverse CFG for bottom-up. 2908 bool BottomUpNestingDetected = false; 2909 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = 2910 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend(); 2911 I != E; ++I) 2912 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains); 2913 2914 // Use reverse-postorder for top-down. 2915 bool TopDownNestingDetected = false; 2916 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I = 2917 PostOrder.rbegin(), E = PostOrder.rend(); 2918 I != E; ++I) 2919 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases); 2920 2921 return TopDownNestingDetected && BottomUpNestingDetected; 2922} 2923 2924/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove. 2925void ObjCARCOpt::MoveCalls(Value *Arg, 2926 RRInfo &RetainsToMove, 2927 RRInfo &ReleasesToMove, 2928 MapVector<Value *, RRInfo> &Retains, 2929 DenseMap<Value *, RRInfo> &Releases, 2930 SmallVectorImpl<Instruction *> &DeadInsts, 2931 Module *M) { 2932 Type *ArgTy = Arg->getType(); 2933 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext())); 2934 2935 // Insert the new retain and release calls. 2936 for (SmallPtrSet<Instruction *, 2>::const_iterator 2937 PI = ReleasesToMove.ReverseInsertPts.begin(), 2938 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) { 2939 Instruction *InsertPt = *PI; 2940 Value *MyArg = ArgTy == ParamTy ? Arg : 2941 new BitCastInst(Arg, ParamTy, "", InsertPt); 2942 CallInst *Call = 2943 CallInst::Create(RetainsToMove.IsRetainBlock ? 2944 getRetainBlockCallee(M) : getRetainCallee(M), 2945 MyArg, "", InsertPt); 2946 Call->setDoesNotThrow(); 2947 if (RetainsToMove.IsRetainBlock) 2948 Call->setMetadata(CopyOnEscapeMDKind, 2949 MDNode::get(M->getContext(), ArrayRef<Value *>())); 2950 else 2951 Call->setTailCall(); 2952 } 2953 for (SmallPtrSet<Instruction *, 2>::const_iterator 2954 PI = RetainsToMove.ReverseInsertPts.begin(), 2955 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) { 2956 Instruction *LastUse = *PI; 2957 Instruction *InsertPts[] = { 0, 0, 0 }; 2958 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) { 2959 // We can't insert code immediately after an invoke instruction, so 2960 // insert code at the beginning of both successor blocks instead. 2961 // The invoke's return value isn't available in the unwind block, 2962 // but our releases will never depend on it, because they must be 2963 // paired with retains from before the invoke. 2964 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt(); 2965 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt(); 2966 } else { 2967 // Insert code immediately after the last use. 2968 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse)); 2969 } 2970 2971 for (Instruction **I = InsertPts; *I; ++I) { 2972 Instruction *InsertPt = *I; 2973 Value *MyArg = ArgTy == ParamTy ? Arg : 2974 new BitCastInst(Arg, ParamTy, "", InsertPt); 2975 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg, 2976 "", InsertPt); 2977 // Attach a clang.imprecise_release metadata tag, if appropriate. 2978 if (MDNode *M = ReleasesToMove.ReleaseMetadata) 2979 Call->setMetadata(ImpreciseReleaseMDKind, M); 2980 Call->setDoesNotThrow(); 2981 if (ReleasesToMove.IsTailCallRelease) 2982 Call->setTailCall(); 2983 } 2984 } 2985 2986 // Delete the original retain and release calls. 2987 for (SmallPtrSet<Instruction *, 2>::const_iterator 2988 AI = RetainsToMove.Calls.begin(), 2989 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) { 2990 Instruction *OrigRetain = *AI; 2991 Retains.blot(OrigRetain); 2992 DeadInsts.push_back(OrigRetain); 2993 } 2994 for (SmallPtrSet<Instruction *, 2>::const_iterator 2995 AI = ReleasesToMove.Calls.begin(), 2996 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) { 2997 Instruction *OrigRelease = *AI; 2998 Releases.erase(OrigRelease); 2999 DeadInsts.push_back(OrigRelease); 3000 } 3001} 3002 3003bool 3004ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState> 3005 &BBStates, 3006 MapVector<Value *, RRInfo> &Retains, 3007 DenseMap<Value *, RRInfo> &Releases, 3008 Module *M) { 3009 bool AnyPairsCompletelyEliminated = false; 3010 RRInfo RetainsToMove; 3011 RRInfo ReleasesToMove; 3012 SmallVector<Instruction *, 4> NewRetains; 3013 SmallVector<Instruction *, 4> NewReleases; 3014 SmallVector<Instruction *, 8> DeadInsts; 3015 3016 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(), 3017 E = Retains.end(); I != E; ++I) { 3018 Value *V = I->first; 3019 if (!V) continue; // blotted 3020 3021 Instruction *Retain = cast<Instruction>(V); 3022 Value *Arg = GetObjCArg(Retain); 3023 3024 // If the object being released is in static or stack storage, we know it's 3025 // not being managed by ObjC reference counting, so we can delete pairs 3026 // regardless of what possible decrements or uses lie between them. 3027 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg); 3028 3029 // A constant pointer can't be pointing to an object on the heap. It may 3030 // be reference-counted, but it won't be deleted. 3031 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg)) 3032 if (const GlobalVariable *GV = 3033 dyn_cast<GlobalVariable>( 3034 StripPointerCastsAndObjCCalls(LI->getPointerOperand()))) 3035 if (GV->isConstant()) 3036 KnownSafe = true; 3037 3038 // If a pair happens in a region where it is known that the reference count 3039 // is already incremented, we can similarly ignore possible decrements. 3040 bool KnownSafeTD = true, KnownSafeBU = true; 3041 3042 // Connect the dots between the top-down-collected RetainsToMove and 3043 // bottom-up-collected ReleasesToMove to form sets of related calls. 3044 // This is an iterative process so that we connect multiple releases 3045 // to multiple retains if needed. 3046 unsigned OldDelta = 0; 3047 unsigned NewDelta = 0; 3048 unsigned OldCount = 0; 3049 unsigned NewCount = 0; 3050 bool FirstRelease = true; 3051 bool FirstRetain = true; 3052 NewRetains.push_back(Retain); 3053 for (;;) { 3054 for (SmallVectorImpl<Instruction *>::const_iterator 3055 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) { 3056 Instruction *NewRetain = *NI; 3057 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain); 3058 assert(It != Retains.end()); 3059 const RRInfo &NewRetainRRI = It->second; 3060 KnownSafeTD &= NewRetainRRI.KnownSafe; 3061 for (SmallPtrSet<Instruction *, 2>::const_iterator 3062 LI = NewRetainRRI.Calls.begin(), 3063 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) { 3064 Instruction *NewRetainRelease = *LI; 3065 DenseMap<Value *, RRInfo>::const_iterator Jt = 3066 Releases.find(NewRetainRelease); 3067 if (Jt == Releases.end()) 3068 goto next_retain; 3069 const RRInfo &NewRetainReleaseRRI = Jt->second; 3070 assert(NewRetainReleaseRRI.Calls.count(NewRetain)); 3071 if (ReleasesToMove.Calls.insert(NewRetainRelease)) { 3072 OldDelta -= 3073 BBStates[NewRetainRelease->getParent()].GetAllPathCount(); 3074 3075 // Merge the ReleaseMetadata and IsTailCallRelease values. 3076 if (FirstRelease) { 3077 ReleasesToMove.ReleaseMetadata = 3078 NewRetainReleaseRRI.ReleaseMetadata; 3079 ReleasesToMove.IsTailCallRelease = 3080 NewRetainReleaseRRI.IsTailCallRelease; 3081 FirstRelease = false; 3082 } else { 3083 if (ReleasesToMove.ReleaseMetadata != 3084 NewRetainReleaseRRI.ReleaseMetadata) 3085 ReleasesToMove.ReleaseMetadata = 0; 3086 if (ReleasesToMove.IsTailCallRelease != 3087 NewRetainReleaseRRI.IsTailCallRelease) 3088 ReleasesToMove.IsTailCallRelease = false; 3089 } 3090 3091 // Collect the optimal insertion points. 3092 if (!KnownSafe) 3093 for (SmallPtrSet<Instruction *, 2>::const_iterator 3094 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(), 3095 RE = NewRetainReleaseRRI.ReverseInsertPts.end(); 3096 RI != RE; ++RI) { 3097 Instruction *RIP = *RI; 3098 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) 3099 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount(); 3100 } 3101 NewReleases.push_back(NewRetainRelease); 3102 } 3103 } 3104 } 3105 NewRetains.clear(); 3106 if (NewReleases.empty()) break; 3107 3108 // Back the other way. 3109 for (SmallVectorImpl<Instruction *>::const_iterator 3110 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) { 3111 Instruction *NewRelease = *NI; 3112 DenseMap<Value *, RRInfo>::const_iterator It = 3113 Releases.find(NewRelease); 3114 assert(It != Releases.end()); 3115 const RRInfo &NewReleaseRRI = It->second; 3116 KnownSafeBU &= NewReleaseRRI.KnownSafe; 3117 for (SmallPtrSet<Instruction *, 2>::const_iterator 3118 LI = NewReleaseRRI.Calls.begin(), 3119 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) { 3120 Instruction *NewReleaseRetain = *LI; 3121 MapVector<Value *, RRInfo>::const_iterator Jt = 3122 Retains.find(NewReleaseRetain); 3123 if (Jt == Retains.end()) 3124 goto next_retain; 3125 const RRInfo &NewReleaseRetainRRI = Jt->second; 3126 assert(NewReleaseRetainRRI.Calls.count(NewRelease)); 3127 if (RetainsToMove.Calls.insert(NewReleaseRetain)) { 3128 unsigned PathCount = 3129 BBStates[NewReleaseRetain->getParent()].GetAllPathCount(); 3130 OldDelta += PathCount; 3131 OldCount += PathCount; 3132 3133 // Merge the IsRetainBlock values. 3134 if (FirstRetain) { 3135 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock; 3136 FirstRetain = false; 3137 } else if (ReleasesToMove.IsRetainBlock != 3138 NewReleaseRetainRRI.IsRetainBlock) 3139 // It's not possible to merge the sequences if one uses 3140 // objc_retain and the other uses objc_retainBlock. 3141 goto next_retain; 3142 3143 // Collect the optimal insertion points. 3144 if (!KnownSafe) 3145 for (SmallPtrSet<Instruction *, 2>::const_iterator 3146 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(), 3147 RE = NewReleaseRetainRRI.ReverseInsertPts.end(); 3148 RI != RE; ++RI) { 3149 Instruction *RIP = *RI; 3150 if (RetainsToMove.ReverseInsertPts.insert(RIP)) { 3151 PathCount = BBStates[RIP->getParent()].GetAllPathCount(); 3152 NewDelta += PathCount; 3153 NewCount += PathCount; 3154 } 3155 } 3156 NewRetains.push_back(NewReleaseRetain); 3157 } 3158 } 3159 } 3160 NewReleases.clear(); 3161 if (NewRetains.empty()) break; 3162 } 3163 3164 // If the pointer is known incremented or nested, we can safely delete the 3165 // pair regardless of what's between them. 3166 if (KnownSafeTD || KnownSafeBU) { 3167 RetainsToMove.ReverseInsertPts.clear(); 3168 ReleasesToMove.ReverseInsertPts.clear(); 3169 NewCount = 0; 3170 } else { 3171 // Determine whether the new insertion points we computed preserve the 3172 // balance of retain and release calls through the program. 3173 // TODO: If the fully aggressive solution isn't valid, try to find a 3174 // less aggressive solution which is. 3175 if (NewDelta != 0) 3176 goto next_retain; 3177 } 3178 3179 // Determine whether the original call points are balanced in the retain and 3180 // release calls through the program. If not, conservatively don't touch 3181 // them. 3182 // TODO: It's theoretically possible to do code motion in this case, as 3183 // long as the existing imbalances are maintained. 3184 if (OldDelta != 0) 3185 goto next_retain; 3186 3187 // Ok, everything checks out and we're all set. Let's move some code! 3188 Changed = true; 3189 AnyPairsCompletelyEliminated = NewCount == 0; 3190 NumRRs += OldCount - NewCount; 3191 MoveCalls(Arg, RetainsToMove, ReleasesToMove, 3192 Retains, Releases, DeadInsts, M); 3193 3194 next_retain: 3195 NewReleases.clear(); 3196 NewRetains.clear(); 3197 RetainsToMove.clear(); 3198 ReleasesToMove.clear(); 3199 } 3200 3201 // Now that we're done moving everything, we can delete the newly dead 3202 // instructions, as we no longer need them as insert points. 3203 while (!DeadInsts.empty()) 3204 EraseInstruction(DeadInsts.pop_back_val()); 3205 3206 return AnyPairsCompletelyEliminated; 3207} 3208 3209/// OptimizeWeakCalls - Weak pointer optimizations. 3210void ObjCARCOpt::OptimizeWeakCalls(Function &F) { 3211 // First, do memdep-style RLE and S2L optimizations. We can't use memdep 3212 // itself because it uses AliasAnalysis and we need to do provenance 3213 // queries instead. 3214 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 3215 Instruction *Inst = &*I++; 3216 InstructionClass Class = GetBasicInstructionClass(Inst); 3217 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained) 3218 continue; 3219 3220 // Delete objc_loadWeak calls with no users. 3221 if (Class == IC_LoadWeak && Inst->use_empty()) { 3222 Inst->eraseFromParent(); 3223 continue; 3224 } 3225 3226 // TODO: For now, just look for an earlier available version of this value 3227 // within the same block. Theoretically, we could do memdep-style non-local 3228 // analysis too, but that would want caching. A better approach would be to 3229 // use the technique that EarlyCSE uses. 3230 inst_iterator Current = llvm::prior(I); 3231 BasicBlock *CurrentBB = Current.getBasicBlockIterator(); 3232 for (BasicBlock::iterator B = CurrentBB->begin(), 3233 J = Current.getInstructionIterator(); 3234 J != B; --J) { 3235 Instruction *EarlierInst = &*llvm::prior(J); 3236 InstructionClass EarlierClass = GetInstructionClass(EarlierInst); 3237 switch (EarlierClass) { 3238 case IC_LoadWeak: 3239 case IC_LoadWeakRetained: { 3240 // If this is loading from the same pointer, replace this load's value 3241 // with that one. 3242 CallInst *Call = cast<CallInst>(Inst); 3243 CallInst *EarlierCall = cast<CallInst>(EarlierInst); 3244 Value *Arg = Call->getArgOperand(0); 3245 Value *EarlierArg = EarlierCall->getArgOperand(0); 3246 switch (PA.getAA()->alias(Arg, EarlierArg)) { 3247 case AliasAnalysis::MustAlias: 3248 Changed = true; 3249 // If the load has a builtin retain, insert a plain retain for it. 3250 if (Class == IC_LoadWeakRetained) { 3251 CallInst *CI = 3252 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, 3253 "", Call); 3254 CI->setTailCall(); 3255 } 3256 // Zap the fully redundant load. 3257 Call->replaceAllUsesWith(EarlierCall); 3258 Call->eraseFromParent(); 3259 goto clobbered; 3260 case AliasAnalysis::MayAlias: 3261 case AliasAnalysis::PartialAlias: 3262 goto clobbered; 3263 case AliasAnalysis::NoAlias: 3264 break; 3265 } 3266 break; 3267 } 3268 case IC_StoreWeak: 3269 case IC_InitWeak: { 3270 // If this is storing to the same pointer and has the same size etc. 3271 // replace this load's value with the stored value. 3272 CallInst *Call = cast<CallInst>(Inst); 3273 CallInst *EarlierCall = cast<CallInst>(EarlierInst); 3274 Value *Arg = Call->getArgOperand(0); 3275 Value *EarlierArg = EarlierCall->getArgOperand(0); 3276 switch (PA.getAA()->alias(Arg, EarlierArg)) { 3277 case AliasAnalysis::MustAlias: 3278 Changed = true; 3279 // If the load has a builtin retain, insert a plain retain for it. 3280 if (Class == IC_LoadWeakRetained) { 3281 CallInst *CI = 3282 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall, 3283 "", Call); 3284 CI->setTailCall(); 3285 } 3286 // Zap the fully redundant load. 3287 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1)); 3288 Call->eraseFromParent(); 3289 goto clobbered; 3290 case AliasAnalysis::MayAlias: 3291 case AliasAnalysis::PartialAlias: 3292 goto clobbered; 3293 case AliasAnalysis::NoAlias: 3294 break; 3295 } 3296 break; 3297 } 3298 case IC_MoveWeak: 3299 case IC_CopyWeak: 3300 // TOOD: Grab the copied value. 3301 goto clobbered; 3302 case IC_AutoreleasepoolPush: 3303 case IC_None: 3304 case IC_User: 3305 // Weak pointers are only modified through the weak entry points 3306 // (and arbitrary calls, which could call the weak entry points). 3307 break; 3308 default: 3309 // Anything else could modify the weak pointer. 3310 goto clobbered; 3311 } 3312 } 3313 clobbered:; 3314 } 3315 3316 // Then, for each destroyWeak with an alloca operand, check to see if 3317 // the alloca and all its users can be zapped. 3318 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 3319 Instruction *Inst = &*I++; 3320 InstructionClass Class = GetBasicInstructionClass(Inst); 3321 if (Class != IC_DestroyWeak) 3322 continue; 3323 3324 CallInst *Call = cast<CallInst>(Inst); 3325 Value *Arg = Call->getArgOperand(0); 3326 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) { 3327 for (Value::use_iterator UI = Alloca->use_begin(), 3328 UE = Alloca->use_end(); UI != UE; ++UI) { 3329 Instruction *UserInst = cast<Instruction>(*UI); 3330 switch (GetBasicInstructionClass(UserInst)) { 3331 case IC_InitWeak: 3332 case IC_StoreWeak: 3333 case IC_DestroyWeak: 3334 continue; 3335 default: 3336 goto done; 3337 } 3338 } 3339 Changed = true; 3340 for (Value::use_iterator UI = Alloca->use_begin(), 3341 UE = Alloca->use_end(); UI != UE; ) { 3342 CallInst *UserInst = cast<CallInst>(*UI++); 3343 if (!UserInst->use_empty()) 3344 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0)); 3345 UserInst->eraseFromParent(); 3346 } 3347 Alloca->eraseFromParent(); 3348 done:; 3349 } 3350 } 3351} 3352 3353/// OptimizeSequences - Identify program paths which execute sequences of 3354/// retains and releases which can be eliminated. 3355bool ObjCARCOpt::OptimizeSequences(Function &F) { 3356 /// Releases, Retains - These are used to store the results of the main flow 3357 /// analysis. These use Value* as the key instead of Instruction* so that the 3358 /// map stays valid when we get around to rewriting code and calls get 3359 /// replaced by arguments. 3360 DenseMap<Value *, RRInfo> Releases; 3361 MapVector<Value *, RRInfo> Retains; 3362 3363 /// BBStates, This is used during the traversal of the function to track the 3364 /// states for each identified object at each block. 3365 DenseMap<const BasicBlock *, BBState> BBStates; 3366 3367 // Analyze the CFG of the function, and all instructions. 3368 bool NestingDetected = Visit(F, BBStates, Retains, Releases); 3369 3370 // Transform. 3371 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) && 3372 NestingDetected; 3373} 3374 3375/// OptimizeReturns - Look for this pattern: 3376/// 3377/// %call = call i8* @something(...) 3378/// %2 = call i8* @objc_retain(i8* %call) 3379/// %3 = call i8* @objc_autorelease(i8* %2) 3380/// ret i8* %3 3381/// 3382/// And delete the retain and autorelease. 3383/// 3384/// Otherwise if it's just this: 3385/// 3386/// %3 = call i8* @objc_autorelease(i8* %2) 3387/// ret i8* %3 3388/// 3389/// convert the autorelease to autoreleaseRV. 3390void ObjCARCOpt::OptimizeReturns(Function &F) { 3391 if (!F.getReturnType()->isPointerTy()) 3392 return; 3393 3394 SmallPtrSet<Instruction *, 4> DependingInstructions; 3395 SmallPtrSet<const BasicBlock *, 4> Visited; 3396 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) { 3397 BasicBlock *BB = FI; 3398 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back()); 3399 if (!Ret) continue; 3400 3401 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0)); 3402 FindDependencies(NeedsPositiveRetainCount, Arg, 3403 BB, Ret, DependingInstructions, Visited, PA); 3404 if (DependingInstructions.size() != 1) 3405 goto next_block; 3406 3407 { 3408 CallInst *Autorelease = 3409 dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); 3410 if (!Autorelease) 3411 goto next_block; 3412 InstructionClass AutoreleaseClass = 3413 GetBasicInstructionClass(Autorelease); 3414 if (!IsAutorelease(AutoreleaseClass)) 3415 goto next_block; 3416 if (GetObjCArg(Autorelease) != Arg) 3417 goto next_block; 3418 3419 DependingInstructions.clear(); 3420 Visited.clear(); 3421 3422 // Check that there is nothing that can affect the reference 3423 // count between the autorelease and the retain. 3424 FindDependencies(CanChangeRetainCount, Arg, 3425 BB, Autorelease, DependingInstructions, Visited, PA); 3426 if (DependingInstructions.size() != 1) 3427 goto next_block; 3428 3429 { 3430 CallInst *Retain = 3431 dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); 3432 3433 // Check that we found a retain with the same argument. 3434 if (!Retain || 3435 !IsRetain(GetBasicInstructionClass(Retain)) || 3436 GetObjCArg(Retain) != Arg) 3437 goto next_block; 3438 3439 DependingInstructions.clear(); 3440 Visited.clear(); 3441 3442 // Convert the autorelease to an autoreleaseRV, since it's 3443 // returning the value. 3444 if (AutoreleaseClass == IC_Autorelease) { 3445 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent())); 3446 AutoreleaseClass = IC_AutoreleaseRV; 3447 } 3448 3449 // Check that there is nothing that can affect the reference 3450 // count between the retain and the call. 3451 // Note that Retain need not be in BB. 3452 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain, 3453 DependingInstructions, Visited, PA); 3454 if (DependingInstructions.size() != 1) 3455 goto next_block; 3456 3457 { 3458 CallInst *Call = 3459 dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); 3460 3461 // Check that the pointer is the return value of the call. 3462 if (!Call || Arg != Call) 3463 goto next_block; 3464 3465 // Check that the call is a regular call. 3466 InstructionClass Class = GetBasicInstructionClass(Call); 3467 if (Class != IC_CallOrUser && Class != IC_Call) 3468 goto next_block; 3469 3470 // If so, we can zap the retain and autorelease. 3471 Changed = true; 3472 ++NumRets; 3473 EraseInstruction(Retain); 3474 EraseInstruction(Autorelease); 3475 } 3476 } 3477 } 3478 3479 next_block: 3480 DependingInstructions.clear(); 3481 Visited.clear(); 3482 } 3483} 3484 3485bool ObjCARCOpt::doInitialization(Module &M) { 3486 if (!EnableARCOpts) 3487 return false; 3488 3489 Run = ModuleHasARC(M); 3490 if (!Run) 3491 return false; 3492 3493 // Identify the imprecise release metadata kind. 3494 ImpreciseReleaseMDKind = 3495 M.getContext().getMDKindID("clang.imprecise_release"); 3496 CopyOnEscapeMDKind = 3497 M.getContext().getMDKindID("clang.arc.copy_on_escape"); 3498 3499 // Intuitively, objc_retain and others are nocapture, however in practice 3500 // they are not, because they return their argument value. And objc_release 3501 // calls finalizers. 3502 3503 // These are initialized lazily. 3504 RetainRVCallee = 0; 3505 AutoreleaseRVCallee = 0; 3506 ReleaseCallee = 0; 3507 RetainCallee = 0; 3508 RetainBlockCallee = 0; 3509 AutoreleaseCallee = 0; 3510 3511 return false; 3512} 3513 3514bool ObjCARCOpt::runOnFunction(Function &F) { 3515 if (!EnableARCOpts) 3516 return false; 3517 3518 // If nothing in the Module uses ARC, don't do anything. 3519 if (!Run) 3520 return false; 3521 3522 Changed = false; 3523 3524 PA.setAA(&getAnalysis<AliasAnalysis>()); 3525 3526 // This pass performs several distinct transformations. As a compile-time aid 3527 // when compiling code that isn't ObjC, skip these if the relevant ObjC 3528 // library functions aren't declared. 3529 3530 // Preliminary optimizations. This also computs UsedInThisFunction. 3531 OptimizeIndividualCalls(F); 3532 3533 // Optimizations for weak pointers. 3534 if (UsedInThisFunction & ((1 << IC_LoadWeak) | 3535 (1 << IC_LoadWeakRetained) | 3536 (1 << IC_StoreWeak) | 3537 (1 << IC_InitWeak) | 3538 (1 << IC_CopyWeak) | 3539 (1 << IC_MoveWeak) | 3540 (1 << IC_DestroyWeak))) 3541 OptimizeWeakCalls(F); 3542 3543 // Optimizations for retain+release pairs. 3544 if (UsedInThisFunction & ((1 << IC_Retain) | 3545 (1 << IC_RetainRV) | 3546 (1 << IC_RetainBlock))) 3547 if (UsedInThisFunction & (1 << IC_Release)) 3548 // Run OptimizeSequences until it either stops making changes or 3549 // no retain+release pair nesting is detected. 3550 while (OptimizeSequences(F)) {} 3551 3552 // Optimizations if objc_autorelease is used. 3553 if (UsedInThisFunction & 3554 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV))) 3555 OptimizeReturns(F); 3556 3557 return Changed; 3558} 3559 3560void ObjCARCOpt::releaseMemory() { 3561 PA.clear(); 3562} 3563 3564//===----------------------------------------------------------------------===// 3565// ARC contraction. 3566//===----------------------------------------------------------------------===// 3567 3568// TODO: ObjCARCContract could insert PHI nodes when uses aren't 3569// dominated by single calls. 3570 3571#include "llvm/Operator.h" 3572#include "llvm/InlineAsm.h" 3573#include "llvm/Analysis/Dominators.h" 3574 3575STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed"); 3576 3577namespace { 3578 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way 3579 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late. 3580 class ObjCARCContract : public FunctionPass { 3581 bool Changed; 3582 AliasAnalysis *AA; 3583 DominatorTree *DT; 3584 ProvenanceAnalysis PA; 3585 3586 /// Run - A flag indicating whether this optimization pass should run. 3587 bool Run; 3588 3589 /// StoreStrongCallee, etc. - Declarations for ObjC runtime 3590 /// functions, for use in creating calls to them. These are initialized 3591 /// lazily to avoid cluttering up the Module with unused declarations. 3592 Constant *StoreStrongCallee, 3593 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee; 3594 3595 /// RetainRVMarker - The inline asm string to insert between calls and 3596 /// RetainRV calls to make the optimization work on targets which need it. 3597 const MDString *RetainRVMarker; 3598 3599 Constant *getStoreStrongCallee(Module *M); 3600 Constant *getRetainAutoreleaseCallee(Module *M); 3601 Constant *getRetainAutoreleaseRVCallee(Module *M); 3602 3603 bool ContractAutorelease(Function &F, Instruction *Autorelease, 3604 InstructionClass Class, 3605 SmallPtrSet<Instruction *, 4> 3606 &DependingInstructions, 3607 SmallPtrSet<const BasicBlock *, 4> 3608 &Visited); 3609 3610 void ContractRelease(Instruction *Release, 3611 inst_iterator &Iter); 3612 3613 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 3614 virtual bool doInitialization(Module &M); 3615 virtual bool runOnFunction(Function &F); 3616 3617 public: 3618 static char ID; 3619 ObjCARCContract() : FunctionPass(ID) { 3620 initializeObjCARCContractPass(*PassRegistry::getPassRegistry()); 3621 } 3622 }; 3623} 3624 3625char ObjCARCContract::ID = 0; 3626INITIALIZE_PASS_BEGIN(ObjCARCContract, 3627 "objc-arc-contract", "ObjC ARC contraction", false, false) 3628INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 3629INITIALIZE_PASS_DEPENDENCY(DominatorTree) 3630INITIALIZE_PASS_END(ObjCARCContract, 3631 "objc-arc-contract", "ObjC ARC contraction", false, false) 3632 3633Pass *llvm::createObjCARCContractPass() { 3634 return new ObjCARCContract(); 3635} 3636 3637void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const { 3638 AU.addRequired<AliasAnalysis>(); 3639 AU.addRequired<DominatorTree>(); 3640 AU.setPreservesCFG(); 3641} 3642 3643Constant *ObjCARCContract::getStoreStrongCallee(Module *M) { 3644 if (!StoreStrongCallee) { 3645 LLVMContext &C = M->getContext(); 3646 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); 3647 Type *I8XX = PointerType::getUnqual(I8X); 3648 std::vector<Type *> Params; 3649 Params.push_back(I8XX); 3650 Params.push_back(I8X); 3651 3652 AttrListPtr Attributes; 3653 Attributes.addAttr(~0u, Attribute::NoUnwind); 3654 Attributes.addAttr(1, Attribute::NoCapture); 3655 3656 StoreStrongCallee = 3657 M->getOrInsertFunction( 3658 "objc_storeStrong", 3659 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false), 3660 Attributes); 3661 } 3662 return StoreStrongCallee; 3663} 3664 3665Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) { 3666 if (!RetainAutoreleaseCallee) { 3667 LLVMContext &C = M->getContext(); 3668 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); 3669 std::vector<Type *> Params; 3670 Params.push_back(I8X); 3671 FunctionType *FTy = 3672 FunctionType::get(I8X, Params, /*isVarArg=*/false); 3673 AttrListPtr Attributes; 3674 Attributes.addAttr(~0u, Attribute::NoUnwind); 3675 RetainAutoreleaseCallee = 3676 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes); 3677 } 3678 return RetainAutoreleaseCallee; 3679} 3680 3681Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) { 3682 if (!RetainAutoreleaseRVCallee) { 3683 LLVMContext &C = M->getContext(); 3684 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); 3685 std::vector<Type *> Params; 3686 Params.push_back(I8X); 3687 FunctionType *FTy = 3688 FunctionType::get(I8X, Params, /*isVarArg=*/false); 3689 AttrListPtr Attributes; 3690 Attributes.addAttr(~0u, Attribute::NoUnwind); 3691 RetainAutoreleaseRVCallee = 3692 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy, 3693 Attributes); 3694 } 3695 return RetainAutoreleaseRVCallee; 3696} 3697 3698/// ContractAutorelease - Merge an autorelease with a retain into a fused 3699/// call. 3700bool 3701ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease, 3702 InstructionClass Class, 3703 SmallPtrSet<Instruction *, 4> 3704 &DependingInstructions, 3705 SmallPtrSet<const BasicBlock *, 4> 3706 &Visited) { 3707 const Value *Arg = GetObjCArg(Autorelease); 3708 3709 // Check that there are no instructions between the retain and the autorelease 3710 // (such as an autorelease_pop) which may change the count. 3711 CallInst *Retain = 0; 3712 if (Class == IC_AutoreleaseRV) 3713 FindDependencies(RetainAutoreleaseRVDep, Arg, 3714 Autorelease->getParent(), Autorelease, 3715 DependingInstructions, Visited, PA); 3716 else 3717 FindDependencies(RetainAutoreleaseDep, Arg, 3718 Autorelease->getParent(), Autorelease, 3719 DependingInstructions, Visited, PA); 3720 3721 Visited.clear(); 3722 if (DependingInstructions.size() != 1) { 3723 DependingInstructions.clear(); 3724 return false; 3725 } 3726 3727 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin()); 3728 DependingInstructions.clear(); 3729 3730 if (!Retain || 3731 GetBasicInstructionClass(Retain) != IC_Retain || 3732 GetObjCArg(Retain) != Arg) 3733 return false; 3734 3735 Changed = true; 3736 ++NumPeeps; 3737 3738 if (Class == IC_AutoreleaseRV) 3739 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent())); 3740 else 3741 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent())); 3742 3743 EraseInstruction(Autorelease); 3744 return true; 3745} 3746 3747/// ContractRelease - Attempt to merge an objc_release with a store, load, and 3748/// objc_retain to form an objc_storeStrong. This can be a little tricky because 3749/// the instructions don't always appear in order, and there may be unrelated 3750/// intervening instructions. 3751void ObjCARCContract::ContractRelease(Instruction *Release, 3752 inst_iterator &Iter) { 3753 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release)); 3754 if (!Load || !Load->isSimple()) return; 3755 3756 // For now, require everything to be in one basic block. 3757 BasicBlock *BB = Release->getParent(); 3758 if (Load->getParent() != BB) return; 3759 3760 // Walk down to find the store. 3761 BasicBlock::iterator I = Load, End = BB->end(); 3762 ++I; 3763 AliasAnalysis::Location Loc = AA->getLocation(Load); 3764 while (I != End && 3765 (&*I == Release || 3766 IsRetain(GetBasicInstructionClass(I)) || 3767 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod))) 3768 ++I; 3769 StoreInst *Store = dyn_cast<StoreInst>(I); 3770 if (!Store || !Store->isSimple()) return; 3771 if (Store->getPointerOperand() != Loc.Ptr) return; 3772 3773 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand()); 3774 3775 // Walk up to find the retain. 3776 I = Store; 3777 BasicBlock::iterator Begin = BB->begin(); 3778 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain) 3779 --I; 3780 Instruction *Retain = I; 3781 if (GetBasicInstructionClass(Retain) != IC_Retain) return; 3782 if (GetObjCArg(Retain) != New) return; 3783 3784 Changed = true; 3785 ++NumStoreStrongs; 3786 3787 LLVMContext &C = Release->getContext(); 3788 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C)); 3789 Type *I8XX = PointerType::getUnqual(I8X); 3790 3791 Value *Args[] = { Load->getPointerOperand(), New }; 3792 if (Args[0]->getType() != I8XX) 3793 Args[0] = new BitCastInst(Args[0], I8XX, "", Store); 3794 if (Args[1]->getType() != I8X) 3795 Args[1] = new BitCastInst(Args[1], I8X, "", Store); 3796 CallInst *StoreStrong = 3797 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()), 3798 Args, "", Store); 3799 StoreStrong->setDoesNotThrow(); 3800 StoreStrong->setDebugLoc(Store->getDebugLoc()); 3801 3802 if (&*Iter == Store) ++Iter; 3803 Store->eraseFromParent(); 3804 Release->eraseFromParent(); 3805 EraseInstruction(Retain); 3806 if (Load->use_empty()) 3807 Load->eraseFromParent(); 3808} 3809 3810bool ObjCARCContract::doInitialization(Module &M) { 3811 Run = ModuleHasARC(M); 3812 if (!Run) 3813 return false; 3814 3815 // These are initialized lazily. 3816 StoreStrongCallee = 0; 3817 RetainAutoreleaseCallee = 0; 3818 RetainAutoreleaseRVCallee = 0; 3819 3820 // Initialize RetainRVMarker. 3821 RetainRVMarker = 0; 3822 if (NamedMDNode *NMD = 3823 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker")) 3824 if (NMD->getNumOperands() == 1) { 3825 const MDNode *N = NMD->getOperand(0); 3826 if (N->getNumOperands() == 1) 3827 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0))) 3828 RetainRVMarker = S; 3829 } 3830 3831 return false; 3832} 3833 3834bool ObjCARCContract::runOnFunction(Function &F) { 3835 if (!EnableARCOpts) 3836 return false; 3837 3838 // If nothing in the Module uses ARC, don't do anything. 3839 if (!Run) 3840 return false; 3841 3842 Changed = false; 3843 AA = &getAnalysis<AliasAnalysis>(); 3844 DT = &getAnalysis<DominatorTree>(); 3845 3846 PA.setAA(&getAnalysis<AliasAnalysis>()); 3847 3848 // For ObjC library calls which return their argument, replace uses of the 3849 // argument with uses of the call return value, if it dominates the use. This 3850 // reduces register pressure. 3851 SmallPtrSet<Instruction *, 4> DependingInstructions; 3852 SmallPtrSet<const BasicBlock *, 4> Visited; 3853 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 3854 Instruction *Inst = &*I++; 3855 3856 // Only these library routines return their argument. In particular, 3857 // objc_retainBlock does not necessarily return its argument. 3858 InstructionClass Class = GetBasicInstructionClass(Inst); 3859 switch (Class) { 3860 case IC_Retain: 3861 case IC_FusedRetainAutorelease: 3862 case IC_FusedRetainAutoreleaseRV: 3863 break; 3864 case IC_Autorelease: 3865 case IC_AutoreleaseRV: 3866 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited)) 3867 continue; 3868 break; 3869 case IC_RetainRV: { 3870 // If we're compiling for a target which needs a special inline-asm 3871 // marker to do the retainAutoreleasedReturnValue optimization, 3872 // insert it now. 3873 if (!RetainRVMarker) 3874 break; 3875 BasicBlock::iterator BBI = Inst; 3876 --BBI; 3877 while (isNoopInstruction(BBI)) --BBI; 3878 if (&*BBI == GetObjCArg(Inst)) { 3879 InlineAsm *IA = 3880 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()), 3881 /*isVarArg=*/false), 3882 RetainRVMarker->getString(), 3883 /*Constraints=*/"", /*hasSideEffects=*/true); 3884 CallInst::Create(IA, "", Inst); 3885 } 3886 break; 3887 } 3888 case IC_InitWeak: { 3889 // objc_initWeak(p, null) => *p = null 3890 CallInst *CI = cast<CallInst>(Inst); 3891 if (isNullOrUndef(CI->getArgOperand(1))) { 3892 Value *Null = 3893 ConstantPointerNull::get(cast<PointerType>(CI->getType())); 3894 Changed = true; 3895 new StoreInst(Null, CI->getArgOperand(0), CI); 3896 CI->replaceAllUsesWith(Null); 3897 CI->eraseFromParent(); 3898 } 3899 continue; 3900 } 3901 case IC_Release: 3902 ContractRelease(Inst, I); 3903 continue; 3904 default: 3905 continue; 3906 } 3907 3908 // Don't use GetObjCArg because we don't want to look through bitcasts 3909 // and such; to do the replacement, the argument must have type i8*. 3910 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0); 3911 for (;;) { 3912 // If we're compiling bugpointed code, don't get in trouble. 3913 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg)) 3914 break; 3915 // Look through the uses of the pointer. 3916 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end(); 3917 UI != UE; ) { 3918 Use &U = UI.getUse(); 3919 unsigned OperandNo = UI.getOperandNo(); 3920 ++UI; // Increment UI now, because we may unlink its element. 3921 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser())) 3922 if (Inst != UserInst && DT->dominates(Inst, UserInst)) { 3923 Changed = true; 3924 Instruction *Replacement = Inst; 3925 Type *UseTy = U.get()->getType(); 3926 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) { 3927 // For PHI nodes, insert the bitcast in the predecessor block. 3928 unsigned ValNo = 3929 PHINode::getIncomingValueNumForOperand(OperandNo); 3930 BasicBlock *BB = 3931 PHI->getIncomingBlock(ValNo); 3932 if (Replacement->getType() != UseTy) 3933 Replacement = new BitCastInst(Replacement, UseTy, "", 3934 &BB->back()); 3935 for (unsigned i = 0, e = PHI->getNumIncomingValues(); 3936 i != e; ++i) 3937 if (PHI->getIncomingBlock(i) == BB) { 3938 // Keep the UI iterator valid. 3939 if (&PHI->getOperandUse( 3940 PHINode::getOperandNumForIncomingValue(i)) == 3941 &UI.getUse()) 3942 ++UI; 3943 PHI->setIncomingValue(i, Replacement); 3944 } 3945 } else { 3946 if (Replacement->getType() != UseTy) 3947 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst); 3948 U.set(Replacement); 3949 } 3950 } 3951 } 3952 3953 // If Arg is a no-op casted pointer, strip one level of casts and 3954 // iterate. 3955 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg)) 3956 Arg = BI->getOperand(0); 3957 else if (isa<GEPOperator>(Arg) && 3958 cast<GEPOperator>(Arg)->hasAllZeroIndices()) 3959 Arg = cast<GEPOperator>(Arg)->getPointerOperand(); 3960 else if (isa<GlobalAlias>(Arg) && 3961 !cast<GlobalAlias>(Arg)->mayBeOverridden()) 3962 Arg = cast<GlobalAlias>(Arg)->getAliasee(); 3963 else 3964 break; 3965 } 3966 } 3967 3968 return Changed; 3969} 3970