109467b48Spatrick //===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick /// \file
909467b48Spatrick /// This file defines late ObjC ARC optimizations. ARC stands for Automatic
1009467b48Spatrick /// Reference Counting and is a system for managing reference counts for objects
1109467b48Spatrick /// in Objective C.
1209467b48Spatrick ///
1309467b48Spatrick /// This specific file mainly deals with ``contracting'' multiple lower level
1409467b48Spatrick /// operations into singular higher level operations through pattern matching.
1509467b48Spatrick ///
1609467b48Spatrick /// WARNING: This file knows about certain library functions. It recognizes them
1709467b48Spatrick /// by name, and hardwires knowledge of their semantics.
1809467b48Spatrick ///
1909467b48Spatrick /// WARNING: This file knows about how certain Objective-C library functions are
2009467b48Spatrick /// used. Naive LLVM IR transformations which would otherwise be
2109467b48Spatrick /// behavior-preserving may break these assumptions.
2209467b48Spatrick ///
2309467b48Spatrick //===----------------------------------------------------------------------===//
2409467b48Spatrick
2509467b48Spatrick // TODO: ObjCARCContract could insert PHI nodes when uses aren't
2609467b48Spatrick // dominated by single calls.
2709467b48Spatrick
2809467b48Spatrick #include "ARCRuntimeEntryPoints.h"
2909467b48Spatrick #include "DependencyAnalysis.h"
3009467b48Spatrick #include "ObjCARC.h"
3109467b48Spatrick #include "ProvenanceAnalysis.h"
3209467b48Spatrick #include "llvm/ADT/Statistic.h"
3373471bf0Spatrick #include "llvm/Analysis/AliasAnalysis.h"
3409467b48Spatrick #include "llvm/Analysis/EHPersonalities.h"
3573471bf0Spatrick #include "llvm/Analysis/ObjCARCUtil.h"
3609467b48Spatrick #include "llvm/IR/Dominators.h"
3709467b48Spatrick #include "llvm/IR/InlineAsm.h"
38097a140dSpatrick #include "llvm/IR/InstIterator.h"
3909467b48Spatrick #include "llvm/IR/Operator.h"
4073471bf0Spatrick #include "llvm/IR/PassManager.h"
4109467b48Spatrick #include "llvm/InitializePasses.h"
4209467b48Spatrick #include "llvm/Support/CommandLine.h"
4309467b48Spatrick #include "llvm/Support/Debug.h"
4409467b48Spatrick #include "llvm/Support/raw_ostream.h"
4573471bf0Spatrick #include "llvm/Transforms/ObjCARC.h"
4609467b48Spatrick
4709467b48Spatrick using namespace llvm;
4809467b48Spatrick using namespace llvm::objcarc;
4909467b48Spatrick
5009467b48Spatrick #define DEBUG_TYPE "objc-arc-contract"
5109467b48Spatrick
5209467b48Spatrick STATISTIC(NumPeeps, "Number of calls peephole-optimized");
5309467b48Spatrick STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
5409467b48Spatrick
5509467b48Spatrick //===----------------------------------------------------------------------===//
5609467b48Spatrick // Declarations
5709467b48Spatrick //===----------------------------------------------------------------------===//
5809467b48Spatrick
5909467b48Spatrick namespace {
6009467b48Spatrick /// Late ARC optimizations
6109467b48Spatrick ///
6209467b48Spatrick /// These change the IR in a way that makes it difficult to be analyzed by
6309467b48Spatrick /// ObjCARCOpt, so it's run late.
6473471bf0Spatrick
6573471bf0Spatrick class ObjCARCContract {
6609467b48Spatrick bool Changed;
6773471bf0Spatrick bool CFGChanged;
6873471bf0Spatrick AAResults *AA;
6909467b48Spatrick DominatorTree *DT;
7009467b48Spatrick ProvenanceAnalysis PA;
7109467b48Spatrick ARCRuntimeEntryPoints EP;
7273471bf0Spatrick BundledRetainClaimRVs *BundledInsts = nullptr;
7309467b48Spatrick
7409467b48Spatrick /// The inline asm string to insert between calls and RetainRV calls to make
7509467b48Spatrick /// the optimization work on targets which need it.
7609467b48Spatrick const MDString *RVInstMarker;
7709467b48Spatrick
7809467b48Spatrick /// The set of inserted objc_storeStrong calls. If at the end of walking the
7909467b48Spatrick /// function we have found no alloca instructions, these calls can be marked
8009467b48Spatrick /// "tail".
8109467b48Spatrick SmallPtrSet<CallInst *, 8> StoreStrongCalls;
8209467b48Spatrick
8309467b48Spatrick /// Returns true if we eliminated Inst.
8409467b48Spatrick bool tryToPeepholeInstruction(
8509467b48Spatrick Function &F, Instruction *Inst, inst_iterator &Iter,
8609467b48Spatrick bool &TailOkForStoreStrong,
8709467b48Spatrick const DenseMap<BasicBlock *, ColorVector> &BlockColors);
8809467b48Spatrick
8909467b48Spatrick bool optimizeRetainCall(Function &F, Instruction *Retain);
9009467b48Spatrick
9173471bf0Spatrick bool contractAutorelease(Function &F, Instruction *Autorelease,
9273471bf0Spatrick ARCInstKind Class);
9309467b48Spatrick
9409467b48Spatrick void tryToContractReleaseIntoStoreStrong(
9509467b48Spatrick Instruction *Release, inst_iterator &Iter,
9609467b48Spatrick const DenseMap<BasicBlock *, ColorVector> &BlockColors);
9709467b48Spatrick
9873471bf0Spatrick public:
9973471bf0Spatrick bool init(Module &M);
10073471bf0Spatrick bool run(Function &F, AAResults *AA, DominatorTree *DT);
hasCFGChanged() const10173471bf0Spatrick bool hasCFGChanged() const { return CFGChanged; }
10273471bf0Spatrick };
10373471bf0Spatrick
10473471bf0Spatrick class ObjCARCContractLegacyPass : public FunctionPass {
10573471bf0Spatrick public:
10609467b48Spatrick void getAnalysisUsage(AnalysisUsage &AU) const override;
10709467b48Spatrick bool runOnFunction(Function &F) override;
10809467b48Spatrick
10909467b48Spatrick static char ID;
ObjCARCContractLegacyPass()11073471bf0Spatrick ObjCARCContractLegacyPass() : FunctionPass(ID) {
11173471bf0Spatrick initializeObjCARCContractLegacyPassPass(*PassRegistry::getPassRegistry());
11209467b48Spatrick }
11309467b48Spatrick };
11409467b48Spatrick }
11509467b48Spatrick
11609467b48Spatrick //===----------------------------------------------------------------------===//
11709467b48Spatrick // Implementation
11809467b48Spatrick //===----------------------------------------------------------------------===//
11909467b48Spatrick
12009467b48Spatrick /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
12109467b48Spatrick /// return value. We do this late so we do not disrupt the dataflow analysis in
12209467b48Spatrick /// ObjCARCOpt.
optimizeRetainCall(Function & F,Instruction * Retain)12309467b48Spatrick bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
124097a140dSpatrick const auto *Call = dyn_cast<CallBase>(GetArgRCIdentityRoot(Retain));
12509467b48Spatrick if (!Call)
12609467b48Spatrick return false;
12709467b48Spatrick if (Call->getParent() != Retain->getParent())
12809467b48Spatrick return false;
12909467b48Spatrick
13009467b48Spatrick // Check that the call is next to the retain.
13109467b48Spatrick BasicBlock::const_iterator I = ++Call->getIterator();
13209467b48Spatrick while (IsNoopInstruction(&*I))
13309467b48Spatrick ++I;
13409467b48Spatrick if (&*I != Retain)
13509467b48Spatrick return false;
13609467b48Spatrick
13709467b48Spatrick // Turn it to an objc_retainAutoreleasedReturnValue.
13809467b48Spatrick Changed = true;
13909467b48Spatrick ++NumPeeps;
14009467b48Spatrick
14109467b48Spatrick LLVM_DEBUG(
14209467b48Spatrick dbgs() << "Transforming objc_retain => "
14309467b48Spatrick "objc_retainAutoreleasedReturnValue since the operand is a "
14409467b48Spatrick "return value.\nOld: "
14509467b48Spatrick << *Retain << "\n");
14609467b48Spatrick
14709467b48Spatrick // We do not have to worry about tail calls/does not throw since
14809467b48Spatrick // retain/retainRV have the same properties.
14909467b48Spatrick Function *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
15009467b48Spatrick cast<CallInst>(Retain)->setCalledFunction(Decl);
15109467b48Spatrick
15209467b48Spatrick LLVM_DEBUG(dbgs() << "New: " << *Retain << "\n");
15309467b48Spatrick return true;
15409467b48Spatrick }
15509467b48Spatrick
15609467b48Spatrick /// Merge an autorelease with a retain into a fused call.
contractAutorelease(Function & F,Instruction * Autorelease,ARCInstKind Class)15773471bf0Spatrick bool ObjCARCContract::contractAutorelease(Function &F, Instruction *Autorelease,
15873471bf0Spatrick ARCInstKind Class) {
15909467b48Spatrick const Value *Arg = GetArgRCIdentityRoot(Autorelease);
16009467b48Spatrick
16109467b48Spatrick // Check that there are no instructions between the retain and the autorelease
16209467b48Spatrick // (such as an autorelease_pop) which may change the count.
16373471bf0Spatrick DependenceKind DK = Class == ARCInstKind::AutoreleaseRV
16473471bf0Spatrick ? RetainAutoreleaseRVDep
16573471bf0Spatrick : RetainAutoreleaseDep;
16673471bf0Spatrick auto *Retain = dyn_cast_or_null<CallInst>(
16773471bf0Spatrick findSingleDependency(DK, Arg, Autorelease->getParent(), Autorelease, PA));
16809467b48Spatrick
16909467b48Spatrick if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
17009467b48Spatrick GetArgRCIdentityRoot(Retain) != Arg)
17109467b48Spatrick return false;
17209467b48Spatrick
17309467b48Spatrick Changed = true;
17409467b48Spatrick ++NumPeeps;
17509467b48Spatrick
17609467b48Spatrick LLVM_DEBUG(dbgs() << " Fusing retain/autorelease!\n"
17709467b48Spatrick " Autorelease:"
17809467b48Spatrick << *Autorelease
17909467b48Spatrick << "\n"
18009467b48Spatrick " Retain: "
18109467b48Spatrick << *Retain << "\n");
18209467b48Spatrick
18309467b48Spatrick Function *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
18409467b48Spatrick ? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
18509467b48Spatrick : ARCRuntimeEntryPointKind::RetainAutorelease);
18609467b48Spatrick Retain->setCalledFunction(Decl);
18709467b48Spatrick
18809467b48Spatrick LLVM_DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
18909467b48Spatrick
19009467b48Spatrick EraseInstruction(Autorelease);
19109467b48Spatrick return true;
19209467b48Spatrick }
19309467b48Spatrick
findSafeStoreForStoreStrongContraction(LoadInst * Load,Instruction * Release,ProvenanceAnalysis & PA,AAResults * AA)19409467b48Spatrick static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
19509467b48Spatrick Instruction *Release,
19609467b48Spatrick ProvenanceAnalysis &PA,
19773471bf0Spatrick AAResults *AA) {
19809467b48Spatrick StoreInst *Store = nullptr;
19909467b48Spatrick bool SawRelease = false;
20009467b48Spatrick
20109467b48Spatrick // Get the location associated with Load.
20209467b48Spatrick MemoryLocation Loc = MemoryLocation::get(Load);
20309467b48Spatrick auto *LocPtr = Loc.Ptr->stripPointerCasts();
20409467b48Spatrick
20509467b48Spatrick // Walk down to find the store and the release, which may be in either order.
20609467b48Spatrick for (auto I = std::next(BasicBlock::iterator(Load)),
20709467b48Spatrick E = Load->getParent()->end();
20809467b48Spatrick I != E; ++I) {
20909467b48Spatrick // If we found the store we were looking for and saw the release,
21009467b48Spatrick // break. There is no more work to be done.
21109467b48Spatrick if (Store && SawRelease)
21209467b48Spatrick break;
21309467b48Spatrick
21409467b48Spatrick // Now we know that we have not seen either the store or the release. If I
21509467b48Spatrick // is the release, mark that we saw the release and continue.
21609467b48Spatrick Instruction *Inst = &*I;
21709467b48Spatrick if (Inst == Release) {
21809467b48Spatrick SawRelease = true;
21909467b48Spatrick continue;
22009467b48Spatrick }
22109467b48Spatrick
22209467b48Spatrick // Otherwise, we check if Inst is a "good" store. Grab the instruction class
22309467b48Spatrick // of Inst.
22409467b48Spatrick ARCInstKind Class = GetBasicARCInstKind(Inst);
22509467b48Spatrick
22609467b48Spatrick // If we have seen the store, but not the release...
22709467b48Spatrick if (Store) {
22809467b48Spatrick // We need to make sure that it is safe to move the release from its
22909467b48Spatrick // current position to the store. This implies proving that any
23009467b48Spatrick // instruction in between Store and the Release conservatively can not use
23109467b48Spatrick // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
23209467b48Spatrick // continue...
23309467b48Spatrick if (!CanUse(Inst, Load, PA, Class)) {
23409467b48Spatrick continue;
23509467b48Spatrick }
23609467b48Spatrick
23709467b48Spatrick // Otherwise, be conservative and return nullptr.
23809467b48Spatrick return nullptr;
23909467b48Spatrick }
24009467b48Spatrick
241*d415bd75Srobert // Ok, now we know we have not seen a store yet.
242*d415bd75Srobert
243*d415bd75Srobert // If Inst is a retain, we don't care about it as it doesn't prevent moving
244*d415bd75Srobert // the load to the store.
245*d415bd75Srobert //
246*d415bd75Srobert // TODO: This is one area where the optimization could be made more
247*d415bd75Srobert // aggressive.
248*d415bd75Srobert if (IsRetain(Class))
249*d415bd75Srobert continue;
250*d415bd75Srobert
251*d415bd75Srobert // See if Inst can write to our load location, if it can not, just ignore
252*d415bd75Srobert // the instruction.
25309467b48Spatrick if (!isModSet(AA->getModRefInfo(Inst, Loc)))
25409467b48Spatrick continue;
25509467b48Spatrick
25609467b48Spatrick Store = dyn_cast<StoreInst>(Inst);
25709467b48Spatrick
25809467b48Spatrick // If Inst can, then check if Inst is a simple store. If Inst is not a
25909467b48Spatrick // store or a store that is not simple, then we have some we do not
26009467b48Spatrick // understand writing to this memory implying we can not move the load
26109467b48Spatrick // over the write to any subsequent store that we may find.
26209467b48Spatrick if (!Store || !Store->isSimple())
26309467b48Spatrick return nullptr;
26409467b48Spatrick
26509467b48Spatrick // Then make sure that the pointer we are storing to is Ptr. If so, we
26609467b48Spatrick // found our Store!
26709467b48Spatrick if (Store->getPointerOperand()->stripPointerCasts() == LocPtr)
26809467b48Spatrick continue;
26909467b48Spatrick
27009467b48Spatrick // Otherwise, we have an unknown store to some other ptr that clobbers
27109467b48Spatrick // Loc.Ptr. Bail!
27209467b48Spatrick return nullptr;
27309467b48Spatrick }
27409467b48Spatrick
27509467b48Spatrick // If we did not find the store or did not see the release, fail.
27609467b48Spatrick if (!Store || !SawRelease)
27709467b48Spatrick return nullptr;
27809467b48Spatrick
27909467b48Spatrick // We succeeded!
28009467b48Spatrick return Store;
28109467b48Spatrick }
28209467b48Spatrick
28309467b48Spatrick static Instruction *
findRetainForStoreStrongContraction(Value * New,StoreInst * Store,Instruction * Release,ProvenanceAnalysis & PA)28409467b48Spatrick findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
28509467b48Spatrick Instruction *Release,
28609467b48Spatrick ProvenanceAnalysis &PA) {
28709467b48Spatrick // Walk up from the Store to find the retain.
28809467b48Spatrick BasicBlock::iterator I = Store->getIterator();
28909467b48Spatrick BasicBlock::iterator Begin = Store->getParent()->begin();
29009467b48Spatrick while (I != Begin && GetBasicARCInstKind(&*I) != ARCInstKind::Retain) {
29109467b48Spatrick Instruction *Inst = &*I;
29209467b48Spatrick
29309467b48Spatrick // It is only safe to move the retain to the store if we can prove
29409467b48Spatrick // conservatively that nothing besides the release can decrement reference
29509467b48Spatrick // counts in between the retain and the store.
29609467b48Spatrick if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
29709467b48Spatrick return nullptr;
29809467b48Spatrick --I;
29909467b48Spatrick }
30009467b48Spatrick Instruction *Retain = &*I;
30109467b48Spatrick if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
30209467b48Spatrick return nullptr;
30309467b48Spatrick if (GetArgRCIdentityRoot(Retain) != New)
30409467b48Spatrick return nullptr;
30509467b48Spatrick return Retain;
30609467b48Spatrick }
30709467b48Spatrick
30809467b48Spatrick /// Attempt to merge an objc_release with a store, load, and objc_retain to form
30909467b48Spatrick /// an objc_storeStrong. An objc_storeStrong:
31009467b48Spatrick ///
31109467b48Spatrick /// objc_storeStrong(i8** %old_ptr, i8* new_value)
31209467b48Spatrick ///
31309467b48Spatrick /// is equivalent to the following IR sequence:
31409467b48Spatrick ///
31509467b48Spatrick /// ; Load old value.
31609467b48Spatrick /// %old_value = load i8** %old_ptr (1)
31709467b48Spatrick ///
31809467b48Spatrick /// ; Increment the new value and then release the old value. This must occur
31909467b48Spatrick /// ; in order in case old_value releases new_value in its destructor causing
32009467b48Spatrick /// ; us to potentially have a dangling ptr.
32109467b48Spatrick /// tail call i8* @objc_retain(i8* %new_value) (2)
32209467b48Spatrick /// tail call void @objc_release(i8* %old_value) (3)
32309467b48Spatrick ///
32409467b48Spatrick /// ; Store the new_value into old_ptr
32509467b48Spatrick /// store i8* %new_value, i8** %old_ptr (4)
32609467b48Spatrick ///
32709467b48Spatrick /// The safety of this optimization is based around the following
32809467b48Spatrick /// considerations:
32909467b48Spatrick ///
33009467b48Spatrick /// 1. We are forming the store strong at the store. Thus to perform this
33109467b48Spatrick /// optimization it must be safe to move the retain, load, and release to
33209467b48Spatrick /// (4).
33309467b48Spatrick /// 2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
33409467b48Spatrick /// safe.
tryToContractReleaseIntoStoreStrong(Instruction * Release,inst_iterator & Iter,const DenseMap<BasicBlock *,ColorVector> & BlockColors)33509467b48Spatrick void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
33609467b48Spatrick Instruction *Release, inst_iterator &Iter,
33709467b48Spatrick const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
33809467b48Spatrick // See if we are releasing something that we just loaded.
33909467b48Spatrick auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
34009467b48Spatrick if (!Load || !Load->isSimple())
34109467b48Spatrick return;
34209467b48Spatrick
34309467b48Spatrick // For now, require everything to be in one basic block.
34409467b48Spatrick BasicBlock *BB = Release->getParent();
34509467b48Spatrick if (Load->getParent() != BB)
34609467b48Spatrick return;
34709467b48Spatrick
34809467b48Spatrick // First scan down the BB from Load, looking for a store of the RCIdentityRoot
34909467b48Spatrick // of Load's
35009467b48Spatrick StoreInst *Store =
35109467b48Spatrick findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
35209467b48Spatrick // If we fail, bail.
35309467b48Spatrick if (!Store)
35409467b48Spatrick return;
35509467b48Spatrick
35609467b48Spatrick // Then find what new_value's RCIdentity Root is.
35709467b48Spatrick Value *New = GetRCIdentityRoot(Store->getValueOperand());
35809467b48Spatrick
35909467b48Spatrick // Then walk up the BB and look for a retain on New without any intervening
36009467b48Spatrick // instructions which conservatively might decrement ref counts.
36109467b48Spatrick Instruction *Retain =
36209467b48Spatrick findRetainForStoreStrongContraction(New, Store, Release, PA);
36309467b48Spatrick
36409467b48Spatrick // If we fail, bail.
36509467b48Spatrick if (!Retain)
36609467b48Spatrick return;
36709467b48Spatrick
36809467b48Spatrick Changed = true;
36909467b48Spatrick ++NumStoreStrongs;
37009467b48Spatrick
37109467b48Spatrick LLVM_DEBUG(
37209467b48Spatrick llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
37309467b48Spatrick << " Old:\n"
37409467b48Spatrick << " Store: " << *Store << "\n"
37509467b48Spatrick << " Release: " << *Release << "\n"
37609467b48Spatrick << " Retain: " << *Retain << "\n"
37709467b48Spatrick << " Load: " << *Load << "\n");
37809467b48Spatrick
37909467b48Spatrick LLVMContext &C = Release->getContext();
38009467b48Spatrick Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
38109467b48Spatrick Type *I8XX = PointerType::getUnqual(I8X);
38209467b48Spatrick
38309467b48Spatrick Value *Args[] = { Load->getPointerOperand(), New };
38409467b48Spatrick if (Args[0]->getType() != I8XX)
38509467b48Spatrick Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
38609467b48Spatrick if (Args[1]->getType() != I8X)
38709467b48Spatrick Args[1] = new BitCastInst(Args[1], I8X, "", Store);
38809467b48Spatrick Function *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
38973471bf0Spatrick CallInst *StoreStrong =
39073471bf0Spatrick objcarc::createCallInstWithColors(Decl, Args, "", Store, BlockColors);
39109467b48Spatrick StoreStrong->setDoesNotThrow();
39209467b48Spatrick StoreStrong->setDebugLoc(Store->getDebugLoc());
39309467b48Spatrick
39409467b48Spatrick // We can't set the tail flag yet, because we haven't yet determined
39509467b48Spatrick // whether there are any escaping allocas. Remember this call, so that
39609467b48Spatrick // we can set the tail flag once we know it's safe.
39709467b48Spatrick StoreStrongCalls.insert(StoreStrong);
39809467b48Spatrick
39909467b48Spatrick LLVM_DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong
40009467b48Spatrick << "\n");
40109467b48Spatrick
40209467b48Spatrick if (&*Iter == Retain) ++Iter;
40309467b48Spatrick if (&*Iter == Store) ++Iter;
40409467b48Spatrick Store->eraseFromParent();
40509467b48Spatrick Release->eraseFromParent();
40609467b48Spatrick EraseInstruction(Retain);
40709467b48Spatrick if (Load->use_empty())
40809467b48Spatrick Load->eraseFromParent();
40909467b48Spatrick }
41009467b48Spatrick
tryToPeepholeInstruction(Function & F,Instruction * Inst,inst_iterator & Iter,bool & TailOkForStoreStrongs,const DenseMap<BasicBlock *,ColorVector> & BlockColors)41109467b48Spatrick bool ObjCARCContract::tryToPeepholeInstruction(
41209467b48Spatrick Function &F, Instruction *Inst, inst_iterator &Iter,
41373471bf0Spatrick bool &TailOkForStoreStrongs,
41409467b48Spatrick const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
41509467b48Spatrick // Only these library routines return their argument. In particular,
41609467b48Spatrick // objc_retainBlock does not necessarily return its argument.
41709467b48Spatrick ARCInstKind Class = GetBasicARCInstKind(Inst);
41809467b48Spatrick switch (Class) {
41909467b48Spatrick case ARCInstKind::FusedRetainAutorelease:
42009467b48Spatrick case ARCInstKind::FusedRetainAutoreleaseRV:
42109467b48Spatrick return false;
42209467b48Spatrick case ARCInstKind::Autorelease:
42309467b48Spatrick case ARCInstKind::AutoreleaseRV:
42473471bf0Spatrick return contractAutorelease(F, Inst, Class);
42509467b48Spatrick case ARCInstKind::Retain:
42609467b48Spatrick // Attempt to convert retains to retainrvs if they are next to function
42709467b48Spatrick // calls.
42809467b48Spatrick if (!optimizeRetainCall(F, Inst))
42909467b48Spatrick return false;
43009467b48Spatrick // If we succeed in our optimization, fall through.
431*d415bd75Srobert [[fallthrough]];
43209467b48Spatrick case ARCInstKind::RetainRV:
433*d415bd75Srobert case ARCInstKind::UnsafeClaimRV: {
434*d415bd75Srobert // Return true if this is a bundled retainRV/claimRV call, which is always
435*d415bd75Srobert // redundant with the attachedcall in the bundle, and is going to be erased
436*d415bd75Srobert // at the end of this pass. This avoids undoing objc-arc-expand and
437*d415bd75Srobert // replacing uses of the retainRV/claimRV call's argument with its result.
438*d415bd75Srobert if (BundledInsts->contains(Inst))
439*d415bd75Srobert return true;
440*d415bd75Srobert
441*d415bd75Srobert // If this isn't a bundled call, and the target doesn't need a special
442*d415bd75Srobert // inline-asm marker, we're done: return now, and undo objc-arc-expand.
44309467b48Spatrick if (!RVInstMarker)
44409467b48Spatrick return false;
44573471bf0Spatrick
446*d415bd75Srobert // The target needs a special inline-asm marker. Insert it.
44773471bf0Spatrick
44809467b48Spatrick BasicBlock::iterator BBI = Inst->getIterator();
44909467b48Spatrick BasicBlock *InstParent = Inst->getParent();
45009467b48Spatrick
45109467b48Spatrick // Step up to see if the call immediately precedes the RV call.
45209467b48Spatrick // If it's an invoke, we have to cross a block boundary. And we have
45309467b48Spatrick // to carefully dodge no-op instructions.
45409467b48Spatrick do {
45509467b48Spatrick if (BBI == InstParent->begin()) {
45609467b48Spatrick BasicBlock *Pred = InstParent->getSinglePredecessor();
45709467b48Spatrick if (!Pred)
45809467b48Spatrick goto decline_rv_optimization;
45909467b48Spatrick BBI = Pred->getTerminator()->getIterator();
46009467b48Spatrick break;
46109467b48Spatrick }
46209467b48Spatrick --BBI;
46309467b48Spatrick } while (IsNoopInstruction(&*BBI));
46409467b48Spatrick
46573471bf0Spatrick if (GetRCIdentityRoot(&*BBI) == GetArgRCIdentityRoot(Inst)) {
46609467b48Spatrick LLVM_DEBUG(dbgs() << "Adding inline asm marker for the return value "
46709467b48Spatrick "optimization.\n");
46809467b48Spatrick Changed = true;
46909467b48Spatrick InlineAsm *IA =
47009467b48Spatrick InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
47109467b48Spatrick /*isVarArg=*/false),
47209467b48Spatrick RVInstMarker->getString(),
47309467b48Spatrick /*Constraints=*/"", /*hasSideEffects=*/true);
47409467b48Spatrick
475*d415bd75Srobert objcarc::createCallInstWithColors(IA, std::nullopt, "", Inst,
476*d415bd75Srobert BlockColors);
47709467b48Spatrick }
47809467b48Spatrick decline_rv_optimization:
47909467b48Spatrick return false;
48009467b48Spatrick }
48109467b48Spatrick case ARCInstKind::InitWeak: {
48209467b48Spatrick // objc_initWeak(p, null) => *p = null
48309467b48Spatrick CallInst *CI = cast<CallInst>(Inst);
48409467b48Spatrick if (IsNullOrUndef(CI->getArgOperand(1))) {
48509467b48Spatrick Value *Null = ConstantPointerNull::get(cast<PointerType>(CI->getType()));
48609467b48Spatrick Changed = true;
48709467b48Spatrick new StoreInst(Null, CI->getArgOperand(0), CI);
48809467b48Spatrick
48909467b48Spatrick LLVM_DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
49009467b48Spatrick << " New = " << *Null << "\n");
49109467b48Spatrick
49209467b48Spatrick CI->replaceAllUsesWith(Null);
49309467b48Spatrick CI->eraseFromParent();
49409467b48Spatrick }
49509467b48Spatrick return true;
49609467b48Spatrick }
49709467b48Spatrick case ARCInstKind::Release:
49809467b48Spatrick // Try to form an objc store strong from our release. If we fail, there is
49909467b48Spatrick // nothing further to do below, so continue.
50009467b48Spatrick tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
50109467b48Spatrick return true;
50209467b48Spatrick case ARCInstKind::User:
50309467b48Spatrick // Be conservative if the function has any alloca instructions.
50409467b48Spatrick // Technically we only care about escaping alloca instructions,
50509467b48Spatrick // but this is sufficient to handle some interesting cases.
50609467b48Spatrick if (isa<AllocaInst>(Inst))
50709467b48Spatrick TailOkForStoreStrongs = false;
50809467b48Spatrick return true;
50909467b48Spatrick case ARCInstKind::IntrinsicUser:
51009467b48Spatrick // Remove calls to @llvm.objc.clang.arc.use(...).
511097a140dSpatrick Changed = true;
51209467b48Spatrick Inst->eraseFromParent();
51309467b48Spatrick return true;
51409467b48Spatrick default:
51573471bf0Spatrick if (auto *CI = dyn_cast<CallInst>(Inst))
51673471bf0Spatrick if (CI->getIntrinsicID() == Intrinsic::objc_clang_arc_noop_use) {
51773471bf0Spatrick // Remove calls to @llvm.objc.clang.arc.noop.use(...).
51873471bf0Spatrick Changed = true;
51973471bf0Spatrick CI->eraseFromParent();
52073471bf0Spatrick }
52109467b48Spatrick return true;
52209467b48Spatrick }
52309467b48Spatrick }
52409467b48Spatrick
52509467b48Spatrick //===----------------------------------------------------------------------===//
52609467b48Spatrick // Top Level Driver
52709467b48Spatrick //===----------------------------------------------------------------------===//
52809467b48Spatrick
init(Module & M)52973471bf0Spatrick bool ObjCARCContract::init(Module &M) {
53073471bf0Spatrick EP.init(&M);
53173471bf0Spatrick
53273471bf0Spatrick // Initialize RVInstMarker.
53373471bf0Spatrick RVInstMarker = getRVInstMarker(M);
53473471bf0Spatrick
53573471bf0Spatrick return false;
53673471bf0Spatrick }
53773471bf0Spatrick
run(Function & F,AAResults * A,DominatorTree * D)53873471bf0Spatrick bool ObjCARCContract::run(Function &F, AAResults *A, DominatorTree *D) {
53909467b48Spatrick if (!EnableARCOpts)
54009467b48Spatrick return false;
54109467b48Spatrick
54273471bf0Spatrick Changed = CFGChanged = false;
54373471bf0Spatrick AA = A;
54473471bf0Spatrick DT = D;
54573471bf0Spatrick PA.setAA(A);
546*d415bd75Srobert BundledRetainClaimRVs BRV(/*ContractPass=*/true);
54773471bf0Spatrick BundledInsts = &BRV;
54809467b48Spatrick
54973471bf0Spatrick std::pair<bool, bool> R = BundledInsts->insertAfterInvokes(F, DT);
55073471bf0Spatrick Changed |= R.first;
55173471bf0Spatrick CFGChanged |= R.second;
55209467b48Spatrick
55309467b48Spatrick DenseMap<BasicBlock *, ColorVector> BlockColors;
55409467b48Spatrick if (F.hasPersonalityFn() &&
55509467b48Spatrick isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
55609467b48Spatrick BlockColors = colorEHFunclets(F);
55709467b48Spatrick
55809467b48Spatrick LLVM_DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
55909467b48Spatrick
56009467b48Spatrick // Track whether it's ok to mark objc_storeStrong calls with the "tail"
56109467b48Spatrick // keyword. Be conservative if the function has variadic arguments.
56209467b48Spatrick // It seems that functions which "return twice" are also unsafe for the
56309467b48Spatrick // "tail" argument, because they are setjmp, which could need to
56409467b48Spatrick // return to an earlier stack state.
56509467b48Spatrick bool TailOkForStoreStrongs =
56609467b48Spatrick !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
56709467b48Spatrick
56809467b48Spatrick // For ObjC library calls which return their argument, replace uses of the
56909467b48Spatrick // argument with uses of the call return value, if it dominates the use. This
57009467b48Spatrick // reduces register pressure.
57109467b48Spatrick for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
57209467b48Spatrick Instruction *Inst = &*I++;
57309467b48Spatrick
57409467b48Spatrick LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
57509467b48Spatrick
57673471bf0Spatrick if (auto *CI = dyn_cast<CallInst>(Inst))
57773471bf0Spatrick if (objcarc::hasAttachedCallOpBundle(CI)) {
57873471bf0Spatrick BundledInsts->insertRVCallWithColors(&*I, CI, BlockColors);
57973471bf0Spatrick --I;
58073471bf0Spatrick Changed = true;
58173471bf0Spatrick }
58273471bf0Spatrick
58309467b48Spatrick // First try to peephole Inst. If there is nothing further we can do in
58409467b48Spatrick // terms of undoing objc-arc-expand, process the next inst.
58573471bf0Spatrick if (tryToPeepholeInstruction(F, Inst, I, TailOkForStoreStrongs,
58673471bf0Spatrick BlockColors))
58709467b48Spatrick continue;
58809467b48Spatrick
58909467b48Spatrick // Otherwise, try to undo objc-arc-expand.
59009467b48Spatrick
59109467b48Spatrick // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
59209467b48Spatrick // and such; to do the replacement, the argument must have type i8*.
59309467b48Spatrick
59409467b48Spatrick // Function for replacing uses of Arg dominated by Inst.
595097a140dSpatrick auto ReplaceArgUses = [Inst, this](Value *Arg) {
59609467b48Spatrick // If we're compiling bugpointed code, don't get in trouble.
59709467b48Spatrick if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
59809467b48Spatrick return;
59909467b48Spatrick
60009467b48Spatrick // Look through the uses of the pointer.
60109467b48Spatrick for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
60209467b48Spatrick UI != UE; ) {
60309467b48Spatrick // Increment UI now, because we may unlink its element.
60409467b48Spatrick Use &U = *UI++;
60509467b48Spatrick unsigned OperandNo = U.getOperandNo();
60609467b48Spatrick
60709467b48Spatrick // If the call's return value dominates a use of the call's argument
60809467b48Spatrick // value, rewrite the use to use the return value. We check for
60909467b48Spatrick // reachability here because an unreachable call is considered to
61009467b48Spatrick // trivially dominate itself, which would lead us to rewriting its
61109467b48Spatrick // argument in terms of its return value, which would lead to
61209467b48Spatrick // infinite loops in GetArgRCIdentityRoot.
61309467b48Spatrick if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
61409467b48Spatrick continue;
61509467b48Spatrick
61609467b48Spatrick Changed = true;
61709467b48Spatrick Instruction *Replacement = Inst;
61809467b48Spatrick Type *UseTy = U.get()->getType();
61909467b48Spatrick if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
62009467b48Spatrick // For PHI nodes, insert the bitcast in the predecessor block.
62109467b48Spatrick unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
62209467b48Spatrick BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
62309467b48Spatrick if (Replacement->getType() != UseTy) {
62409467b48Spatrick // A catchswitch is both a pad and a terminator, meaning a basic
62509467b48Spatrick // block with a catchswitch has no insertion point. Keep going up
62609467b48Spatrick // the dominator tree until we find a non-catchswitch.
62709467b48Spatrick BasicBlock *InsertBB = IncomingBB;
62809467b48Spatrick while (isa<CatchSwitchInst>(InsertBB->getFirstNonPHI())) {
62909467b48Spatrick InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
63009467b48Spatrick }
63109467b48Spatrick
63209467b48Spatrick assert(DT->dominates(Inst, &InsertBB->back()) &&
63309467b48Spatrick "Invalid insertion point for bitcast");
63409467b48Spatrick Replacement =
63509467b48Spatrick new BitCastInst(Replacement, UseTy, "", &InsertBB->back());
63609467b48Spatrick }
63709467b48Spatrick
63809467b48Spatrick // While we're here, rewrite all edges for this PHI, rather
63909467b48Spatrick // than just one use at a time, to minimize the number of
64009467b48Spatrick // bitcasts we emit.
64109467b48Spatrick for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
64209467b48Spatrick if (PHI->getIncomingBlock(i) == IncomingBB) {
64309467b48Spatrick // Keep the UI iterator valid.
64409467b48Spatrick if (UI != UE &&
64509467b48Spatrick &PHI->getOperandUse(
64609467b48Spatrick PHINode::getOperandNumForIncomingValue(i)) == &*UI)
64709467b48Spatrick ++UI;
64809467b48Spatrick PHI->setIncomingValue(i, Replacement);
64909467b48Spatrick }
65009467b48Spatrick } else {
65109467b48Spatrick if (Replacement->getType() != UseTy)
65209467b48Spatrick Replacement = new BitCastInst(Replacement, UseTy, "",
65309467b48Spatrick cast<Instruction>(U.getUser()));
65409467b48Spatrick U.set(Replacement);
65509467b48Spatrick }
65609467b48Spatrick }
65709467b48Spatrick };
65809467b48Spatrick
65909467b48Spatrick Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
66009467b48Spatrick Value *OrigArg = Arg;
66109467b48Spatrick
66209467b48Spatrick // TODO: Change this to a do-while.
66309467b48Spatrick for (;;) {
66409467b48Spatrick ReplaceArgUses(Arg);
66509467b48Spatrick
66609467b48Spatrick // If Arg is a no-op casted pointer, strip one level of casts and iterate.
66709467b48Spatrick if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
66809467b48Spatrick Arg = BI->getOperand(0);
66909467b48Spatrick else if (isa<GEPOperator>(Arg) &&
67009467b48Spatrick cast<GEPOperator>(Arg)->hasAllZeroIndices())
67109467b48Spatrick Arg = cast<GEPOperator>(Arg)->getPointerOperand();
67209467b48Spatrick else if (isa<GlobalAlias>(Arg) &&
67309467b48Spatrick !cast<GlobalAlias>(Arg)->isInterposable())
67409467b48Spatrick Arg = cast<GlobalAlias>(Arg)->getAliasee();
67509467b48Spatrick else {
67609467b48Spatrick // If Arg is a PHI node, get PHIs that are equivalent to it and replace
67709467b48Spatrick // their uses.
67809467b48Spatrick if (PHINode *PN = dyn_cast<PHINode>(Arg)) {
67909467b48Spatrick SmallVector<Value *, 1> PHIList;
68009467b48Spatrick getEquivalentPHIs(*PN, PHIList);
68109467b48Spatrick for (Value *PHI : PHIList)
68209467b48Spatrick ReplaceArgUses(PHI);
68309467b48Spatrick }
68409467b48Spatrick break;
68509467b48Spatrick }
68609467b48Spatrick }
68709467b48Spatrick
68809467b48Spatrick // Replace bitcast users of Arg that are dominated by Inst.
68909467b48Spatrick SmallVector<BitCastInst *, 2> BitCastUsers;
69009467b48Spatrick
69109467b48Spatrick // Add all bitcast users of the function argument first.
69209467b48Spatrick for (User *U : OrigArg->users())
69309467b48Spatrick if (auto *BC = dyn_cast<BitCastInst>(U))
69409467b48Spatrick BitCastUsers.push_back(BC);
69509467b48Spatrick
69609467b48Spatrick // Replace the bitcasts with the call return. Iterate until list is empty.
69709467b48Spatrick while (!BitCastUsers.empty()) {
69809467b48Spatrick auto *BC = BitCastUsers.pop_back_val();
69909467b48Spatrick for (User *U : BC->users())
70009467b48Spatrick if (auto *B = dyn_cast<BitCastInst>(U))
70109467b48Spatrick BitCastUsers.push_back(B);
70209467b48Spatrick
70309467b48Spatrick ReplaceArgUses(BC);
70409467b48Spatrick }
70509467b48Spatrick }
70609467b48Spatrick
70709467b48Spatrick // If this function has no escaping allocas or suspicious vararg usage,
70809467b48Spatrick // objc_storeStrong calls can be marked with the "tail" keyword.
70909467b48Spatrick if (TailOkForStoreStrongs)
71009467b48Spatrick for (CallInst *CI : StoreStrongCalls)
71109467b48Spatrick CI->setTailCall();
71209467b48Spatrick StoreStrongCalls.clear();
71309467b48Spatrick
71409467b48Spatrick return Changed;
71509467b48Spatrick }
71609467b48Spatrick
71709467b48Spatrick //===----------------------------------------------------------------------===//
71809467b48Spatrick // Misc Pass Manager
71909467b48Spatrick //===----------------------------------------------------------------------===//
72009467b48Spatrick
72173471bf0Spatrick char ObjCARCContractLegacyPass::ID = 0;
72273471bf0Spatrick INITIALIZE_PASS_BEGIN(ObjCARCContractLegacyPass, "objc-arc-contract",
72309467b48Spatrick "ObjC ARC contraction", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)72409467b48Spatrick INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
72509467b48Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
72673471bf0Spatrick INITIALIZE_PASS_END(ObjCARCContractLegacyPass, "objc-arc-contract",
72709467b48Spatrick "ObjC ARC contraction", false, false)
72809467b48Spatrick
72973471bf0Spatrick void ObjCARCContractLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
73009467b48Spatrick AU.addRequired<AAResultsWrapperPass>();
73109467b48Spatrick AU.addRequired<DominatorTreeWrapperPass>();
73209467b48Spatrick }
73309467b48Spatrick
createObjCARCContractPass()73473471bf0Spatrick Pass *llvm::createObjCARCContractPass() {
73573471bf0Spatrick return new ObjCARCContractLegacyPass();
73673471bf0Spatrick }
73709467b48Spatrick
runOnFunction(Function & F)73873471bf0Spatrick bool ObjCARCContractLegacyPass::runOnFunction(Function &F) {
739*d415bd75Srobert ObjCARCContract OCARCC;
740*d415bd75Srobert OCARCC.init(*F.getParent());
74173471bf0Spatrick auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
74273471bf0Spatrick auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
74373471bf0Spatrick return OCARCC.run(F, AA, DT);
74473471bf0Spatrick }
74509467b48Spatrick
run(Function & F,FunctionAnalysisManager & AM)74673471bf0Spatrick PreservedAnalyses ObjCARCContractPass::run(Function &F,
74773471bf0Spatrick FunctionAnalysisManager &AM) {
74873471bf0Spatrick ObjCARCContract OCAC;
74973471bf0Spatrick OCAC.init(*F.getParent());
75009467b48Spatrick
75173471bf0Spatrick bool Changed = OCAC.run(F, &AM.getResult<AAManager>(F),
75273471bf0Spatrick &AM.getResult<DominatorTreeAnalysis>(F));
75373471bf0Spatrick bool CFGChanged = OCAC.hasCFGChanged();
75473471bf0Spatrick if (Changed) {
75573471bf0Spatrick PreservedAnalyses PA;
75673471bf0Spatrick if (!CFGChanged)
75773471bf0Spatrick PA.preserveSet<CFGAnalyses>();
75873471bf0Spatrick return PA;
75973471bf0Spatrick }
76073471bf0Spatrick return PreservedAnalyses::all();
76109467b48Spatrick }
762