134af5e1cSBill Schmidt //===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
234af5e1cSBill Schmidt //
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
634af5e1cSBill Schmidt //
734af5e1cSBill Schmidt //===---------------------------------------------------------------------===//
834af5e1cSBill Schmidt //
934af5e1cSBill Schmidt // This pass performs peephole optimizations to clean up ugly code
1034af5e1cSBill Schmidt // sequences at the MachineInstruction layer.  It runs at the end of
1134af5e1cSBill Schmidt // the SSA phases, following VSX swap removal.  A pass of dead code
1234af5e1cSBill Schmidt // elimination follows this one for quick clean-up of any dead
1334af5e1cSBill Schmidt // instructions introduced here.  Although we could do this as callbacks
1434af5e1cSBill Schmidt // from the generic peephole pass, this would have a couple of bad
1534af5e1cSBill Schmidt // effects:  it might remove optimization opportunities for VSX swap
1634af5e1cSBill Schmidt // removal, and it would miss cleanups made possible following VSX
1734af5e1cSBill Schmidt // swap removal.
1834af5e1cSBill Schmidt //
1934af5e1cSBill Schmidt //===---------------------------------------------------------------------===//
2034af5e1cSBill Schmidt 
21f0ba1aecSczhengsz #include "MCTargetDesc/PPCMCTargetDesc.h"
2205da2fe5SReid Kleckner #include "MCTargetDesc/PPCPredicates.h"
2334af5e1cSBill Schmidt #include "PPC.h"
2434af5e1cSBill Schmidt #include "PPCInstrBuilder.h"
256bda14b3SChandler Carruth #include "PPCInstrInfo.h"
266c9a392cSNemanja Ivanovic #include "PPCMachineFunctionInfo.h"
2734af5e1cSBill Schmidt #include "PPCTargetMachine.h"
282d9c5f3bSTony Jiang #include "llvm/ADT/Statistic.h"
296c9a392cSNemanja Ivanovic #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
302d9c5f3bSTony Jiang #include "llvm/CodeGen/MachineDominators.h"
31989f1c72Sserge-sans-paille #include "llvm/CodeGen/MachineFrameInfo.h"
3234af5e1cSBill Schmidt #include "llvm/CodeGen/MachineFunctionPass.h"
3334af5e1cSBill Schmidt #include "llvm/CodeGen/MachineInstrBuilder.h"
3405da2fe5SReid Kleckner #include "llvm/CodeGen/MachinePostDominators.h"
3534af5e1cSBill Schmidt #include "llvm/CodeGen/MachineRegisterInfo.h"
3605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
3734af5e1cSBill Schmidt #include "llvm/Support/Debug.h"
3834af5e1cSBill Schmidt 
3934af5e1cSBill Schmidt using namespace llvm;
4034af5e1cSBill Schmidt 
4134af5e1cSBill Schmidt #define DEBUG_TYPE "ppc-mi-peepholes"
4234af5e1cSBill Schmidt 
43f94d58d9SZaara Syeda STATISTIC(RemoveTOCSave, "Number of TOC saves removed");
44f94d58d9SZaara Syeda STATISTIC(MultiTOCSaves,
45f94d58d9SZaara Syeda           "Number of functions with multiple TOC saves that must be kept");
466c9a392cSNemanja Ivanovic STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue");
47e3a3e3c9SHiroshi Inoue STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
48e3a3e3c9SHiroshi Inoue STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
492d9c5f3bSTony Jiang STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
506995e5daSNemanja Ivanovic STATISTIC(NumConvertedToImmediateForm,
516995e5daSNemanja Ivanovic           "Number of instructions converted to their immediate form");
526995e5daSNemanja Ivanovic STATISTIC(NumFunctionsEnteredInMIPeephole,
536995e5daSNemanja Ivanovic           "Number of functions entered in PPC MI Peepholes");
546995e5daSNemanja Ivanovic STATISTIC(NumFixedPointIterations,
556995e5daSNemanja Ivanovic           "Number of fixed-point iterations converting reg-reg instructions "
566995e5daSNemanja Ivanovic           "to reg-imm ones");
577c842fadSNemanja Ivanovic STATISTIC(NumRotatesCollapsed,
587c842fadSNemanja Ivanovic           "Number of pairs of rotate left, clear left/right collapsed");
591931ed73SKai Luo STATISTIC(NumEXTSWAndSLDICombined,
601931ed73SKai Luo           "Number of pairs of EXTSW and SLDI combined as EXTSWSLI");
61cd83333fSKamau Bridgeman STATISTIC(NumLoadImmZeroFoldedAndRemoved,
62cd83333fSKamau Bridgeman           "Number of LI(8) reg, 0 that are folded to r0 and removed");
636995e5daSNemanja Ivanovic 
646995e5daSNemanja Ivanovic static cl::opt<bool>
656995e5daSNemanja Ivanovic FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true),
666995e5daSNemanja Ivanovic                    cl::desc("Iterate to a fixed point when attempting to "
676995e5daSNemanja Ivanovic                             "convert reg-reg instructions to reg-imm"));
686995e5daSNemanja Ivanovic 
696995e5daSNemanja Ivanovic static cl::opt<bool>
704e1f5e07SNemanja Ivanovic ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true),
716995e5daSNemanja Ivanovic               cl::desc("Convert eligible reg+reg instructions to reg+imm"));
722d9c5f3bSTony Jiang 
73e3a3e3c9SHiroshi Inoue static cl::opt<bool>
74e3a3e3c9SHiroshi Inoue     EnableSExtElimination("ppc-eliminate-signext",
75e3a3e3c9SHiroshi Inoue                           cl::desc("enable elimination of sign-extensions"),
760026c06eSNemanja Ivanovic                           cl::init(false), cl::Hidden);
77e3a3e3c9SHiroshi Inoue 
78e3a3e3c9SHiroshi Inoue static cl::opt<bool>
79e3a3e3c9SHiroshi Inoue     EnableZExtElimination("ppc-eliminate-zeroext",
80e3a3e3c9SHiroshi Inoue                           cl::desc("enable elimination of zero-extensions"),
810026c06eSNemanja Ivanovic                           cl::init(false), cl::Hidden);
82e3a3e3c9SHiroshi Inoue 
8386e77cdbSVictor Huang static cl::opt<bool>
8486e77cdbSVictor Huang     EnableTrapOptimization("ppc-opt-conditional-trap",
8586e77cdbSVictor Huang                            cl::desc("enable optimization of conditional traps"),
8686e77cdbSVictor Huang                            cl::init(false), cl::Hidden);
8786e77cdbSVictor Huang 
8834af5e1cSBill Schmidt namespace {
8934af5e1cSBill Schmidt 
9034af5e1cSBill Schmidt struct PPCMIPeephole : public MachineFunctionPass {
9134af5e1cSBill Schmidt 
9234af5e1cSBill Schmidt   static char ID;
9334af5e1cSBill Schmidt   const PPCInstrInfo *TII;
9434af5e1cSBill Schmidt   MachineFunction *MF;
9534af5e1cSBill Schmidt   MachineRegisterInfo *MRI;
9634af5e1cSBill Schmidt 
PPCMIPeephole__anonee9fa6900111::PPCMIPeephole9734af5e1cSBill Schmidt   PPCMIPeephole() : MachineFunctionPass(ID) {
9834af5e1cSBill Schmidt     initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
9934af5e1cSBill Schmidt   }
10034af5e1cSBill Schmidt 
10134af5e1cSBill Schmidt private:
1022d9c5f3bSTony Jiang   MachineDominatorTree *MDT;
1036c9a392cSNemanja Ivanovic   MachinePostDominatorTree *MPDT;
1046c9a392cSNemanja Ivanovic   MachineBlockFrequencyInfo *MBFI;
1056c9a392cSNemanja Ivanovic   uint64_t EntryFreq;
1062d9c5f3bSTony Jiang 
10734af5e1cSBill Schmidt   // Initialize class variables.
10834af5e1cSBill Schmidt   void initialize(MachineFunction &MFParm);
10934af5e1cSBill Schmidt 
11034af5e1cSBill Schmidt   // Perform peepholes.
1117e163afdSKazu Hirata   bool simplifyCode();
11234af5e1cSBill Schmidt 
113614453b7SHiroshi Inoue   // Perform peepholes.
1147e163afdSKazu Hirata   bool eliminateRedundantCompare();
115f94d58d9SZaara Syeda   bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves);
1161931ed73SKai Luo   bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase);
117d6a8bc7aSKai Luo   bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI);
118f94d58d9SZaara Syeda   void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves,
119f94d58d9SZaara Syeda                       MachineInstr *MI);
12034af5e1cSBill Schmidt 
12134af5e1cSBill Schmidt public:
1222d9c5f3bSTony Jiang 
getAnalysisUsage__anonee9fa6900111::PPCMIPeephole1232d9c5f3bSTony Jiang   void getAnalysisUsage(AnalysisUsage &AU) const override {
1242d9c5f3bSTony Jiang     AU.addRequired<MachineDominatorTree>();
1256c9a392cSNemanja Ivanovic     AU.addRequired<MachinePostDominatorTree>();
1266c9a392cSNemanja Ivanovic     AU.addRequired<MachineBlockFrequencyInfo>();
1272d9c5f3bSTony Jiang     AU.addPreserved<MachineDominatorTree>();
1286c9a392cSNemanja Ivanovic     AU.addPreserved<MachinePostDominatorTree>();
1296c9a392cSNemanja Ivanovic     AU.addPreserved<MachineBlockFrequencyInfo>();
1302d9c5f3bSTony Jiang     MachineFunctionPass::getAnalysisUsage(AU);
1312d9c5f3bSTony Jiang   }
1322d9c5f3bSTony Jiang 
13334af5e1cSBill Schmidt   // Main entry point for this pass.
runOnMachineFunction__anonee9fa6900111::PPCMIPeephole13434af5e1cSBill Schmidt   bool runOnMachineFunction(MachineFunction &MF) override {
1356c4b40deSStefan Pintilie     initialize(MF);
13664d44ae7SVictor Huang     // At this point, TOC pointer should not be used in a function that uses
13764d44ae7SVictor Huang     // PC-Relative addressing.
13864d44ae7SVictor Huang     assert((MF.getRegInfo().use_empty(PPC::X2) ||
13964d44ae7SVictor Huang             !MF.getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) &&
14064d44ae7SVictor Huang            "TOC pointer used in a function using PC-Relative addressing!");
141f1caa283SMatthias Braun     if (skipFunction(MF.getFunction()))
142289bd5f6SAndrew Kaylor       return false;
14334af5e1cSBill Schmidt     return simplifyCode();
14434af5e1cSBill Schmidt   }
14534af5e1cSBill Schmidt };
14634af5e1cSBill Schmidt 
14734af5e1cSBill Schmidt // Initialize class variables.
initialize(MachineFunction & MFParm)14834af5e1cSBill Schmidt void PPCMIPeephole::initialize(MachineFunction &MFParm) {
14934af5e1cSBill Schmidt   MF = &MFParm;
15034af5e1cSBill Schmidt   MRI = &MF->getRegInfo();
1512d9c5f3bSTony Jiang   MDT = &getAnalysis<MachineDominatorTree>();
1526c9a392cSNemanja Ivanovic   MPDT = &getAnalysis<MachinePostDominatorTree>();
1536c9a392cSNemanja Ivanovic   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1546c9a392cSNemanja Ivanovic   EntryFreq = MBFI->getEntryFreq();
15534af5e1cSBill Schmidt   TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
156d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
157d34e60caSNicola Zaghen   LLVM_DEBUG(MF->dump());
15834af5e1cSBill Schmidt }
15934af5e1cSBill Schmidt 
getVRegDefOrNull(MachineOperand * Op,MachineRegisterInfo * MRI)1602d9c5f3bSTony Jiang static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
1612d9c5f3bSTony Jiang                                       MachineRegisterInfo *MRI) {
1622d9c5f3bSTony Jiang   assert(Op && "Invalid Operand!");
1632d9c5f3bSTony Jiang   if (!Op->isReg())
1642d9c5f3bSTony Jiang     return nullptr;
1652d9c5f3bSTony Jiang 
1660c476111SDaniel Sanders   Register Reg = Op->getReg();
1672bea69bfSDaniel Sanders   if (!Register::isVirtualRegister(Reg))
1682d9c5f3bSTony Jiang     return nullptr;
1692d9c5f3bSTony Jiang 
1702d9c5f3bSTony Jiang   return MRI->getVRegDef(Reg);
1712d9c5f3bSTony Jiang }
1722d9c5f3bSTony Jiang 
173e3a3e3c9SHiroshi Inoue // This function returns number of known zero bits in output of MI
174e3a3e3c9SHiroshi Inoue // starting from the most significant bit.
175e3a3e3c9SHiroshi Inoue static unsigned
getKnownLeadingZeroCount(MachineInstr * MI,const PPCInstrInfo * TII)176e3a3e3c9SHiroshi Inoue getKnownLeadingZeroCount(MachineInstr *MI, const PPCInstrInfo *TII) {
177e3a3e3c9SHiroshi Inoue   unsigned Opcode = MI->getOpcode();
17824ee4edeSJinsong Ji   if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
17924ee4edeSJinsong Ji       Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec)
180e3a3e3c9SHiroshi Inoue     return MI->getOperand(3).getImm();
181e3a3e3c9SHiroshi Inoue 
18224ee4edeSJinsong Ji   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
183e3a3e3c9SHiroshi Inoue       MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
184e3a3e3c9SHiroshi Inoue     return MI->getOperand(3).getImm();
185e3a3e3c9SHiroshi Inoue 
18624ee4edeSJinsong Ji   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
18724ee4edeSJinsong Ji        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
188e3a3e3c9SHiroshi Inoue        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
189e3a3e3c9SHiroshi Inoue       MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
190e3a3e3c9SHiroshi Inoue     return 32 + MI->getOperand(3).getImm();
191e3a3e3c9SHiroshi Inoue 
19224ee4edeSJinsong Ji   if (Opcode == PPC::ANDI_rec) {
193e3a3e3c9SHiroshi Inoue     uint16_t Imm = MI->getOperand(2).getImm();
194e3a3e3c9SHiroshi Inoue     return 48 + countLeadingZeros(Imm);
195e3a3e3c9SHiroshi Inoue   }
196e3a3e3c9SHiroshi Inoue 
19724ee4edeSJinsong Ji   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
19824ee4edeSJinsong Ji       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
199e3a3e3c9SHiroshi Inoue       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
200e3a3e3c9SHiroshi Inoue     // The result ranges from 0 to 32.
201e3a3e3c9SHiroshi Inoue     return 58;
202e3a3e3c9SHiroshi Inoue 
20324ee4edeSJinsong Ji   if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
20424ee4edeSJinsong Ji       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec)
205e3a3e3c9SHiroshi Inoue     // The result ranges from 0 to 64.
206e3a3e3c9SHiroshi Inoue     return 57;
207e3a3e3c9SHiroshi Inoue 
208e3a3e3c9SHiroshi Inoue   if (Opcode == PPC::LHZ   || Opcode == PPC::LHZX  ||
209e3a3e3c9SHiroshi Inoue       Opcode == PPC::LHZ8  || Opcode == PPC::LHZX8 ||
210e3a3e3c9SHiroshi Inoue       Opcode == PPC::LHZU  || Opcode == PPC::LHZUX ||
211e3a3e3c9SHiroshi Inoue       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
212e3a3e3c9SHiroshi Inoue     return 48;
213e3a3e3c9SHiroshi Inoue 
214e3a3e3c9SHiroshi Inoue   if (Opcode == PPC::LBZ   || Opcode == PPC::LBZX  ||
215e3a3e3c9SHiroshi Inoue       Opcode == PPC::LBZ8  || Opcode == PPC::LBZX8 ||
216e3a3e3c9SHiroshi Inoue       Opcode == PPC::LBZU  || Opcode == PPC::LBZUX ||
217e3a3e3c9SHiroshi Inoue       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
218e3a3e3c9SHiroshi Inoue     return 56;
219e3a3e3c9SHiroshi Inoue 
220e3a3e3c9SHiroshi Inoue   if (TII->isZeroExtended(*MI))
221e3a3e3c9SHiroshi Inoue     return 32;
222e3a3e3c9SHiroshi Inoue 
223e3a3e3c9SHiroshi Inoue   return 0;
224e3a3e3c9SHiroshi Inoue }
225e3a3e3c9SHiroshi Inoue 
226f94d58d9SZaara Syeda // This function maintains a map for the pairs <TOC Save Instr, Keep>
2270f7f59f0SHiroshi Inoue // Each time a new TOC save is encountered, it checks if any of the existing
2280f7f59f0SHiroshi Inoue // ones are dominated by the new one. If so, it marks the existing one as
229f94d58d9SZaara Syeda // redundant by setting it's entry in the map as false. It then adds the new
230f94d58d9SZaara Syeda // instruction to the map with either true or false depending on if any
2310f7f59f0SHiroshi Inoue // existing instructions dominated the new one.
UpdateTOCSaves(std::map<MachineInstr *,bool> & TOCSaves,MachineInstr * MI)232f94d58d9SZaara Syeda void PPCMIPeephole::UpdateTOCSaves(
233f94d58d9SZaara Syeda   std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) {
234f94d58d9SZaara Syeda   assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here");
23552f33f79SQiu Chaofan   // FIXME: Saving TOC in prologue hasn't been implemented well in AIX ABI part,
23652f33f79SQiu Chaofan   // here only support it under ELFv2.
23752f33f79SQiu Chaofan   if (MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) {
2386c9a392cSNemanja Ivanovic     PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2396c9a392cSNemanja Ivanovic 
2406c9a392cSNemanja Ivanovic     MachineBasicBlock *Entry = &MF->front();
2416c9a392cSNemanja Ivanovic     uint64_t CurrBlockFreq = MBFI->getBlockFreq(MI->getParent()).getFrequency();
2426c9a392cSNemanja Ivanovic 
2436c9a392cSNemanja Ivanovic     // If the block in which the TOC save resides is in a block that
2446c9a392cSNemanja Ivanovic     // post-dominates Entry, or a block that is hotter than entry (keep in mind
2456c9a392cSNemanja Ivanovic     // that early MachineLICM has already run so the TOC save won't be hoisted)
2466c9a392cSNemanja Ivanovic     // we can just do the save in the prologue.
2476c9a392cSNemanja Ivanovic     if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry))
2486c9a392cSNemanja Ivanovic       FI->setMustSaveTOC(true);
2496c9a392cSNemanja Ivanovic 
25052f33f79SQiu Chaofan     // If we are saving the TOC in the prologue, all the TOC saves can be
25152f33f79SQiu Chaofan     // removed from the code.
2526c9a392cSNemanja Ivanovic     if (FI->mustSaveTOC()) {
2536c9a392cSNemanja Ivanovic       for (auto &TOCSave : TOCSaves)
2546c9a392cSNemanja Ivanovic         TOCSave.second = false;
2556c9a392cSNemanja Ivanovic       // Add new instruction to map.
2566c9a392cSNemanja Ivanovic       TOCSaves[MI] = false;
2576c9a392cSNemanja Ivanovic       return;
2586c9a392cSNemanja Ivanovic     }
25952f33f79SQiu Chaofan   }
2606c9a392cSNemanja Ivanovic 
261f94d58d9SZaara Syeda   bool Keep = true;
262bf039a86SKazu Hirata   for (auto &I : TOCSaves) {
263bf039a86SKazu Hirata     MachineInstr *CurrInst = I.first;
2640f7f59f0SHiroshi Inoue     // If new instruction dominates an existing one, mark existing one as
265f94d58d9SZaara Syeda     // redundant.
266bf039a86SKazu Hirata     if (I.second && MDT->dominates(MI, CurrInst))
267bf039a86SKazu Hirata       I.second = false;
268f94d58d9SZaara Syeda     // Check if the new instruction is redundant.
269f94d58d9SZaara Syeda     if (MDT->dominates(CurrInst, MI)) {
270f94d58d9SZaara Syeda       Keep = false;
271f94d58d9SZaara Syeda       break;
272f94d58d9SZaara Syeda     }
273f94d58d9SZaara Syeda   }
274f94d58d9SZaara Syeda   // Add new instruction to map.
275f94d58d9SZaara Syeda   TOCSaves[MI] = Keep;
276f94d58d9SZaara Syeda }
277f94d58d9SZaara Syeda 
27845ec3a37SBaptiste Saleil // This function returns a list of all PHI nodes in the tree starting from
27945ec3a37SBaptiste Saleil // the RootPHI node. We perform a BFS traversal to get an ordered list of nodes.
28045ec3a37SBaptiste Saleil // The list initially only contains the root PHI. When we visit a PHI node, we
28145ec3a37SBaptiste Saleil // add it to the list. We continue to look for other PHI node operands while
28245ec3a37SBaptiste Saleil // there are nodes to visit in the list. The function returns false if the
28345ec3a37SBaptiste Saleil // optimization cannot be applied on this tree.
collectUnprimedAccPHIs(MachineRegisterInfo * MRI,MachineInstr * RootPHI,SmallVectorImpl<MachineInstr * > & PHIs)28445ec3a37SBaptiste Saleil static bool collectUnprimedAccPHIs(MachineRegisterInfo *MRI,
28545ec3a37SBaptiste Saleil                                    MachineInstr *RootPHI,
28645ec3a37SBaptiste Saleil                                    SmallVectorImpl<MachineInstr *> &PHIs) {
28745ec3a37SBaptiste Saleil   PHIs.push_back(RootPHI);
28845ec3a37SBaptiste Saleil   unsigned VisitedIndex = 0;
28945ec3a37SBaptiste Saleil   while (VisitedIndex < PHIs.size()) {
29045ec3a37SBaptiste Saleil     MachineInstr *VisitedPHI = PHIs[VisitedIndex];
29145ec3a37SBaptiste Saleil     for (unsigned PHIOp = 1, NumOps = VisitedPHI->getNumOperands();
29245ec3a37SBaptiste Saleil          PHIOp != NumOps; PHIOp += 2) {
29345ec3a37SBaptiste Saleil       Register RegOp = VisitedPHI->getOperand(PHIOp).getReg();
29445ec3a37SBaptiste Saleil       if (!Register::isVirtualRegister(RegOp))
29545ec3a37SBaptiste Saleil         return false;
29645ec3a37SBaptiste Saleil       MachineInstr *Instr = MRI->getVRegDef(RegOp);
29745ec3a37SBaptiste Saleil       // While collecting the PHI nodes, we check if they can be converted (i.e.
29845ec3a37SBaptiste Saleil       // all the operands are either copies, implicit defs or PHI nodes).
29945ec3a37SBaptiste Saleil       unsigned Opcode = Instr->getOpcode();
30045ec3a37SBaptiste Saleil       if (Opcode == PPC::COPY) {
30145ec3a37SBaptiste Saleil         Register Reg = Instr->getOperand(1).getReg();
30245ec3a37SBaptiste Saleil         if (!Register::isVirtualRegister(Reg) ||
30345ec3a37SBaptiste Saleil             MRI->getRegClass(Reg) != &PPC::ACCRCRegClass)
30445ec3a37SBaptiste Saleil           return false;
30545ec3a37SBaptiste Saleil       } else if (Opcode != PPC::IMPLICIT_DEF && Opcode != PPC::PHI)
30645ec3a37SBaptiste Saleil         return false;
30745ec3a37SBaptiste Saleil       // If we detect a cycle in the PHI nodes, we exit. It would be
30845ec3a37SBaptiste Saleil       // possible to change cycles as well, but that would add a lot
30945ec3a37SBaptiste Saleil       // of complexity for a case that is unlikely to occur with MMA
31045ec3a37SBaptiste Saleil       // code.
31145ec3a37SBaptiste Saleil       if (Opcode != PPC::PHI)
31245ec3a37SBaptiste Saleil         continue;
313913515e4SKazu Hirata       if (llvm::is_contained(PHIs, Instr))
31445ec3a37SBaptiste Saleil         return false;
31545ec3a37SBaptiste Saleil       PHIs.push_back(Instr);
31645ec3a37SBaptiste Saleil     }
31745ec3a37SBaptiste Saleil     VisitedIndex++;
31845ec3a37SBaptiste Saleil   }
31945ec3a37SBaptiste Saleil   return true;
32045ec3a37SBaptiste Saleil }
32145ec3a37SBaptiste Saleil 
32245ec3a37SBaptiste Saleil // This function changes the unprimed accumulator PHI nodes in the PHIs list to
32345ec3a37SBaptiste Saleil // primed accumulator PHI nodes. The list is traversed in reverse order to
32445ec3a37SBaptiste Saleil // change all the PHI operands of a PHI node before changing the node itself.
32545ec3a37SBaptiste Saleil // We keep a map to associate each changed PHI node to its non-changed form.
convertUnprimedAccPHIs(const PPCInstrInfo * TII,MachineRegisterInfo * MRI,SmallVectorImpl<MachineInstr * > & PHIs,Register Dst)32645ec3a37SBaptiste Saleil static void convertUnprimedAccPHIs(const PPCInstrInfo *TII,
32745ec3a37SBaptiste Saleil                                    MachineRegisterInfo *MRI,
32845ec3a37SBaptiste Saleil                                    SmallVectorImpl<MachineInstr *> &PHIs,
32945ec3a37SBaptiste Saleil                                    Register Dst) {
33045ec3a37SBaptiste Saleil   DenseMap<MachineInstr *, MachineInstr *> ChangedPHIMap;
33114d656b3SKazu Hirata   for (MachineInstr *PHI : llvm::reverse(PHIs)) {
33245ec3a37SBaptiste Saleil     SmallVector<std::pair<MachineOperand, MachineOperand>, 4> PHIOps;
33345ec3a37SBaptiste Saleil     // We check if the current PHI node can be changed by looking at its
33445ec3a37SBaptiste Saleil     // operands. If all the operands are either copies from primed
33545ec3a37SBaptiste Saleil     // accumulators, implicit definitions or other unprimed accumulator
33645ec3a37SBaptiste Saleil     // PHI nodes, we change it.
33745ec3a37SBaptiste Saleil     for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
33845ec3a37SBaptiste Saleil          PHIOp += 2) {
33945ec3a37SBaptiste Saleil       Register RegOp = PHI->getOperand(PHIOp).getReg();
34045ec3a37SBaptiste Saleil       MachineInstr *PHIInput = MRI->getVRegDef(RegOp);
34145ec3a37SBaptiste Saleil       unsigned Opcode = PHIInput->getOpcode();
34245ec3a37SBaptiste Saleil       assert((Opcode == PPC::COPY || Opcode == PPC::IMPLICIT_DEF ||
34345ec3a37SBaptiste Saleil               Opcode == PPC::PHI) &&
34445ec3a37SBaptiste Saleil              "Unexpected instruction");
34545ec3a37SBaptiste Saleil       if (Opcode == PPC::COPY) {
34645ec3a37SBaptiste Saleil         assert(MRI->getRegClass(PHIInput->getOperand(1).getReg()) ==
34745ec3a37SBaptiste Saleil                    &PPC::ACCRCRegClass &&
34845ec3a37SBaptiste Saleil                "Unexpected register class");
34945ec3a37SBaptiste Saleil         PHIOps.push_back({PHIInput->getOperand(1), PHI->getOperand(PHIOp + 1)});
35045ec3a37SBaptiste Saleil       } else if (Opcode == PPC::IMPLICIT_DEF) {
35145ec3a37SBaptiste Saleil         Register AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
35245ec3a37SBaptiste Saleil         BuildMI(*PHIInput->getParent(), PHIInput, PHIInput->getDebugLoc(),
35345ec3a37SBaptiste Saleil                 TII->get(PPC::IMPLICIT_DEF), AccReg);
35445ec3a37SBaptiste Saleil         PHIOps.push_back({MachineOperand::CreateReg(AccReg, false),
35545ec3a37SBaptiste Saleil                           PHI->getOperand(PHIOp + 1)});
35645ec3a37SBaptiste Saleil       } else if (Opcode == PPC::PHI) {
35745ec3a37SBaptiste Saleil         // We found a PHI operand. At this point we know this operand
35845ec3a37SBaptiste Saleil         // has already been changed so we get its associated changed form
35945ec3a37SBaptiste Saleil         // from the map.
36045ec3a37SBaptiste Saleil         assert(ChangedPHIMap.count(PHIInput) == 1 &&
36145ec3a37SBaptiste Saleil                "This PHI node should have already been changed.");
36245ec3a37SBaptiste Saleil         MachineInstr *PrimedAccPHI = ChangedPHIMap.lookup(PHIInput);
36345ec3a37SBaptiste Saleil         PHIOps.push_back({MachineOperand::CreateReg(
36445ec3a37SBaptiste Saleil                               PrimedAccPHI->getOperand(0).getReg(), false),
36545ec3a37SBaptiste Saleil                           PHI->getOperand(PHIOp + 1)});
36645ec3a37SBaptiste Saleil       }
36745ec3a37SBaptiste Saleil     }
36845ec3a37SBaptiste Saleil     Register AccReg = Dst;
36945ec3a37SBaptiste Saleil     // If the PHI node we are changing is the root node, the register it defines
37045ec3a37SBaptiste Saleil     // will be the destination register of the original copy (of the PHI def).
37145ec3a37SBaptiste Saleil     // For all other PHI's in the list, we need to create another primed
37245ec3a37SBaptiste Saleil     // accumulator virtual register as the PHI will no longer define the
37345ec3a37SBaptiste Saleil     // unprimed accumulator.
37445ec3a37SBaptiste Saleil     if (PHI != PHIs[0])
37545ec3a37SBaptiste Saleil       AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
37645ec3a37SBaptiste Saleil     MachineInstrBuilder NewPHI = BuildMI(
37745ec3a37SBaptiste Saleil         *PHI->getParent(), PHI, PHI->getDebugLoc(), TII->get(PPC::PHI), AccReg);
37845ec3a37SBaptiste Saleil     for (auto RegMBB : PHIOps)
37945ec3a37SBaptiste Saleil       NewPHI.add(RegMBB.first).add(RegMBB.second);
38045ec3a37SBaptiste Saleil     ChangedPHIMap[PHI] = NewPHI.getInstr();
38145ec3a37SBaptiste Saleil   }
38245ec3a37SBaptiste Saleil }
38345ec3a37SBaptiste Saleil 
38434af5e1cSBill Schmidt // Perform peephole optimizations.
simplifyCode()3857e163afdSKazu Hirata bool PPCMIPeephole::simplifyCode() {
38634af5e1cSBill Schmidt   bool Simplified = false;
387ae27ca9aSVictor Huang   bool TrapOpt = false;
38834af5e1cSBill Schmidt   MachineInstr* ToErase = nullptr;
389f94d58d9SZaara Syeda   std::map<MachineInstr *, bool> TOCSaves;
39065359936SZaara Syeda   const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
3916995e5daSNemanja Ivanovic   NumFunctionsEnteredInMIPeephole++;
3926995e5daSNemanja Ivanovic   if (ConvertRegReg) {
3936995e5daSNemanja Ivanovic     // Fixed-point conversion of reg/reg instructions fed by load-immediate
3946995e5daSNemanja Ivanovic     // into reg/imm instructions. FIXME: This is expensive, control it with
3956995e5daSNemanja Ivanovic     // an option.
3966995e5daSNemanja Ivanovic     bool SomethingChanged = false;
3976995e5daSNemanja Ivanovic     do {
3986995e5daSNemanja Ivanovic       NumFixedPointIterations++;
3996995e5daSNemanja Ivanovic       SomethingChanged = false;
4006995e5daSNemanja Ivanovic       for (MachineBasicBlock &MBB : *MF) {
4016995e5daSNemanja Ivanovic         for (MachineInstr &MI : MBB) {
402801bf7ebSShiva Chen           if (MI.isDebugInstr())
4036995e5daSNemanja Ivanovic             continue;
4046995e5daSNemanja Ivanovic 
4056995e5daSNemanja Ivanovic           if (TII->convertToImmediateForm(MI)) {
4066995e5daSNemanja Ivanovic             // We don't erase anything in case the def has other uses. Let DCE
4076995e5daSNemanja Ivanovic             // remove it if it can be removed.
408d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
409d34e60caSNicola Zaghen             LLVM_DEBUG(MI.dump());
4106995e5daSNemanja Ivanovic             NumConvertedToImmediateForm++;
4116995e5daSNemanja Ivanovic             SomethingChanged = true;
4126995e5daSNemanja Ivanovic             Simplified = true;
4136995e5daSNemanja Ivanovic             continue;
4146995e5daSNemanja Ivanovic           }
4156995e5daSNemanja Ivanovic         }
4166995e5daSNemanja Ivanovic       }
4176995e5daSNemanja Ivanovic     } while (SomethingChanged && FixedPointRegToImm);
4186995e5daSNemanja Ivanovic   }
4196995e5daSNemanja Ivanovic 
42034af5e1cSBill Schmidt   for (MachineBasicBlock &MBB : *MF) {
42134af5e1cSBill Schmidt     for (MachineInstr &MI : MBB) {
42234af5e1cSBill Schmidt 
42334af5e1cSBill Schmidt       // If the previous instruction was marked for elimination,
42434af5e1cSBill Schmidt       // remove it now.
42534af5e1cSBill Schmidt       if (ToErase) {
42634af5e1cSBill Schmidt         ToErase->eraseFromParent();
42734af5e1cSBill Schmidt         ToErase = nullptr;
42834af5e1cSBill Schmidt       }
429ae27ca9aSVictor Huang       // If a conditional trap instruction got optimized to an
43040c65655SVictor Huang       // unconditional trap, eliminate all the instructions after
43140c65655SVictor Huang       // the trap.
43286e77cdbSVictor Huang       if (EnableTrapOptimization && TrapOpt) {
433ae27ca9aSVictor Huang         ToErase = &MI;
434ae27ca9aSVictor Huang         continue;
435ae27ca9aSVictor Huang       }
43634af5e1cSBill Schmidt 
43734af5e1cSBill Schmidt       // Ignore debug instructions.
438801bf7ebSShiva Chen       if (MI.isDebugInstr())
43934af5e1cSBill Schmidt         continue;
44034af5e1cSBill Schmidt 
44134af5e1cSBill Schmidt       // Per-opcode peepholes.
44234af5e1cSBill Schmidt       switch (MI.getOpcode()) {
44334af5e1cSBill Schmidt 
44434af5e1cSBill Schmidt       default:
44534af5e1cSBill Schmidt         break;
44645ec3a37SBaptiste Saleil       case PPC::COPY: {
44745ec3a37SBaptiste Saleil         Register Src = MI.getOperand(1).getReg();
44845ec3a37SBaptiste Saleil         Register Dst = MI.getOperand(0).getReg();
44945ec3a37SBaptiste Saleil         if (!Register::isVirtualRegister(Src) ||
45045ec3a37SBaptiste Saleil             !Register::isVirtualRegister(Dst))
45145ec3a37SBaptiste Saleil           break;
45245ec3a37SBaptiste Saleil         if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass ||
45345ec3a37SBaptiste Saleil             MRI->getRegClass(Dst) != &PPC::ACCRCRegClass)
45445ec3a37SBaptiste Saleil           break;
45545ec3a37SBaptiste Saleil 
45645ec3a37SBaptiste Saleil         // We are copying an unprimed accumulator to a primed accumulator.
45745ec3a37SBaptiste Saleil         // If the input to the copy is a PHI that is fed only by (i) copies in
45845ec3a37SBaptiste Saleil         // the other direction (ii) implicitly defined unprimed accumulators or
45945ec3a37SBaptiste Saleil         // (iii) other PHI nodes satisfying (i) and (ii), we can change
46045ec3a37SBaptiste Saleil         // the PHI to a PHI on primed accumulators (as long as we also change
46145ec3a37SBaptiste Saleil         // its operands). To detect and change such copies, we first get a list
46245ec3a37SBaptiste Saleil         // of all the PHI nodes starting from the root PHI node in BFS order.
46345ec3a37SBaptiste Saleil         // We then visit all these PHI nodes to check if they can be changed to
46445ec3a37SBaptiste Saleil         // primed accumulator PHI nodes and if so, we change them.
46545ec3a37SBaptiste Saleil         MachineInstr *RootPHI = MRI->getVRegDef(Src);
46645ec3a37SBaptiste Saleil         if (RootPHI->getOpcode() != PPC::PHI)
46745ec3a37SBaptiste Saleil           break;
46845ec3a37SBaptiste Saleil 
46945ec3a37SBaptiste Saleil         SmallVector<MachineInstr *, 4> PHIs;
47045ec3a37SBaptiste Saleil         if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs))
47145ec3a37SBaptiste Saleil           break;
47245ec3a37SBaptiste Saleil 
47345ec3a37SBaptiste Saleil         convertUnprimedAccPHIs(TII, MRI, PHIs, Dst);
47445ec3a37SBaptiste Saleil 
47545ec3a37SBaptiste Saleil         ToErase = &MI;
47645ec3a37SBaptiste Saleil         break;
47745ec3a37SBaptiste Saleil       }
478cd83333fSKamau Bridgeman       case PPC::LI:
479cd83333fSKamau Bridgeman       case PPC::LI8: {
480cd83333fSKamau Bridgeman         // If we are materializing a zero, look for any use operands for which
481cd83333fSKamau Bridgeman         // zero means immediate zero. All such operands can be replaced with
482cd83333fSKamau Bridgeman         // PPC::ZERO.
483cd83333fSKamau Bridgeman         if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0)
484cd83333fSKamau Bridgeman           break;
485d6b07348SJim Lin         Register MIDestReg = MI.getOperand(0).getReg();
486cd83333fSKamau Bridgeman         for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg))
487cd83333fSKamau Bridgeman           Simplified |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg);
488cd83333fSKamau Bridgeman         if (MRI->use_nodbg_empty(MIDestReg)) {
489cd83333fSKamau Bridgeman           ++NumLoadImmZeroFoldedAndRemoved;
490cd83333fSKamau Bridgeman           ToErase = &MI;
491cd83333fSKamau Bridgeman         }
492cd83333fSKamau Bridgeman         break;
493cd83333fSKamau Bridgeman       }
49452f33f79SQiu Chaofan       case PPC::STW:
495f94d58d9SZaara Syeda       case PPC::STD: {
496f94d58d9SZaara Syeda         MachineFrameInfo &MFI = MF->getFrameInfo();
497f94d58d9SZaara Syeda         if (MFI.hasVarSizedObjects() ||
49852f33f79SQiu Chaofan             (!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() &&
49952f33f79SQiu Chaofan              !MF->getSubtarget<PPCSubtarget>().isAIXABI()))
500f94d58d9SZaara Syeda           break;
501f94d58d9SZaara Syeda         // When encountering a TOC save instruction, call UpdateTOCSaves
5020f7f59f0SHiroshi Inoue         // to add it to the TOCSaves map and mark any existing TOC saves
503f94d58d9SZaara Syeda         // it dominates as redundant.
504f94d58d9SZaara Syeda         if (TII->isTOCSaveMI(MI))
505f94d58d9SZaara Syeda           UpdateTOCSaves(TOCSaves, &MI);
506f94d58d9SZaara Syeda         break;
507f94d58d9SZaara Syeda       }
50834af5e1cSBill Schmidt       case PPC::XXPERMDI: {
50934af5e1cSBill Schmidt         // Perform simplifications of 2x64 vector swaps and splats.
51034af5e1cSBill Schmidt         // A swap is identified by an immediate value of 2, and a splat
51134af5e1cSBill Schmidt         // is identified by an immediate value of 0 or 3.
51234af5e1cSBill Schmidt         int Immed = MI.getOperand(3).getImm();
51334af5e1cSBill Schmidt 
514a0b025b8SJinsong Ji         if (Immed == 1)
515a0b025b8SJinsong Ji           break;
51634af5e1cSBill Schmidt 
51734af5e1cSBill Schmidt         // For each of these simplifications, we need the two source
51834af5e1cSBill Schmidt         // regs to match.  Unfortunately, MachineCSE ignores COPY and
51934af5e1cSBill Schmidt         // SUBREG_TO_REG, so for example we can see
52034af5e1cSBill Schmidt         //   XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
52134af5e1cSBill Schmidt         // We have to look through chains of COPY and SUBREG_TO_REG
52234af5e1cSBill Schmidt         // to find the real source values for comparison.
523d6b07348SJim Lin         Register TrueReg1 =
52465359936SZaara Syeda           TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
525d6b07348SJim Lin         Register TrueReg2 =
52665359936SZaara Syeda           TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
52734af5e1cSBill Schmidt 
528a0b025b8SJinsong Ji         if (!(TrueReg1 == TrueReg2 && Register::isVirtualRegister(TrueReg1)))
529a0b025b8SJinsong Ji           break;
530a0b025b8SJinsong Ji 
53134af5e1cSBill Schmidt         MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
532a0b025b8SJinsong Ji 
533a0b025b8SJinsong Ji         if (!DefMI)
534a0b025b8SJinsong Ji           break;
535a0b025b8SJinsong Ji 
536a0b025b8SJinsong Ji         unsigned DefOpc = DefMI->getOpcode();
53715748f49SNemanja Ivanovic 
53815748f49SNemanja Ivanovic         // If this is a splat fed by a splatting load, the splat is
53915748f49SNemanja Ivanovic         // redundant. Replace with a copy. This doesn't happen directly due
54015748f49SNemanja Ivanovic         // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
54115748f49SNemanja Ivanovic         // a load of a double to a vector of 64-bit integers.
54215748f49SNemanja Ivanovic         auto isConversionOfLoadAndSplat = [=]() -> bool {
54315748f49SNemanja Ivanovic           if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
54415748f49SNemanja Ivanovic             return false;
545d6b07348SJim Lin           Register FeedReg1 =
54665359936SZaara Syeda             TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
547a0b025b8SJinsong Ji           if (Register::isVirtualRegister(FeedReg1)) {
548a0b025b8SJinsong Ji             MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1);
54915748f49SNemanja Ivanovic             if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
55015748f49SNemanja Ivanovic               return true;
55115748f49SNemanja Ivanovic           }
55215748f49SNemanja Ivanovic           return false;
55315748f49SNemanja Ivanovic         };
554a0b025b8SJinsong Ji         if ((Immed == 0 || Immed == 3) &&
555a0b025b8SJinsong Ji             (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) {
556d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
55715748f49SNemanja Ivanovic                                "to load-and-splat/copy: ");
558d34e60caSNicola Zaghen           LLVM_DEBUG(MI.dump());
559116bbab4SDiana Picus           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
560116bbab4SDiana Picus                   MI.getOperand(0).getReg())
561116bbab4SDiana Picus               .add(MI.getOperand(1));
56215748f49SNemanja Ivanovic           ToErase = &MI;
56315748f49SNemanja Ivanovic           Simplified = true;
56415748f49SNemanja Ivanovic         }
56534af5e1cSBill Schmidt 
56634af5e1cSBill Schmidt         // If this is a splat or a swap fed by another splat, we
56734af5e1cSBill Schmidt         // can replace it with a copy.
56815748f49SNemanja Ivanovic         if (DefOpc == PPC::XXPERMDI) {
569d6b07348SJim Lin           Register DefReg1 = DefMI->getOperand(1).getReg();
570d6b07348SJim Lin           Register DefReg2 = DefMI->getOperand(2).getReg();
57188435154SKai Luo           unsigned DefImmed = DefMI->getOperand(3).getImm();
57234af5e1cSBill Schmidt 
57388435154SKai Luo           // If the two inputs are not the same register, check to see if
57488435154SKai Luo           // they originate from the same virtual register after only
57588435154SKai Luo           // copy-like instructions.
57688435154SKai Luo           if (DefReg1 != DefReg2) {
577d6b07348SJim Lin             Register FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI);
578d6b07348SJim Lin             Register FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI);
57988435154SKai Luo 
580a0b025b8SJinsong Ji             if (!(FeedReg1 == FeedReg2 &&
581a0b025b8SJinsong Ji                   Register::isVirtualRegister(FeedReg1)))
58288435154SKai Luo               break;
58388435154SKai Luo           }
58488435154SKai Luo 
58588435154SKai Luo           if (DefImmed == 0 || DefImmed == 3) {
586d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
58734af5e1cSBill Schmidt                                  "to splat/copy: ");
588d34e60caSNicola Zaghen             LLVM_DEBUG(MI.dump());
589116bbab4SDiana Picus             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
590116bbab4SDiana Picus                     MI.getOperand(0).getReg())
591116bbab4SDiana Picus                 .add(MI.getOperand(1));
59234af5e1cSBill Schmidt             ToErase = &MI;
59334af5e1cSBill Schmidt             Simplified = true;
59434af5e1cSBill Schmidt           }
59534af5e1cSBill Schmidt 
59634af5e1cSBill Schmidt           // If this is a splat fed by a swap, we can simplify modify
59734af5e1cSBill Schmidt           // the splat to splat the other value from the swap's input
59834af5e1cSBill Schmidt           // parameter.
59988435154SKai Luo           else if ((Immed == 0 || Immed == 3) && DefImmed == 2) {
600d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
601d34e60caSNicola Zaghen             LLVM_DEBUG(MI.dump());
60288435154SKai Luo             MI.getOperand(1).setReg(DefReg1);
60388435154SKai Luo             MI.getOperand(2).setReg(DefReg2);
60434af5e1cSBill Schmidt             MI.getOperand(3).setImm(3 - Immed);
60534af5e1cSBill Schmidt             Simplified = true;
60634af5e1cSBill Schmidt           }
60734af5e1cSBill Schmidt 
60834af5e1cSBill Schmidt           // If this is a swap fed by a swap, we can replace it
60934af5e1cSBill Schmidt           // with a copy from the first swap's input.
61088435154SKai Luo           else if (Immed == 2 && DefImmed == 2) {
611d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
612d34e60caSNicola Zaghen             LLVM_DEBUG(MI.dump());
613116bbab4SDiana Picus             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
614116bbab4SDiana Picus                     MI.getOperand(0).getReg())
615116bbab4SDiana Picus                 .add(DefMI->getOperand(1));
61634af5e1cSBill Schmidt             ToErase = &MI;
61734af5e1cSBill Schmidt             Simplified = true;
61834af5e1cSBill Schmidt           }
6195a8b1963SChen Zheng         } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
6205a8b1963SChen Zheng                    DefOpc == PPC::XXPERMDIs &&
62115748f49SNemanja Ivanovic                    (DefMI->getOperand(2).getImm() == 0 ||
62215748f49SNemanja Ivanovic                     DefMI->getOperand(2).getImm() == 3)) {
6235a8b1963SChen Zheng           ToErase = &MI;
6245a8b1963SChen Zheng           Simplified = true;
6255a8b1963SChen Zheng           // Swap of a splat, convert to copy.
6265a8b1963SChen Zheng           if (Immed == 2) {
6275a8b1963SChen Zheng             LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): ");
6285a8b1963SChen Zheng             LLVM_DEBUG(MI.dump());
6295a8b1963SChen Zheng             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
6305a8b1963SChen Zheng                     MI.getOperand(0).getReg())
6315a8b1963SChen Zheng                 .add(MI.getOperand(1));
6325a8b1963SChen Zheng             break;
6335a8b1963SChen Zheng           }
63411049f8fSNemanja Ivanovic           // Splat fed by another splat - switch the output of the first
63511049f8fSNemanja Ivanovic           // and remove the second.
63611049f8fSNemanja Ivanovic           DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
637d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
638d34e60caSNicola Zaghen           LLVM_DEBUG(MI.dump());
63934af5e1cSBill Schmidt         }
64034af5e1cSBill Schmidt         break;
64134af5e1cSBill Schmidt       }
64211049f8fSNemanja Ivanovic       case PPC::VSPLTB:
64311049f8fSNemanja Ivanovic       case PPC::VSPLTH:
64411049f8fSNemanja Ivanovic       case PPC::XXSPLTW: {
64511049f8fSNemanja Ivanovic         unsigned MyOpcode = MI.getOpcode();
64611049f8fSNemanja Ivanovic         unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
647d6b07348SJim Lin         Register TrueReg =
64865359936SZaara Syeda           TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
6492bea69bfSDaniel Sanders         if (!Register::isVirtualRegister(TrueReg))
65015748f49SNemanja Ivanovic           break;
65111049f8fSNemanja Ivanovic         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
65211049f8fSNemanja Ivanovic         if (!DefMI)
65311049f8fSNemanja Ivanovic           break;
65411049f8fSNemanja Ivanovic         unsigned DefOpcode = DefMI->getOpcode();
65515748f49SNemanja Ivanovic         auto isConvertOfSplat = [=]() -> bool {
65615748f49SNemanja Ivanovic           if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
65715748f49SNemanja Ivanovic             return false;
6580c476111SDaniel Sanders           Register ConvReg = DefMI->getOperand(1).getReg();
6592bea69bfSDaniel Sanders           if (!Register::isVirtualRegister(ConvReg))
66015748f49SNemanja Ivanovic             return false;
66115748f49SNemanja Ivanovic           MachineInstr *Splt = MRI->getVRegDef(ConvReg);
66215748f49SNemanja Ivanovic           return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
66315748f49SNemanja Ivanovic             Splt->getOpcode() == PPC::XXSPLTW);
66415748f49SNemanja Ivanovic         };
66515748f49SNemanja Ivanovic         bool AlreadySplat = (MyOpcode == DefOpcode) ||
66611049f8fSNemanja Ivanovic           (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
66711049f8fSNemanja Ivanovic           (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
66815748f49SNemanja Ivanovic           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
66915748f49SNemanja Ivanovic           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
67015748f49SNemanja Ivanovic           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
67115748f49SNemanja Ivanovic           (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
67215748f49SNemanja Ivanovic         // If the instruction[s] that feed this splat have already splat
67315748f49SNemanja Ivanovic         // the value, this splat is redundant.
67415748f49SNemanja Ivanovic         if (AlreadySplat) {
675d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
676d34e60caSNicola Zaghen           LLVM_DEBUG(MI.dump());
6774ff62b18STim Shen           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
6784ff62b18STim Shen                   MI.getOperand(0).getReg())
679116bbab4SDiana Picus               .add(MI.getOperand(OpNo));
68011049f8fSNemanja Ivanovic           ToErase = &MI;
68111049f8fSNemanja Ivanovic           Simplified = true;
68211049f8fSNemanja Ivanovic         }
68311049f8fSNemanja Ivanovic         // Splat fed by a shift. Usually when we align value to splat into
68411049f8fSNemanja Ivanovic         // vector element zero.
68511049f8fSNemanja Ivanovic         if (DefOpcode == PPC::XXSLDWI) {
6860c476111SDaniel Sanders           Register ShiftRes = DefMI->getOperand(0).getReg();
6870c476111SDaniel Sanders           Register ShiftOp1 = DefMI->getOperand(1).getReg();
6880c476111SDaniel Sanders           Register ShiftOp2 = DefMI->getOperand(2).getReg();
68911049f8fSNemanja Ivanovic           unsigned ShiftImm = DefMI->getOperand(3).getImm();
69035909ff6SAmy Kwan           unsigned SplatImm =
69135909ff6SAmy Kwan               MI.getOperand(MyOpcode == PPC::XXSPLTW ? 2 : 1).getImm();
69211049f8fSNemanja Ivanovic           if (ShiftOp1 == ShiftOp2) {
69311049f8fSNemanja Ivanovic             unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
69411049f8fSNemanja Ivanovic             if (MRI->hasOneNonDBGUse(ShiftRes)) {
695d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
696d34e60caSNicola Zaghen               LLVM_DEBUG(DefMI->dump());
69711049f8fSNemanja Ivanovic               ToErase = DefMI;
69811049f8fSNemanja Ivanovic             }
69911049f8fSNemanja Ivanovic             Simplified = true;
700d34e60caSNicola Zaghen             LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
701d34e60caSNicola Zaghen                               << " to " << NewElem << " in instruction: ");
702d34e60caSNicola Zaghen             LLVM_DEBUG(MI.dump());
70311049f8fSNemanja Ivanovic             MI.getOperand(1).setReg(ShiftOp1);
70411049f8fSNemanja Ivanovic             MI.getOperand(2).setImm(NewElem);
70511049f8fSNemanja Ivanovic           }
70611049f8fSNemanja Ivanovic         }
70711049f8fSNemanja Ivanovic         break;
70811049f8fSNemanja Ivanovic       }
70915748f49SNemanja Ivanovic       case PPC::XVCVDPSP: {
71015748f49SNemanja Ivanovic         // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
711d6b07348SJim Lin         Register TrueReg =
71265359936SZaara Syeda           TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
7132bea69bfSDaniel Sanders         if (!Register::isVirtualRegister(TrueReg))
71415748f49SNemanja Ivanovic           break;
71515748f49SNemanja Ivanovic         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
71634af5e1cSBill Schmidt 
71715748f49SNemanja Ivanovic         // This can occur when building a vector of single precision or integer
71815748f49SNemanja Ivanovic         // values.
71915748f49SNemanja Ivanovic         if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
720d6b07348SJim Lin           Register DefsReg1 =
72165359936SZaara Syeda             TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
722d6b07348SJim Lin           Register DefsReg2 =
72365359936SZaara Syeda             TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
7242bea69bfSDaniel Sanders           if (!Register::isVirtualRegister(DefsReg1) ||
7252bea69bfSDaniel Sanders               !Register::isVirtualRegister(DefsReg2))
72615748f49SNemanja Ivanovic             break;
72715748f49SNemanja Ivanovic           MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
72815748f49SNemanja Ivanovic           MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
72915748f49SNemanja Ivanovic 
73015748f49SNemanja Ivanovic           if (!P1 || !P2)
73115748f49SNemanja Ivanovic             break;
73215748f49SNemanja Ivanovic 
73371f1ab53SQiu Chaofan           // Remove the passed FRSP/XSRSP instruction if it only feeds this MI
73471f1ab53SQiu Chaofan           // and set any uses of that FRSP/XSRSP (in this MI) to the source of
73571f1ab53SQiu Chaofan           // the FRSP/XSRSP.
73615748f49SNemanja Ivanovic           auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
73771f1ab53SQiu Chaofan             unsigned Opc = RoundInstr->getOpcode();
73871f1ab53SQiu Chaofan             if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) &&
73915748f49SNemanja Ivanovic                 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
74015748f49SNemanja Ivanovic               Simplified = true;
7410c476111SDaniel Sanders               Register ConvReg1 = RoundInstr->getOperand(1).getReg();
7420c476111SDaniel Sanders               Register FRSPDefines = RoundInstr->getOperand(0).getReg();
743909d6c86SVictor Huang               MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines));
74415748f49SNemanja Ivanovic               for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
74515748f49SNemanja Ivanovic                 if (Use.getOperand(i).isReg() &&
74615748f49SNemanja Ivanovic                     Use.getOperand(i).getReg() == FRSPDefines)
74715748f49SNemanja Ivanovic                   Use.getOperand(i).setReg(ConvReg1);
74871f1ab53SQiu Chaofan               LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n");
749d34e60caSNicola Zaghen               LLVM_DEBUG(RoundInstr->dump());
750d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
751d34e60caSNicola Zaghen               LLVM_DEBUG(MI.dump());
752d34e60caSNicola Zaghen               LLVM_DEBUG(dbgs() << "Through instruction:\n");
753d34e60caSNicola Zaghen               LLVM_DEBUG(DefMI->dump());
75415748f49SNemanja Ivanovic               RoundInstr->eraseFromParent();
75515748f49SNemanja Ivanovic             }
75615748f49SNemanja Ivanovic           };
75715748f49SNemanja Ivanovic 
75815748f49SNemanja Ivanovic           // If the input to XVCVDPSP is a vector that was built (even
75915748f49SNemanja Ivanovic           // partially) out of FRSP's, the FRSP(s) can safely be removed
76015748f49SNemanja Ivanovic           // since this instruction performs the same operation.
76115748f49SNemanja Ivanovic           if (P1 != P2) {
76215748f49SNemanja Ivanovic             removeFRSPIfPossible(P1);
76315748f49SNemanja Ivanovic             removeFRSPIfPossible(P2);
76415748f49SNemanja Ivanovic             break;
76515748f49SNemanja Ivanovic           }
76615748f49SNemanja Ivanovic           removeFRSPIfPossible(P1);
76715748f49SNemanja Ivanovic         }
76815748f49SNemanja Ivanovic         break;
76915748f49SNemanja Ivanovic       }
770e3a3e3c9SHiroshi Inoue       case PPC::EXTSH:
771e3a3e3c9SHiroshi Inoue       case PPC::EXTSH8:
772e3a3e3c9SHiroshi Inoue       case PPC::EXTSH8_32_64: {
773e3a3e3c9SHiroshi Inoue         if (!EnableSExtElimination) break;
7740c476111SDaniel Sanders         Register NarrowReg = MI.getOperand(1).getReg();
7752bea69bfSDaniel Sanders         if (!Register::isVirtualRegister(NarrowReg))
776e3a3e3c9SHiroshi Inoue           break;
777e3a3e3c9SHiroshi Inoue 
778e3a3e3c9SHiroshi Inoue         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
779e3a3e3c9SHiroshi Inoue         // If we've used a zero-extending load that we will sign-extend,
780e3a3e3c9SHiroshi Inoue         // just do a sign-extending load.
781e3a3e3c9SHiroshi Inoue         if (SrcMI->getOpcode() == PPC::LHZ ||
782e3a3e3c9SHiroshi Inoue             SrcMI->getOpcode() == PPC::LHZX) {
783e3a3e3c9SHiroshi Inoue           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
784e3a3e3c9SHiroshi Inoue             break;
785e3a3e3c9SHiroshi Inoue           auto is64Bit = [] (unsigned Opcode) {
786e3a3e3c9SHiroshi Inoue             return Opcode == PPC::EXTSH8;
787e3a3e3c9SHiroshi Inoue           };
788e3a3e3c9SHiroshi Inoue           auto isXForm = [] (unsigned Opcode) {
789e3a3e3c9SHiroshi Inoue             return Opcode == PPC::LHZX;
790e3a3e3c9SHiroshi Inoue           };
791e3a3e3c9SHiroshi Inoue           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
792e3a3e3c9SHiroshi Inoue             if (is64Bit)
793e3a3e3c9SHiroshi Inoue               if (isXForm) return PPC::LHAX8;
794e3a3e3c9SHiroshi Inoue               else         return PPC::LHA8;
795e3a3e3c9SHiroshi Inoue             else
796e3a3e3c9SHiroshi Inoue               if (isXForm) return PPC::LHAX;
797e3a3e3c9SHiroshi Inoue               else         return PPC::LHA;
798e3a3e3c9SHiroshi Inoue           };
799e3a3e3c9SHiroshi Inoue           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
800e3a3e3c9SHiroshi Inoue                                        isXForm(SrcMI->getOpcode()));
801d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
802d34e60caSNicola Zaghen           LLVM_DEBUG(SrcMI->dump());
803d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "and sign-extension\n");
804d34e60caSNicola Zaghen           LLVM_DEBUG(MI.dump());
805d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
806e3a3e3c9SHiroshi Inoue           SrcMI->setDesc(TII->get(Opc));
807e3a3e3c9SHiroshi Inoue           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
808e3a3e3c9SHiroshi Inoue           ToErase = &MI;
809e3a3e3c9SHiroshi Inoue           Simplified = true;
810e3a3e3c9SHiroshi Inoue           NumEliminatedSExt++;
811e3a3e3c9SHiroshi Inoue         }
812e3a3e3c9SHiroshi Inoue         break;
813e3a3e3c9SHiroshi Inoue       }
814e3a3e3c9SHiroshi Inoue       case PPC::EXTSW:
815e3a3e3c9SHiroshi Inoue       case PPC::EXTSW_32:
816e3a3e3c9SHiroshi Inoue       case PPC::EXTSW_32_64: {
817e3a3e3c9SHiroshi Inoue         if (!EnableSExtElimination) break;
8180c476111SDaniel Sanders         Register NarrowReg = MI.getOperand(1).getReg();
8192bea69bfSDaniel Sanders         if (!Register::isVirtualRegister(NarrowReg))
820e3a3e3c9SHiroshi Inoue           break;
821e3a3e3c9SHiroshi Inoue 
822e3a3e3c9SHiroshi Inoue         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
823e3a3e3c9SHiroshi Inoue         // If we've used a zero-extending load that we will sign-extend,
824e3a3e3c9SHiroshi Inoue         // just do a sign-extending load.
825e3a3e3c9SHiroshi Inoue         if (SrcMI->getOpcode() == PPC::LWZ ||
826e3a3e3c9SHiroshi Inoue             SrcMI->getOpcode() == PPC::LWZX) {
827e3a3e3c9SHiroshi Inoue           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
828e3a3e3c9SHiroshi Inoue             break;
829e3a3e3c9SHiroshi Inoue           auto is64Bit = [] (unsigned Opcode) {
830e3a3e3c9SHiroshi Inoue             return Opcode == PPC::EXTSW || Opcode == PPC::EXTSW_32_64;
831e3a3e3c9SHiroshi Inoue           };
832e3a3e3c9SHiroshi Inoue           auto isXForm = [] (unsigned Opcode) {
833e3a3e3c9SHiroshi Inoue             return Opcode == PPC::LWZX;
834e3a3e3c9SHiroshi Inoue           };
835e3a3e3c9SHiroshi Inoue           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
836e3a3e3c9SHiroshi Inoue             if (is64Bit)
837e3a3e3c9SHiroshi Inoue               if (isXForm) return PPC::LWAX;
838e3a3e3c9SHiroshi Inoue               else         return PPC::LWA;
839e3a3e3c9SHiroshi Inoue             else
840e3a3e3c9SHiroshi Inoue               if (isXForm) return PPC::LWAX_32;
841e3a3e3c9SHiroshi Inoue               else         return PPC::LWA_32;
842e3a3e3c9SHiroshi Inoue           };
843e3a3e3c9SHiroshi Inoue           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
844e3a3e3c9SHiroshi Inoue                                        isXForm(SrcMI->getOpcode()));
845d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
846d34e60caSNicola Zaghen           LLVM_DEBUG(SrcMI->dump());
847d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "and sign-extension\n");
848d34e60caSNicola Zaghen           LLVM_DEBUG(MI.dump());
849d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
850e3a3e3c9SHiroshi Inoue           SrcMI->setDesc(TII->get(Opc));
851e3a3e3c9SHiroshi Inoue           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
852e3a3e3c9SHiroshi Inoue           ToErase = &MI;
853e3a3e3c9SHiroshi Inoue           Simplified = true;
854e3a3e3c9SHiroshi Inoue           NumEliminatedSExt++;
855e3a3e3c9SHiroshi Inoue         } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
856e3a3e3c9SHiroshi Inoue                    TII->isSignExtended(*SrcMI)) {
857e3a3e3c9SHiroshi Inoue           // We can eliminate EXTSW if the input is known to be already
858e3a3e3c9SHiroshi Inoue           // sign-extended.
859d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
8600c476111SDaniel Sanders           Register TmpReg =
861e3a3e3c9SHiroshi Inoue               MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
862e3a3e3c9SHiroshi Inoue           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
863e3a3e3c9SHiroshi Inoue                   TmpReg);
864e3a3e3c9SHiroshi Inoue           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
865e3a3e3c9SHiroshi Inoue                   MI.getOperand(0).getReg())
866e3a3e3c9SHiroshi Inoue               .addReg(TmpReg)
867e3a3e3c9SHiroshi Inoue               .addReg(NarrowReg)
868e3a3e3c9SHiroshi Inoue               .addImm(PPC::sub_32);
869e3a3e3c9SHiroshi Inoue           ToErase = &MI;
870e3a3e3c9SHiroshi Inoue           Simplified = true;
871e3a3e3c9SHiroshi Inoue           NumEliminatedSExt++;
872e3a3e3c9SHiroshi Inoue         }
873e3a3e3c9SHiroshi Inoue         break;
874e3a3e3c9SHiroshi Inoue       }
875e3a3e3c9SHiroshi Inoue       case PPC::RLDICL: {
876e3a3e3c9SHiroshi Inoue         // We can eliminate RLDICL (e.g. for zero-extension)
877e3a3e3c9SHiroshi Inoue         // if all bits to clear are already zero in the input.
878e3a3e3c9SHiroshi Inoue         // This code assume following code sequence for zero-extension.
879a8a83d15SFrancis Visoiu Mistrih         //   %6 = COPY %5:sub_32; (optional)
880a8a83d15SFrancis Visoiu Mistrih         //   %8 = IMPLICIT_DEF;
88193ef1458SFrancis Visoiu Mistrih         //   %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
882e3a3e3c9SHiroshi Inoue         if (!EnableZExtElimination) break;
883e3a3e3c9SHiroshi Inoue 
884e3a3e3c9SHiroshi Inoue         if (MI.getOperand(2).getImm() != 0)
885e3a3e3c9SHiroshi Inoue           break;
886e3a3e3c9SHiroshi Inoue 
8870c476111SDaniel Sanders         Register SrcReg = MI.getOperand(1).getReg();
8882bea69bfSDaniel Sanders         if (!Register::isVirtualRegister(SrcReg))
889e3a3e3c9SHiroshi Inoue           break;
890e3a3e3c9SHiroshi Inoue 
891e3a3e3c9SHiroshi Inoue         MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
892e3a3e3c9SHiroshi Inoue         if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
893e3a3e3c9SHiroshi Inoue               SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
894e3a3e3c9SHiroshi Inoue           break;
895e3a3e3c9SHiroshi Inoue 
896e3a3e3c9SHiroshi Inoue         MachineInstr *ImpDefMI, *SubRegMI;
897e3a3e3c9SHiroshi Inoue         ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
898e3a3e3c9SHiroshi Inoue         SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
899e3a3e3c9SHiroshi Inoue         if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
900e3a3e3c9SHiroshi Inoue 
901e3a3e3c9SHiroshi Inoue         SrcMI = SubRegMI;
902e3a3e3c9SHiroshi Inoue         if (SubRegMI->getOpcode() == PPC::COPY) {
9030c476111SDaniel Sanders           Register CopyReg = SubRegMI->getOperand(1).getReg();
9042bea69bfSDaniel Sanders           if (Register::isVirtualRegister(CopyReg))
905e3a3e3c9SHiroshi Inoue             SrcMI = MRI->getVRegDef(CopyReg);
906e3a3e3c9SHiroshi Inoue         }
907e3a3e3c9SHiroshi Inoue 
908e3a3e3c9SHiroshi Inoue         unsigned KnownZeroCount = getKnownLeadingZeroCount(SrcMI, TII);
909e3a3e3c9SHiroshi Inoue         if (MI.getOperand(3).getImm() <= KnownZeroCount) {
910d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
911e3a3e3c9SHiroshi Inoue           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
912e3a3e3c9SHiroshi Inoue                   MI.getOperand(0).getReg())
913e3a3e3c9SHiroshi Inoue               .addReg(SrcReg);
914e3a3e3c9SHiroshi Inoue           ToErase = &MI;
915e3a3e3c9SHiroshi Inoue           Simplified = true;
916e3a3e3c9SHiroshi Inoue           NumEliminatedZExt++;
917e3a3e3c9SHiroshi Inoue         }
918e3a3e3c9SHiroshi Inoue         break;
919e3a3e3c9SHiroshi Inoue       }
9202d9c5f3bSTony Jiang 
9212d9c5f3bSTony Jiang       // TODO: Any instruction that has an immediate form fed only by a PHI
9222d9c5f3bSTony Jiang       // whose operands are all load immediate can be folded away. We currently
9232d9c5f3bSTony Jiang       // do this for ADD instructions, but should expand it to arithmetic and
9242d9c5f3bSTony Jiang       // binary instructions with immediate forms in the future.
9252d9c5f3bSTony Jiang       case PPC::ADD4:
9262d9c5f3bSTony Jiang       case PPC::ADD8: {
9272d9c5f3bSTony Jiang         auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
9282d9c5f3bSTony Jiang           assert(PhiOp && "Invalid Operand!");
9292d9c5f3bSTony Jiang           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
9302d9c5f3bSTony Jiang 
9312d9c5f3bSTony Jiang           return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
9322d9c5f3bSTony Jiang                  MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
9332d9c5f3bSTony Jiang         };
9342d9c5f3bSTony Jiang 
9352d9c5f3bSTony Jiang         auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
9362d9c5f3bSTony Jiang                                             MachineOperand *PhiOp) {
9372d9c5f3bSTony Jiang           assert(PhiOp && "Invalid Operand!");
9382d9c5f3bSTony Jiang           assert(DominatorOp && "Invalid Operand!");
9392d9c5f3bSTony Jiang           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
9402d9c5f3bSTony Jiang           MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
9412d9c5f3bSTony Jiang 
9422d9c5f3bSTony Jiang           // Note: the vregs only show up at odd indices position of PHI Node,
9432d9c5f3bSTony Jiang           // the even indices position save the BB info.
9442d9c5f3bSTony Jiang           for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
9452d9c5f3bSTony Jiang             MachineInstr *LiMI =
9462d9c5f3bSTony Jiang                 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
9477bf866ebSNemanja Ivanovic             if (!LiMI ||
9487bf866ebSNemanja Ivanovic                 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
9497bf866ebSNemanja Ivanovic                 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
9507bf866ebSNemanja Ivanovic                 !MDT->dominates(DefDomMI, LiMI))
9512d9c5f3bSTony Jiang               return false;
9522d9c5f3bSTony Jiang           }
9532d9c5f3bSTony Jiang 
9542d9c5f3bSTony Jiang           return true;
9552d9c5f3bSTony Jiang         };
9562d9c5f3bSTony Jiang 
9572d9c5f3bSTony Jiang         MachineOperand Op1 = MI.getOperand(1);
9582d9c5f3bSTony Jiang         MachineOperand Op2 = MI.getOperand(2);
9592d9c5f3bSTony Jiang         if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
9602d9c5f3bSTony Jiang           std::swap(Op1, Op2);
9612d9c5f3bSTony Jiang         else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
9622d9c5f3bSTony Jiang           break; // We don't have an ADD fed by LI's that can be transformed
9632d9c5f3bSTony Jiang 
9642d9c5f3bSTony Jiang         // Now we know that Op1 is the PHI node and Op2 is the dominator
9650c476111SDaniel Sanders         Register DominatorReg = Op2.getReg();
9662d9c5f3bSTony Jiang 
9672d9c5f3bSTony Jiang         const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
9682d9c5f3bSTony Jiang                                              ? &PPC::G8RC_and_G8RC_NOX0RegClass
9692d9c5f3bSTony Jiang                                              : &PPC::GPRC_and_GPRC_NOR0RegClass;
9702d9c5f3bSTony Jiang         MRI->setRegClass(DominatorReg, TRC);
9712d9c5f3bSTony Jiang 
9722d9c5f3bSTony Jiang         // replace LIs with ADDIs
9732d9c5f3bSTony Jiang         MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
9742d9c5f3bSTony Jiang         for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
9752d9c5f3bSTony Jiang           MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
976d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
977d34e60caSNicola Zaghen           LLVM_DEBUG(LiMI->dump());
9782d9c5f3bSTony Jiang 
979a8a83d15SFrancis Visoiu Mistrih           // There could be repeated registers in the PHI, e.g: %1 =
98025528d6dSFrancis Visoiu Mistrih           // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
9812d9c5f3bSTony Jiang           // already replaced the def instruction, skip.
9822d9c5f3bSTony Jiang           if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
9832d9c5f3bSTony Jiang             continue;
9842d9c5f3bSTony Jiang 
9852d9c5f3bSTony Jiang           assert((LiMI->getOpcode() == PPC::LI ||
9862d9c5f3bSTony Jiang                   LiMI->getOpcode() == PPC::LI8) &&
9872d9c5f3bSTony Jiang                  "Invalid Opcode!");
9882d9c5f3bSTony Jiang           auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
989*37b37838SShengchen Kan           LiMI->removeOperand(1);                    // remove the imm of LI
9902d9c5f3bSTony Jiang           LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
9912d9c5f3bSTony Jiang                                                               : PPC::ADDI8));
9922d9c5f3bSTony Jiang           MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
9932d9c5f3bSTony Jiang               .addReg(DominatorReg)
9942d9c5f3bSTony Jiang               .addImm(LiImm); // restore the imm of LI
995d34e60caSNicola Zaghen           LLVM_DEBUG(LiMI->dump());
9962d9c5f3bSTony Jiang         }
9972d9c5f3bSTony Jiang 
9982d9c5f3bSTony Jiang         // Replace ADD with COPY
999d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
1000d34e60caSNicola Zaghen         LLVM_DEBUG(MI.dump());
10012d9c5f3bSTony Jiang         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
10022d9c5f3bSTony Jiang                 MI.getOperand(0).getReg())
10032d9c5f3bSTony Jiang             .add(Op1);
10042d9c5f3bSTony Jiang         ToErase = &MI;
10052d9c5f3bSTony Jiang         Simplified = true;
10062d9c5f3bSTony Jiang         NumOptADDLIs++;
10072d9c5f3bSTony Jiang         break;
100815748f49SNemanja Ivanovic       }
10097c842fadSNemanja Ivanovic       case PPC::RLDICR: {
10101931ed73SKai Luo         Simplified |= emitRLDICWhenLoweringJumpTables(MI) ||
10111931ed73SKai Luo                       combineSEXTAndSHL(MI, ToErase);
10127c842fadSNemanja Ivanovic         break;
10137c842fadSNemanja Ivanovic       }
1014f0ba1aecSczhengsz       case PPC::RLWINM:
101524ee4edeSJinsong Ji       case PPC::RLWINM_rec:
1016f0ba1aecSczhengsz       case PPC::RLWINM8:
101724ee4edeSJinsong Ji       case PPC::RLWINM8_rec: {
10182ea7210eSEsme-Yi         Simplified = TII->combineRLWINM(MI, &ToErase);
1019b969dfe2SEsme-Yi         if (Simplified)
102026ba160dSZheng Chen           ++NumRotatesCollapsed;
1021f0ba1aecSczhengsz         break;
1022f0ba1aecSczhengsz       }
1023ae27ca9aSVictor Huang       // We will replace TD/TW/TDI/TWI with an unconditional trap if it will
1024ae27ca9aSVictor Huang       // always trap, we will delete the node if it will never trap.
1025ae27ca9aSVictor Huang       case PPC::TDI:
1026ae27ca9aSVictor Huang       case PPC::TWI:
1027ae27ca9aSVictor Huang       case PPC::TD:
1028ae27ca9aSVictor Huang       case PPC::TW: {
102986e77cdbSVictor Huang         if (!EnableTrapOptimization) break;
1030ae27ca9aSVictor Huang         MachineInstr *LiMI1 = getVRegDefOrNull(&MI.getOperand(1), MRI);
1031ae27ca9aSVictor Huang         MachineInstr *LiMI2 = getVRegDefOrNull(&MI.getOperand(2), MRI);
1032ae27ca9aSVictor Huang         bool IsOperand2Immediate = MI.getOperand(2).isImm();
1033ae27ca9aSVictor Huang         // We can only do the optimization if we can get immediates
1034ae27ca9aSVictor Huang         // from both operands
10358b8e8704SBenjamin Kramer         if (!(LiMI1 && (LiMI1->getOpcode() == PPC::LI ||
10368b8e8704SBenjamin Kramer                         LiMI1->getOpcode() == PPC::LI8)))
1037ae27ca9aSVictor Huang           break;
1038ae27ca9aSVictor Huang         if (!IsOperand2Immediate &&
10398b8e8704SBenjamin Kramer             !(LiMI2 && (LiMI2->getOpcode() == PPC::LI ||
10408b8e8704SBenjamin Kramer                         LiMI2->getOpcode() == PPC::LI8)))
1041ae27ca9aSVictor Huang           break;
1042ae27ca9aSVictor Huang 
1043ae27ca9aSVictor Huang         auto ImmOperand0 = MI.getOperand(0).getImm();
1044ae27ca9aSVictor Huang         auto ImmOperand1 = LiMI1->getOperand(1).getImm();
1045ae27ca9aSVictor Huang         auto ImmOperand2 = IsOperand2Immediate ? MI.getOperand(2).getImm()
1046ae27ca9aSVictor Huang                                                : LiMI2->getOperand(1).getImm();
1047ae27ca9aSVictor Huang 
1048ae27ca9aSVictor Huang         // We will replace the MI with an unconditional trap if it will always
1049ae27ca9aSVictor Huang         // trap.
1050ae27ca9aSVictor Huang         if ((ImmOperand0 == 31) ||
1051ae27ca9aSVictor Huang             ((ImmOperand0 & 0x10) &&
1052ae27ca9aSVictor Huang              ((int64_t)ImmOperand1 < (int64_t)ImmOperand2)) ||
1053ae27ca9aSVictor Huang             ((ImmOperand0 & 0x8) &&
1054ae27ca9aSVictor Huang              ((int64_t)ImmOperand1 > (int64_t)ImmOperand2)) ||
1055ae27ca9aSVictor Huang             ((ImmOperand0 & 0x2) &&
1056ae27ca9aSVictor Huang              ((uint64_t)ImmOperand1 < (uint64_t)ImmOperand2)) ||
1057ae27ca9aSVictor Huang             ((ImmOperand0 & 0x1) &&
1058ae27ca9aSVictor Huang              ((uint64_t)ImmOperand1 > (uint64_t)ImmOperand2)) ||
1059ae27ca9aSVictor Huang             ((ImmOperand0 & 0x4) && (ImmOperand1 == ImmOperand2))) {
1060ae27ca9aSVictor Huang           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::TRAP));
1061ae27ca9aSVictor Huang           TrapOpt = true;
1062ae27ca9aSVictor Huang         }
1063ae27ca9aSVictor Huang         // We will delete the MI if it will never trap.
1064ae27ca9aSVictor Huang         ToErase = &MI;
1065ae27ca9aSVictor Huang         Simplified = true;
1066ae27ca9aSVictor Huang         break;
1067ae27ca9aSVictor Huang       }
106815748f49SNemanja Ivanovic       }
10692d9c5f3bSTony Jiang     }
10702d9c5f3bSTony Jiang 
107134af5e1cSBill Schmidt     // If the last instruction was marked for elimination,
107234af5e1cSBill Schmidt     // remove it now.
107334af5e1cSBill Schmidt     if (ToErase) {
107434af5e1cSBill Schmidt       ToErase->eraseFromParent();
107534af5e1cSBill Schmidt       ToErase = nullptr;
107634af5e1cSBill Schmidt     }
1077ae27ca9aSVictor Huang     // Reset TrapOpt to false at the end of the basic block.
107886e77cdbSVictor Huang     if (EnableTrapOptimization)
1079ae27ca9aSVictor Huang       TrapOpt = false;
108034af5e1cSBill Schmidt   }
108134af5e1cSBill Schmidt 
1082f94d58d9SZaara Syeda   // Eliminate all the TOC save instructions which are redundant.
1083f94d58d9SZaara Syeda   Simplified |= eliminateRedundantTOCSaves(TOCSaves);
10846c9a392cSNemanja Ivanovic   PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
10856c9a392cSNemanja Ivanovic   if (FI->mustSaveTOC())
10866c9a392cSNemanja Ivanovic     NumTOCSavesInPrologue++;
10876c9a392cSNemanja Ivanovic 
1088614453b7SHiroshi Inoue   // We try to eliminate redundant compare instruction.
10891794cdc4SNemanja Ivanovic   Simplified |= eliminateRedundantCompare();
1090614453b7SHiroshi Inoue 
1091614453b7SHiroshi Inoue   return Simplified;
1092614453b7SHiroshi Inoue }
1093614453b7SHiroshi Inoue 
1094614453b7SHiroshi Inoue // helper functions for eliminateRedundantCompare
isEqOrNe(MachineInstr * BI)1095614453b7SHiroshi Inoue static bool isEqOrNe(MachineInstr *BI) {
1096614453b7SHiroshi Inoue   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1097614453b7SHiroshi Inoue   unsigned PredCond = PPC::getPredicateCondition(Pred);
1098614453b7SHiroshi Inoue   return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
1099614453b7SHiroshi Inoue }
1100614453b7SHiroshi Inoue 
isSupportedCmpOp(unsigned opCode)1101614453b7SHiroshi Inoue static bool isSupportedCmpOp(unsigned opCode) {
1102614453b7SHiroshi Inoue   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD  ||
1103614453b7SHiroshi Inoue           opCode == PPC::CMPLW  || opCode == PPC::CMPW  ||
1104614453b7SHiroshi Inoue           opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
1105614453b7SHiroshi Inoue           opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
1106614453b7SHiroshi Inoue }
1107614453b7SHiroshi Inoue 
is64bitCmpOp(unsigned opCode)1108614453b7SHiroshi Inoue static bool is64bitCmpOp(unsigned opCode) {
1109614453b7SHiroshi Inoue   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD ||
1110614453b7SHiroshi Inoue           opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
1111614453b7SHiroshi Inoue }
1112614453b7SHiroshi Inoue 
isSignedCmpOp(unsigned opCode)1113614453b7SHiroshi Inoue static bool isSignedCmpOp(unsigned opCode) {
1114614453b7SHiroshi Inoue   return (opCode == PPC::CMPD  || opCode == PPC::CMPW ||
1115614453b7SHiroshi Inoue           opCode == PPC::CMPDI || opCode == PPC::CMPWI);
1116614453b7SHiroshi Inoue }
1117614453b7SHiroshi Inoue 
getSignedCmpOpCode(unsigned opCode)1118614453b7SHiroshi Inoue static unsigned getSignedCmpOpCode(unsigned opCode) {
1119614453b7SHiroshi Inoue   if (opCode == PPC::CMPLD)  return PPC::CMPD;
1120614453b7SHiroshi Inoue   if (opCode == PPC::CMPLW)  return PPC::CMPW;
1121614453b7SHiroshi Inoue   if (opCode == PPC::CMPLDI) return PPC::CMPDI;
1122614453b7SHiroshi Inoue   if (opCode == PPC::CMPLWI) return PPC::CMPWI;
1123614453b7SHiroshi Inoue   return opCode;
1124614453b7SHiroshi Inoue }
1125614453b7SHiroshi Inoue 
1126614453b7SHiroshi Inoue // We can decrement immediate x in (GE x) by changing it to (GT x-1) or
1127614453b7SHiroshi Inoue // (LT x) to (LE x-1)
getPredicateToDecImm(MachineInstr * BI,MachineInstr * CMPI)1128614453b7SHiroshi Inoue static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
1129614453b7SHiroshi Inoue   uint64_t Imm = CMPI->getOperand(2).getImm();
1130614453b7SHiroshi Inoue   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1131614453b7SHiroshi Inoue   if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
1132614453b7SHiroshi Inoue     return 0;
1133614453b7SHiroshi Inoue 
1134614453b7SHiroshi Inoue   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1135614453b7SHiroshi Inoue   unsigned PredCond = PPC::getPredicateCondition(Pred);
1136614453b7SHiroshi Inoue   unsigned PredHint = PPC::getPredicateHint(Pred);
1137614453b7SHiroshi Inoue   if (PredCond == PPC::PRED_GE)
1138614453b7SHiroshi Inoue     return PPC::getPredicate(PPC::PRED_GT, PredHint);
1139614453b7SHiroshi Inoue   if (PredCond == PPC::PRED_LT)
1140614453b7SHiroshi Inoue     return PPC::getPredicate(PPC::PRED_LE, PredHint);
1141614453b7SHiroshi Inoue 
1142614453b7SHiroshi Inoue   return 0;
1143614453b7SHiroshi Inoue }
1144614453b7SHiroshi Inoue 
1145614453b7SHiroshi Inoue // We can increment immediate x in (GT x) by changing it to (GE x+1) or
1146614453b7SHiroshi Inoue // (LE x) to (LT x+1)
getPredicateToIncImm(MachineInstr * BI,MachineInstr * CMPI)1147614453b7SHiroshi Inoue static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
1148614453b7SHiroshi Inoue   uint64_t Imm = CMPI->getOperand(2).getImm();
1149614453b7SHiroshi Inoue   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1150614453b7SHiroshi Inoue   if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
1151614453b7SHiroshi Inoue     return 0;
1152614453b7SHiroshi Inoue 
1153614453b7SHiroshi Inoue   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1154614453b7SHiroshi Inoue   unsigned PredCond = PPC::getPredicateCondition(Pred);
1155614453b7SHiroshi Inoue   unsigned PredHint = PPC::getPredicateHint(Pred);
1156614453b7SHiroshi Inoue   if (PredCond == PPC::PRED_GT)
1157614453b7SHiroshi Inoue     return PPC::getPredicate(PPC::PRED_GE, PredHint);
1158614453b7SHiroshi Inoue   if (PredCond == PPC::PRED_LE)
1159614453b7SHiroshi Inoue     return PPC::getPredicate(PPC::PRED_LT, PredHint);
1160614453b7SHiroshi Inoue 
1161614453b7SHiroshi Inoue   return 0;
1162614453b7SHiroshi Inoue }
1163614453b7SHiroshi Inoue 
11640f7f59f0SHiroshi Inoue // This takes a Phi node and returns a register value for the specified BB.
getIncomingRegForBlock(MachineInstr * Phi,MachineBasicBlock * MBB)116579c0bec0SHiroshi Inoue static unsigned getIncomingRegForBlock(MachineInstr *Phi,
116679c0bec0SHiroshi Inoue                                        MachineBasicBlock *MBB) {
116779c0bec0SHiroshi Inoue   for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
116879c0bec0SHiroshi Inoue     MachineOperand &MO = Phi->getOperand(I);
116979c0bec0SHiroshi Inoue     if (MO.getMBB() == MBB)
117079c0bec0SHiroshi Inoue       return Phi->getOperand(I-1).getReg();
117179c0bec0SHiroshi Inoue   }
117279c0bec0SHiroshi Inoue   llvm_unreachable("invalid src basic block for this Phi node\n");
117379c0bec0SHiroshi Inoue   return 0;
117479c0bec0SHiroshi Inoue }
117579c0bec0SHiroshi Inoue 
117679c0bec0SHiroshi Inoue // This function tracks the source of the register through register copy.
117779c0bec0SHiroshi Inoue // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
117879c0bec0SHiroshi Inoue // assuming that the control comes from BB1 into BB2.
getSrcVReg(unsigned Reg,MachineBasicBlock * BB1,MachineBasicBlock * BB2,MachineRegisterInfo * MRI)117979c0bec0SHiroshi Inoue static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
118079c0bec0SHiroshi Inoue                            MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
118179c0bec0SHiroshi Inoue   unsigned SrcReg = Reg;
11822aed0813SKazu Hirata   while (true) {
118379c0bec0SHiroshi Inoue     unsigned NextReg = SrcReg;
118479c0bec0SHiroshi Inoue     MachineInstr *Inst = MRI->getVRegDef(SrcReg);
118579c0bec0SHiroshi Inoue     if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
118679c0bec0SHiroshi Inoue       NextReg = getIncomingRegForBlock(Inst, BB1);
118779c0bec0SHiroshi Inoue       // We track through PHI only once to avoid infinite loop.
118879c0bec0SHiroshi Inoue       BB1 = nullptr;
118979c0bec0SHiroshi Inoue     }
119079c0bec0SHiroshi Inoue     else if (Inst->isFullCopy())
119179c0bec0SHiroshi Inoue       NextReg = Inst->getOperand(1).getReg();
11922bea69bfSDaniel Sanders     if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg))
119379c0bec0SHiroshi Inoue       break;
119479c0bec0SHiroshi Inoue     SrcReg = NextReg;
119579c0bec0SHiroshi Inoue   }
119679c0bec0SHiroshi Inoue   return SrcReg;
119779c0bec0SHiroshi Inoue }
119879c0bec0SHiroshi Inoue 
eligibleForCompareElimination(MachineBasicBlock & MBB,MachineBasicBlock * & PredMBB,MachineBasicBlock * & MBBtoMoveCmp,MachineRegisterInfo * MRI)1199614453b7SHiroshi Inoue static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
120079c0bec0SHiroshi Inoue                                           MachineBasicBlock *&PredMBB,
120179c0bec0SHiroshi Inoue                                           MachineBasicBlock *&MBBtoMoveCmp,
1202614453b7SHiroshi Inoue                                           MachineRegisterInfo *MRI) {
1203614453b7SHiroshi Inoue 
1204614453b7SHiroshi Inoue   auto isEligibleBB = [&](MachineBasicBlock &BB) {
1205614453b7SHiroshi Inoue     auto BII = BB.getFirstInstrTerminator();
1206614453b7SHiroshi Inoue     // We optimize BBs ending with a conditional branch.
1207614453b7SHiroshi Inoue     // We check only for BCC here, not BCCLR, because BCCLR
1208614453b7SHiroshi Inoue     // will be formed only later in the pipeline.
1209614453b7SHiroshi Inoue     if (BB.succ_size() == 2 &&
1210614453b7SHiroshi Inoue         BII != BB.instr_end() &&
1211614453b7SHiroshi Inoue         (*BII).getOpcode() == PPC::BCC &&
1212614453b7SHiroshi Inoue         (*BII).getOperand(1).isReg()) {
1213614453b7SHiroshi Inoue       // We optimize only if the condition code is used only by one BCC.
12140c476111SDaniel Sanders       Register CndReg = (*BII).getOperand(1).getReg();
12152bea69bfSDaniel Sanders       if (!Register::isVirtualRegister(CndReg) || !MRI->hasOneNonDBGUse(CndReg))
1216614453b7SHiroshi Inoue         return false;
1217614453b7SHiroshi Inoue 
1218614453b7SHiroshi Inoue       MachineInstr *CMPI = MRI->getVRegDef(CndReg);
121972a1f98aSHiroshi Inoue       // We assume compare and branch are in the same BB for ease of analysis.
122072a1f98aSHiroshi Inoue       if (CMPI->getParent() != &BB)
122172a1f98aSHiroshi Inoue         return false;
122272a1f98aSHiroshi Inoue 
122372a1f98aSHiroshi Inoue       // We skip this BB if a physical register is used in comparison.
1224614453b7SHiroshi Inoue       for (MachineOperand &MO : CMPI->operands())
12252bea69bfSDaniel Sanders         if (MO.isReg() && !Register::isVirtualRegister(MO.getReg()))
1226614453b7SHiroshi Inoue           return false;
1227614453b7SHiroshi Inoue 
1228614453b7SHiroshi Inoue       return true;
1229614453b7SHiroshi Inoue     }
1230614453b7SHiroshi Inoue     return false;
1231614453b7SHiroshi Inoue   };
1232614453b7SHiroshi Inoue 
123379c0bec0SHiroshi Inoue   // If this BB has more than one successor, we can create a new BB and
123479c0bec0SHiroshi Inoue   // move the compare instruction in the new BB.
123579c0bec0SHiroshi Inoue   // So far, we do not move compare instruction to a BB having multiple
123679c0bec0SHiroshi Inoue   // successors to avoid potentially increasing code size.
123779c0bec0SHiroshi Inoue   auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
123879c0bec0SHiroshi Inoue     return BB.succ_size() == 1;
123979c0bec0SHiroshi Inoue   };
124079c0bec0SHiroshi Inoue 
124179c0bec0SHiroshi Inoue   if (!isEligibleBB(MBB))
1242614453b7SHiroshi Inoue     return false;
1243614453b7SHiroshi Inoue 
124479c0bec0SHiroshi Inoue   unsigned NumPredBBs = MBB.pred_size();
124579c0bec0SHiroshi Inoue   if (NumPredBBs == 1) {
124679c0bec0SHiroshi Inoue     MachineBasicBlock *TmpMBB = *MBB.pred_begin();
124779c0bec0SHiroshi Inoue     if (isEligibleBB(*TmpMBB)) {
124879c0bec0SHiroshi Inoue       PredMBB = TmpMBB;
124979c0bec0SHiroshi Inoue       MBBtoMoveCmp = nullptr;
1250614453b7SHiroshi Inoue       return true;
125179c0bec0SHiroshi Inoue     }
125279c0bec0SHiroshi Inoue   }
125379c0bec0SHiroshi Inoue   else if (NumPredBBs == 2) {
125479c0bec0SHiroshi Inoue     // We check for partially redundant case.
125579c0bec0SHiroshi Inoue     // So far, we support cases with only two predecessors
125679c0bec0SHiroshi Inoue     // to avoid increasing the number of instructions.
125779c0bec0SHiroshi Inoue     MachineBasicBlock::pred_iterator PI = MBB.pred_begin();
125879c0bec0SHiroshi Inoue     MachineBasicBlock *Pred1MBB = *PI;
125979c0bec0SHiroshi Inoue     MachineBasicBlock *Pred2MBB = *(PI+1);
126079c0bec0SHiroshi Inoue 
126179c0bec0SHiroshi Inoue     if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
126279c0bec0SHiroshi Inoue       // We assume Pred1MBB is the BB containing the compare to be merged and
126379c0bec0SHiroshi Inoue       // Pred2MBB is the BB to which we will append a compare instruction.
126479c0bec0SHiroshi Inoue       // Hence we can proceed as is.
126579c0bec0SHiroshi Inoue     }
126679c0bec0SHiroshi Inoue     else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
126779c0bec0SHiroshi Inoue       // We need to swap Pred1MBB and Pred2MBB to canonicalize.
126879c0bec0SHiroshi Inoue       std::swap(Pred1MBB, Pred2MBB);
126979c0bec0SHiroshi Inoue     }
127079c0bec0SHiroshi Inoue     else return false;
127179c0bec0SHiroshi Inoue 
127279c0bec0SHiroshi Inoue     // Here, Pred2MBB is the BB to which we need to append a compare inst.
127379c0bec0SHiroshi Inoue     // We cannot move the compare instruction if operands are not available
127479c0bec0SHiroshi Inoue     // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
127579c0bec0SHiroshi Inoue     MachineInstr *BI = &*MBB.getFirstInstrTerminator();
127679c0bec0SHiroshi Inoue     MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
127779c0bec0SHiroshi Inoue     for (int I = 1; I <= 2; I++)
127879c0bec0SHiroshi Inoue       if (CMPI->getOperand(I).isReg()) {
127979c0bec0SHiroshi Inoue         MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
128079c0bec0SHiroshi Inoue         if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
128179c0bec0SHiroshi Inoue           return false;
128279c0bec0SHiroshi Inoue       }
128379c0bec0SHiroshi Inoue 
128479c0bec0SHiroshi Inoue     PredMBB = Pred1MBB;
128579c0bec0SHiroshi Inoue     MBBtoMoveCmp = Pred2MBB;
128679c0bec0SHiroshi Inoue     return true;
128779c0bec0SHiroshi Inoue   }
1288614453b7SHiroshi Inoue 
1289614453b7SHiroshi Inoue   return false;
1290614453b7SHiroshi Inoue }
1291614453b7SHiroshi Inoue 
1292f94d58d9SZaara Syeda // This function will iterate over the input map containing a pair of TOC save
1293df28fb6aSZaara Syeda // instruction and a flag. The flag will be set to false if the TOC save is
1294df28fb6aSZaara Syeda // proven redundant. This function will erase from the basic block all the TOC
1295df28fb6aSZaara Syeda // saves marked as redundant.
eliminateRedundantTOCSaves(std::map<MachineInstr *,bool> & TOCSaves)1296f94d58d9SZaara Syeda bool PPCMIPeephole::eliminateRedundantTOCSaves(
1297f94d58d9SZaara Syeda     std::map<MachineInstr *, bool> &TOCSaves) {
1298f94d58d9SZaara Syeda   bool Simplified = false;
1299f94d58d9SZaara Syeda   int NumKept = 0;
1300f94d58d9SZaara Syeda   for (auto TOCSave : TOCSaves) {
1301f94d58d9SZaara Syeda     if (!TOCSave.second) {
1302f94d58d9SZaara Syeda       TOCSave.first->eraseFromParent();
1303f94d58d9SZaara Syeda       RemoveTOCSave++;
1304f94d58d9SZaara Syeda       Simplified = true;
1305f94d58d9SZaara Syeda     } else {
1306f94d58d9SZaara Syeda       NumKept++;
1307f94d58d9SZaara Syeda     }
1308f94d58d9SZaara Syeda   }
1309f94d58d9SZaara Syeda 
1310f94d58d9SZaara Syeda   if (NumKept > 1)
1311f94d58d9SZaara Syeda     MultiTOCSaves++;
1312f94d58d9SZaara Syeda 
1313f94d58d9SZaara Syeda   return Simplified;
1314f94d58d9SZaara Syeda }
1315f94d58d9SZaara Syeda 
1316614453b7SHiroshi Inoue // If multiple conditional branches are executed based on the (essentially)
1317614453b7SHiroshi Inoue // same comparison, we merge compare instructions into one and make multiple
1318614453b7SHiroshi Inoue // conditional branches on this comparison.
1319614453b7SHiroshi Inoue // For example,
1320614453b7SHiroshi Inoue //   if (a == 0) { ... }
1321614453b7SHiroshi Inoue //   else if (a < 0) { ... }
1322614453b7SHiroshi Inoue // can be executed by one compare and two conditional branches instead of
1323614453b7SHiroshi Inoue // two pairs of a compare and a conditional branch.
1324614453b7SHiroshi Inoue //
1325614453b7SHiroshi Inoue // This method merges two compare instructions in two MBBs and modifies the
1326614453b7SHiroshi Inoue // compare and conditional branch instructions if needed.
1327614453b7SHiroshi Inoue // For the above example, the input for this pass looks like:
1328614453b7SHiroshi Inoue //   cmplwi r3, 0
1329614453b7SHiroshi Inoue //   beq    0, .LBB0_3
1330614453b7SHiroshi Inoue //   cmpwi  r3, -1
1331614453b7SHiroshi Inoue //   bgt    0, .LBB0_4
1332614453b7SHiroshi Inoue // So, before merging two compares, we need to modify these instructions as
1333614453b7SHiroshi Inoue //   cmpwi  r3, 0       ; cmplwi and cmpwi yield same result for beq
1334614453b7SHiroshi Inoue //   beq    0, .LBB0_3
1335614453b7SHiroshi Inoue //   cmpwi  r3, 0       ; greather than -1 means greater or equal to 0
1336614453b7SHiroshi Inoue //   bge    0, .LBB0_4
1337614453b7SHiroshi Inoue 
eliminateRedundantCompare()13387e163afdSKazu Hirata bool PPCMIPeephole::eliminateRedundantCompare() {
1339614453b7SHiroshi Inoue   bool Simplified = false;
1340614453b7SHiroshi Inoue 
1341614453b7SHiroshi Inoue   for (MachineBasicBlock &MBB2 : *MF) {
134279c0bec0SHiroshi Inoue     MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
134379c0bec0SHiroshi Inoue 
134479c0bec0SHiroshi Inoue     // For fully redundant case, we select two basic blocks MBB1 and MBB2
134579c0bec0SHiroshi Inoue     // as an optimization target if
1346614453b7SHiroshi Inoue     // - both MBBs end with a conditional branch,
1347614453b7SHiroshi Inoue     // - MBB1 is the only predecessor of MBB2, and
1348614453b7SHiroshi Inoue     // - compare does not take a physical register as a operand in both MBBs.
134979c0bec0SHiroshi Inoue     // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
135079c0bec0SHiroshi Inoue     //
135179c0bec0SHiroshi Inoue     // As partially redundant case, we additionally handle if MBB2 has one
135279c0bec0SHiroshi Inoue     // additional predecessor, which has only one successor (MBB2).
135372a1f98aSHiroshi Inoue     // In this case, we move the compare instruction originally in MBB2 into
135479c0bec0SHiroshi Inoue     // MBBtoMoveCmp. This partially redundant case is typically appear by
135579c0bec0SHiroshi Inoue     // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
135679c0bec0SHiroshi Inoue     //
135779c0bec0SHiroshi Inoue     // Overview of CFG of related basic blocks
135879c0bec0SHiroshi Inoue     // Fully redundant case        Partially redundant case
135979c0bec0SHiroshi Inoue     //   --------                   ----------------  --------
136079c0bec0SHiroshi Inoue     //   | MBB1 | (w/ 2 succ)       | MBBtoMoveCmp |  | MBB1 | (w/ 2 succ)
136179c0bec0SHiroshi Inoue     //   --------                   ----------------  --------
136279c0bec0SHiroshi Inoue     //      |    \                     (w/ 1 succ) \     |    \
136379c0bec0SHiroshi Inoue     //      |     \                                 \    |     \
136479c0bec0SHiroshi Inoue     //      |                                        \   |
136579c0bec0SHiroshi Inoue     //   --------                                     --------
136679c0bec0SHiroshi Inoue     //   | MBB2 | (w/ 1 pred                          | MBB2 | (w/ 2 pred
136779c0bec0SHiroshi Inoue     //   -------- and 2 succ)                         -------- and 2 succ)
136879c0bec0SHiroshi Inoue     //      |    \                                       |    \
136979c0bec0SHiroshi Inoue     //      |     \                                      |     \
137079c0bec0SHiroshi Inoue     //
137179c0bec0SHiroshi Inoue     if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
1372614453b7SHiroshi Inoue       continue;
1373614453b7SHiroshi Inoue 
1374614453b7SHiroshi Inoue     MachineInstr *BI1   = &*MBB1->getFirstInstrTerminator();
1375614453b7SHiroshi Inoue     MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
1376614453b7SHiroshi Inoue 
1377614453b7SHiroshi Inoue     MachineInstr *BI2   = &*MBB2.getFirstInstrTerminator();
1378614453b7SHiroshi Inoue     MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
137979c0bec0SHiroshi Inoue     bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
1380614453b7SHiroshi Inoue 
1381614453b7SHiroshi Inoue     // We cannot optimize an unsupported compare opcode or
1382614453b7SHiroshi Inoue     // a mix of 32-bit and 64-bit comaprisons
1383614453b7SHiroshi Inoue     if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
1384614453b7SHiroshi Inoue         !isSupportedCmpOp(CMPI2->getOpcode()) ||
1385614453b7SHiroshi Inoue         is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
1386614453b7SHiroshi Inoue       continue;
1387614453b7SHiroshi Inoue 
1388614453b7SHiroshi Inoue     unsigned NewOpCode = 0;
1389614453b7SHiroshi Inoue     unsigned NewPredicate1 = 0, NewPredicate2 = 0;
1390614453b7SHiroshi Inoue     int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
139179c0bec0SHiroshi Inoue     bool SwapOperands = false;
1392614453b7SHiroshi Inoue 
1393614453b7SHiroshi Inoue     if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
1394614453b7SHiroshi Inoue       // Typically, unsigned comparison is used for equality check, but
1395614453b7SHiroshi Inoue       // we replace it with a signed comparison if the comparison
1396614453b7SHiroshi Inoue       // to be merged is a signed comparison.
1397614453b7SHiroshi Inoue       // In other cases of opcode mismatch, we cannot optimize this.
139811e571e0SHiroshi Inoue 
139911e571e0SHiroshi Inoue       // We cannot change opcode when comparing against an immediate
140011e571e0SHiroshi Inoue       // if the most significant bit of the immediate is one
140111e571e0SHiroshi Inoue       // due to the difference in sign extension.
140211e571e0SHiroshi Inoue       auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
140311e571e0SHiroshi Inoue         if (!I->getOperand(2).isImm())
140411e571e0SHiroshi Inoue           return false;
140511e571e0SHiroshi Inoue         int16_t Imm = (int16_t)I->getOperand(2).getImm();
140611e571e0SHiroshi Inoue         return Imm < 0;
140711e571e0SHiroshi Inoue       };
140811e571e0SHiroshi Inoue 
140911e571e0SHiroshi Inoue       if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
1410614453b7SHiroshi Inoue           CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
1411614453b7SHiroshi Inoue         NewOpCode = CMPI1->getOpcode();
141211e571e0SHiroshi Inoue       else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
1413614453b7SHiroshi Inoue                getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
1414614453b7SHiroshi Inoue         NewOpCode = CMPI2->getOpcode();
1415614453b7SHiroshi Inoue       else continue;
1416614453b7SHiroshi Inoue     }
1417614453b7SHiroshi Inoue 
1418614453b7SHiroshi Inoue     if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
1419614453b7SHiroshi Inoue       // In case of comparisons between two registers, these two registers
1420614453b7SHiroshi Inoue       // must be same to merge two comparisons.
142179c0bec0SHiroshi Inoue       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
142279c0bec0SHiroshi Inoue                                          nullptr, nullptr, MRI);
142379c0bec0SHiroshi Inoue       unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
142479c0bec0SHiroshi Inoue                                          nullptr, nullptr, MRI);
142579c0bec0SHiroshi Inoue       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
142679c0bec0SHiroshi Inoue                                          MBB1, &MBB2, MRI);
142779c0bec0SHiroshi Inoue       unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
142879c0bec0SHiroshi Inoue                                          MBB1, &MBB2, MRI);
142979c0bec0SHiroshi Inoue 
1430614453b7SHiroshi Inoue       if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
1431614453b7SHiroshi Inoue         // Same pair of registers in the same order; ready to merge as is.
1432614453b7SHiroshi Inoue       }
1433614453b7SHiroshi Inoue       else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
1434614453b7SHiroshi Inoue         // Same pair of registers in different order.
1435614453b7SHiroshi Inoue         // We reverse the predicate to merge compare instructions.
1436614453b7SHiroshi Inoue         PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm();
1437614453b7SHiroshi Inoue         NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
143879c0bec0SHiroshi Inoue         // In case of partial redundancy, we need to swap operands
143979c0bec0SHiroshi Inoue         // in another compare instruction.
144079c0bec0SHiroshi Inoue         SwapOperands = true;
1441614453b7SHiroshi Inoue       }
1442614453b7SHiroshi Inoue       else continue;
1443614453b7SHiroshi Inoue     }
1444614453b7SHiroshi Inoue     else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
1445614453b7SHiroshi Inoue       // In case of comparisons between a register and an immediate,
1446614453b7SHiroshi Inoue       // the operand register must be same for two compare instructions.
144779c0bec0SHiroshi Inoue       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
144879c0bec0SHiroshi Inoue                                          nullptr, nullptr, MRI);
144979c0bec0SHiroshi Inoue       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
145079c0bec0SHiroshi Inoue                                          MBB1, &MBB2, MRI);
145179c0bec0SHiroshi Inoue       if (Cmp1Operand1 != Cmp2Operand1)
1452614453b7SHiroshi Inoue         continue;
1453614453b7SHiroshi Inoue 
1454614453b7SHiroshi Inoue       NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
1455614453b7SHiroshi Inoue       NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
1456614453b7SHiroshi Inoue 
1457614453b7SHiroshi Inoue       // If immediate are not same, we try to adjust by changing predicate;
1458614453b7SHiroshi Inoue       // e.g. GT imm means GE (imm+1).
1459614453b7SHiroshi Inoue       if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
1460614453b7SHiroshi Inoue         int Diff = Imm1 - Imm2;
1461614453b7SHiroshi Inoue         if (Diff < -2 || Diff > 2)
1462614453b7SHiroshi Inoue           continue;
1463614453b7SHiroshi Inoue 
1464614453b7SHiroshi Inoue         unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
1465614453b7SHiroshi Inoue         unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
1466614453b7SHiroshi Inoue         unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
1467614453b7SHiroshi Inoue         unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
1468614453b7SHiroshi Inoue         if (Diff == 2) {
1469614453b7SHiroshi Inoue           if (PredToInc2 && PredToDec1) {
1470614453b7SHiroshi Inoue             NewPredicate2 = PredToInc2;
1471614453b7SHiroshi Inoue             NewPredicate1 = PredToDec1;
1472614453b7SHiroshi Inoue             NewImm2++;
1473614453b7SHiroshi Inoue             NewImm1--;
1474614453b7SHiroshi Inoue           }
1475614453b7SHiroshi Inoue         }
1476614453b7SHiroshi Inoue         else if (Diff == 1) {
1477614453b7SHiroshi Inoue           if (PredToInc2) {
1478614453b7SHiroshi Inoue             NewImm2++;
1479614453b7SHiroshi Inoue             NewPredicate2 = PredToInc2;
1480614453b7SHiroshi Inoue           }
1481614453b7SHiroshi Inoue           else if (PredToDec1) {
1482614453b7SHiroshi Inoue             NewImm1--;
1483614453b7SHiroshi Inoue             NewPredicate1 = PredToDec1;
1484614453b7SHiroshi Inoue           }
1485614453b7SHiroshi Inoue         }
1486614453b7SHiroshi Inoue         else if (Diff == -1) {
1487614453b7SHiroshi Inoue           if (PredToDec2) {
1488614453b7SHiroshi Inoue             NewImm2--;
1489614453b7SHiroshi Inoue             NewPredicate2 = PredToDec2;
1490614453b7SHiroshi Inoue           }
1491614453b7SHiroshi Inoue           else if (PredToInc1) {
1492614453b7SHiroshi Inoue             NewImm1++;
1493614453b7SHiroshi Inoue             NewPredicate1 = PredToInc1;
1494614453b7SHiroshi Inoue           }
1495614453b7SHiroshi Inoue         }
1496614453b7SHiroshi Inoue         else if (Diff == -2) {
1497614453b7SHiroshi Inoue           if (PredToDec2 && PredToInc1) {
1498614453b7SHiroshi Inoue             NewPredicate2 = PredToDec2;
1499614453b7SHiroshi Inoue             NewPredicate1 = PredToInc1;
1500614453b7SHiroshi Inoue             NewImm2--;
1501614453b7SHiroshi Inoue             NewImm1++;
1502614453b7SHiroshi Inoue           }
1503614453b7SHiroshi Inoue         }
1504614453b7SHiroshi Inoue       }
1505614453b7SHiroshi Inoue 
15060f7f59f0SHiroshi Inoue       // We cannot merge two compares if the immediates are not same.
1507614453b7SHiroshi Inoue       if (NewImm2 != NewImm1)
1508614453b7SHiroshi Inoue         continue;
1509614453b7SHiroshi Inoue     }
1510614453b7SHiroshi Inoue 
1511d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
1512d34e60caSNicola Zaghen     LLVM_DEBUG(CMPI1->dump());
1513d34e60caSNicola Zaghen     LLVM_DEBUG(BI1->dump());
1514d34e60caSNicola Zaghen     LLVM_DEBUG(CMPI2->dump());
1515d34e60caSNicola Zaghen     LLVM_DEBUG(BI2->dump());
1516614453b7SHiroshi Inoue 
1517614453b7SHiroshi Inoue     // We adjust opcode, predicates and immediate as we determined above.
1518614453b7SHiroshi Inoue     if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
1519614453b7SHiroshi Inoue       CMPI1->setDesc(TII->get(NewOpCode));
1520614453b7SHiroshi Inoue     }
1521614453b7SHiroshi Inoue     if (NewPredicate1) {
1522614453b7SHiroshi Inoue       BI1->getOperand(0).setImm(NewPredicate1);
1523614453b7SHiroshi Inoue     }
1524614453b7SHiroshi Inoue     if (NewPredicate2) {
1525614453b7SHiroshi Inoue       BI2->getOperand(0).setImm(NewPredicate2);
1526614453b7SHiroshi Inoue     }
1527614453b7SHiroshi Inoue     if (NewImm1 != Imm1) {
1528614453b7SHiroshi Inoue       CMPI1->getOperand(2).setImm(NewImm1);
1529614453b7SHiroshi Inoue     }
1530614453b7SHiroshi Inoue 
153179c0bec0SHiroshi Inoue     if (IsPartiallyRedundant) {
153279c0bec0SHiroshi Inoue       // We touch up the compare instruction in MBB2 and move it to
153379c0bec0SHiroshi Inoue       // a previous BB to handle partially redundant case.
153479c0bec0SHiroshi Inoue       if (SwapOperands) {
15350c476111SDaniel Sanders         Register Op1 = CMPI2->getOperand(1).getReg();
15360c476111SDaniel Sanders         Register Op2 = CMPI2->getOperand(2).getReg();
153779c0bec0SHiroshi Inoue         CMPI2->getOperand(1).setReg(Op2);
153879c0bec0SHiroshi Inoue         CMPI2->getOperand(2).setReg(Op1);
153979c0bec0SHiroshi Inoue       }
154079c0bec0SHiroshi Inoue       if (NewImm2 != Imm2)
154179c0bec0SHiroshi Inoue         CMPI2->getOperand(2).setImm(NewImm2);
154279c0bec0SHiroshi Inoue 
154379c0bec0SHiroshi Inoue       for (int I = 1; I <= 2; I++) {
154479c0bec0SHiroshi Inoue         if (CMPI2->getOperand(I).isReg()) {
154579c0bec0SHiroshi Inoue           MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
154679c0bec0SHiroshi Inoue           if (Inst->getParent() != &MBB2)
154779c0bec0SHiroshi Inoue             continue;
154879c0bec0SHiroshi Inoue 
154979c0bec0SHiroshi Inoue           assert(Inst->getOpcode() == PPC::PHI &&
155079c0bec0SHiroshi Inoue                  "We cannot support if an operand comes from this BB.");
155179c0bec0SHiroshi Inoue           unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
155279c0bec0SHiroshi Inoue           CMPI2->getOperand(I).setReg(SrcReg);
155379c0bec0SHiroshi Inoue         }
155479c0bec0SHiroshi Inoue       }
155579c0bec0SHiroshi Inoue       auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
155679c0bec0SHiroshi Inoue       MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
155779c0bec0SHiroshi Inoue 
155879c0bec0SHiroshi Inoue       DebugLoc DL = CMPI2->getDebugLoc();
15590c476111SDaniel Sanders       Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
156079c0bec0SHiroshi Inoue       BuildMI(MBB2, MBB2.begin(), DL,
156179c0bec0SHiroshi Inoue               TII->get(PPC::PHI), NewVReg)
156279c0bec0SHiroshi Inoue         .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
156379c0bec0SHiroshi Inoue         .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
156479c0bec0SHiroshi Inoue       BI2->getOperand(1).setReg(NewVReg);
156579c0bec0SHiroshi Inoue     }
156679c0bec0SHiroshi Inoue     else {
1567614453b7SHiroshi Inoue       // We finally eliminate compare instruction in MBB2.
1568614453b7SHiroshi Inoue       BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
156979c0bec0SHiroshi Inoue       CMPI2->eraseFromParent();
157079c0bec0SHiroshi Inoue     }
1571614453b7SHiroshi Inoue     BI2->getOperand(1).setIsKill(true);
1572614453b7SHiroshi Inoue     BI1->getOperand(1).setIsKill(false);
1573614453b7SHiroshi Inoue 
1574d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "into a compare and two branches:\n");
1575d34e60caSNicola Zaghen     LLVM_DEBUG(CMPI1->dump());
1576d34e60caSNicola Zaghen     LLVM_DEBUG(BI1->dump());
1577d34e60caSNicola Zaghen     LLVM_DEBUG(BI2->dump());
157879c0bec0SHiroshi Inoue     if (IsPartiallyRedundant) {
1579d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "The following compare is moved into "
158025528d6dSFrancis Visoiu Mistrih                         << printMBBReference(*MBBtoMoveCmp)
158125528d6dSFrancis Visoiu Mistrih                         << " to handle partial redundancy.\n");
1582d34e60caSNicola Zaghen       LLVM_DEBUG(CMPI2->dump());
158379c0bec0SHiroshi Inoue     }
1584614453b7SHiroshi Inoue 
1585614453b7SHiroshi Inoue     Simplified = true;
1586614453b7SHiroshi Inoue   }
1587614453b7SHiroshi Inoue 
158834af5e1cSBill Schmidt   return Simplified;
158934af5e1cSBill Schmidt }
159034af5e1cSBill Schmidt 
1591174b4ff7SKai Luo // We miss the opportunity to emit an RLDIC when lowering jump tables
1592174b4ff7SKai Luo // since ISEL sees only a single basic block. When selecting, the clear
1593174b4ff7SKai Luo // and shift left will be in different blocks.
emitRLDICWhenLoweringJumpTables(MachineInstr & MI)1594d6a8bc7aSKai Luo bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI) {
1595174b4ff7SKai Luo   if (MI.getOpcode() != PPC::RLDICR)
1596d6a8bc7aSKai Luo     return false;
1597174b4ff7SKai Luo 
15980c476111SDaniel Sanders   Register SrcReg = MI.getOperand(1).getReg();
15992bea69bfSDaniel Sanders   if (!Register::isVirtualRegister(SrcReg))
1600d6a8bc7aSKai Luo     return false;
1601174b4ff7SKai Luo 
1602174b4ff7SKai Luo   MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1603174b4ff7SKai Luo   if (SrcMI->getOpcode() != PPC::RLDICL)
1604d6a8bc7aSKai Luo     return false;
1605174b4ff7SKai Luo 
1606174b4ff7SKai Luo   MachineOperand MOpSHSrc = SrcMI->getOperand(2);
1607174b4ff7SKai Luo   MachineOperand MOpMBSrc = SrcMI->getOperand(3);
1608174b4ff7SKai Luo   MachineOperand MOpSHMI = MI.getOperand(2);
1609174b4ff7SKai Luo   MachineOperand MOpMEMI = MI.getOperand(3);
1610174b4ff7SKai Luo   if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() &&
1611174b4ff7SKai Luo         MOpMEMI.isImm()))
1612d6a8bc7aSKai Luo     return false;
1613174b4ff7SKai Luo 
1614174b4ff7SKai Luo   uint64_t SHSrc = MOpSHSrc.getImm();
1615174b4ff7SKai Luo   uint64_t MBSrc = MOpMBSrc.getImm();
1616174b4ff7SKai Luo   uint64_t SHMI = MOpSHMI.getImm();
1617174b4ff7SKai Luo   uint64_t MEMI = MOpMEMI.getImm();
1618174b4ff7SKai Luo   uint64_t NewSH = SHSrc + SHMI;
1619174b4ff7SKai Luo   uint64_t NewMB = MBSrc - SHMI;
1620174b4ff7SKai Luo   if (NewMB > 63 || NewSH > 63)
1621d6a8bc7aSKai Luo     return false;
1622174b4ff7SKai Luo 
1623174b4ff7SKai Luo   // The bits cleared with RLDICL are [0, MBSrc).
1624174b4ff7SKai Luo   // The bits cleared with RLDICR are (MEMI, 63].
1625174b4ff7SKai Luo   // After the sequence, the bits cleared are:
1626174b4ff7SKai Luo   // [0, MBSrc-SHMI) and (MEMI, 63).
1627174b4ff7SKai Luo   //
1628174b4ff7SKai Luo   // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63].
1629174b4ff7SKai Luo   if ((63 - NewSH) != MEMI)
1630d6a8bc7aSKai Luo     return false;
1631174b4ff7SKai Luo 
1632174b4ff7SKai Luo   LLVM_DEBUG(dbgs() << "Converting pair: ");
1633174b4ff7SKai Luo   LLVM_DEBUG(SrcMI->dump());
1634174b4ff7SKai Luo   LLVM_DEBUG(MI.dump());
1635174b4ff7SKai Luo 
1636174b4ff7SKai Luo   MI.setDesc(TII->get(PPC::RLDIC));
1637174b4ff7SKai Luo   MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
1638174b4ff7SKai Luo   MI.getOperand(2).setImm(NewSH);
1639174b4ff7SKai Luo   MI.getOperand(3).setImm(NewMB);
164069289cc1SNemanja Ivanovic   MI.getOperand(1).setIsKill(SrcMI->getOperand(1).isKill());
164169289cc1SNemanja Ivanovic   SrcMI->getOperand(1).setIsKill(false);
1642174b4ff7SKai Luo 
1643174b4ff7SKai Luo   LLVM_DEBUG(dbgs() << "To: ");
1644174b4ff7SKai Luo   LLVM_DEBUG(MI.dump());
1645174b4ff7SKai Luo   NumRotatesCollapsed++;
1646c9790d54SAnil Mahmud   // If SrcReg has no non-debug use it's safe to delete its def SrcMI.
1647c9790d54SAnil Mahmud   if (MRI->use_nodbg_empty(SrcReg)) {
1648c9790d54SAnil Mahmud     assert(!SrcMI->hasImplicitDef() &&
1649c9790d54SAnil Mahmud            "Not expecting an implicit def with this instr.");
1650c9790d54SAnil Mahmud     SrcMI->eraseFromParent();
1651c9790d54SAnil Mahmud   }
1652d6a8bc7aSKai Luo   return true;
1653174b4ff7SKai Luo }
1654174b4ff7SKai Luo 
16551931ed73SKai Luo // For case in LLVM IR
16561931ed73SKai Luo // entry:
16571931ed73SKai Luo //   %iconv = sext i32 %index to i64
16581931ed73SKai Luo //   br i1 undef label %true, label %false
16591931ed73SKai Luo // true:
16601931ed73SKai Luo //   %ptr = getelementptr inbounds i32, i32* null, i64 %iconv
16611931ed73SKai Luo // ...
16621931ed73SKai Luo // PPCISelLowering::combineSHL fails to combine, because sext and shl are in
16631931ed73SKai Luo // different BBs when conducting instruction selection. We can do a peephole
16641931ed73SKai Luo // optimization to combine these two instructions into extswsli after
16651931ed73SKai Luo // instruction selection.
combineSEXTAndSHL(MachineInstr & MI,MachineInstr * & ToErase)16661931ed73SKai Luo bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI,
16671931ed73SKai Luo                                       MachineInstr *&ToErase) {
16681931ed73SKai Luo   if (MI.getOpcode() != PPC::RLDICR)
16691931ed73SKai Luo     return false;
16701931ed73SKai Luo 
16711931ed73SKai Luo   if (!MF->getSubtarget<PPCSubtarget>().isISA3_0())
16721931ed73SKai Luo     return false;
16731931ed73SKai Luo 
16741931ed73SKai Luo   assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands");
16751931ed73SKai Luo 
16761931ed73SKai Luo   MachineOperand MOpSHMI = MI.getOperand(2);
16771931ed73SKai Luo   MachineOperand MOpMEMI = MI.getOperand(3);
16781931ed73SKai Luo   if (!(MOpSHMI.isImm() && MOpMEMI.isImm()))
16791931ed73SKai Luo     return false;
16801931ed73SKai Luo 
16811931ed73SKai Luo   uint64_t SHMI = MOpSHMI.getImm();
16821931ed73SKai Luo   uint64_t MEMI = MOpMEMI.getImm();
16831931ed73SKai Luo   if (SHMI + MEMI != 63)
16841931ed73SKai Luo     return false;
16851931ed73SKai Luo 
16860c476111SDaniel Sanders   Register SrcReg = MI.getOperand(1).getReg();
16872bea69bfSDaniel Sanders   if (!Register::isVirtualRegister(SrcReg))
16881931ed73SKai Luo     return false;
16891931ed73SKai Luo 
16901931ed73SKai Luo   MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
16911931ed73SKai Luo   if (SrcMI->getOpcode() != PPC::EXTSW &&
16921931ed73SKai Luo       SrcMI->getOpcode() != PPC::EXTSW_32_64)
16931931ed73SKai Luo     return false;
16941931ed73SKai Luo 
16951931ed73SKai Luo   // If the register defined by extsw has more than one use, combination is not
16961931ed73SKai Luo   // needed.
16971931ed73SKai Luo   if (!MRI->hasOneNonDBGUse(SrcReg))
16981931ed73SKai Luo     return false;
16991931ed73SKai Luo 
1700fec7da82SKai Luo   assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands");
1701fec7da82SKai Luo   assert(SrcMI->getOperand(1).isReg() &&
1702fec7da82SKai Luo          "EXTSW's second operand should be a register");
1703fec7da82SKai Luo   if (!Register::isVirtualRegister(SrcMI->getOperand(1).getReg()))
1704fec7da82SKai Luo     return false;
1705fec7da82SKai Luo 
17061931ed73SKai Luo   LLVM_DEBUG(dbgs() << "Combining pair: ");
17071931ed73SKai Luo   LLVM_DEBUG(SrcMI->dump());
17081931ed73SKai Luo   LLVM_DEBUG(MI.dump());
17091931ed73SKai Luo 
17101931ed73SKai Luo   MachineInstr *NewInstr =
17111931ed73SKai Luo       BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
17121931ed73SKai Luo               SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI)
17131931ed73SKai Luo                                                : TII->get(PPC::EXTSWSLI_32_64),
17141931ed73SKai Luo               MI.getOperand(0).getReg())
17151931ed73SKai Luo           .add(SrcMI->getOperand(1))
17161931ed73SKai Luo           .add(MOpSHMI);
1717619e39bcSKai Luo   (void)NewInstr;
17181931ed73SKai Luo 
17191931ed73SKai Luo   LLVM_DEBUG(dbgs() << "TO: ");
17201931ed73SKai Luo   LLVM_DEBUG(NewInstr->dump());
17211931ed73SKai Luo   ++NumEXTSWAndSLDICombined;
17221931ed73SKai Luo   ToErase = &MI;
17231931ed73SKai Luo   // SrcMI, which is extsw, is of no use now, erase it.
17241931ed73SKai Luo   SrcMI->eraseFromParent();
17251931ed73SKai Luo   return true;
17261931ed73SKai Luo }
17271931ed73SKai Luo 
172834af5e1cSBill Schmidt } // end default namespace
172934af5e1cSBill Schmidt 
173034af5e1cSBill Schmidt INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
173134af5e1cSBill Schmidt                       "PowerPC MI Peephole Optimization", false, false)
17326c9a392cSNemanja Ivanovic INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
17336c9a392cSNemanja Ivanovic INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
17346c9a392cSNemanja Ivanovic INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
173534af5e1cSBill Schmidt INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
173634af5e1cSBill Schmidt                     "PowerPC MI Peephole Optimization", false, false)
173734af5e1cSBill Schmidt 
173834af5e1cSBill Schmidt char PPCMIPeephole::ID = 0;
173934af5e1cSBill Schmidt FunctionPass*
createPPCMIPeepholePass()174034af5e1cSBill Schmidt llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
1741