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