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