1 //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic 11 /// Reference Counting and is a system for managing reference counts for objects 12 /// in Objective C. 13 /// 14 /// The optimizations performed include elimination of redundant, partially 15 /// redundant, and inconsequential reference count operations, elimination of 16 /// redundant weak pointer operations, and numerous minor simplifications. 17 /// 18 /// WARNING: This file knows about certain library functions. It recognizes them 19 /// by name, and hardwires knowledge of their semantics. 20 /// 21 /// WARNING: This file knows about how certain Objective-C library functions are 22 /// used. Naive LLVM IR transformations which would otherwise be 23 /// behavior-preserving may break these assumptions. 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "ARCRuntimeEntryPoints.h" 28 #include "BlotMapVector.h" 29 #include "DependencyAnalysis.h" 30 #include "ObjCARC.h" 31 #include "ProvenanceAnalysis.h" 32 #include "PtrState.h" 33 #include "llvm/ADT/DenseMap.h" 34 #include "llvm/ADT/None.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/SmallPtrSet.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/ADT/Statistic.h" 39 #include "llvm/Analysis/AliasAnalysis.h" 40 #include "llvm/Analysis/EHPersonalities.h" 41 #include "llvm/Analysis/ObjCARCAliasAnalysis.h" 42 #include "llvm/Analysis/ObjCARCAnalysisUtils.h" 43 #include "llvm/Analysis/ObjCARCInstKind.h" 44 #include "llvm/IR/BasicBlock.h" 45 #include "llvm/IR/CFG.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DerivedTypes.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/GlobalVariable.h" 51 #include "llvm/IR/InstIterator.h" 52 #include "llvm/IR/InstrTypes.h" 53 #include "llvm/IR/Instruction.h" 54 #include "llvm/IR/Instructions.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/User.h" 59 #include "llvm/IR/Value.h" 60 #include "llvm/InitializePasses.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Compiler.h" 65 #include "llvm/Support/Debug.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include <cassert> 69 #include <iterator> 70 #include <utility> 71 72 using namespace llvm; 73 using namespace llvm::objcarc; 74 75 #define DEBUG_TYPE "objc-arc-opts" 76 77 static cl::opt<unsigned> MaxPtrStates("arc-opt-max-ptr-states", 78 cl::Hidden, 79 cl::desc("Maximum number of ptr states the optimizer keeps track of"), 80 cl::init(4095)); 81 82 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC. 83 /// @{ 84 85 /// This is similar to GetRCIdentityRoot but it stops as soon 86 /// as it finds a value with multiple uses. 87 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) { 88 // ConstantData (like ConstantPointerNull and UndefValue) is used across 89 // modules. It's never a single-use value. 90 if (isa<ConstantData>(Arg)) 91 return nullptr; 92 93 if (Arg->hasOneUse()) { 94 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg)) 95 return FindSingleUseIdentifiedObject(BC->getOperand(0)); 96 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg)) 97 if (GEP->hasAllZeroIndices()) 98 return FindSingleUseIdentifiedObject(GEP->getPointerOperand()); 99 if (IsForwarding(GetBasicARCInstKind(Arg))) 100 return FindSingleUseIdentifiedObject( 101 cast<CallInst>(Arg)->getArgOperand(0)); 102 if (!IsObjCIdentifiedObject(Arg)) 103 return nullptr; 104 return Arg; 105 } 106 107 // If we found an identifiable object but it has multiple uses, but they are 108 // trivial uses, we can still consider this to be a single-use value. 109 if (IsObjCIdentifiedObject(Arg)) { 110 for (const User *U : Arg->users()) 111 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg) 112 return nullptr; 113 114 return Arg; 115 } 116 117 return nullptr; 118 } 119 120 /// @} 121 /// 122 /// \defgroup ARCOpt ARC Optimization. 123 /// @{ 124 125 // TODO: On code like this: 126 // 127 // objc_retain(%x) 128 // stuff_that_cannot_release() 129 // objc_autorelease(%x) 130 // stuff_that_cannot_release() 131 // objc_retain(%x) 132 // stuff_that_cannot_release() 133 // objc_autorelease(%x) 134 // 135 // The second retain and autorelease can be deleted. 136 137 // TODO: It should be possible to delete 138 // objc_autoreleasePoolPush and objc_autoreleasePoolPop 139 // pairs if nothing is actually autoreleased between them. Also, autorelease 140 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code 141 // after inlining) can be turned into plain release calls. 142 143 // TODO: Critical-edge splitting. If the optimial insertion point is 144 // a critical edge, the current algorithm has to fail, because it doesn't 145 // know how to split edges. It should be possible to make the optimizer 146 // think in terms of edges, rather than blocks, and then split critical 147 // edges on demand. 148 149 // TODO: OptimizeSequences could generalized to be Interprocedural. 150 151 // TODO: Recognize that a bunch of other objc runtime calls have 152 // non-escaping arguments and non-releasing arguments, and may be 153 // non-autoreleasing. 154 155 // TODO: Sink autorelease calls as far as possible. Unfortunately we 156 // usually can't sink them past other calls, which would be the main 157 // case where it would be useful. 158 159 // TODO: The pointer returned from objc_loadWeakRetained is retained. 160 161 // TODO: Delete release+retain pairs (rare). 162 163 STATISTIC(NumNoops, "Number of no-op objc calls eliminated"); 164 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated"); 165 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases"); 166 STATISTIC(NumRets, "Number of return value forwarding " 167 "retain+autoreleases eliminated"); 168 STATISTIC(NumRRs, "Number of retain+release paths eliminated"); 169 STATISTIC(NumPeeps, "Number of calls peephole-optimized"); 170 #ifndef NDEBUG 171 STATISTIC(NumRetainsBeforeOpt, 172 "Number of retains before optimization"); 173 STATISTIC(NumReleasesBeforeOpt, 174 "Number of releases before optimization"); 175 STATISTIC(NumRetainsAfterOpt, 176 "Number of retains after optimization"); 177 STATISTIC(NumReleasesAfterOpt, 178 "Number of releases after optimization"); 179 #endif 180 181 namespace { 182 183 /// Per-BasicBlock state. 184 class BBState { 185 /// The number of unique control paths from the entry which can reach this 186 /// block. 187 unsigned TopDownPathCount = 0; 188 189 /// The number of unique control paths to exits from this block. 190 unsigned BottomUpPathCount = 0; 191 192 /// The top-down traversal uses this to record information known about a 193 /// pointer at the bottom of each block. 194 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown; 195 196 /// The bottom-up traversal uses this to record information known about a 197 /// pointer at the top of each block. 198 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp; 199 200 /// Effective predecessors of the current block ignoring ignorable edges and 201 /// ignored backedges. 202 SmallVector<BasicBlock *, 2> Preds; 203 204 /// Effective successors of the current block ignoring ignorable edges and 205 /// ignored backedges. 206 SmallVector<BasicBlock *, 2> Succs; 207 208 public: 209 static const unsigned OverflowOccurredValue; 210 211 BBState() = default; 212 213 using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator; 214 using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator; 215 216 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); } 217 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); } 218 const_top_down_ptr_iterator top_down_ptr_begin() const { 219 return PerPtrTopDown.begin(); 220 } 221 const_top_down_ptr_iterator top_down_ptr_end() const { 222 return PerPtrTopDown.end(); 223 } 224 bool hasTopDownPtrs() const { 225 return !PerPtrTopDown.empty(); 226 } 227 228 unsigned top_down_ptr_list_size() const { 229 return std::distance(top_down_ptr_begin(), top_down_ptr_end()); 230 } 231 232 using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator; 233 using const_bottom_up_ptr_iterator = 234 decltype(PerPtrBottomUp)::const_iterator; 235 236 bottom_up_ptr_iterator bottom_up_ptr_begin() { 237 return PerPtrBottomUp.begin(); 238 } 239 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); } 240 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const { 241 return PerPtrBottomUp.begin(); 242 } 243 const_bottom_up_ptr_iterator bottom_up_ptr_end() const { 244 return PerPtrBottomUp.end(); 245 } 246 bool hasBottomUpPtrs() const { 247 return !PerPtrBottomUp.empty(); 248 } 249 250 unsigned bottom_up_ptr_list_size() const { 251 return std::distance(bottom_up_ptr_begin(), bottom_up_ptr_end()); 252 } 253 254 /// Mark this block as being an entry block, which has one path from the 255 /// entry by definition. 256 void SetAsEntry() { TopDownPathCount = 1; } 257 258 /// Mark this block as being an exit block, which has one path to an exit by 259 /// definition. 260 void SetAsExit() { BottomUpPathCount = 1; } 261 262 /// Attempt to find the PtrState object describing the top down state for 263 /// pointer Arg. Return a new initialized PtrState describing the top down 264 /// state for Arg if we do not find one. 265 TopDownPtrState &getPtrTopDownState(const Value *Arg) { 266 return PerPtrTopDown[Arg]; 267 } 268 269 /// Attempt to find the PtrState object describing the bottom up state for 270 /// pointer Arg. Return a new initialized PtrState describing the bottom up 271 /// state for Arg if we do not find one. 272 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) { 273 return PerPtrBottomUp[Arg]; 274 } 275 276 /// Attempt to find the PtrState object describing the bottom up state for 277 /// pointer Arg. 278 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) { 279 return PerPtrBottomUp.find(Arg); 280 } 281 282 void clearBottomUpPointers() { 283 PerPtrBottomUp.clear(); 284 } 285 286 void clearTopDownPointers() { 287 PerPtrTopDown.clear(); 288 } 289 290 void InitFromPred(const BBState &Other); 291 void InitFromSucc(const BBState &Other); 292 void MergePred(const BBState &Other); 293 void MergeSucc(const BBState &Other); 294 295 /// Compute the number of possible unique paths from an entry to an exit 296 /// which pass through this block. This is only valid after both the 297 /// top-down and bottom-up traversals are complete. 298 /// 299 /// Returns true if overflow occurred. Returns false if overflow did not 300 /// occur. 301 bool GetAllPathCountWithOverflow(unsigned &PathCount) const { 302 if (TopDownPathCount == OverflowOccurredValue || 303 BottomUpPathCount == OverflowOccurredValue) 304 return true; 305 unsigned long long Product = 306 (unsigned long long)TopDownPathCount*BottomUpPathCount; 307 // Overflow occurred if any of the upper bits of Product are set or if all 308 // the lower bits of Product are all set. 309 return (Product >> 32) || 310 ((PathCount = Product) == OverflowOccurredValue); 311 } 312 313 // Specialized CFG utilities. 314 using edge_iterator = SmallVectorImpl<BasicBlock *>::const_iterator; 315 316 edge_iterator pred_begin() const { return Preds.begin(); } 317 edge_iterator pred_end() const { return Preds.end(); } 318 edge_iterator succ_begin() const { return Succs.begin(); } 319 edge_iterator succ_end() const { return Succs.end(); } 320 321 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); } 322 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); } 323 324 bool isExit() const { return Succs.empty(); } 325 }; 326 327 } // end anonymous namespace 328 329 const unsigned BBState::OverflowOccurredValue = 0xffffffff; 330 331 namespace llvm { 332 333 raw_ostream &operator<<(raw_ostream &OS, 334 BBState &BBState) LLVM_ATTRIBUTE_UNUSED; 335 336 } // end namespace llvm 337 338 void BBState::InitFromPred(const BBState &Other) { 339 PerPtrTopDown = Other.PerPtrTopDown; 340 TopDownPathCount = Other.TopDownPathCount; 341 } 342 343 void BBState::InitFromSucc(const BBState &Other) { 344 PerPtrBottomUp = Other.PerPtrBottomUp; 345 BottomUpPathCount = Other.BottomUpPathCount; 346 } 347 348 /// The top-down traversal uses this to merge information about predecessors to 349 /// form the initial state for a new block. 350 void BBState::MergePred(const BBState &Other) { 351 if (TopDownPathCount == OverflowOccurredValue) 352 return; 353 354 // Other.TopDownPathCount can be 0, in which case it is either dead or a 355 // loop backedge. Loop backedges are special. 356 TopDownPathCount += Other.TopDownPathCount; 357 358 // In order to be consistent, we clear the top down pointers when by adding 359 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow 360 // has not occurred. 361 if (TopDownPathCount == OverflowOccurredValue) { 362 clearTopDownPointers(); 363 return; 364 } 365 366 // Check for overflow. If we have overflow, fall back to conservative 367 // behavior. 368 if (TopDownPathCount < Other.TopDownPathCount) { 369 TopDownPathCount = OverflowOccurredValue; 370 clearTopDownPointers(); 371 return; 372 } 373 374 // For each entry in the other set, if our set has an entry with the same key, 375 // merge the entries. Otherwise, copy the entry and merge it with an empty 376 // entry. 377 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end(); 378 MI != ME; ++MI) { 379 auto Pair = PerPtrTopDown.insert(*MI); 380 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second, 381 /*TopDown=*/true); 382 } 383 384 // For each entry in our set, if the other set doesn't have an entry with the 385 // same key, force it to merge with an empty entry. 386 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI) 387 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end()) 388 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true); 389 } 390 391 /// The bottom-up traversal uses this to merge information about successors to 392 /// form the initial state for a new block. 393 void BBState::MergeSucc(const BBState &Other) { 394 if (BottomUpPathCount == OverflowOccurredValue) 395 return; 396 397 // Other.BottomUpPathCount can be 0, in which case it is either dead or a 398 // loop backedge. Loop backedges are special. 399 BottomUpPathCount += Other.BottomUpPathCount; 400 401 // In order to be consistent, we clear the top down pointers when by adding 402 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow 403 // has not occurred. 404 if (BottomUpPathCount == OverflowOccurredValue) { 405 clearBottomUpPointers(); 406 return; 407 } 408 409 // Check for overflow. If we have overflow, fall back to conservative 410 // behavior. 411 if (BottomUpPathCount < Other.BottomUpPathCount) { 412 BottomUpPathCount = OverflowOccurredValue; 413 clearBottomUpPointers(); 414 return; 415 } 416 417 // For each entry in the other set, if our set has an entry with the 418 // same key, merge the entries. Otherwise, copy the entry and merge 419 // it with an empty entry. 420 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end(); 421 MI != ME; ++MI) { 422 auto Pair = PerPtrBottomUp.insert(*MI); 423 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second, 424 /*TopDown=*/false); 425 } 426 427 // For each entry in our set, if the other set doesn't have an entry 428 // with the same key, force it to merge with an empty entry. 429 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME; 430 ++MI) 431 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end()) 432 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false); 433 } 434 435 raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) { 436 // Dump the pointers we are tracking. 437 OS << " TopDown State:\n"; 438 if (!BBInfo.hasTopDownPtrs()) { 439 LLVM_DEBUG(dbgs() << " NONE!\n"); 440 } else { 441 for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end(); 442 I != E; ++I) { 443 const PtrState &P = I->second; 444 OS << " Ptr: " << *I->first 445 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false") 446 << "\n ImpreciseRelease: " 447 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n" 448 << " HasCFGHazards: " 449 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n" 450 << " KnownPositive: " 451 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n" 452 << " Seq: " 453 << P.GetSeq() << "\n"; 454 } 455 } 456 457 OS << " BottomUp State:\n"; 458 if (!BBInfo.hasBottomUpPtrs()) { 459 LLVM_DEBUG(dbgs() << " NONE!\n"); 460 } else { 461 for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end(); 462 I != E; ++I) { 463 const PtrState &P = I->second; 464 OS << " Ptr: " << *I->first 465 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false") 466 << "\n ImpreciseRelease: " 467 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n" 468 << " HasCFGHazards: " 469 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n" 470 << " KnownPositive: " 471 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n" 472 << " Seq: " 473 << P.GetSeq() << "\n"; 474 } 475 } 476 477 return OS; 478 } 479 480 namespace { 481 482 /// The main ARC optimization pass. 483 class ObjCARCOpt : public FunctionPass { 484 bool Changed; 485 ProvenanceAnalysis PA; 486 487 /// A cache of references to runtime entry point constants. 488 ARCRuntimeEntryPoints EP; 489 490 /// A cache of MDKinds that can be passed into other functions to propagate 491 /// MDKind identifiers. 492 ARCMDKindCache MDKindCache; 493 494 /// A flag indicating whether this optimization pass should run. 495 bool Run; 496 497 /// A flag indicating whether the optimization that removes or moves 498 /// retain/release pairs should be performed. 499 bool DisableRetainReleasePairing = false; 500 501 /// Flags which determine whether each of the interesting runtime functions 502 /// is in fact used in the current function. 503 unsigned UsedInThisFunction; 504 505 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV); 506 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, 507 ARCInstKind &Class); 508 void OptimizeIndividualCalls(Function &F); 509 510 /// Optimize an individual call, optionally passing the 511 /// GetArgRCIdentityRoot if it has already been computed. 512 void OptimizeIndividualCallImpl( 513 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 514 Instruction *Inst, ARCInstKind Class, const Value *Arg); 515 516 /// Try to optimize an AutoreleaseRV with a RetainRV or ClaimRV. If the 517 /// optimization occurs, returns true to indicate that the caller should 518 /// assume the instructions are dead. 519 bool OptimizeInlinedAutoreleaseRVCall( 520 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 521 Instruction *Inst, const Value *&Arg, ARCInstKind Class, 522 Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg); 523 524 void CheckForCFGHazards(const BasicBlock *BB, 525 DenseMap<const BasicBlock *, BBState> &BBStates, 526 BBState &MyStates) const; 527 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB, 528 BlotMapVector<Value *, RRInfo> &Retains, 529 BBState &MyStates); 530 bool VisitBottomUp(BasicBlock *BB, 531 DenseMap<const BasicBlock *, BBState> &BBStates, 532 BlotMapVector<Value *, RRInfo> &Retains); 533 bool VisitInstructionTopDown(Instruction *Inst, 534 DenseMap<Value *, RRInfo> &Releases, 535 BBState &MyStates); 536 bool VisitTopDown(BasicBlock *BB, 537 DenseMap<const BasicBlock *, BBState> &BBStates, 538 DenseMap<Value *, RRInfo> &Releases); 539 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates, 540 BlotMapVector<Value *, RRInfo> &Retains, 541 DenseMap<Value *, RRInfo> &Releases); 542 543 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove, 544 BlotMapVector<Value *, RRInfo> &Retains, 545 DenseMap<Value *, RRInfo> &Releases, 546 SmallVectorImpl<Instruction *> &DeadInsts, Module *M); 547 548 bool 549 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates, 550 BlotMapVector<Value *, RRInfo> &Retains, 551 DenseMap<Value *, RRInfo> &Releases, Module *M, 552 Instruction * Retain, 553 SmallVectorImpl<Instruction *> &DeadInsts, 554 RRInfo &RetainsToMove, RRInfo &ReleasesToMove, 555 Value *Arg, bool KnownSafe, 556 bool &AnyPairsCompletelyEliminated); 557 558 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates, 559 BlotMapVector<Value *, RRInfo> &Retains, 560 DenseMap<Value *, RRInfo> &Releases, Module *M); 561 562 void OptimizeWeakCalls(Function &F); 563 564 bool OptimizeSequences(Function &F); 565 566 void OptimizeReturns(Function &F); 567 568 #ifndef NDEBUG 569 void GatherStatistics(Function &F, bool AfterOptimization = false); 570 #endif 571 572 void getAnalysisUsage(AnalysisUsage &AU) const override; 573 bool doInitialization(Module &M) override; 574 bool runOnFunction(Function &F) override; 575 void releaseMemory() override; 576 577 public: 578 static char ID; 579 580 ObjCARCOpt() : FunctionPass(ID) { 581 initializeObjCARCOptPass(*PassRegistry::getPassRegistry()); 582 } 583 }; 584 585 } // end anonymous namespace 586 587 char ObjCARCOpt::ID = 0; 588 589 INITIALIZE_PASS_BEGIN(ObjCARCOpt, 590 "objc-arc", "ObjC ARC optimization", false, false) 591 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass) 592 INITIALIZE_PASS_END(ObjCARCOpt, 593 "objc-arc", "ObjC ARC optimization", false, false) 594 595 Pass *llvm::createObjCARCOptPass() { 596 return new ObjCARCOpt(); 597 } 598 599 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const { 600 AU.addRequired<ObjCARCAAWrapperPass>(); 601 AU.addRequired<AAResultsWrapperPass>(); 602 // ARC optimization doesn't currently split critical edges. 603 AU.setPreservesCFG(); 604 } 605 606 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is 607 /// not a return value. 608 bool 609 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) { 610 // Check for the argument being from an immediately preceding call or invoke. 611 const Value *Arg = GetArgRCIdentityRoot(RetainRV); 612 if (const Instruction *Call = dyn_cast<CallBase>(Arg)) { 613 if (Call->getParent() == RetainRV->getParent()) { 614 BasicBlock::const_iterator I(Call); 615 ++I; 616 while (IsNoopInstruction(&*I)) 617 ++I; 618 if (&*I == RetainRV) 619 return false; 620 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 621 BasicBlock *RetainRVParent = RetainRV->getParent(); 622 if (II->getNormalDest() == RetainRVParent) { 623 BasicBlock::const_iterator I = RetainRVParent->begin(); 624 while (IsNoopInstruction(&*I)) 625 ++I; 626 if (&*I == RetainRV) 627 return false; 628 } 629 } 630 } 631 632 // Turn it to a plain objc_retain. 633 Changed = true; 634 ++NumPeeps; 635 636 LLVM_DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => " 637 "objc_retain since the operand is not a return value.\n" 638 "Old = " 639 << *RetainRV << "\n"); 640 641 Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain); 642 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl); 643 644 LLVM_DEBUG(dbgs() << "New = " << *RetainRV << "\n"); 645 646 return false; 647 } 648 649 bool ObjCARCOpt::OptimizeInlinedAutoreleaseRVCall( 650 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 651 Instruction *Inst, const Value *&Arg, ARCInstKind Class, 652 Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg) { 653 // Must be in the same basic block. 654 assert(Inst->getParent() == AutoreleaseRV->getParent()); 655 656 // Must operate on the same root. 657 Arg = GetArgRCIdentityRoot(Inst); 658 AutoreleaseRVArg = GetArgRCIdentityRoot(AutoreleaseRV); 659 if (Arg != AutoreleaseRVArg) { 660 // If there isn't an exact match, check if we have equivalent PHIs. 661 const PHINode *PN = dyn_cast<PHINode>(Arg); 662 if (!PN) 663 return false; 664 665 SmallVector<const Value *, 4> ArgUsers; 666 getEquivalentPHIs(*PN, ArgUsers); 667 if (llvm::find(ArgUsers, AutoreleaseRVArg) == ArgUsers.end()) 668 return false; 669 } 670 671 // Okay, this is a match. Merge them. 672 ++NumPeeps; 673 LLVM_DEBUG(dbgs() << "Found inlined objc_autoreleaseReturnValue '" 674 << *AutoreleaseRV << "' paired with '" << *Inst << "'\n"); 675 676 // Delete the RV pair, starting with the AutoreleaseRV. 677 AutoreleaseRV->replaceAllUsesWith( 678 cast<CallInst>(AutoreleaseRV)->getArgOperand(0)); 679 EraseInstruction(AutoreleaseRV); 680 if (Class == ARCInstKind::RetainRV) { 681 // AutoreleaseRV and RetainRV cancel out. Delete the RetainRV. 682 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0)); 683 EraseInstruction(Inst); 684 return true; 685 } 686 687 // ClaimRV is a frontend peephole for RetainRV + Release. Since the 688 // AutoreleaseRV and RetainRV cancel out, replace the ClaimRV with a Release. 689 assert(Class == ARCInstKind::ClaimRV); 690 Value *CallArg = cast<CallInst>(Inst)->getArgOperand(0); 691 CallInst *Release = CallInst::Create( 692 EP.get(ARCRuntimeEntryPointKind::Release), CallArg, "", Inst); 693 assert(IsAlwaysTail(ARCInstKind::ClaimRV) && 694 "Expected ClaimRV to be safe to tail call"); 695 Release->setTailCall(); 696 Inst->replaceAllUsesWith(CallArg); 697 EraseInstruction(Inst); 698 699 // Run the normal optimizations on Release. 700 OptimizeIndividualCallImpl(F, BlockColors, Release, ARCInstKind::Release, 701 Arg); 702 return true; 703 } 704 705 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not 706 /// used as a return value. 707 void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, 708 Instruction *AutoreleaseRV, 709 ARCInstKind &Class) { 710 // Check for a return of the pointer value. 711 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV); 712 713 // If the argument is ConstantPointerNull or UndefValue, its other users 714 // aren't actually interesting to look at. 715 if (isa<ConstantData>(Ptr)) 716 return; 717 718 SmallVector<const Value *, 2> Users; 719 Users.push_back(Ptr); 720 721 // Add PHIs that are equivalent to Ptr to Users. 722 if (const PHINode *PN = dyn_cast<PHINode>(Ptr)) 723 getEquivalentPHIs(*PN, Users); 724 725 do { 726 Ptr = Users.pop_back_val(); 727 for (const User *U : Ptr->users()) { 728 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV) 729 return; 730 if (isa<BitCastInst>(U)) 731 Users.push_back(U); 732 } 733 } while (!Users.empty()); 734 735 Changed = true; 736 ++NumPeeps; 737 738 LLVM_DEBUG( 739 dbgs() << "Transforming objc_autoreleaseReturnValue => " 740 "objc_autorelease since its operand is not used as a return " 741 "value.\n" 742 "Old = " 743 << *AutoreleaseRV << "\n"); 744 745 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV); 746 Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease); 747 AutoreleaseRVCI->setCalledFunction(NewDecl); 748 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease. 749 Class = ARCInstKind::Autorelease; 750 751 LLVM_DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n"); 752 } 753 754 namespace { 755 Instruction * 756 CloneCallInstForBB(CallInst &CI, BasicBlock &BB, 757 const DenseMap<BasicBlock *, ColorVector> &BlockColors) { 758 SmallVector<OperandBundleDef, 1> OpBundles; 759 for (unsigned I = 0, E = CI.getNumOperandBundles(); I != E; ++I) { 760 auto Bundle = CI.getOperandBundleAt(I); 761 // Funclets will be reassociated in the future. 762 if (Bundle.getTagID() == LLVMContext::OB_funclet) 763 continue; 764 OpBundles.emplace_back(Bundle); 765 } 766 767 if (!BlockColors.empty()) { 768 const ColorVector &CV = BlockColors.find(&BB)->second; 769 assert(CV.size() == 1 && "non-unique color for block!"); 770 Instruction *EHPad = CV.front()->getFirstNonPHI(); 771 if (EHPad->isEHPad()) 772 OpBundles.emplace_back("funclet", EHPad); 773 } 774 775 return CallInst::Create(&CI, OpBundles); 776 } 777 } 778 779 /// Visit each call, one at a time, and make simplifications without doing any 780 /// additional analysis. 781 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) { 782 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n"); 783 // Reset all the flags in preparation for recomputing them. 784 UsedInThisFunction = 0; 785 786 DenseMap<BasicBlock *, ColorVector> BlockColors; 787 if (F.hasPersonalityFn() && 788 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 789 BlockColors = colorEHFunclets(F); 790 791 // Store any delayed AutoreleaseRV intrinsics, so they can be easily paired 792 // with RetainRV and ClaimRV. 793 Instruction *DelayedAutoreleaseRV = nullptr; 794 const Value *DelayedAutoreleaseRVArg = nullptr; 795 auto setDelayedAutoreleaseRV = [&](Instruction *AutoreleaseRV) { 796 assert(!DelayedAutoreleaseRV || !AutoreleaseRV); 797 DelayedAutoreleaseRV = AutoreleaseRV; 798 DelayedAutoreleaseRVArg = nullptr; 799 }; 800 auto optimizeDelayedAutoreleaseRV = [&]() { 801 if (!DelayedAutoreleaseRV) 802 return; 803 OptimizeIndividualCallImpl(F, BlockColors, DelayedAutoreleaseRV, 804 ARCInstKind::AutoreleaseRV, 805 DelayedAutoreleaseRVArg); 806 setDelayedAutoreleaseRV(nullptr); 807 }; 808 auto shouldDelayAutoreleaseRV = [&](Instruction *NonARCInst) { 809 // Nothing to delay, but we may as well skip the logic below. 810 if (!DelayedAutoreleaseRV) 811 return true; 812 813 // If we hit the end of the basic block we're not going to find an RV-pair. 814 // Stop delaying. 815 if (NonARCInst->isTerminator()) 816 return false; 817 818 // Given the frontend rules for emitting AutoreleaseRV, RetainRV, and 819 // ClaimRV, it's probably safe to skip over even opaque function calls 820 // here since OptimizeInlinedAutoreleaseRVCall will confirm that they 821 // have the same RCIdentityRoot. However, what really matters is 822 // skipping instructions or intrinsics that the inliner could leave behind; 823 // be conservative for now and don't skip over opaque calls, which could 824 // potentially include other ARC calls. 825 auto *CB = dyn_cast<CallBase>(NonARCInst); 826 if (!CB) 827 return true; 828 return CB->getIntrinsicID() != Intrinsic::not_intrinsic; 829 }; 830 831 // Visit all objc_* calls in F. 832 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 833 Instruction *Inst = &*I++; 834 835 ARCInstKind Class = GetBasicARCInstKind(Inst); 836 837 // Skip this loop if this instruction isn't itself an ARC intrinsic. 838 const Value *Arg = nullptr; 839 switch (Class) { 840 default: 841 optimizeDelayedAutoreleaseRV(); 842 break; 843 case ARCInstKind::CallOrUser: 844 case ARCInstKind::User: 845 case ARCInstKind::None: 846 // This is a non-ARC instruction. If we're delaying an AutoreleaseRV, 847 // check if it's safe to skip over it; if not, optimize the AutoreleaseRV 848 // now. 849 if (!shouldDelayAutoreleaseRV(Inst)) 850 optimizeDelayedAutoreleaseRV(); 851 continue; 852 case ARCInstKind::AutoreleaseRV: 853 optimizeDelayedAutoreleaseRV(); 854 setDelayedAutoreleaseRV(Inst); 855 continue; 856 case ARCInstKind::RetainRV: 857 case ARCInstKind::ClaimRV: 858 if (DelayedAutoreleaseRV) { 859 // We have a potential RV pair. Check if they cancel out. 860 if (OptimizeInlinedAutoreleaseRVCall(F, BlockColors, Inst, Arg, Class, 861 DelayedAutoreleaseRV, 862 DelayedAutoreleaseRVArg)) { 863 setDelayedAutoreleaseRV(nullptr); 864 continue; 865 } 866 optimizeDelayedAutoreleaseRV(); 867 } 868 break; 869 } 870 871 OptimizeIndividualCallImpl(F, BlockColors, Inst, Class, Arg); 872 } 873 874 // Catch the final delayed AutoreleaseRV. 875 optimizeDelayedAutoreleaseRV(); 876 } 877 878 /// This function returns true if the value is inert. An ObjC ARC runtime call 879 /// taking an inert operand can be safely deleted. 880 static bool isInertARCValue(Value *V, SmallPtrSet<Value *, 1> &VisitedPhis) { 881 V = V->stripPointerCasts(); 882 883 if (IsNullOrUndef(V)) 884 return true; 885 886 // See if this is a global attribute annotated with an 'objc_arc_inert'. 887 if (auto *GV = dyn_cast<GlobalVariable>(V)) 888 if (GV->hasAttribute("objc_arc_inert")) 889 return true; 890 891 if (auto PN = dyn_cast<PHINode>(V)) { 892 // Ignore this phi if it has already been discovered. 893 if (!VisitedPhis.insert(PN).second) 894 return true; 895 // Look through phis's operands. 896 for (Value *Opnd : PN->incoming_values()) 897 if (!isInertARCValue(Opnd, VisitedPhis)) 898 return false; 899 return true; 900 } 901 902 return false; 903 } 904 905 void ObjCARCOpt::OptimizeIndividualCallImpl( 906 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 907 Instruction *Inst, ARCInstKind Class, const Value *Arg) { 908 LLVM_DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n"); 909 910 // We can delete this call if it takes an inert value. 911 SmallPtrSet<Value *, 1> VisitedPhis; 912 913 if (IsNoopOnGlobal(Class)) 914 if (isInertARCValue(Inst->getOperand(0), VisitedPhis)) { 915 if (!Inst->getType()->isVoidTy()) 916 Inst->replaceAllUsesWith(Inst->getOperand(0)); 917 Inst->eraseFromParent(); 918 return; 919 } 920 921 switch (Class) { 922 default: 923 break; 924 925 // Delete no-op casts. These function calls have special semantics, but 926 // the semantics are entirely implemented via lowering in the front-end, 927 // so by the time they reach the optimizer, they are just no-op calls 928 // which return their argument. 929 // 930 // There are gray areas here, as the ability to cast reference-counted 931 // pointers to raw void* and back allows code to break ARC assumptions, 932 // however these are currently considered to be unimportant. 933 case ARCInstKind::NoopCast: 934 Changed = true; 935 ++NumNoops; 936 LLVM_DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n"); 937 EraseInstruction(Inst); 938 return; 939 940 // If the pointer-to-weak-pointer is null, it's undefined behavior. 941 case ARCInstKind::StoreWeak: 942 case ARCInstKind::LoadWeak: 943 case ARCInstKind::LoadWeakRetained: 944 case ARCInstKind::InitWeak: 945 case ARCInstKind::DestroyWeak: { 946 CallInst *CI = cast<CallInst>(Inst); 947 if (IsNullOrUndef(CI->getArgOperand(0))) { 948 Changed = true; 949 Type *Ty = CI->getArgOperand(0)->getType(); 950 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), 951 Constant::getNullValue(Ty), CI); 952 Value *NewValue = UndefValue::get(CI->getType()); 953 LLVM_DEBUG( 954 dbgs() << "A null pointer-to-weak-pointer is undefined behavior." 955 "\nOld = " 956 << *CI << "\nNew = " << *NewValue << "\n"); 957 CI->replaceAllUsesWith(NewValue); 958 CI->eraseFromParent(); 959 return; 960 } 961 break; 962 } 963 case ARCInstKind::CopyWeak: 964 case ARCInstKind::MoveWeak: { 965 CallInst *CI = cast<CallInst>(Inst); 966 if (IsNullOrUndef(CI->getArgOperand(0)) || 967 IsNullOrUndef(CI->getArgOperand(1))) { 968 Changed = true; 969 Type *Ty = CI->getArgOperand(0)->getType(); 970 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), 971 Constant::getNullValue(Ty), CI); 972 973 Value *NewValue = UndefValue::get(CI->getType()); 974 LLVM_DEBUG( 975 dbgs() << "A null pointer-to-weak-pointer is undefined behavior." 976 "\nOld = " 977 << *CI << "\nNew = " << *NewValue << "\n"); 978 979 CI->replaceAllUsesWith(NewValue); 980 CI->eraseFromParent(); 981 return; 982 } 983 break; 984 } 985 case ARCInstKind::RetainRV: 986 if (OptimizeRetainRVCall(F, Inst)) 987 return; 988 break; 989 case ARCInstKind::AutoreleaseRV: 990 OptimizeAutoreleaseRVCall(F, Inst, Class); 991 break; 992 } 993 994 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused. 995 if (IsAutorelease(Class) && Inst->use_empty()) { 996 CallInst *Call = cast<CallInst>(Inst); 997 const Value *Arg = Call->getArgOperand(0); 998 Arg = FindSingleUseIdentifiedObject(Arg); 999 if (Arg) { 1000 Changed = true; 1001 ++NumAutoreleases; 1002 1003 // Create the declaration lazily. 1004 LLVMContext &C = Inst->getContext(); 1005 1006 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release); 1007 CallInst *NewCall = 1008 CallInst::Create(Decl, Call->getArgOperand(0), "", Call); 1009 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), 1010 MDNode::get(C, None)); 1011 1012 LLVM_DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) " 1013 "since x is otherwise unused.\nOld: " 1014 << *Call << "\nNew: " << *NewCall << "\n"); 1015 1016 EraseInstruction(Call); 1017 Inst = NewCall; 1018 Class = ARCInstKind::Release; 1019 } 1020 } 1021 1022 // For functions which can never be passed stack arguments, add 1023 // a tail keyword. 1024 if (IsAlwaysTail(Class) && !cast<CallInst>(Inst)->isNoTailCall()) { 1025 Changed = true; 1026 LLVM_DEBUG( 1027 dbgs() << "Adding tail keyword to function since it can never be " 1028 "passed stack args: " 1029 << *Inst << "\n"); 1030 cast<CallInst>(Inst)->setTailCall(); 1031 } 1032 1033 // Ensure that functions that can never have a "tail" keyword due to the 1034 // semantics of ARC truly do not do so. 1035 if (IsNeverTail(Class)) { 1036 Changed = true; 1037 LLVM_DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst 1038 << "\n"); 1039 cast<CallInst>(Inst)->setTailCall(false); 1040 } 1041 1042 // Set nounwind as needed. 1043 if (IsNoThrow(Class)) { 1044 Changed = true; 1045 LLVM_DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst 1046 << "\n"); 1047 cast<CallInst>(Inst)->setDoesNotThrow(); 1048 } 1049 1050 // Note: This catches instructions unrelated to ARC. 1051 if (!IsNoopOnNull(Class)) { 1052 UsedInThisFunction |= 1 << unsigned(Class); 1053 return; 1054 } 1055 1056 // If we haven't already looked up the root, look it up now. 1057 if (!Arg) 1058 Arg = GetArgRCIdentityRoot(Inst); 1059 1060 // ARC calls with null are no-ops. Delete them. 1061 if (IsNullOrUndef(Arg)) { 1062 Changed = true; 1063 ++NumNoops; 1064 LLVM_DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst 1065 << "\n"); 1066 EraseInstruction(Inst); 1067 return; 1068 } 1069 1070 // Keep track of which of retain, release, autorelease, and retain_block 1071 // are actually present in this function. 1072 UsedInThisFunction |= 1 << unsigned(Class); 1073 1074 // If Arg is a PHI, and one or more incoming values to the 1075 // PHI are null, and the call is control-equivalent to the PHI, and there 1076 // are no relevant side effects between the PHI and the call, and the call 1077 // is not a release that doesn't have the clang.imprecise_release tag, the 1078 // call could be pushed up to just those paths with non-null incoming 1079 // values. For now, don't bother splitting critical edges for this. 1080 if (Class == ARCInstKind::Release && 1081 !Inst->getMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease))) 1082 return; 1083 1084 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist; 1085 Worklist.push_back(std::make_pair(Inst, Arg)); 1086 do { 1087 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val(); 1088 Inst = Pair.first; 1089 Arg = Pair.second; 1090 1091 const PHINode *PN = dyn_cast<PHINode>(Arg); 1092 if (!PN) 1093 continue; 1094 1095 // Determine if the PHI has any null operands, or any incoming 1096 // critical edges. 1097 bool HasNull = false; 1098 bool HasCriticalEdges = false; 1099 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1100 Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i)); 1101 if (IsNullOrUndef(Incoming)) 1102 HasNull = true; 1103 else if (PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() != 1104 1) { 1105 HasCriticalEdges = true; 1106 break; 1107 } 1108 } 1109 // If we have null operands and no critical edges, optimize. 1110 if (HasCriticalEdges) 1111 continue; 1112 if (!HasNull) 1113 continue; 1114 1115 SmallPtrSet<Instruction *, 4> DependingInstructions; 1116 SmallPtrSet<const BasicBlock *, 4> Visited; 1117 1118 // Check that there is nothing that cares about the reference 1119 // count between the call and the phi. 1120 switch (Class) { 1121 case ARCInstKind::Retain: 1122 case ARCInstKind::RetainBlock: 1123 // These can always be moved up. 1124 break; 1125 case ARCInstKind::Release: 1126 // These can't be moved across things that care about the retain 1127 // count. 1128 FindDependencies(NeedsPositiveRetainCount, Arg, Inst->getParent(), Inst, 1129 DependingInstructions, Visited, PA); 1130 break; 1131 case ARCInstKind::Autorelease: 1132 // These can't be moved across autorelease pool scope boundaries. 1133 FindDependencies(AutoreleasePoolBoundary, Arg, Inst->getParent(), Inst, 1134 DependingInstructions, Visited, PA); 1135 break; 1136 case ARCInstKind::ClaimRV: 1137 case ARCInstKind::RetainRV: 1138 case ARCInstKind::AutoreleaseRV: 1139 // Don't move these; the RV optimization depends on the autoreleaseRV 1140 // being tail called, and the retainRV being immediately after a call 1141 // (which might still happen if we get lucky with codegen layout, but 1142 // it's not worth taking the chance). 1143 continue; 1144 default: 1145 llvm_unreachable("Invalid dependence flavor"); 1146 } 1147 1148 if (DependingInstructions.size() != 1) 1149 continue; 1150 if (*DependingInstructions.begin() != PN) 1151 continue; 1152 1153 Changed = true; 1154 ++NumPartialNoops; 1155 // Clone the call into each predecessor that has a non-null value. 1156 CallInst *CInst = cast<CallInst>(Inst); 1157 Type *ParamTy = CInst->getArgOperand(0)->getType(); 1158 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1159 Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i)); 1160 if (IsNullOrUndef(Incoming)) 1161 continue; 1162 Value *Op = PN->getIncomingValue(i); 1163 Instruction *InsertPos = &PN->getIncomingBlock(i)->back(); 1164 CallInst *Clone = cast<CallInst>( 1165 CloneCallInstForBB(*CInst, *InsertPos->getParent(), BlockColors)); 1166 if (Op->getType() != ParamTy) 1167 Op = new BitCastInst(Op, ParamTy, "", InsertPos); 1168 Clone->setArgOperand(0, Op); 1169 Clone->insertBefore(InsertPos); 1170 1171 LLVM_DEBUG(dbgs() << "Cloning " << *CInst << "\n" 1172 "And inserting clone at " 1173 << *InsertPos << "\n"); 1174 Worklist.push_back(std::make_pair(Clone, Incoming)); 1175 } 1176 // Erase the original call. 1177 LLVM_DEBUG(dbgs() << "Erasing: " << *CInst << "\n"); 1178 EraseInstruction(CInst); 1179 } while (!Worklist.empty()); 1180 } 1181 1182 /// If we have a top down pointer in the S_Use state, make sure that there are 1183 /// no CFG hazards by checking the states of various bottom up pointers. 1184 static void CheckForUseCFGHazard(const Sequence SuccSSeq, 1185 const bool SuccSRRIKnownSafe, 1186 TopDownPtrState &S, 1187 bool &SomeSuccHasSame, 1188 bool &AllSuccsHaveSame, 1189 bool &NotAllSeqEqualButKnownSafe, 1190 bool &ShouldContinue) { 1191 switch (SuccSSeq) { 1192 case S_CanRelease: { 1193 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) { 1194 S.ClearSequenceProgress(); 1195 break; 1196 } 1197 S.SetCFGHazardAfflicted(true); 1198 ShouldContinue = true; 1199 break; 1200 } 1201 case S_Use: 1202 SomeSuccHasSame = true; 1203 break; 1204 case S_Stop: 1205 case S_Release: 1206 case S_MovableRelease: 1207 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) 1208 AllSuccsHaveSame = false; 1209 else 1210 NotAllSeqEqualButKnownSafe = true; 1211 break; 1212 case S_Retain: 1213 llvm_unreachable("bottom-up pointer in retain state!"); 1214 case S_None: 1215 llvm_unreachable("This should have been handled earlier."); 1216 } 1217 } 1218 1219 /// If we have a Top Down pointer in the S_CanRelease state, make sure that 1220 /// there are no CFG hazards by checking the states of various bottom up 1221 /// pointers. 1222 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq, 1223 const bool SuccSRRIKnownSafe, 1224 TopDownPtrState &S, 1225 bool &SomeSuccHasSame, 1226 bool &AllSuccsHaveSame, 1227 bool &NotAllSeqEqualButKnownSafe) { 1228 switch (SuccSSeq) { 1229 case S_CanRelease: 1230 SomeSuccHasSame = true; 1231 break; 1232 case S_Stop: 1233 case S_Release: 1234 case S_MovableRelease: 1235 case S_Use: 1236 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) 1237 AllSuccsHaveSame = false; 1238 else 1239 NotAllSeqEqualButKnownSafe = true; 1240 break; 1241 case S_Retain: 1242 llvm_unreachable("bottom-up pointer in retain state!"); 1243 case S_None: 1244 llvm_unreachable("This should have been handled earlier."); 1245 } 1246 } 1247 1248 /// Check for critical edges, loop boundaries, irreducible control flow, or 1249 /// other CFG structures where moving code across the edge would result in it 1250 /// being executed more. 1251 void 1252 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB, 1253 DenseMap<const BasicBlock *, BBState> &BBStates, 1254 BBState &MyStates) const { 1255 // If any top-down local-use or possible-dec has a succ which is earlier in 1256 // the sequence, forget it. 1257 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end(); 1258 I != E; ++I) { 1259 TopDownPtrState &S = I->second; 1260 const Sequence Seq = I->second.GetSeq(); 1261 1262 // We only care about S_Retain, S_CanRelease, and S_Use. 1263 if (Seq == S_None) 1264 continue; 1265 1266 // Make sure that if extra top down states are added in the future that this 1267 // code is updated to handle it. 1268 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) && 1269 "Unknown top down sequence state."); 1270 1271 const Value *Arg = I->first; 1272 bool SomeSuccHasSame = false; 1273 bool AllSuccsHaveSame = true; 1274 bool NotAllSeqEqualButKnownSafe = false; 1275 1276 for (const BasicBlock *Succ : successors(BB)) { 1277 // If VisitBottomUp has pointer information for this successor, take 1278 // what we know about it. 1279 const DenseMap<const BasicBlock *, BBState>::iterator BBI = 1280 BBStates.find(Succ); 1281 assert(BBI != BBStates.end()); 1282 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); 1283 const Sequence SuccSSeq = SuccS.GetSeq(); 1284 1285 // If bottom up, the pointer is in an S_None state, clear the sequence 1286 // progress since the sequence in the bottom up state finished 1287 // suggesting a mismatch in between retains/releases. This is true for 1288 // all three cases that we are handling here: S_Retain, S_Use, and 1289 // S_CanRelease. 1290 if (SuccSSeq == S_None) { 1291 S.ClearSequenceProgress(); 1292 continue; 1293 } 1294 1295 // If we have S_Use or S_CanRelease, perform our check for cfg hazard 1296 // checks. 1297 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe(); 1298 1299 // *NOTE* We do not use Seq from above here since we are allowing for 1300 // S.GetSeq() to change while we are visiting basic blocks. 1301 switch(S.GetSeq()) { 1302 case S_Use: { 1303 bool ShouldContinue = false; 1304 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame, 1305 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe, 1306 ShouldContinue); 1307 if (ShouldContinue) 1308 continue; 1309 break; 1310 } 1311 case S_CanRelease: 1312 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, 1313 SomeSuccHasSame, AllSuccsHaveSame, 1314 NotAllSeqEqualButKnownSafe); 1315 break; 1316 case S_Retain: 1317 case S_None: 1318 case S_Stop: 1319 case S_Release: 1320 case S_MovableRelease: 1321 break; 1322 } 1323 } 1324 1325 // If the state at the other end of any of the successor edges 1326 // matches the current state, require all edges to match. This 1327 // guards against loops in the middle of a sequence. 1328 if (SomeSuccHasSame && !AllSuccsHaveSame) { 1329 S.ClearSequenceProgress(); 1330 } else if (NotAllSeqEqualButKnownSafe) { 1331 // If we would have cleared the state foregoing the fact that we are known 1332 // safe, stop code motion. This is because whether or not it is safe to 1333 // remove RR pairs via KnownSafe is an orthogonal concept to whether we 1334 // are allowed to perform code motion. 1335 S.SetCFGHazardAfflicted(true); 1336 } 1337 } 1338 } 1339 1340 bool ObjCARCOpt::VisitInstructionBottomUp( 1341 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains, 1342 BBState &MyStates) { 1343 bool NestingDetected = false; 1344 ARCInstKind Class = GetARCInstKind(Inst); 1345 const Value *Arg = nullptr; 1346 1347 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n"); 1348 1349 switch (Class) { 1350 case ARCInstKind::Release: { 1351 Arg = GetArgRCIdentityRoot(Inst); 1352 1353 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg); 1354 NestingDetected |= S.InitBottomUp(MDKindCache, Inst); 1355 break; 1356 } 1357 case ARCInstKind::RetainBlock: 1358 // In OptimizeIndividualCalls, we have strength reduced all optimizable 1359 // objc_retainBlocks to objc_retains. Thus at this point any 1360 // objc_retainBlocks that we see are not optimizable. 1361 break; 1362 case ARCInstKind::Retain: 1363 case ARCInstKind::RetainRV: { 1364 Arg = GetArgRCIdentityRoot(Inst); 1365 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg); 1366 if (S.MatchWithRetain()) { 1367 // Don't do retain+release tracking for ARCInstKind::RetainRV, because 1368 // it's better to let it remain as the first instruction after a call. 1369 if (Class != ARCInstKind::RetainRV) { 1370 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n"); 1371 Retains[Inst] = S.GetRRInfo(); 1372 } 1373 S.ClearSequenceProgress(); 1374 } 1375 // A retain moving bottom up can be a use. 1376 break; 1377 } 1378 case ARCInstKind::AutoreleasepoolPop: 1379 // Conservatively, clear MyStates for all known pointers. 1380 MyStates.clearBottomUpPointers(); 1381 return NestingDetected; 1382 case ARCInstKind::AutoreleasepoolPush: 1383 case ARCInstKind::None: 1384 // These are irrelevant. 1385 return NestingDetected; 1386 default: 1387 break; 1388 } 1389 1390 // Consider any other possible effects of this instruction on each 1391 // pointer being tracked. 1392 for (auto MI = MyStates.bottom_up_ptr_begin(), 1393 ME = MyStates.bottom_up_ptr_end(); 1394 MI != ME; ++MI) { 1395 const Value *Ptr = MI->first; 1396 if (Ptr == Arg) 1397 continue; // Handled above. 1398 BottomUpPtrState &S = MI->second; 1399 1400 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class)) 1401 continue; 1402 1403 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class); 1404 } 1405 1406 return NestingDetected; 1407 } 1408 1409 bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB, 1410 DenseMap<const BasicBlock *, BBState> &BBStates, 1411 BlotMapVector<Value *, RRInfo> &Retains) { 1412 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n"); 1413 1414 bool NestingDetected = false; 1415 BBState &MyStates = BBStates[BB]; 1416 1417 // Merge the states from each successor to compute the initial state 1418 // for the current block. 1419 BBState::edge_iterator SI(MyStates.succ_begin()), 1420 SE(MyStates.succ_end()); 1421 if (SI != SE) { 1422 const BasicBlock *Succ = *SI; 1423 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ); 1424 assert(I != BBStates.end()); 1425 MyStates.InitFromSucc(I->second); 1426 ++SI; 1427 for (; SI != SE; ++SI) { 1428 Succ = *SI; 1429 I = BBStates.find(Succ); 1430 assert(I != BBStates.end()); 1431 MyStates.MergeSucc(I->second); 1432 } 1433 } 1434 1435 LLVM_DEBUG(dbgs() << "Before:\n" 1436 << BBStates[BB] << "\n" 1437 << "Performing Dataflow:\n"); 1438 1439 // Visit all the instructions, bottom-up. 1440 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) { 1441 Instruction *Inst = &*std::prev(I); 1442 1443 // Invoke instructions are visited as part of their successors (below). 1444 if (isa<InvokeInst>(Inst)) 1445 continue; 1446 1447 LLVM_DEBUG(dbgs() << " Visiting " << *Inst << "\n"); 1448 1449 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates); 1450 1451 // Bail out if the number of pointers being tracked becomes too large so 1452 // that this pass can complete in a reasonable amount of time. 1453 if (MyStates.bottom_up_ptr_list_size() > MaxPtrStates) { 1454 DisableRetainReleasePairing = true; 1455 return false; 1456 } 1457 } 1458 1459 // If there's a predecessor with an invoke, visit the invoke as if it were 1460 // part of this block, since we can't insert code after an invoke in its own 1461 // block, and we don't want to split critical edges. 1462 for (BBState::edge_iterator PI(MyStates.pred_begin()), 1463 PE(MyStates.pred_end()); PI != PE; ++PI) { 1464 BasicBlock *Pred = *PI; 1465 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back())) 1466 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates); 1467 } 1468 1469 LLVM_DEBUG(dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n"); 1470 1471 return NestingDetected; 1472 } 1473 1474 bool 1475 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst, 1476 DenseMap<Value *, RRInfo> &Releases, 1477 BBState &MyStates) { 1478 bool NestingDetected = false; 1479 ARCInstKind Class = GetARCInstKind(Inst); 1480 const Value *Arg = nullptr; 1481 1482 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n"); 1483 1484 switch (Class) { 1485 case ARCInstKind::RetainBlock: 1486 // In OptimizeIndividualCalls, we have strength reduced all optimizable 1487 // objc_retainBlocks to objc_retains. Thus at this point any 1488 // objc_retainBlocks that we see are not optimizable. We need to break since 1489 // a retain can be a potential use. 1490 break; 1491 case ARCInstKind::Retain: 1492 case ARCInstKind::RetainRV: { 1493 Arg = GetArgRCIdentityRoot(Inst); 1494 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg); 1495 NestingDetected |= S.InitTopDown(Class, Inst); 1496 // A retain can be a potential use; proceed to the generic checking 1497 // code below. 1498 break; 1499 } 1500 case ARCInstKind::Release: { 1501 Arg = GetArgRCIdentityRoot(Inst); 1502 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg); 1503 // Try to form a tentative pair in between this release instruction and the 1504 // top down pointers that we are tracking. 1505 if (S.MatchWithRelease(MDKindCache, Inst)) { 1506 // If we succeed, copy S's RRInfo into the Release -> {Retain Set 1507 // Map}. Then we clear S. 1508 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n"); 1509 Releases[Inst] = S.GetRRInfo(); 1510 S.ClearSequenceProgress(); 1511 } 1512 break; 1513 } 1514 case ARCInstKind::AutoreleasepoolPop: 1515 // Conservatively, clear MyStates for all known pointers. 1516 MyStates.clearTopDownPointers(); 1517 return false; 1518 case ARCInstKind::AutoreleasepoolPush: 1519 case ARCInstKind::None: 1520 // These can not be uses of 1521 return false; 1522 default: 1523 break; 1524 } 1525 1526 // Consider any other possible effects of this instruction on each 1527 // pointer being tracked. 1528 for (auto MI = MyStates.top_down_ptr_begin(), 1529 ME = MyStates.top_down_ptr_end(); 1530 MI != ME; ++MI) { 1531 const Value *Ptr = MI->first; 1532 if (Ptr == Arg) 1533 continue; // Handled above. 1534 TopDownPtrState &S = MI->second; 1535 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class)) 1536 continue; 1537 1538 S.HandlePotentialUse(Inst, Ptr, PA, Class); 1539 } 1540 1541 return NestingDetected; 1542 } 1543 1544 bool 1545 ObjCARCOpt::VisitTopDown(BasicBlock *BB, 1546 DenseMap<const BasicBlock *, BBState> &BBStates, 1547 DenseMap<Value *, RRInfo> &Releases) { 1548 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n"); 1549 bool NestingDetected = false; 1550 BBState &MyStates = BBStates[BB]; 1551 1552 // Merge the states from each predecessor to compute the initial state 1553 // for the current block. 1554 BBState::edge_iterator PI(MyStates.pred_begin()), 1555 PE(MyStates.pred_end()); 1556 if (PI != PE) { 1557 const BasicBlock *Pred = *PI; 1558 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred); 1559 assert(I != BBStates.end()); 1560 MyStates.InitFromPred(I->second); 1561 ++PI; 1562 for (; PI != PE; ++PI) { 1563 Pred = *PI; 1564 I = BBStates.find(Pred); 1565 assert(I != BBStates.end()); 1566 MyStates.MergePred(I->second); 1567 } 1568 } 1569 1570 // Check that BB and MyStates have the same number of predecessors. This 1571 // prevents retain calls that live outside a loop from being moved into the 1572 // loop. 1573 if (!BB->hasNPredecessors(MyStates.pred_end() - MyStates.pred_begin())) 1574 for (auto I = MyStates.top_down_ptr_begin(), 1575 E = MyStates.top_down_ptr_end(); 1576 I != E; ++I) 1577 I->second.SetCFGHazardAfflicted(true); 1578 1579 LLVM_DEBUG(dbgs() << "Before:\n" 1580 << BBStates[BB] << "\n" 1581 << "Performing Dataflow:\n"); 1582 1583 // Visit all the instructions, top-down. 1584 for (Instruction &Inst : *BB) { 1585 LLVM_DEBUG(dbgs() << " Visiting " << Inst << "\n"); 1586 1587 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates); 1588 1589 // Bail out if the number of pointers being tracked becomes too large so 1590 // that this pass can complete in a reasonable amount of time. 1591 if (MyStates.top_down_ptr_list_size() > MaxPtrStates) { 1592 DisableRetainReleasePairing = true; 1593 return false; 1594 } 1595 } 1596 1597 LLVM_DEBUG(dbgs() << "\nState Before Checking for CFG Hazards:\n" 1598 << BBStates[BB] << "\n\n"); 1599 CheckForCFGHazards(BB, BBStates, MyStates); 1600 LLVM_DEBUG(dbgs() << "Final State:\n" << BBStates[BB] << "\n"); 1601 return NestingDetected; 1602 } 1603 1604 static void 1605 ComputePostOrders(Function &F, 1606 SmallVectorImpl<BasicBlock *> &PostOrder, 1607 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder, 1608 unsigned NoObjCARCExceptionsMDKind, 1609 DenseMap<const BasicBlock *, BBState> &BBStates) { 1610 /// The visited set, for doing DFS walks. 1611 SmallPtrSet<BasicBlock *, 16> Visited; 1612 1613 // Do DFS, computing the PostOrder. 1614 SmallPtrSet<BasicBlock *, 16> OnStack; 1615 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack; 1616 1617 // Functions always have exactly one entry block, and we don't have 1618 // any other block that we treat like an entry block. 1619 BasicBlock *EntryBB = &F.getEntryBlock(); 1620 BBState &MyStates = BBStates[EntryBB]; 1621 MyStates.SetAsEntry(); 1622 Instruction *EntryTI = EntryBB->getTerminator(); 1623 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI))); 1624 Visited.insert(EntryBB); 1625 OnStack.insert(EntryBB); 1626 do { 1627 dfs_next_succ: 1628 BasicBlock *CurrBB = SuccStack.back().first; 1629 succ_iterator SE(CurrBB->getTerminator(), false); 1630 1631 while (SuccStack.back().second != SE) { 1632 BasicBlock *SuccBB = *SuccStack.back().second++; 1633 if (Visited.insert(SuccBB).second) { 1634 SuccStack.push_back( 1635 std::make_pair(SuccBB, succ_iterator(SuccBB->getTerminator()))); 1636 BBStates[CurrBB].addSucc(SuccBB); 1637 BBState &SuccStates = BBStates[SuccBB]; 1638 SuccStates.addPred(CurrBB); 1639 OnStack.insert(SuccBB); 1640 goto dfs_next_succ; 1641 } 1642 1643 if (!OnStack.count(SuccBB)) { 1644 BBStates[CurrBB].addSucc(SuccBB); 1645 BBStates[SuccBB].addPred(CurrBB); 1646 } 1647 } 1648 OnStack.erase(CurrBB); 1649 PostOrder.push_back(CurrBB); 1650 SuccStack.pop_back(); 1651 } while (!SuccStack.empty()); 1652 1653 Visited.clear(); 1654 1655 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder. 1656 // Functions may have many exits, and there also blocks which we treat 1657 // as exits due to ignored edges. 1658 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack; 1659 for (BasicBlock &ExitBB : F) { 1660 BBState &MyStates = BBStates[&ExitBB]; 1661 if (!MyStates.isExit()) 1662 continue; 1663 1664 MyStates.SetAsExit(); 1665 1666 PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin())); 1667 Visited.insert(&ExitBB); 1668 while (!PredStack.empty()) { 1669 reverse_dfs_next_succ: 1670 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end(); 1671 while (PredStack.back().second != PE) { 1672 BasicBlock *BB = *PredStack.back().second++; 1673 if (Visited.insert(BB).second) { 1674 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin())); 1675 goto reverse_dfs_next_succ; 1676 } 1677 } 1678 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first); 1679 } 1680 } 1681 } 1682 1683 // Visit the function both top-down and bottom-up. 1684 bool ObjCARCOpt::Visit(Function &F, 1685 DenseMap<const BasicBlock *, BBState> &BBStates, 1686 BlotMapVector<Value *, RRInfo> &Retains, 1687 DenseMap<Value *, RRInfo> &Releases) { 1688 // Use reverse-postorder traversals, because we magically know that loops 1689 // will be well behaved, i.e. they won't repeatedly call retain on a single 1690 // pointer without doing a release. We can't use the ReversePostOrderTraversal 1691 // class here because we want the reverse-CFG postorder to consider each 1692 // function exit point, and we want to ignore selected cycle edges. 1693 SmallVector<BasicBlock *, 16> PostOrder; 1694 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder; 1695 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder, 1696 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions), 1697 BBStates); 1698 1699 // Use reverse-postorder on the reverse CFG for bottom-up. 1700 bool BottomUpNestingDetected = false; 1701 for (BasicBlock *BB : llvm::reverse(ReverseCFGPostOrder)) { 1702 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains); 1703 if (DisableRetainReleasePairing) 1704 return false; 1705 } 1706 1707 // Use reverse-postorder for top-down. 1708 bool TopDownNestingDetected = false; 1709 for (BasicBlock *BB : llvm::reverse(PostOrder)) { 1710 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases); 1711 if (DisableRetainReleasePairing) 1712 return false; 1713 } 1714 1715 return TopDownNestingDetected && BottomUpNestingDetected; 1716 } 1717 1718 /// Move the calls in RetainsToMove and ReleasesToMove. 1719 void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove, 1720 RRInfo &ReleasesToMove, 1721 BlotMapVector<Value *, RRInfo> &Retains, 1722 DenseMap<Value *, RRInfo> &Releases, 1723 SmallVectorImpl<Instruction *> &DeadInsts, 1724 Module *M) { 1725 Type *ArgTy = Arg->getType(); 1726 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext())); 1727 1728 LLVM_DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n"); 1729 1730 // Insert the new retain and release calls. 1731 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) { 1732 Value *MyArg = ArgTy == ParamTy ? Arg : 1733 new BitCastInst(Arg, ParamTy, "", InsertPt); 1734 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain); 1735 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt); 1736 Call->setDoesNotThrow(); 1737 Call->setTailCall(); 1738 1739 LLVM_DEBUG(dbgs() << "Inserting new Retain: " << *Call 1740 << "\n" 1741 "At insertion point: " 1742 << *InsertPt << "\n"); 1743 } 1744 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) { 1745 Value *MyArg = ArgTy == ParamTy ? Arg : 1746 new BitCastInst(Arg, ParamTy, "", InsertPt); 1747 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release); 1748 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt); 1749 // Attach a clang.imprecise_release metadata tag, if appropriate. 1750 if (MDNode *M = ReleasesToMove.ReleaseMetadata) 1751 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M); 1752 Call->setDoesNotThrow(); 1753 if (ReleasesToMove.IsTailCallRelease) 1754 Call->setTailCall(); 1755 1756 LLVM_DEBUG(dbgs() << "Inserting new Release: " << *Call 1757 << "\n" 1758 "At insertion point: " 1759 << *InsertPt << "\n"); 1760 } 1761 1762 // Delete the original retain and release calls. 1763 for (Instruction *OrigRetain : RetainsToMove.Calls) { 1764 Retains.blot(OrigRetain); 1765 DeadInsts.push_back(OrigRetain); 1766 LLVM_DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n"); 1767 } 1768 for (Instruction *OrigRelease : ReleasesToMove.Calls) { 1769 Releases.erase(OrigRelease); 1770 DeadInsts.push_back(OrigRelease); 1771 LLVM_DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n"); 1772 } 1773 } 1774 1775 bool ObjCARCOpt::PairUpRetainsAndReleases( 1776 DenseMap<const BasicBlock *, BBState> &BBStates, 1777 BlotMapVector<Value *, RRInfo> &Retains, 1778 DenseMap<Value *, RRInfo> &Releases, Module *M, 1779 Instruction *Retain, 1780 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove, 1781 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe, 1782 bool &AnyPairsCompletelyEliminated) { 1783 // If a pair happens in a region where it is known that the reference count 1784 // is already incremented, we can similarly ignore possible decrements unless 1785 // we are dealing with a retainable object with multiple provenance sources. 1786 bool KnownSafeTD = true, KnownSafeBU = true; 1787 bool CFGHazardAfflicted = false; 1788 1789 // Connect the dots between the top-down-collected RetainsToMove and 1790 // bottom-up-collected ReleasesToMove to form sets of related calls. 1791 // This is an iterative process so that we connect multiple releases 1792 // to multiple retains if needed. 1793 unsigned OldDelta = 0; 1794 unsigned NewDelta = 0; 1795 unsigned OldCount = 0; 1796 unsigned NewCount = 0; 1797 bool FirstRelease = true; 1798 for (SmallVector<Instruction *, 4> NewRetains{Retain};;) { 1799 SmallVector<Instruction *, 4> NewReleases; 1800 for (Instruction *NewRetain : NewRetains) { 1801 auto It = Retains.find(NewRetain); 1802 assert(It != Retains.end()); 1803 const RRInfo &NewRetainRRI = It->second; 1804 KnownSafeTD &= NewRetainRRI.KnownSafe; 1805 CFGHazardAfflicted |= NewRetainRRI.CFGHazardAfflicted; 1806 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) { 1807 auto Jt = Releases.find(NewRetainRelease); 1808 if (Jt == Releases.end()) 1809 return false; 1810 const RRInfo &NewRetainReleaseRRI = Jt->second; 1811 1812 // If the release does not have a reference to the retain as well, 1813 // something happened which is unaccounted for. Do not do anything. 1814 // 1815 // This can happen if we catch an additive overflow during path count 1816 // merging. 1817 if (!NewRetainReleaseRRI.Calls.count(NewRetain)) 1818 return false; 1819 1820 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) { 1821 // If we overflow when we compute the path count, don't remove/move 1822 // anything. 1823 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()]; 1824 unsigned PathCount = BBState::OverflowOccurredValue; 1825 if (NRRBBState.GetAllPathCountWithOverflow(PathCount)) 1826 return false; 1827 assert(PathCount != BBState::OverflowOccurredValue && 1828 "PathCount at this point can not be " 1829 "OverflowOccurredValue."); 1830 OldDelta -= PathCount; 1831 1832 // Merge the ReleaseMetadata and IsTailCallRelease values. 1833 if (FirstRelease) { 1834 ReleasesToMove.ReleaseMetadata = 1835 NewRetainReleaseRRI.ReleaseMetadata; 1836 ReleasesToMove.IsTailCallRelease = 1837 NewRetainReleaseRRI.IsTailCallRelease; 1838 FirstRelease = false; 1839 } else { 1840 if (ReleasesToMove.ReleaseMetadata != 1841 NewRetainReleaseRRI.ReleaseMetadata) 1842 ReleasesToMove.ReleaseMetadata = nullptr; 1843 if (ReleasesToMove.IsTailCallRelease != 1844 NewRetainReleaseRRI.IsTailCallRelease) 1845 ReleasesToMove.IsTailCallRelease = false; 1846 } 1847 1848 // Collect the optimal insertion points. 1849 if (!KnownSafe) 1850 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) { 1851 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) { 1852 // If we overflow when we compute the path count, don't 1853 // remove/move anything. 1854 const BBState &RIPBBState = BBStates[RIP->getParent()]; 1855 PathCount = BBState::OverflowOccurredValue; 1856 if (RIPBBState.GetAllPathCountWithOverflow(PathCount)) 1857 return false; 1858 assert(PathCount != BBState::OverflowOccurredValue && 1859 "PathCount at this point can not be " 1860 "OverflowOccurredValue."); 1861 NewDelta -= PathCount; 1862 } 1863 } 1864 NewReleases.push_back(NewRetainRelease); 1865 } 1866 } 1867 } 1868 NewRetains.clear(); 1869 if (NewReleases.empty()) break; 1870 1871 // Back the other way. 1872 for (Instruction *NewRelease : NewReleases) { 1873 auto It = Releases.find(NewRelease); 1874 assert(It != Releases.end()); 1875 const RRInfo &NewReleaseRRI = It->second; 1876 KnownSafeBU &= NewReleaseRRI.KnownSafe; 1877 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted; 1878 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) { 1879 auto Jt = Retains.find(NewReleaseRetain); 1880 if (Jt == Retains.end()) 1881 return false; 1882 const RRInfo &NewReleaseRetainRRI = Jt->second; 1883 1884 // If the retain does not have a reference to the release as well, 1885 // something happened which is unaccounted for. Do not do anything. 1886 // 1887 // This can happen if we catch an additive overflow during path count 1888 // merging. 1889 if (!NewReleaseRetainRRI.Calls.count(NewRelease)) 1890 return false; 1891 1892 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) { 1893 // If we overflow when we compute the path count, don't remove/move 1894 // anything. 1895 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()]; 1896 unsigned PathCount = BBState::OverflowOccurredValue; 1897 if (NRRBBState.GetAllPathCountWithOverflow(PathCount)) 1898 return false; 1899 assert(PathCount != BBState::OverflowOccurredValue && 1900 "PathCount at this point can not be " 1901 "OverflowOccurredValue."); 1902 OldDelta += PathCount; 1903 OldCount += PathCount; 1904 1905 // Collect the optimal insertion points. 1906 if (!KnownSafe) 1907 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) { 1908 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) { 1909 // If we overflow when we compute the path count, don't 1910 // remove/move anything. 1911 const BBState &RIPBBState = BBStates[RIP->getParent()]; 1912 1913 PathCount = BBState::OverflowOccurredValue; 1914 if (RIPBBState.GetAllPathCountWithOverflow(PathCount)) 1915 return false; 1916 assert(PathCount != BBState::OverflowOccurredValue && 1917 "PathCount at this point can not be " 1918 "OverflowOccurredValue."); 1919 NewDelta += PathCount; 1920 NewCount += PathCount; 1921 } 1922 } 1923 NewRetains.push_back(NewReleaseRetain); 1924 } 1925 } 1926 } 1927 if (NewRetains.empty()) break; 1928 } 1929 1930 // We can only remove pointers if we are known safe in both directions. 1931 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU; 1932 if (UnconditionallySafe) { 1933 RetainsToMove.ReverseInsertPts.clear(); 1934 ReleasesToMove.ReverseInsertPts.clear(); 1935 NewCount = 0; 1936 } else { 1937 // Determine whether the new insertion points we computed preserve the 1938 // balance of retain and release calls through the program. 1939 // TODO: If the fully aggressive solution isn't valid, try to find a 1940 // less aggressive solution which is. 1941 if (NewDelta != 0) 1942 return false; 1943 1944 // At this point, we are not going to remove any RR pairs, but we still are 1945 // able to move RR pairs. If one of our pointers is afflicted with 1946 // CFGHazards, we cannot perform such code motion so exit early. 1947 const bool WillPerformCodeMotion = 1948 !RetainsToMove.ReverseInsertPts.empty() || 1949 !ReleasesToMove.ReverseInsertPts.empty(); 1950 if (CFGHazardAfflicted && WillPerformCodeMotion) 1951 return false; 1952 } 1953 1954 // Determine whether the original call points are balanced in the retain and 1955 // release calls through the program. If not, conservatively don't touch 1956 // them. 1957 // TODO: It's theoretically possible to do code motion in this case, as 1958 // long as the existing imbalances are maintained. 1959 if (OldDelta != 0) 1960 return false; 1961 1962 Changed = true; 1963 assert(OldCount != 0 && "Unreachable code?"); 1964 NumRRs += OldCount - NewCount; 1965 // Set to true if we completely removed any RR pairs. 1966 AnyPairsCompletelyEliminated = NewCount == 0; 1967 1968 // We can move calls! 1969 return true; 1970 } 1971 1972 /// Identify pairings between the retains and releases, and delete and/or move 1973 /// them. 1974 bool ObjCARCOpt::PerformCodePlacement( 1975 DenseMap<const BasicBlock *, BBState> &BBStates, 1976 BlotMapVector<Value *, RRInfo> &Retains, 1977 DenseMap<Value *, RRInfo> &Releases, Module *M) { 1978 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n"); 1979 1980 bool AnyPairsCompletelyEliminated = false; 1981 SmallVector<Instruction *, 8> DeadInsts; 1982 1983 // Visit each retain. 1984 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(), 1985 E = Retains.end(); 1986 I != E; ++I) { 1987 Value *V = I->first; 1988 if (!V) continue; // blotted 1989 1990 Instruction *Retain = cast<Instruction>(V); 1991 1992 LLVM_DEBUG(dbgs() << "Visiting: " << *Retain << "\n"); 1993 1994 Value *Arg = GetArgRCIdentityRoot(Retain); 1995 1996 // If the object being released is in static or stack storage, we know it's 1997 // not being managed by ObjC reference counting, so we can delete pairs 1998 // regardless of what possible decrements or uses lie between them. 1999 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg); 2000 2001 // A constant pointer can't be pointing to an object on the heap. It may 2002 // be reference-counted, but it won't be deleted. 2003 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg)) 2004 if (const GlobalVariable *GV = 2005 dyn_cast<GlobalVariable>( 2006 GetRCIdentityRoot(LI->getPointerOperand()))) 2007 if (GV->isConstant()) 2008 KnownSafe = true; 2009 2010 // Connect the dots between the top-down-collected RetainsToMove and 2011 // bottom-up-collected ReleasesToMove to form sets of related calls. 2012 RRInfo RetainsToMove, ReleasesToMove; 2013 2014 bool PerformMoveCalls = PairUpRetainsAndReleases( 2015 BBStates, Retains, Releases, M, Retain, DeadInsts, 2016 RetainsToMove, ReleasesToMove, Arg, KnownSafe, 2017 AnyPairsCompletelyEliminated); 2018 2019 if (PerformMoveCalls) { 2020 // Ok, everything checks out and we're all set. Let's move/delete some 2021 // code! 2022 MoveCalls(Arg, RetainsToMove, ReleasesToMove, 2023 Retains, Releases, DeadInsts, M); 2024 } 2025 } 2026 2027 // Now that we're done moving everything, we can delete the newly dead 2028 // instructions, as we no longer need them as insert points. 2029 while (!DeadInsts.empty()) 2030 EraseInstruction(DeadInsts.pop_back_val()); 2031 2032 return AnyPairsCompletelyEliminated; 2033 } 2034 2035 /// Weak pointer optimizations. 2036 void ObjCARCOpt::OptimizeWeakCalls(Function &F) { 2037 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n"); 2038 2039 // First, do memdep-style RLE and S2L optimizations. We can't use memdep 2040 // itself because it uses AliasAnalysis and we need to do provenance 2041 // queries instead. 2042 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 2043 Instruction *Inst = &*I++; 2044 2045 LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n"); 2046 2047 ARCInstKind Class = GetBasicARCInstKind(Inst); 2048 if (Class != ARCInstKind::LoadWeak && 2049 Class != ARCInstKind::LoadWeakRetained) 2050 continue; 2051 2052 // Delete objc_loadWeak calls with no users. 2053 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) { 2054 Inst->eraseFromParent(); 2055 continue; 2056 } 2057 2058 // TODO: For now, just look for an earlier available version of this value 2059 // within the same block. Theoretically, we could do memdep-style non-local 2060 // analysis too, but that would want caching. A better approach would be to 2061 // use the technique that EarlyCSE uses. 2062 inst_iterator Current = std::prev(I); 2063 BasicBlock *CurrentBB = &*Current.getBasicBlockIterator(); 2064 for (BasicBlock::iterator B = CurrentBB->begin(), 2065 J = Current.getInstructionIterator(); 2066 J != B; --J) { 2067 Instruction *EarlierInst = &*std::prev(J); 2068 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst); 2069 switch (EarlierClass) { 2070 case ARCInstKind::LoadWeak: 2071 case ARCInstKind::LoadWeakRetained: { 2072 // If this is loading from the same pointer, replace this load's value 2073 // with that one. 2074 CallInst *Call = cast<CallInst>(Inst); 2075 CallInst *EarlierCall = cast<CallInst>(EarlierInst); 2076 Value *Arg = Call->getArgOperand(0); 2077 Value *EarlierArg = EarlierCall->getArgOperand(0); 2078 switch (PA.getAA()->alias(Arg, EarlierArg)) { 2079 case MustAlias: 2080 Changed = true; 2081 // If the load has a builtin retain, insert a plain retain for it. 2082 if (Class == ARCInstKind::LoadWeakRetained) { 2083 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain); 2084 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call); 2085 CI->setTailCall(); 2086 } 2087 // Zap the fully redundant load. 2088 Call->replaceAllUsesWith(EarlierCall); 2089 Call->eraseFromParent(); 2090 goto clobbered; 2091 case MayAlias: 2092 case PartialAlias: 2093 goto clobbered; 2094 case NoAlias: 2095 break; 2096 } 2097 break; 2098 } 2099 case ARCInstKind::StoreWeak: 2100 case ARCInstKind::InitWeak: { 2101 // If this is storing to the same pointer and has the same size etc. 2102 // replace this load's value with the stored value. 2103 CallInst *Call = cast<CallInst>(Inst); 2104 CallInst *EarlierCall = cast<CallInst>(EarlierInst); 2105 Value *Arg = Call->getArgOperand(0); 2106 Value *EarlierArg = EarlierCall->getArgOperand(0); 2107 switch (PA.getAA()->alias(Arg, EarlierArg)) { 2108 case MustAlias: 2109 Changed = true; 2110 // If the load has a builtin retain, insert a plain retain for it. 2111 if (Class == ARCInstKind::LoadWeakRetained) { 2112 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain); 2113 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call); 2114 CI->setTailCall(); 2115 } 2116 // Zap the fully redundant load. 2117 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1)); 2118 Call->eraseFromParent(); 2119 goto clobbered; 2120 case MayAlias: 2121 case PartialAlias: 2122 goto clobbered; 2123 case NoAlias: 2124 break; 2125 } 2126 break; 2127 } 2128 case ARCInstKind::MoveWeak: 2129 case ARCInstKind::CopyWeak: 2130 // TOOD: Grab the copied value. 2131 goto clobbered; 2132 case ARCInstKind::AutoreleasepoolPush: 2133 case ARCInstKind::None: 2134 case ARCInstKind::IntrinsicUser: 2135 case ARCInstKind::User: 2136 // Weak pointers are only modified through the weak entry points 2137 // (and arbitrary calls, which could call the weak entry points). 2138 break; 2139 default: 2140 // Anything else could modify the weak pointer. 2141 goto clobbered; 2142 } 2143 } 2144 clobbered:; 2145 } 2146 2147 // Then, for each destroyWeak with an alloca operand, check to see if 2148 // the alloca and all its users can be zapped. 2149 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 2150 Instruction *Inst = &*I++; 2151 ARCInstKind Class = GetBasicARCInstKind(Inst); 2152 if (Class != ARCInstKind::DestroyWeak) 2153 continue; 2154 2155 CallInst *Call = cast<CallInst>(Inst); 2156 Value *Arg = Call->getArgOperand(0); 2157 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) { 2158 for (User *U : Alloca->users()) { 2159 const Instruction *UserInst = cast<Instruction>(U); 2160 switch (GetBasicARCInstKind(UserInst)) { 2161 case ARCInstKind::InitWeak: 2162 case ARCInstKind::StoreWeak: 2163 case ARCInstKind::DestroyWeak: 2164 continue; 2165 default: 2166 goto done; 2167 } 2168 } 2169 Changed = true; 2170 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) { 2171 CallInst *UserInst = cast<CallInst>(*UI++); 2172 switch (GetBasicARCInstKind(UserInst)) { 2173 case ARCInstKind::InitWeak: 2174 case ARCInstKind::StoreWeak: 2175 // These functions return their second argument. 2176 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1)); 2177 break; 2178 case ARCInstKind::DestroyWeak: 2179 // No return value. 2180 break; 2181 default: 2182 llvm_unreachable("alloca really is used!"); 2183 } 2184 UserInst->eraseFromParent(); 2185 } 2186 Alloca->eraseFromParent(); 2187 done:; 2188 } 2189 } 2190 } 2191 2192 /// Identify program paths which execute sequences of retains and releases which 2193 /// can be eliminated. 2194 bool ObjCARCOpt::OptimizeSequences(Function &F) { 2195 // Releases, Retains - These are used to store the results of the main flow 2196 // analysis. These use Value* as the key instead of Instruction* so that the 2197 // map stays valid when we get around to rewriting code and calls get 2198 // replaced by arguments. 2199 DenseMap<Value *, RRInfo> Releases; 2200 BlotMapVector<Value *, RRInfo> Retains; 2201 2202 // This is used during the traversal of the function to track the 2203 // states for each identified object at each block. 2204 DenseMap<const BasicBlock *, BBState> BBStates; 2205 2206 // Analyze the CFG of the function, and all instructions. 2207 bool NestingDetected = Visit(F, BBStates, Retains, Releases); 2208 2209 if (DisableRetainReleasePairing) 2210 return false; 2211 2212 // Transform. 2213 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains, 2214 Releases, 2215 F.getParent()); 2216 2217 return AnyPairsCompletelyEliminated && NestingDetected; 2218 } 2219 2220 /// Check if there is a dependent call earlier that does not have anything in 2221 /// between the Retain and the call that can affect the reference count of their 2222 /// shared pointer argument. Note that Retain need not be in BB. 2223 static bool 2224 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain, 2225 SmallPtrSetImpl<Instruction *> &DepInsts, 2226 SmallPtrSetImpl<const BasicBlock *> &Visited, 2227 ProvenanceAnalysis &PA) { 2228 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain, 2229 DepInsts, Visited, PA); 2230 if (DepInsts.size() != 1) 2231 return false; 2232 2233 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin()); 2234 2235 // Check that the pointer is the return value of the call. 2236 if (!Call || Arg != Call) 2237 return false; 2238 2239 // Check that the call is a regular call. 2240 ARCInstKind Class = GetBasicARCInstKind(Call); 2241 return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call; 2242 } 2243 2244 /// Find a dependent retain that precedes the given autorelease for which there 2245 /// is nothing in between the two instructions that can affect the ref count of 2246 /// Arg. 2247 static CallInst * 2248 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB, 2249 Instruction *Autorelease, 2250 SmallPtrSetImpl<Instruction *> &DepInsts, 2251 SmallPtrSetImpl<const BasicBlock *> &Visited, 2252 ProvenanceAnalysis &PA) { 2253 FindDependencies(CanChangeRetainCount, Arg, 2254 BB, Autorelease, DepInsts, Visited, PA); 2255 if (DepInsts.size() != 1) 2256 return nullptr; 2257 2258 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin()); 2259 2260 // Check that we found a retain with the same argument. 2261 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) || 2262 GetArgRCIdentityRoot(Retain) != Arg) { 2263 return nullptr; 2264 } 2265 2266 return Retain; 2267 } 2268 2269 /// Look for an ``autorelease'' instruction dependent on Arg such that there are 2270 /// no instructions dependent on Arg that need a positive ref count in between 2271 /// the autorelease and the ret. 2272 static CallInst * 2273 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB, 2274 ReturnInst *Ret, 2275 SmallPtrSetImpl<Instruction *> &DepInsts, 2276 SmallPtrSetImpl<const BasicBlock *> &V, 2277 ProvenanceAnalysis &PA) { 2278 FindDependencies(NeedsPositiveRetainCount, Arg, 2279 BB, Ret, DepInsts, V, PA); 2280 if (DepInsts.size() != 1) 2281 return nullptr; 2282 2283 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin()); 2284 if (!Autorelease) 2285 return nullptr; 2286 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease); 2287 if (!IsAutorelease(AutoreleaseClass)) 2288 return nullptr; 2289 if (GetArgRCIdentityRoot(Autorelease) != Arg) 2290 return nullptr; 2291 2292 return Autorelease; 2293 } 2294 2295 /// Look for this pattern: 2296 /// \code 2297 /// %call = call i8* @something(...) 2298 /// %2 = call i8* @objc_retain(i8* %call) 2299 /// %3 = call i8* @objc_autorelease(i8* %2) 2300 /// ret i8* %3 2301 /// \endcode 2302 /// And delete the retain and autorelease. 2303 void ObjCARCOpt::OptimizeReturns(Function &F) { 2304 if (!F.getReturnType()->isPointerTy()) 2305 return; 2306 2307 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n"); 2308 2309 SmallPtrSet<Instruction *, 4> DependingInstructions; 2310 SmallPtrSet<const BasicBlock *, 4> Visited; 2311 for (BasicBlock &BB: F) { 2312 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back()); 2313 if (!Ret) 2314 continue; 2315 2316 LLVM_DEBUG(dbgs() << "Visiting: " << *Ret << "\n"); 2317 2318 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0)); 2319 2320 // Look for an ``autorelease'' instruction that is a predecessor of Ret and 2321 // dependent on Arg such that there are no instructions dependent on Arg 2322 // that need a positive ref count in between the autorelease and Ret. 2323 CallInst *Autorelease = FindPredecessorAutoreleaseWithSafePath( 2324 Arg, &BB, Ret, DependingInstructions, Visited, PA); 2325 DependingInstructions.clear(); 2326 Visited.clear(); 2327 2328 if (!Autorelease) 2329 continue; 2330 2331 CallInst *Retain = FindPredecessorRetainWithSafePath( 2332 Arg, Autorelease->getParent(), Autorelease, DependingInstructions, 2333 Visited, PA); 2334 DependingInstructions.clear(); 2335 Visited.clear(); 2336 2337 if (!Retain) 2338 continue; 2339 2340 // Check that there is nothing that can affect the reference count 2341 // between the retain and the call. Note that Retain need not be in BB. 2342 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain, 2343 DependingInstructions, 2344 Visited, PA); 2345 2346 // Don't remove retainRV/autoreleaseRV pairs if the call isn't a tail call. 2347 if (HasSafePathToCall && 2348 GetBasicARCInstKind(Retain) == ARCInstKind::RetainRV && 2349 GetBasicARCInstKind(Autorelease) == ARCInstKind::AutoreleaseRV && 2350 !cast<CallInst>(*DependingInstructions.begin())->isTailCall()) 2351 continue; 2352 2353 DependingInstructions.clear(); 2354 Visited.clear(); 2355 2356 if (!HasSafePathToCall) 2357 continue; 2358 2359 // If so, we can zap the retain and autorelease. 2360 Changed = true; 2361 ++NumRets; 2362 LLVM_DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: " << *Autorelease 2363 << "\n"); 2364 EraseInstruction(Retain); 2365 EraseInstruction(Autorelease); 2366 } 2367 } 2368 2369 #ifndef NDEBUG 2370 void 2371 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) { 2372 Statistic &NumRetains = 2373 AfterOptimization ? NumRetainsAfterOpt : NumRetainsBeforeOpt; 2374 Statistic &NumReleases = 2375 AfterOptimization ? NumReleasesAfterOpt : NumReleasesBeforeOpt; 2376 2377 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 2378 Instruction *Inst = &*I++; 2379 switch (GetBasicARCInstKind(Inst)) { 2380 default: 2381 break; 2382 case ARCInstKind::Retain: 2383 ++NumRetains; 2384 break; 2385 case ARCInstKind::Release: 2386 ++NumReleases; 2387 break; 2388 } 2389 } 2390 } 2391 #endif 2392 2393 bool ObjCARCOpt::doInitialization(Module &M) { 2394 if (!EnableARCOpts) 2395 return false; 2396 2397 // If nothing in the Module uses ARC, don't do anything. 2398 Run = ModuleHasARC(M); 2399 if (!Run) 2400 return false; 2401 2402 // Intuitively, objc_retain and others are nocapture, however in practice 2403 // they are not, because they return their argument value. And objc_release 2404 // calls finalizers which can have arbitrary side effects. 2405 MDKindCache.init(&M); 2406 2407 // Initialize our runtime entry point cache. 2408 EP.init(&M); 2409 2410 return false; 2411 } 2412 2413 bool ObjCARCOpt::runOnFunction(Function &F) { 2414 if (!EnableARCOpts) 2415 return false; 2416 2417 // If nothing in the Module uses ARC, don't do anything. 2418 if (!Run) 2419 return false; 2420 2421 Changed = false; 2422 2423 LLVM_DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() 2424 << " >>>" 2425 "\n"); 2426 2427 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults()); 2428 2429 #ifndef NDEBUG 2430 if (AreStatisticsEnabled()) { 2431 GatherStatistics(F, false); 2432 } 2433 #endif 2434 2435 // This pass performs several distinct transformations. As a compile-time aid 2436 // when compiling code that isn't ObjC, skip these if the relevant ObjC 2437 // library functions aren't declared. 2438 2439 // Preliminary optimizations. This also computes UsedInThisFunction. 2440 OptimizeIndividualCalls(F); 2441 2442 // Optimizations for weak pointers. 2443 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) | 2444 (1 << unsigned(ARCInstKind::LoadWeakRetained)) | 2445 (1 << unsigned(ARCInstKind::StoreWeak)) | 2446 (1 << unsigned(ARCInstKind::InitWeak)) | 2447 (1 << unsigned(ARCInstKind::CopyWeak)) | 2448 (1 << unsigned(ARCInstKind::MoveWeak)) | 2449 (1 << unsigned(ARCInstKind::DestroyWeak)))) 2450 OptimizeWeakCalls(F); 2451 2452 // Optimizations for retain+release pairs. 2453 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) | 2454 (1 << unsigned(ARCInstKind::RetainRV)) | 2455 (1 << unsigned(ARCInstKind::RetainBlock)))) 2456 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release))) 2457 // Run OptimizeSequences until it either stops making changes or 2458 // no retain+release pair nesting is detected. 2459 while (OptimizeSequences(F)) {} 2460 2461 // Optimizations if objc_autorelease is used. 2462 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) | 2463 (1 << unsigned(ARCInstKind::AutoreleaseRV)))) 2464 OptimizeReturns(F); 2465 2466 // Gather statistics after optimization. 2467 #ifndef NDEBUG 2468 if (AreStatisticsEnabled()) { 2469 GatherStatistics(F, true); 2470 } 2471 #endif 2472 2473 LLVM_DEBUG(dbgs() << "\n"); 2474 2475 return Changed; 2476 } 2477 2478 void ObjCARCOpt::releaseMemory() { 2479 PA.clear(); 2480 } 2481 2482 /// @} 2483 /// 2484