16f590bf8SNemanja Ivanovic //===---- PPCReduceCRLogicals.cpp - Reduce CR Bit Logical operations ------===//
26f590bf8SNemanja Ivanovic //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66f590bf8SNemanja Ivanovic //
76f590bf8SNemanja Ivanovic //===---------------------------------------------------------------------===//
86f590bf8SNemanja Ivanovic //
96f590bf8SNemanja Ivanovic // This pass aims to reduce the number of logical operations on bits in the CR
106f590bf8SNemanja Ivanovic // register. These instructions have a fairly high latency and only a single
116f590bf8SNemanja Ivanovic // pipeline at their disposal in modern PPC cores. Furthermore, they have a
126f590bf8SNemanja Ivanovic // tendency to occur in fairly small blocks where there's little opportunity
136f590bf8SNemanja Ivanovic // to hide the latency between the CR logical operation and its user.
146f590bf8SNemanja Ivanovic //
156f590bf8SNemanja Ivanovic //===---------------------------------------------------------------------===//
166f590bf8SNemanja Ivanovic 
176f590bf8SNemanja Ivanovic #include "PPC.h"
18d8a6f93aSDavid Blaikie #include "PPCInstrInfo.h"
196f590bf8SNemanja Ivanovic #include "PPCTargetMachine.h"
206f590bf8SNemanja Ivanovic #include "llvm/ADT/Statistic.h"
21d8a6f93aSDavid Blaikie #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
22d8a6f93aSDavid Blaikie #include "llvm/CodeGen/MachineDominators.h"
23d8a6f93aSDavid Blaikie #include "llvm/CodeGen/MachineFunctionPass.h"
24d8a6f93aSDavid Blaikie #include "llvm/CodeGen/MachineInstrBuilder.h"
25d8a6f93aSDavid Blaikie #include "llvm/CodeGen/MachineRegisterInfo.h"
26432a3883SNico Weber #include "llvm/Config/llvm-config.h"
2705da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
28d8a6f93aSDavid Blaikie #include "llvm/Support/Debug.h"
296f590bf8SNemanja Ivanovic 
306f590bf8SNemanja Ivanovic using namespace llvm;
316f590bf8SNemanja Ivanovic 
326f590bf8SNemanja Ivanovic #define DEBUG_TYPE "ppc-reduce-cr-ops"
336f590bf8SNemanja Ivanovic 
346f590bf8SNemanja Ivanovic STATISTIC(NumContainedSingleUseBinOps,
356f590bf8SNemanja Ivanovic           "Number of single-use binary CR logical ops contained in a block");
366f590bf8SNemanja Ivanovic STATISTIC(NumToSplitBlocks,
376f590bf8SNemanja Ivanovic           "Number of binary CR logical ops that can be used to split blocks");
386f590bf8SNemanja Ivanovic STATISTIC(TotalCRLogicals, "Number of CR logical ops.");
396f590bf8SNemanja Ivanovic STATISTIC(TotalNullaryCRLogicals,
406f590bf8SNemanja Ivanovic           "Number of nullary CR logical ops (CRSET/CRUNSET).");
416f590bf8SNemanja Ivanovic STATISTIC(TotalUnaryCRLogicals, "Number of unary CR logical ops.");
426f590bf8SNemanja Ivanovic STATISTIC(TotalBinaryCRLogicals, "Number of CR logical ops.");
436f590bf8SNemanja Ivanovic STATISTIC(NumBlocksSplitOnBinaryCROp,
446f590bf8SNemanja Ivanovic           "Number of blocks split on CR binary logical ops.");
456f590bf8SNemanja Ivanovic STATISTIC(NumNotSplitIdenticalOperands,
466f590bf8SNemanja Ivanovic           "Number of blocks not split due to operands being identical.");
476f590bf8SNemanja Ivanovic STATISTIC(NumNotSplitChainCopies,
486f590bf8SNemanja Ivanovic           "Number of blocks not split due to operands being chained copies.");
496f590bf8SNemanja Ivanovic STATISTIC(NumNotSplitWrongOpcode,
506f590bf8SNemanja Ivanovic           "Number of blocks not split due to the wrong opcode.");
516f590bf8SNemanja Ivanovic 
52d8a6f93aSDavid Blaikie /// Given a basic block \p Successor that potentially contains PHIs, this
53d8a6f93aSDavid Blaikie /// function will look for any incoming values in the PHIs that are supposed to
54d8a6f93aSDavid Blaikie /// be coming from \p OrigMBB but whose definition is actually in \p NewMBB.
55d8a6f93aSDavid Blaikie /// Any such PHIs will be updated to reflect reality.
updatePHIs(MachineBasicBlock * Successor,MachineBasicBlock * OrigMBB,MachineBasicBlock * NewMBB,MachineRegisterInfo * MRI)56d8a6f93aSDavid Blaikie static void updatePHIs(MachineBasicBlock *Successor, MachineBasicBlock *OrigMBB,
57d8a6f93aSDavid Blaikie                        MachineBasicBlock *NewMBB, MachineRegisterInfo *MRI) {
58d8a6f93aSDavid Blaikie   for (auto &MI : Successor->instrs()) {
59d8a6f93aSDavid Blaikie     if (!MI.isPHI())
60d8a6f93aSDavid Blaikie       continue;
61d8a6f93aSDavid Blaikie     // This is a really ugly-looking loop, but it was pillaged directly from
62d8a6f93aSDavid Blaikie     // MachineBasicBlock::transferSuccessorsAndUpdatePHIs().
63d8a6f93aSDavid Blaikie     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
64d8a6f93aSDavid Blaikie       MachineOperand &MO = MI.getOperand(i);
65d8a6f93aSDavid Blaikie       if (MO.getMBB() == OrigMBB) {
66cd83d459SHiroshi Inoue         // Check if the instruction is actually defined in NewMBB.
67d8a6f93aSDavid Blaikie         if (MI.getOperand(i - 1).isReg()) {
68d8a6f93aSDavid Blaikie           MachineInstr *DefMI = MRI->getVRegDef(MI.getOperand(i - 1).getReg());
69d8a6f93aSDavid Blaikie           if (DefMI->getParent() == NewMBB ||
70d8a6f93aSDavid Blaikie               !OrigMBB->isSuccessor(Successor)) {
71d8a6f93aSDavid Blaikie             MO.setMBB(NewMBB);
72d8a6f93aSDavid Blaikie             break;
73d8a6f93aSDavid Blaikie           }
74d8a6f93aSDavid Blaikie         }
75d8a6f93aSDavid Blaikie       }
76d8a6f93aSDavid Blaikie     }
77d8a6f93aSDavid Blaikie   }
78d8a6f93aSDavid Blaikie }
79d8a6f93aSDavid Blaikie 
80d8a6f93aSDavid Blaikie /// Given a basic block \p Successor that potentially contains PHIs, this
81d8a6f93aSDavid Blaikie /// function will look for PHIs that have an incoming value from \p OrigMBB
82d8a6f93aSDavid Blaikie /// and will add the same incoming value from \p NewMBB.
83d8a6f93aSDavid Blaikie /// NOTE: This should only be used if \p NewMBB is an immediate dominator of
84d8a6f93aSDavid Blaikie /// \p OrigMBB.
addIncomingValuesToPHIs(MachineBasicBlock * Successor,MachineBasicBlock * OrigMBB,MachineBasicBlock * NewMBB,MachineRegisterInfo * MRI)85d8a6f93aSDavid Blaikie static void addIncomingValuesToPHIs(MachineBasicBlock *Successor,
86d8a6f93aSDavid Blaikie                                     MachineBasicBlock *OrigMBB,
87d8a6f93aSDavid Blaikie                                     MachineBasicBlock *NewMBB,
88d8a6f93aSDavid Blaikie                                     MachineRegisterInfo *MRI) {
89d8a6f93aSDavid Blaikie   assert(OrigMBB->isSuccessor(NewMBB) &&
900f7f59f0SHiroshi Inoue          "NewMBB must be a successor of OrigMBB");
91d8a6f93aSDavid Blaikie   for (auto &MI : Successor->instrs()) {
92d8a6f93aSDavid Blaikie     if (!MI.isPHI())
93d8a6f93aSDavid Blaikie       continue;
94d8a6f93aSDavid Blaikie     // This is a really ugly-looking loop, but it was pillaged directly from
95d8a6f93aSDavid Blaikie     // MachineBasicBlock::transferSuccessorsAndUpdatePHIs().
96d8a6f93aSDavid Blaikie     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
97d8a6f93aSDavid Blaikie       MachineOperand &MO = MI.getOperand(i);
98d8a6f93aSDavid Blaikie       if (MO.getMBB() == OrigMBB) {
99d8a6f93aSDavid Blaikie         MachineInstrBuilder MIB(*MI.getParent()->getParent(), &MI);
100d8a6f93aSDavid Blaikie         MIB.addReg(MI.getOperand(i - 1).getReg()).addMBB(NewMBB);
101d8a6f93aSDavid Blaikie         break;
102d8a6f93aSDavid Blaikie       }
103d8a6f93aSDavid Blaikie     }
104d8a6f93aSDavid Blaikie   }
105d8a6f93aSDavid Blaikie }
106d8a6f93aSDavid Blaikie 
107d8a6f93aSDavid Blaikie struct BlockSplitInfo {
108d8a6f93aSDavid Blaikie   MachineInstr *OrigBranch;
109d8a6f93aSDavid Blaikie   MachineInstr *SplitBefore;
110d8a6f93aSDavid Blaikie   MachineInstr *SplitCond;
111d8a6f93aSDavid Blaikie   bool InvertNewBranch;
112d8a6f93aSDavid Blaikie   bool InvertOrigBranch;
113d8a6f93aSDavid Blaikie   bool BranchToFallThrough;
114d8a6f93aSDavid Blaikie   const MachineBranchProbabilityInfo *MBPI;
115d8a6f93aSDavid Blaikie   MachineInstr *MIToDelete;
116d8a6f93aSDavid Blaikie   MachineInstr *NewCond;
allInstrsInSameMBBBlockSplitInfo117d8a6f93aSDavid Blaikie   bool allInstrsInSameMBB() {
118d8a6f93aSDavid Blaikie     if (!OrigBranch || !SplitBefore || !SplitCond)
119d8a6f93aSDavid Blaikie       return false;
120d8a6f93aSDavid Blaikie     MachineBasicBlock *MBB = OrigBranch->getParent();
121d8a6f93aSDavid Blaikie     if (SplitBefore->getParent() != MBB || SplitCond->getParent() != MBB)
122d8a6f93aSDavid Blaikie       return false;
123d8a6f93aSDavid Blaikie     if (MIToDelete && MIToDelete->getParent() != MBB)
124d8a6f93aSDavid Blaikie       return false;
125d8a6f93aSDavid Blaikie     if (NewCond && NewCond->getParent() != MBB)
126d8a6f93aSDavid Blaikie       return false;
127d8a6f93aSDavid Blaikie     return true;
128d8a6f93aSDavid Blaikie   }
129d8a6f93aSDavid Blaikie };
130d8a6f93aSDavid Blaikie 
131d8a6f93aSDavid Blaikie /// Splits a MachineBasicBlock to branch before \p SplitBefore. The original
132d8a6f93aSDavid Blaikie /// branch is \p OrigBranch. The target of the new branch can either be the same
133d8a6f93aSDavid Blaikie /// as the target of the original branch or the fallthrough successor of the
134d8a6f93aSDavid Blaikie /// original block as determined by \p BranchToFallThrough. The branch
135d8a6f93aSDavid Blaikie /// conditions will be inverted according to \p InvertNewBranch and
136d8a6f93aSDavid Blaikie /// \p InvertOrigBranch. If an instruction that previously fed the branch is to
137d8a6f93aSDavid Blaikie /// be deleted, it is provided in \p MIToDelete and \p NewCond will be used as
138d8a6f93aSDavid Blaikie /// the branch condition. The branch probabilities will be set if the
139d8a6f93aSDavid Blaikie /// MachineBranchProbabilityInfo isn't null.
splitMBB(BlockSplitInfo & BSI)140d8a6f93aSDavid Blaikie static bool splitMBB(BlockSplitInfo &BSI) {
141d8a6f93aSDavid Blaikie   assert(BSI.allInstrsInSameMBB() &&
142d8a6f93aSDavid Blaikie          "All instructions must be in the same block.");
143d8a6f93aSDavid Blaikie 
144d8a6f93aSDavid Blaikie   MachineBasicBlock *ThisMBB = BSI.OrigBranch->getParent();
145d8a6f93aSDavid Blaikie   MachineFunction *MF = ThisMBB->getParent();
146d8a6f93aSDavid Blaikie   MachineRegisterInfo *MRI = &MF->getRegInfo();
147d8a6f93aSDavid Blaikie   assert(MRI->isSSA() && "Can only do this while the function is in SSA form.");
148d8a6f93aSDavid Blaikie   if (ThisMBB->succ_size() != 2) {
149d34e60caSNicola Zaghen     LLVM_DEBUG(
150d34e60caSNicola Zaghen         dbgs() << "Don't know how to handle blocks that don't have exactly"
151cd83d459SHiroshi Inoue                << " two successors.\n");
152d8a6f93aSDavid Blaikie     return false;
153d8a6f93aSDavid Blaikie   }
154d8a6f93aSDavid Blaikie 
155d8a6f93aSDavid Blaikie   const PPCInstrInfo *TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
156d8a6f93aSDavid Blaikie   unsigned OrigBROpcode = BSI.OrigBranch->getOpcode();
157d8a6f93aSDavid Blaikie   unsigned InvertedOpcode =
158d8a6f93aSDavid Blaikie       OrigBROpcode == PPC::BC
159d8a6f93aSDavid Blaikie           ? PPC::BCn
160d8a6f93aSDavid Blaikie           : OrigBROpcode == PPC::BCn
161d8a6f93aSDavid Blaikie                 ? PPC::BC
162d8a6f93aSDavid Blaikie                 : OrigBROpcode == PPC::BCLR ? PPC::BCLRn : PPC::BCLR;
163d8a6f93aSDavid Blaikie   unsigned NewBROpcode = BSI.InvertNewBranch ? InvertedOpcode : OrigBROpcode;
164d8a6f93aSDavid Blaikie   MachineBasicBlock *OrigTarget = BSI.OrigBranch->getOperand(1).getMBB();
165d8a6f93aSDavid Blaikie   MachineBasicBlock *OrigFallThrough = OrigTarget == *ThisMBB->succ_begin()
166d8a6f93aSDavid Blaikie                                            ? *ThisMBB->succ_rbegin()
167d8a6f93aSDavid Blaikie                                            : *ThisMBB->succ_begin();
168d8a6f93aSDavid Blaikie   MachineBasicBlock *NewBRTarget =
169d8a6f93aSDavid Blaikie       BSI.BranchToFallThrough ? OrigFallThrough : OrigTarget;
170c3a24e93SGuozhi Wei 
171c3a24e93SGuozhi Wei   // It's impossible to know the precise branch probability after the split.
172c3a24e93SGuozhi Wei   // But it still needs to be reasonable, the whole probability to original
173c3a24e93SGuozhi Wei   // targets should not be changed.
174c3a24e93SGuozhi Wei   // After split NewBRTarget will get two incoming edges. Assume P0 is the
175c3a24e93SGuozhi Wei   // original branch probability to NewBRTarget, P1 and P2 are new branch
176c3a24e93SGuozhi Wei   // probabilies to NewBRTarget after split. If the two edge frequencies are
177c3a24e93SGuozhi Wei   // same, then
178c3a24e93SGuozhi Wei   //      F * P1 = F * P0 / 2            ==>  P1 = P0 / 2
179c3a24e93SGuozhi Wei   //      F * (1 - P1) * P2 = F * P1     ==>  P2 = P1 / (1 - P1)
180c3a24e93SGuozhi Wei   BranchProbability ProbToNewTarget, ProbFallThrough;     // Prob for new Br.
181c3a24e93SGuozhi Wei   BranchProbability ProbOrigTarget, ProbOrigFallThrough;  // Prob for orig Br.
182c3a24e93SGuozhi Wei   ProbToNewTarget = ProbFallThrough = BranchProbability::getUnknown();
183c3a24e93SGuozhi Wei   ProbOrigTarget = ProbOrigFallThrough = BranchProbability::getUnknown();
184c3a24e93SGuozhi Wei   if (BSI.MBPI) {
185c3a24e93SGuozhi Wei     if (BSI.BranchToFallThrough) {
186c3a24e93SGuozhi Wei       ProbToNewTarget = BSI.MBPI->getEdgeProbability(ThisMBB, OrigFallThrough) / 2;
187c3a24e93SGuozhi Wei       ProbFallThrough = ProbToNewTarget.getCompl();
188c3a24e93SGuozhi Wei       ProbOrigFallThrough = ProbToNewTarget / ProbToNewTarget.getCompl();
189c3a24e93SGuozhi Wei       ProbOrigTarget = ProbOrigFallThrough.getCompl();
190c3a24e93SGuozhi Wei     } else {
191c3a24e93SGuozhi Wei       ProbToNewTarget = BSI.MBPI->getEdgeProbability(ThisMBB, OrigTarget) / 2;
192c3a24e93SGuozhi Wei       ProbFallThrough = ProbToNewTarget.getCompl();
193c3a24e93SGuozhi Wei       ProbOrigTarget = ProbToNewTarget / ProbToNewTarget.getCompl();
194c3a24e93SGuozhi Wei       ProbOrigFallThrough = ProbOrigTarget.getCompl();
195c3a24e93SGuozhi Wei     }
196c3a24e93SGuozhi Wei   }
197d8a6f93aSDavid Blaikie 
198d8a6f93aSDavid Blaikie   // Create a new basic block.
199d8a6f93aSDavid Blaikie   MachineBasicBlock::iterator InsertPoint = BSI.SplitBefore;
200d8a6f93aSDavid Blaikie   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
201d8a6f93aSDavid Blaikie   MachineFunction::iterator It = ThisMBB->getIterator();
202d8a6f93aSDavid Blaikie   MachineBasicBlock *NewMBB = MF->CreateMachineBasicBlock(LLVM_BB);
203d8a6f93aSDavid Blaikie   MF->insert(++It, NewMBB);
204d8a6f93aSDavid Blaikie 
205d8a6f93aSDavid Blaikie   // Move everything after SplitBefore into the new block.
206d8a6f93aSDavid Blaikie   NewMBB->splice(NewMBB->end(), ThisMBB, InsertPoint, ThisMBB->end());
207d8a6f93aSDavid Blaikie   NewMBB->transferSuccessors(ThisMBB);
208c3a24e93SGuozhi Wei   if (!ProbOrigTarget.isUnknown()) {
209*88572024SKazu Hirata     auto MBBI = find(NewMBB->successors(), OrigTarget);
210c3a24e93SGuozhi Wei     NewMBB->setSuccProbability(MBBI, ProbOrigTarget);
211*88572024SKazu Hirata     MBBI = find(NewMBB->successors(), OrigFallThrough);
212c3a24e93SGuozhi Wei     NewMBB->setSuccProbability(MBBI, ProbOrigFallThrough);
213c3a24e93SGuozhi Wei   }
214d8a6f93aSDavid Blaikie 
215c3a24e93SGuozhi Wei   // Add the two successors to ThisMBB.
216d8a6f93aSDavid Blaikie   ThisMBB->addSuccessor(NewBRTarget, ProbToNewTarget);
217c3a24e93SGuozhi Wei   ThisMBB->addSuccessor(NewMBB, ProbFallThrough);
218d8a6f93aSDavid Blaikie 
219d8a6f93aSDavid Blaikie   // Add the branches to ThisMBB.
220d8a6f93aSDavid Blaikie   BuildMI(*ThisMBB, ThisMBB->end(), BSI.SplitBefore->getDebugLoc(),
221d8a6f93aSDavid Blaikie           TII->get(NewBROpcode))
222d8a6f93aSDavid Blaikie       .addReg(BSI.SplitCond->getOperand(0).getReg())
223d8a6f93aSDavid Blaikie       .addMBB(NewBRTarget);
224d8a6f93aSDavid Blaikie   BuildMI(*ThisMBB, ThisMBB->end(), BSI.SplitBefore->getDebugLoc(),
225d8a6f93aSDavid Blaikie           TII->get(PPC::B))
226d8a6f93aSDavid Blaikie       .addMBB(NewMBB);
227d8a6f93aSDavid Blaikie   if (BSI.MIToDelete)
228d8a6f93aSDavid Blaikie     BSI.MIToDelete->eraseFromParent();
229d8a6f93aSDavid Blaikie 
230d8a6f93aSDavid Blaikie   // Change the condition on the original branch and invert it if requested.
231d8a6f93aSDavid Blaikie   auto FirstTerminator = NewMBB->getFirstTerminator();
232d8a6f93aSDavid Blaikie   if (BSI.NewCond) {
233d8a6f93aSDavid Blaikie     assert(FirstTerminator->getOperand(0).isReg() &&
234d8a6f93aSDavid Blaikie            "Can't update condition of unconditional branch.");
235d8a6f93aSDavid Blaikie     FirstTerminator->getOperand(0).setReg(BSI.NewCond->getOperand(0).getReg());
236d8a6f93aSDavid Blaikie   }
237d8a6f93aSDavid Blaikie   if (BSI.InvertOrigBranch)
238d8a6f93aSDavid Blaikie     FirstTerminator->setDesc(TII->get(InvertedOpcode));
239d8a6f93aSDavid Blaikie 
240d8a6f93aSDavid Blaikie   // If any of the PHIs in the successors of NewMBB reference values that
241d8a6f93aSDavid Blaikie   // now come from NewMBB, they need to be updated.
242d8a6f93aSDavid Blaikie   for (auto *Succ : NewMBB->successors()) {
243d8a6f93aSDavid Blaikie     updatePHIs(Succ, ThisMBB, NewMBB, MRI);
244d8a6f93aSDavid Blaikie   }
245d8a6f93aSDavid Blaikie   addIncomingValuesToPHIs(NewBRTarget, ThisMBB, NewMBB, MRI);
246d8a6f93aSDavid Blaikie 
247d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "After splitting, ThisMBB:\n"; ThisMBB->dump());
248d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "NewMBB:\n"; NewMBB->dump());
249d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "New branch-to block:\n"; NewBRTarget->dump());
250d8a6f93aSDavid Blaikie   return true;
251d8a6f93aSDavid Blaikie }
2526f590bf8SNemanja Ivanovic 
isBinary(MachineInstr & MI)2536f590bf8SNemanja Ivanovic static bool isBinary(MachineInstr &MI) {
2546f590bf8SNemanja Ivanovic   return MI.getNumOperands() == 3;
2556f590bf8SNemanja Ivanovic }
2566f590bf8SNemanja Ivanovic 
isNullary(MachineInstr & MI)2576f590bf8SNemanja Ivanovic static bool isNullary(MachineInstr &MI) {
2586f590bf8SNemanja Ivanovic   return MI.getNumOperands() == 1;
2596f590bf8SNemanja Ivanovic }
2606f590bf8SNemanja Ivanovic 
2616f590bf8SNemanja Ivanovic /// Given a CR logical operation \p CROp, branch opcode \p BROp as well as
2626f590bf8SNemanja Ivanovic /// a flag to indicate if the first operand of \p CROp is used as the
2636f590bf8SNemanja Ivanovic /// SplitBefore operand, determines whether either of the branches are to be
2646f590bf8SNemanja Ivanovic /// inverted as well as whether the new target should be the original
2656f590bf8SNemanja Ivanovic /// fall-through block.
2666f590bf8SNemanja Ivanovic static void
computeBranchTargetAndInversion(unsigned CROp,unsigned BROp,bool UsingDef1,bool & InvertNewBranch,bool & InvertOrigBranch,bool & TargetIsFallThrough)2676f590bf8SNemanja Ivanovic computeBranchTargetAndInversion(unsigned CROp, unsigned BROp, bool UsingDef1,
2686f590bf8SNemanja Ivanovic                                 bool &InvertNewBranch, bool &InvertOrigBranch,
2696f590bf8SNemanja Ivanovic                                 bool &TargetIsFallThrough) {
2706f590bf8SNemanja Ivanovic   // The conditions under which each of the output operands should be [un]set
2716f590bf8SNemanja Ivanovic   // can certainly be written much more concisely with just 3 if statements or
2726f590bf8SNemanja Ivanovic   // ternary expressions. However, this provides a much clearer overview to the
2736f590bf8SNemanja Ivanovic   // reader as to what is set for each <CROp, BROp, OpUsed> combination.
2746f590bf8SNemanja Ivanovic   if (BROp == PPC::BC || BROp == PPC::BCLR) {
2756f590bf8SNemanja Ivanovic     // Regular branches.
2766f590bf8SNemanja Ivanovic     switch (CROp) {
2776f590bf8SNemanja Ivanovic     default:
2786f590bf8SNemanja Ivanovic       llvm_unreachable("Don't know how to handle this CR logical.");
2796f590bf8SNemanja Ivanovic     case PPC::CROR:
2806f590bf8SNemanja Ivanovic       InvertNewBranch = false;
2816f590bf8SNemanja Ivanovic       InvertOrigBranch = false;
2826f590bf8SNemanja Ivanovic       TargetIsFallThrough = false;
2836f590bf8SNemanja Ivanovic       return;
2846f590bf8SNemanja Ivanovic     case PPC::CRAND:
2856f590bf8SNemanja Ivanovic       InvertNewBranch = true;
2866f590bf8SNemanja Ivanovic       InvertOrigBranch = false;
2876f590bf8SNemanja Ivanovic       TargetIsFallThrough = true;
2886f590bf8SNemanja Ivanovic       return;
2896f590bf8SNemanja Ivanovic     case PPC::CRNAND:
2906f590bf8SNemanja Ivanovic       InvertNewBranch = true;
2916f590bf8SNemanja Ivanovic       InvertOrigBranch = true;
2926f590bf8SNemanja Ivanovic       TargetIsFallThrough = false;
2936f590bf8SNemanja Ivanovic       return;
2946f590bf8SNemanja Ivanovic     case PPC::CRNOR:
2956f590bf8SNemanja Ivanovic       InvertNewBranch = false;
2966f590bf8SNemanja Ivanovic       InvertOrigBranch = true;
2976f590bf8SNemanja Ivanovic       TargetIsFallThrough = true;
2986f590bf8SNemanja Ivanovic       return;
2996f590bf8SNemanja Ivanovic     case PPC::CRORC:
3006f590bf8SNemanja Ivanovic       InvertNewBranch = UsingDef1;
3016f590bf8SNemanja Ivanovic       InvertOrigBranch = !UsingDef1;
3026f590bf8SNemanja Ivanovic       TargetIsFallThrough = false;
3036f590bf8SNemanja Ivanovic       return;
3046f590bf8SNemanja Ivanovic     case PPC::CRANDC:
3056f590bf8SNemanja Ivanovic       InvertNewBranch = !UsingDef1;
3066f590bf8SNemanja Ivanovic       InvertOrigBranch = !UsingDef1;
3076f590bf8SNemanja Ivanovic       TargetIsFallThrough = true;
3086f590bf8SNemanja Ivanovic       return;
3096f590bf8SNemanja Ivanovic     }
3106f590bf8SNemanja Ivanovic   } else if (BROp == PPC::BCn || BROp == PPC::BCLRn) {
3116f590bf8SNemanja Ivanovic     // Negated branches.
3126f590bf8SNemanja Ivanovic     switch (CROp) {
3136f590bf8SNemanja Ivanovic     default:
3146f590bf8SNemanja Ivanovic       llvm_unreachable("Don't know how to handle this CR logical.");
3156f590bf8SNemanja Ivanovic     case PPC::CROR:
3166f590bf8SNemanja Ivanovic       InvertNewBranch = true;
3176f590bf8SNemanja Ivanovic       InvertOrigBranch = false;
3186f590bf8SNemanja Ivanovic       TargetIsFallThrough = true;
3196f590bf8SNemanja Ivanovic       return;
3206f590bf8SNemanja Ivanovic     case PPC::CRAND:
3216f590bf8SNemanja Ivanovic       InvertNewBranch = false;
3226f590bf8SNemanja Ivanovic       InvertOrigBranch = false;
3236f590bf8SNemanja Ivanovic       TargetIsFallThrough = false;
3246f590bf8SNemanja Ivanovic       return;
3256f590bf8SNemanja Ivanovic     case PPC::CRNAND:
3266f590bf8SNemanja Ivanovic       InvertNewBranch = false;
3276f590bf8SNemanja Ivanovic       InvertOrigBranch = true;
3286f590bf8SNemanja Ivanovic       TargetIsFallThrough = true;
3296f590bf8SNemanja Ivanovic       return;
3306f590bf8SNemanja Ivanovic     case PPC::CRNOR:
3316f590bf8SNemanja Ivanovic       InvertNewBranch = true;
3326f590bf8SNemanja Ivanovic       InvertOrigBranch = true;
3336f590bf8SNemanja Ivanovic       TargetIsFallThrough = false;
3346f590bf8SNemanja Ivanovic       return;
3356f590bf8SNemanja Ivanovic     case PPC::CRORC:
3366f590bf8SNemanja Ivanovic       InvertNewBranch = !UsingDef1;
3376f590bf8SNemanja Ivanovic       InvertOrigBranch = !UsingDef1;
3386f590bf8SNemanja Ivanovic       TargetIsFallThrough = true;
3396f590bf8SNemanja Ivanovic       return;
3406f590bf8SNemanja Ivanovic     case PPC::CRANDC:
3416f590bf8SNemanja Ivanovic       InvertNewBranch = UsingDef1;
3426f590bf8SNemanja Ivanovic       InvertOrigBranch = !UsingDef1;
3436f590bf8SNemanja Ivanovic       TargetIsFallThrough = false;
3446f590bf8SNemanja Ivanovic       return;
3456f590bf8SNemanja Ivanovic     }
3466f590bf8SNemanja Ivanovic   } else
3476f590bf8SNemanja Ivanovic     llvm_unreachable("Don't know how to handle this branch.");
3486f590bf8SNemanja Ivanovic }
3496f590bf8SNemanja Ivanovic 
350d8a6f93aSDavid Blaikie namespace {
351d8a6f93aSDavid Blaikie 
3526f590bf8SNemanja Ivanovic class PPCReduceCRLogicals : public MachineFunctionPass {
3536f590bf8SNemanja Ivanovic 
3546f590bf8SNemanja Ivanovic public:
3556f590bf8SNemanja Ivanovic   static char ID;
3566f590bf8SNemanja Ivanovic   struct CRLogicalOpInfo {
3576f590bf8SNemanja Ivanovic     MachineInstr *MI;
3586f590bf8SNemanja Ivanovic     // FIXME: If chains of copies are to be handled, this should be a vector.
3596f590bf8SNemanja Ivanovic     std::pair<MachineInstr*, MachineInstr*> CopyDefs;
3606f590bf8SNemanja Ivanovic     std::pair<MachineInstr*, MachineInstr*> TrueDefs;
3616f590bf8SNemanja Ivanovic     unsigned IsBinary : 1;
3626f590bf8SNemanja Ivanovic     unsigned IsNullary : 1;
3636f590bf8SNemanja Ivanovic     unsigned ContainedInBlock : 1;
3646f590bf8SNemanja Ivanovic     unsigned FeedsISEL : 1;
3656f590bf8SNemanja Ivanovic     unsigned FeedsBR : 1;
3666f590bf8SNemanja Ivanovic     unsigned FeedsLogical : 1;
3676f590bf8SNemanja Ivanovic     unsigned SingleUse : 1;
3686f590bf8SNemanja Ivanovic     unsigned DefsSingleUse : 1;
3696f590bf8SNemanja Ivanovic     unsigned SubregDef1;
3706f590bf8SNemanja Ivanovic     unsigned SubregDef2;
CRLogicalOpInfo__anon661ddca30111::PPCReduceCRLogicals::CRLogicalOpInfo3716f590bf8SNemanja Ivanovic     CRLogicalOpInfo() : MI(nullptr), IsBinary(0), IsNullary(0),
3726f590bf8SNemanja Ivanovic                         ContainedInBlock(0), FeedsISEL(0), FeedsBR(0),
3736f590bf8SNemanja Ivanovic                         FeedsLogical(0), SingleUse(0), DefsSingleUse(1),
3746f590bf8SNemanja Ivanovic                         SubregDef1(0), SubregDef2(0) { }
3756f590bf8SNemanja Ivanovic     void dump();
3766f590bf8SNemanja Ivanovic   };
3776f590bf8SNemanja Ivanovic 
3786f590bf8SNemanja Ivanovic private:
37966f2ed07SSimon Pilgrim   const PPCInstrInfo *TII = nullptr;
38066f2ed07SSimon Pilgrim   MachineFunction *MF = nullptr;
38166f2ed07SSimon Pilgrim   MachineRegisterInfo *MRI = nullptr;
38266f2ed07SSimon Pilgrim   const MachineBranchProbabilityInfo *MBPI = nullptr;
3836f590bf8SNemanja Ivanovic 
3846f590bf8SNemanja Ivanovic   // A vector to contain all the CR logical operations
385f2c8f3b1SNemanja Ivanovic   SmallVector<CRLogicalOpInfo, 16> AllCRLogicalOps;
3866f590bf8SNemanja Ivanovic   void initialize(MachineFunction &MFParm);
3876f590bf8SNemanja Ivanovic   void collectCRLogicals();
388f2c8f3b1SNemanja Ivanovic   bool handleCROp(unsigned Idx);
3896f590bf8SNemanja Ivanovic   bool splitBlockOnBinaryCROp(CRLogicalOpInfo &CRI);
isCRLogical(MachineInstr & MI)3906f590bf8SNemanja Ivanovic   static bool isCRLogical(MachineInstr &MI) {
3916f590bf8SNemanja Ivanovic     unsigned Opc = MI.getOpcode();
3926f590bf8SNemanja Ivanovic     return Opc == PPC::CRAND || Opc == PPC::CRNAND || Opc == PPC::CROR ||
3936f590bf8SNemanja Ivanovic       Opc == PPC::CRXOR || Opc == PPC::CRNOR || Opc == PPC::CREQV ||
3946f590bf8SNemanja Ivanovic       Opc == PPC::CRANDC || Opc == PPC::CRORC || Opc == PPC::CRSET ||
3956f590bf8SNemanja Ivanovic       Opc == PPC::CRUNSET || Opc == PPC::CR6SET || Opc == PPC::CR6UNSET;
3966f590bf8SNemanja Ivanovic   }
simplifyCode()3976f590bf8SNemanja Ivanovic   bool simplifyCode() {
3986f590bf8SNemanja Ivanovic     bool Changed = false;
3996f590bf8SNemanja Ivanovic     // Not using a range-based for loop here as the vector may grow while being
4006f590bf8SNemanja Ivanovic     // operated on.
4016f590bf8SNemanja Ivanovic     for (unsigned i = 0; i < AllCRLogicalOps.size(); i++)
402f2c8f3b1SNemanja Ivanovic       Changed |= handleCROp(i);
4036f590bf8SNemanja Ivanovic     return Changed;
4046f590bf8SNemanja Ivanovic   }
4056f590bf8SNemanja Ivanovic 
4066f590bf8SNemanja Ivanovic public:
PPCReduceCRLogicals()4076f590bf8SNemanja Ivanovic   PPCReduceCRLogicals() : MachineFunctionPass(ID) {
4086f590bf8SNemanja Ivanovic     initializePPCReduceCRLogicalsPass(*PassRegistry::getPassRegistry());
4096f590bf8SNemanja Ivanovic   }
4106f590bf8SNemanja Ivanovic 
4116f590bf8SNemanja Ivanovic   MachineInstr *lookThroughCRCopy(unsigned Reg, unsigned &Subreg,
4126f590bf8SNemanja Ivanovic                                   MachineInstr *&CpDef);
runOnMachineFunction(MachineFunction & MF)4136f590bf8SNemanja Ivanovic   bool runOnMachineFunction(MachineFunction &MF) override {
414f1caa283SMatthias Braun     if (skipFunction(MF.getFunction()))
4156f590bf8SNemanja Ivanovic       return false;
4166f590bf8SNemanja Ivanovic 
4176f590bf8SNemanja Ivanovic     // If the subtarget doesn't use CR bits, there's nothing to do.
4186f590bf8SNemanja Ivanovic     const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
4196f590bf8SNemanja Ivanovic     if (!STI.useCRBits())
4206f590bf8SNemanja Ivanovic       return false;
4216f590bf8SNemanja Ivanovic 
4226f590bf8SNemanja Ivanovic     initialize(MF);
4236f590bf8SNemanja Ivanovic     collectCRLogicals();
4246f590bf8SNemanja Ivanovic     return simplifyCode();
4256f590bf8SNemanja Ivanovic   }
4266f590bf8SNemanja Ivanovic   CRLogicalOpInfo createCRLogicalOpInfo(MachineInstr &MI);
getAnalysisUsage(AnalysisUsage & AU) const4276f590bf8SNemanja Ivanovic   void getAnalysisUsage(AnalysisUsage &AU) const override {
4286f590bf8SNemanja Ivanovic     AU.addRequired<MachineBranchProbabilityInfo>();
4296f590bf8SNemanja Ivanovic     AU.addRequired<MachineDominatorTree>();
4306f590bf8SNemanja Ivanovic     MachineFunctionPass::getAnalysisUsage(AU);
4316f590bf8SNemanja Ivanovic   }
4326f590bf8SNemanja Ivanovic };
4336f590bf8SNemanja Ivanovic 
4346af75240SNemanja Ivanovic #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump()4356af75240SNemanja Ivanovic LLVM_DUMP_METHOD void PPCReduceCRLogicals::CRLogicalOpInfo::dump() {
4366f590bf8SNemanja Ivanovic   dbgs() << "CRLogicalOpMI: ";
4376f590bf8SNemanja Ivanovic   MI->dump();
4386f590bf8SNemanja Ivanovic   dbgs() << "IsBinary: " << IsBinary << ", FeedsISEL: " << FeedsISEL;
4396f590bf8SNemanja Ivanovic   dbgs() << ", FeedsBR: " << FeedsBR << ", FeedsLogical: ";
4406f590bf8SNemanja Ivanovic   dbgs() << FeedsLogical << ", SingleUse: " << SingleUse;
4416f590bf8SNemanja Ivanovic   dbgs() << ", DefsSingleUse: " << DefsSingleUse;
4426f590bf8SNemanja Ivanovic   dbgs() << ", SubregDef1: " << SubregDef1 << ", SubregDef2: ";
4436f590bf8SNemanja Ivanovic   dbgs() << SubregDef2 << ", ContainedInBlock: " << ContainedInBlock;
4446f590bf8SNemanja Ivanovic   if (!IsNullary) {
4456f590bf8SNemanja Ivanovic     dbgs() << "\nDefs:\n";
4466f590bf8SNemanja Ivanovic     TrueDefs.first->dump();
4476f590bf8SNemanja Ivanovic   }
4486f590bf8SNemanja Ivanovic   if (IsBinary)
4496f590bf8SNemanja Ivanovic     TrueDefs.second->dump();
4506f590bf8SNemanja Ivanovic   dbgs() << "\n";
4516f590bf8SNemanja Ivanovic   if (CopyDefs.first) {
4526f590bf8SNemanja Ivanovic     dbgs() << "CopyDef1: ";
4536f590bf8SNemanja Ivanovic     CopyDefs.first->dump();
4546f590bf8SNemanja Ivanovic   }
4556f590bf8SNemanja Ivanovic   if (CopyDefs.second) {
4566f590bf8SNemanja Ivanovic     dbgs() << "CopyDef2: ";
4576f590bf8SNemanja Ivanovic     CopyDefs.second->dump();
4586f590bf8SNemanja Ivanovic   }
4596f590bf8SNemanja Ivanovic }
4606af75240SNemanja Ivanovic #endif
4616f590bf8SNemanja Ivanovic 
4626f590bf8SNemanja Ivanovic PPCReduceCRLogicals::CRLogicalOpInfo
createCRLogicalOpInfo(MachineInstr & MIParam)4636f590bf8SNemanja Ivanovic PPCReduceCRLogicals::createCRLogicalOpInfo(MachineInstr &MIParam) {
4646f590bf8SNemanja Ivanovic   CRLogicalOpInfo Ret;
4656f590bf8SNemanja Ivanovic   Ret.MI = &MIParam;
4666f590bf8SNemanja Ivanovic   // Get the defs
4676f590bf8SNemanja Ivanovic   if (isNullary(MIParam)) {
4686f590bf8SNemanja Ivanovic     Ret.IsNullary = 1;
4696f590bf8SNemanja Ivanovic     Ret.TrueDefs = std::make_pair(nullptr, nullptr);
4706f590bf8SNemanja Ivanovic     Ret.CopyDefs = std::make_pair(nullptr, nullptr);
4716f590bf8SNemanja Ivanovic   } else {
4726f590bf8SNemanja Ivanovic     MachineInstr *Def1 = lookThroughCRCopy(MIParam.getOperand(1).getReg(),
4736f590bf8SNemanja Ivanovic                                            Ret.SubregDef1, Ret.CopyDefs.first);
47466f2ed07SSimon Pilgrim     assert(Def1 && "Must be able to find a definition of operand 1.");
4756f590bf8SNemanja Ivanovic     Ret.DefsSingleUse &=
4766f590bf8SNemanja Ivanovic       MRI->hasOneNonDBGUse(Def1->getOperand(0).getReg());
4776f590bf8SNemanja Ivanovic     Ret.DefsSingleUse &=
4786f590bf8SNemanja Ivanovic       MRI->hasOneNonDBGUse(Ret.CopyDefs.first->getOperand(0).getReg());
4796f590bf8SNemanja Ivanovic     if (isBinary(MIParam)) {
4806f590bf8SNemanja Ivanovic       Ret.IsBinary = 1;
4816f590bf8SNemanja Ivanovic       MachineInstr *Def2 = lookThroughCRCopy(MIParam.getOperand(2).getReg(),
4826f590bf8SNemanja Ivanovic                                              Ret.SubregDef2,
4836f590bf8SNemanja Ivanovic                                              Ret.CopyDefs.second);
48466f2ed07SSimon Pilgrim       assert(Def2 && "Must be able to find a definition of operand 2.");
4856f590bf8SNemanja Ivanovic       Ret.DefsSingleUse &=
4866f590bf8SNemanja Ivanovic         MRI->hasOneNonDBGUse(Def2->getOperand(0).getReg());
4876f590bf8SNemanja Ivanovic       Ret.DefsSingleUse &=
4886f590bf8SNemanja Ivanovic         MRI->hasOneNonDBGUse(Ret.CopyDefs.second->getOperand(0).getReg());
4896f590bf8SNemanja Ivanovic       Ret.TrueDefs = std::make_pair(Def1, Def2);
4906f590bf8SNemanja Ivanovic     } else {
4916f590bf8SNemanja Ivanovic       Ret.TrueDefs = std::make_pair(Def1, nullptr);
4926f590bf8SNemanja Ivanovic       Ret.CopyDefs.second = nullptr;
4936f590bf8SNemanja Ivanovic     }
4946f590bf8SNemanja Ivanovic   }
4956f590bf8SNemanja Ivanovic 
4966f590bf8SNemanja Ivanovic   Ret.ContainedInBlock = 1;
4976f590bf8SNemanja Ivanovic   // Get the uses
4986f590bf8SNemanja Ivanovic   for (MachineInstr &UseMI :
4996f590bf8SNemanja Ivanovic        MRI->use_nodbg_instructions(MIParam.getOperand(0).getReg())) {
5006f590bf8SNemanja Ivanovic     unsigned Opc = UseMI.getOpcode();
5016f590bf8SNemanja Ivanovic     if (Opc == PPC::ISEL || Opc == PPC::ISEL8)
5026f590bf8SNemanja Ivanovic       Ret.FeedsISEL = 1;
5036f590bf8SNemanja Ivanovic     if (Opc == PPC::BC || Opc == PPC::BCn || Opc == PPC::BCLR ||
5046f590bf8SNemanja Ivanovic         Opc == PPC::BCLRn)
5056f590bf8SNemanja Ivanovic       Ret.FeedsBR = 1;
5066f590bf8SNemanja Ivanovic     Ret.FeedsLogical = isCRLogical(UseMI);
5076f590bf8SNemanja Ivanovic     if (UseMI.getParent() != MIParam.getParent())
5086f590bf8SNemanja Ivanovic       Ret.ContainedInBlock = 0;
5096f590bf8SNemanja Ivanovic   }
5106f590bf8SNemanja Ivanovic   Ret.SingleUse = MRI->hasOneNonDBGUse(MIParam.getOperand(0).getReg()) ? 1 : 0;
5116f590bf8SNemanja Ivanovic 
5126f590bf8SNemanja Ivanovic   // We now know whether all the uses of the CR logical are in the same block.
5136f590bf8SNemanja Ivanovic   if (!Ret.IsNullary) {
5146f590bf8SNemanja Ivanovic     Ret.ContainedInBlock &=
5156f590bf8SNemanja Ivanovic       (MIParam.getParent() == Ret.TrueDefs.first->getParent());
5166f590bf8SNemanja Ivanovic     if (Ret.IsBinary)
5176f590bf8SNemanja Ivanovic       Ret.ContainedInBlock &=
5186f590bf8SNemanja Ivanovic         (MIParam.getParent() == Ret.TrueDefs.second->getParent());
5196f590bf8SNemanja Ivanovic   }
520d34e60caSNicola Zaghen   LLVM_DEBUG(Ret.dump());
5216f590bf8SNemanja Ivanovic   if (Ret.IsBinary && Ret.ContainedInBlock && Ret.SingleUse) {
5226f590bf8SNemanja Ivanovic     NumContainedSingleUseBinOps++;
5236f590bf8SNemanja Ivanovic     if (Ret.FeedsBR && Ret.DefsSingleUse)
5246f590bf8SNemanja Ivanovic       NumToSplitBlocks++;
5256f590bf8SNemanja Ivanovic   }
5266f590bf8SNemanja Ivanovic   return Ret;
5276f590bf8SNemanja Ivanovic }
5286f590bf8SNemanja Ivanovic 
5290f7f59f0SHiroshi Inoue /// Looks through a COPY instruction to the actual definition of the CR-bit
5306f590bf8SNemanja Ivanovic /// register and returns the instruction that defines it.
5316f590bf8SNemanja Ivanovic /// FIXME: This currently handles what is by-far the most common case:
5326f590bf8SNemanja Ivanovic /// an instruction that defines a CR field followed by a single copy of a bit
5336f590bf8SNemanja Ivanovic /// from that field into a virtual register. If chains of copies need to be
5346f590bf8SNemanja Ivanovic /// handled, this should have a loop until a non-copy instruction is found.
lookThroughCRCopy(unsigned Reg,unsigned & Subreg,MachineInstr * & CpDef)5356f590bf8SNemanja Ivanovic MachineInstr *PPCReduceCRLogicals::lookThroughCRCopy(unsigned Reg,
5366f590bf8SNemanja Ivanovic                                                      unsigned &Subreg,
5376f590bf8SNemanja Ivanovic                                                      MachineInstr *&CpDef) {
5386f590bf8SNemanja Ivanovic   Subreg = -1;
5392bea69bfSDaniel Sanders   if (!Register::isVirtualRegister(Reg))
5406f590bf8SNemanja Ivanovic     return nullptr;
5416f590bf8SNemanja Ivanovic   MachineInstr *Copy = MRI->getVRegDef(Reg);
5426f590bf8SNemanja Ivanovic   CpDef = Copy;
5436f590bf8SNemanja Ivanovic   if (!Copy->isCopy())
5446f590bf8SNemanja Ivanovic     return Copy;
5450c476111SDaniel Sanders   Register CopySrc = Copy->getOperand(1).getReg();
5466f590bf8SNemanja Ivanovic   Subreg = Copy->getOperand(1).getSubReg();
5472bea69bfSDaniel Sanders   if (!Register::isVirtualRegister(CopySrc)) {
5486f590bf8SNemanja Ivanovic     const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
5496f590bf8SNemanja Ivanovic     // Set the Subreg
5506f590bf8SNemanja Ivanovic     if (CopySrc == PPC::CR0EQ || CopySrc == PPC::CR6EQ)
5516f590bf8SNemanja Ivanovic       Subreg = PPC::sub_eq;
5526f590bf8SNemanja Ivanovic     if (CopySrc == PPC::CR0LT || CopySrc == PPC::CR6LT)
5536f590bf8SNemanja Ivanovic       Subreg = PPC::sub_lt;
5546f590bf8SNemanja Ivanovic     if (CopySrc == PPC::CR0GT || CopySrc == PPC::CR6GT)
5556f590bf8SNemanja Ivanovic       Subreg = PPC::sub_gt;
5566f590bf8SNemanja Ivanovic     if (CopySrc == PPC::CR0UN || CopySrc == PPC::CR6UN)
5576f590bf8SNemanja Ivanovic       Subreg = PPC::sub_un;
5586f590bf8SNemanja Ivanovic     // Loop backwards and return the first MI that modifies the physical CR Reg.
5596f590bf8SNemanja Ivanovic     MachineBasicBlock::iterator Me = Copy, B = Copy->getParent()->begin();
5606f590bf8SNemanja Ivanovic     while (Me != B)
5616f590bf8SNemanja Ivanovic       if ((--Me)->modifiesRegister(CopySrc, TRI))
5626f590bf8SNemanja Ivanovic         return &*Me;
5636f590bf8SNemanja Ivanovic     return nullptr;
5646f590bf8SNemanja Ivanovic   }
5656f590bf8SNemanja Ivanovic   return MRI->getVRegDef(CopySrc);
5666f590bf8SNemanja Ivanovic }
5676f590bf8SNemanja Ivanovic 
initialize(MachineFunction & MFParam)5686f590bf8SNemanja Ivanovic void PPCReduceCRLogicals::initialize(MachineFunction &MFParam) {
5696f590bf8SNemanja Ivanovic   MF = &MFParam;
5706f590bf8SNemanja Ivanovic   MRI = &MF->getRegInfo();
5716f590bf8SNemanja Ivanovic   TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
5726f590bf8SNemanja Ivanovic   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
5736f590bf8SNemanja Ivanovic 
5746f590bf8SNemanja Ivanovic   AllCRLogicalOps.clear();
5756f590bf8SNemanja Ivanovic }
5766f590bf8SNemanja Ivanovic 
5776f590bf8SNemanja Ivanovic /// Contains all the implemented transformations on CR logical operations.
5786f590bf8SNemanja Ivanovic /// For example, a binary CR logical can be used to split a block on its inputs,
5796f590bf8SNemanja Ivanovic /// a unary CR logical might be used to change the condition code on a
5806f590bf8SNemanja Ivanovic /// comparison feeding it. A nullary CR logical might simply be removable
5816f590bf8SNemanja Ivanovic /// if the user of the bit it [un]sets can be transformed.
handleCROp(unsigned Idx)582f2c8f3b1SNemanja Ivanovic bool PPCReduceCRLogicals::handleCROp(unsigned Idx) {
5836f590bf8SNemanja Ivanovic   // We can definitely split a block on the inputs to a binary CR operation
5846f590bf8SNemanja Ivanovic   // whose defs and (single) use are within the same block.
5856f590bf8SNemanja Ivanovic   bool Changed = false;
586f2c8f3b1SNemanja Ivanovic   CRLogicalOpInfo CRI = AllCRLogicalOps[Idx];
5876f590bf8SNemanja Ivanovic   if (CRI.IsBinary && CRI.ContainedInBlock && CRI.SingleUse && CRI.FeedsBR &&
5886f590bf8SNemanja Ivanovic       CRI.DefsSingleUse) {
5896f590bf8SNemanja Ivanovic     Changed = splitBlockOnBinaryCROp(CRI);
5906f590bf8SNemanja Ivanovic     if (Changed)
5916f590bf8SNemanja Ivanovic       NumBlocksSplitOnBinaryCROp++;
5926f590bf8SNemanja Ivanovic   }
5936f590bf8SNemanja Ivanovic   return Changed;
5946f590bf8SNemanja Ivanovic }
5956f590bf8SNemanja Ivanovic 
5966f590bf8SNemanja Ivanovic /// Splits a block that contains a CR-logical operation that feeds a branch
5976f590bf8SNemanja Ivanovic /// and whose operands are produced within the block.
5986f590bf8SNemanja Ivanovic /// Example:
5996f590bf8SNemanja Ivanovic ///    %vr5<def> = CMPDI %vr2, 0; CRRC:%vr5 G8RC:%vr2
6006f590bf8SNemanja Ivanovic ///    %vr6<def> = COPY %vr5:sub_eq; CRBITRC:%vr6 CRRC:%vr5
6016f590bf8SNemanja Ivanovic ///    %vr7<def> = CMPDI %vr3, 0; CRRC:%vr7 G8RC:%vr3
6026f590bf8SNemanja Ivanovic ///    %vr8<def> = COPY %vr7:sub_eq; CRBITRC:%vr8 CRRC:%vr7
6036f590bf8SNemanja Ivanovic ///    %vr9<def> = CROR %vr6<kill>, %vr8<kill>; CRBITRC:%vr9,%vr6,%vr8
6046f590bf8SNemanja Ivanovic ///    BC %vr9<kill>, <BB#2>; CRBITRC:%vr9
6056f590bf8SNemanja Ivanovic /// Becomes:
6066f590bf8SNemanja Ivanovic ///    %vr5<def> = CMPDI %vr2, 0; CRRC:%vr5 G8RC:%vr2
6076f590bf8SNemanja Ivanovic ///    %vr6<def> = COPY %vr5:sub_eq; CRBITRC:%vr6 CRRC:%vr5
6086f590bf8SNemanja Ivanovic ///    BC %vr6<kill>, <BB#2>; CRBITRC:%vr6
6096f590bf8SNemanja Ivanovic ///
6106f590bf8SNemanja Ivanovic ///    %vr7<def> = CMPDI %vr3, 0; CRRC:%vr7 G8RC:%vr3
6116f590bf8SNemanja Ivanovic ///    %vr8<def> = COPY %vr7:sub_eq; CRBITRC:%vr8 CRRC:%vr7
6126f590bf8SNemanja Ivanovic ///    BC %vr9<kill>, <BB#2>; CRBITRC:%vr9
splitBlockOnBinaryCROp(CRLogicalOpInfo & CRI)6136f590bf8SNemanja Ivanovic bool PPCReduceCRLogicals::splitBlockOnBinaryCROp(CRLogicalOpInfo &CRI) {
6146f590bf8SNemanja Ivanovic   if (CRI.CopyDefs.first == CRI.CopyDefs.second) {
615d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Unable to split as the two operands are the same\n");
6166f590bf8SNemanja Ivanovic     NumNotSplitIdenticalOperands++;
6176f590bf8SNemanja Ivanovic     return false;
6186f590bf8SNemanja Ivanovic   }
6196f590bf8SNemanja Ivanovic   if (CRI.TrueDefs.first->isCopy() || CRI.TrueDefs.second->isCopy() ||
6206f590bf8SNemanja Ivanovic       CRI.TrueDefs.first->isPHI() || CRI.TrueDefs.second->isPHI()) {
621d34e60caSNicola Zaghen     LLVM_DEBUG(
622d34e60caSNicola Zaghen         dbgs() << "Unable to split because one of the operands is a PHI or "
6236f590bf8SNemanja Ivanovic                   "chain of copies.\n");
6246f590bf8SNemanja Ivanovic     NumNotSplitChainCopies++;
6256f590bf8SNemanja Ivanovic     return false;
6266f590bf8SNemanja Ivanovic   }
6276f590bf8SNemanja Ivanovic   // Note: keep in sync with computeBranchTargetAndInversion().
6286f590bf8SNemanja Ivanovic   if (CRI.MI->getOpcode() != PPC::CROR &&
6296f590bf8SNemanja Ivanovic       CRI.MI->getOpcode() != PPC::CRAND &&
6306f590bf8SNemanja Ivanovic       CRI.MI->getOpcode() != PPC::CRNOR &&
6316f590bf8SNemanja Ivanovic       CRI.MI->getOpcode() != PPC::CRNAND &&
6326f590bf8SNemanja Ivanovic       CRI.MI->getOpcode() != PPC::CRORC &&
6336f590bf8SNemanja Ivanovic       CRI.MI->getOpcode() != PPC::CRANDC) {
634d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Unable to split blocks on this opcode.\n");
6356f590bf8SNemanja Ivanovic     NumNotSplitWrongOpcode++;
6366f590bf8SNemanja Ivanovic     return false;
6376f590bf8SNemanja Ivanovic   }
638d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Splitting the following CR op:\n"; CRI.dump());
6396f590bf8SNemanja Ivanovic   MachineBasicBlock::iterator Def1It = CRI.TrueDefs.first;
6406f590bf8SNemanja Ivanovic   MachineBasicBlock::iterator Def2It = CRI.TrueDefs.second;
6416f590bf8SNemanja Ivanovic 
6426f590bf8SNemanja Ivanovic   bool UsingDef1 = false;
6436f590bf8SNemanja Ivanovic   MachineInstr *SplitBefore = &*Def2It;
6446f590bf8SNemanja Ivanovic   for (auto E = CRI.MI->getParent()->end(); Def2It != E; ++Def2It) {
6456f590bf8SNemanja Ivanovic     if (Def1It == Def2It) { // Def2 comes before Def1.
6466f590bf8SNemanja Ivanovic       SplitBefore = &*Def1It;
6476f590bf8SNemanja Ivanovic       UsingDef1 = true;
6486f590bf8SNemanja Ivanovic       break;
6496f590bf8SNemanja Ivanovic     }
6506f590bf8SNemanja Ivanovic   }
6516f590bf8SNemanja Ivanovic 
652d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "We will split the following block:\n";);
653d34e60caSNicola Zaghen   LLVM_DEBUG(CRI.MI->getParent()->dump());
654d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Before instruction:\n"; SplitBefore->dump());
6556f590bf8SNemanja Ivanovic 
6566f590bf8SNemanja Ivanovic   // Get the branch instruction.
6576f590bf8SNemanja Ivanovic   MachineInstr *Branch =
6586f590bf8SNemanja Ivanovic     MRI->use_nodbg_begin(CRI.MI->getOperand(0).getReg())->getParent();
6596f590bf8SNemanja Ivanovic 
6606f590bf8SNemanja Ivanovic   // We want the new block to have no code in it other than the definition
6616f590bf8SNemanja Ivanovic   // of the input to the CR logical and the CR logical itself. So we move
6626f590bf8SNemanja Ivanovic   // those to the bottom of the block (just before the branch). Then we
6636f590bf8SNemanja Ivanovic   // will split before the CR logical.
6646f590bf8SNemanja Ivanovic   MachineBasicBlock *MBB = SplitBefore->getParent();
6656f590bf8SNemanja Ivanovic   auto FirstTerminator = MBB->getFirstTerminator();
6666f590bf8SNemanja Ivanovic   MachineBasicBlock::iterator FirstInstrToMove =
6676f590bf8SNemanja Ivanovic     UsingDef1 ? CRI.TrueDefs.first : CRI.TrueDefs.second;
6686f590bf8SNemanja Ivanovic   MachineBasicBlock::iterator SecondInstrToMove =
6696f590bf8SNemanja Ivanovic     UsingDef1 ? CRI.CopyDefs.first : CRI.CopyDefs.second;
6706f590bf8SNemanja Ivanovic 
6716f590bf8SNemanja Ivanovic   // The instructions that need to be moved are not guaranteed to be
6726f590bf8SNemanja Ivanovic   // contiguous. Move them individually.
6736f590bf8SNemanja Ivanovic   // FIXME: If one of the operands is a chain of (single use) copies, they
6746f590bf8SNemanja Ivanovic   // can all be moved and we can still split.
6756f590bf8SNemanja Ivanovic   MBB->splice(FirstTerminator, MBB, FirstInstrToMove);
6766f590bf8SNemanja Ivanovic   if (FirstInstrToMove != SecondInstrToMove)
6776f590bf8SNemanja Ivanovic     MBB->splice(FirstTerminator, MBB, SecondInstrToMove);
6786f590bf8SNemanja Ivanovic   MBB->splice(FirstTerminator, MBB, CRI.MI);
6796f590bf8SNemanja Ivanovic 
6806f590bf8SNemanja Ivanovic   unsigned Opc = CRI.MI->getOpcode();
6816f590bf8SNemanja Ivanovic   bool InvertOrigBranch, InvertNewBranch, TargetIsFallThrough;
6826f590bf8SNemanja Ivanovic   computeBranchTargetAndInversion(Opc, Branch->getOpcode(), UsingDef1,
6836f590bf8SNemanja Ivanovic                                   InvertNewBranch, InvertOrigBranch,
6846f590bf8SNemanja Ivanovic                                   TargetIsFallThrough);
6856f590bf8SNemanja Ivanovic   MachineInstr *SplitCond =
6866f590bf8SNemanja Ivanovic     UsingDef1 ? CRI.CopyDefs.second : CRI.CopyDefs.first;
687d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "We will " << (InvertNewBranch ? "invert" : "copy"));
688d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " the original branch and the target is the "
689d34e60caSNicola Zaghen                     << (TargetIsFallThrough ? "fallthrough block\n"
690d34e60caSNicola Zaghen                                             : "orig. target block\n"));
691d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Original branch instruction: "; Branch->dump());
6926f590bf8SNemanja Ivanovic   BlockSplitInfo BSI { Branch, SplitBefore, SplitCond, InvertNewBranch,
6936f590bf8SNemanja Ivanovic     InvertOrigBranch, TargetIsFallThrough, MBPI, CRI.MI,
6946f590bf8SNemanja Ivanovic     UsingDef1 ? CRI.CopyDefs.first : CRI.CopyDefs.second };
6956f590bf8SNemanja Ivanovic   bool Changed = splitMBB(BSI);
6966f590bf8SNemanja Ivanovic   // If we've split on a CR logical that is fed by a CR logical,
6976f590bf8SNemanja Ivanovic   // recompute the source CR logical as it may be usable for splitting.
6986f590bf8SNemanja Ivanovic   if (Changed) {
6996f590bf8SNemanja Ivanovic     bool Input1CRlogical =
7006f590bf8SNemanja Ivanovic       CRI.TrueDefs.first && isCRLogical(*CRI.TrueDefs.first);
7016f590bf8SNemanja Ivanovic     bool Input2CRlogical =
7026f590bf8SNemanja Ivanovic       CRI.TrueDefs.second && isCRLogical(*CRI.TrueDefs.second);
7036f590bf8SNemanja Ivanovic     if (Input1CRlogical)
7046f590bf8SNemanja Ivanovic       AllCRLogicalOps.push_back(createCRLogicalOpInfo(*CRI.TrueDefs.first));
7056f590bf8SNemanja Ivanovic     if (Input2CRlogical)
7066f590bf8SNemanja Ivanovic       AllCRLogicalOps.push_back(createCRLogicalOpInfo(*CRI.TrueDefs.second));
7076f590bf8SNemanja Ivanovic   }
7086f590bf8SNemanja Ivanovic   return Changed;
7096f590bf8SNemanja Ivanovic }
7106f590bf8SNemanja Ivanovic 
collectCRLogicals()7116f590bf8SNemanja Ivanovic void PPCReduceCRLogicals::collectCRLogicals() {
7126f590bf8SNemanja Ivanovic   for (MachineBasicBlock &MBB : *MF) {
7136f590bf8SNemanja Ivanovic     for (MachineInstr &MI : MBB) {
7146f590bf8SNemanja Ivanovic       if (isCRLogical(MI)) {
7156f590bf8SNemanja Ivanovic         AllCRLogicalOps.push_back(createCRLogicalOpInfo(MI));
7166f590bf8SNemanja Ivanovic         TotalCRLogicals++;
7176f590bf8SNemanja Ivanovic         if (AllCRLogicalOps.back().IsNullary)
7186f590bf8SNemanja Ivanovic           TotalNullaryCRLogicals++;
7196f590bf8SNemanja Ivanovic         else if (AllCRLogicalOps.back().IsBinary)
7206f590bf8SNemanja Ivanovic           TotalBinaryCRLogicals++;
7216f590bf8SNemanja Ivanovic         else
7226f590bf8SNemanja Ivanovic           TotalUnaryCRLogicals++;
7236f590bf8SNemanja Ivanovic       }
7246f590bf8SNemanja Ivanovic     }
7256f590bf8SNemanja Ivanovic   }
7266f590bf8SNemanja Ivanovic }
7276f590bf8SNemanja Ivanovic 
7280f7f59f0SHiroshi Inoue } // end anonymous namespace
7296f590bf8SNemanja Ivanovic 
7306f590bf8SNemanja Ivanovic INITIALIZE_PASS_BEGIN(PPCReduceCRLogicals, DEBUG_TYPE,
7316f590bf8SNemanja Ivanovic                       "PowerPC Reduce CR logical Operation", false, false)
7326f590bf8SNemanja Ivanovic INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
7336f590bf8SNemanja Ivanovic INITIALIZE_PASS_END(PPCReduceCRLogicals, DEBUG_TYPE,
7346f590bf8SNemanja Ivanovic                     "PowerPC Reduce CR logical Operation", false, false)
7356f590bf8SNemanja Ivanovic 
7366f590bf8SNemanja Ivanovic char PPCReduceCRLogicals::ID = 0;
7376f590bf8SNemanja Ivanovic FunctionPass*
createPPCReduceCRLogicalsPass()7386f590bf8SNemanja Ivanovic llvm::createPPCReduceCRLogicalsPass() { return new PPCReduceCRLogicals(); }
739