xref: /llvm-project/llvm/lib/Target/PowerPC/PPCMIPeephole.cpp (revision 398d68f624d667a17727d346a2139a951a1ebce4)
1 //===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===---------------------------------------------------------------------===//
8 //
9 // This pass performs peephole optimizations to clean up ugly code
10 // sequences at the MachineInstruction layer.  It runs at the end of
11 // the SSA phases, following VSX swap removal.  A pass of dead code
12 // elimination follows this one for quick clean-up of any dead
13 // instructions introduced here.  Although we could do this as callbacks
14 // from the generic peephole pass, this would have a couple of bad
15 // effects:  it might remove optimization opportunities for VSX swap
16 // removal, and it would miss cleanups made possible following VSX
17 // swap removal.
18 //
19 //===---------------------------------------------------------------------===//
20 
21 #include "MCTargetDesc/PPCMCTargetDesc.h"
22 #include "MCTargetDesc/PPCPredicates.h"
23 #include "PPC.h"
24 #include "PPCInstrBuilder.h"
25 #include "PPCInstrInfo.h"
26 #include "PPCMachineFunctionInfo.h"
27 #include "PPCTargetMachine.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachinePostDominators.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Support/Debug.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "ppc-mi-peepholes"
42 
43 STATISTIC(RemoveTOCSave, "Number of TOC saves removed");
44 STATISTIC(MultiTOCSaves,
45           "Number of functions with multiple TOC saves that must be kept");
46 STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue");
47 STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
48 STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
49 STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
50 STATISTIC(NumConvertedToImmediateForm,
51           "Number of instructions converted to their immediate form");
52 STATISTIC(NumFunctionsEnteredInMIPeephole,
53           "Number of functions entered in PPC MI Peepholes");
54 STATISTIC(NumFixedPointIterations,
55           "Number of fixed-point iterations converting reg-reg instructions "
56           "to reg-imm ones");
57 STATISTIC(NumRotatesCollapsed,
58           "Number of pairs of rotate left, clear left/right collapsed");
59 STATISTIC(NumEXTSWAndSLDICombined,
60           "Number of pairs of EXTSW and SLDI combined as EXTSWSLI");
61 STATISTIC(NumLoadImmZeroFoldedAndRemoved,
62           "Number of LI(8) reg, 0 that are folded to r0 and removed");
63 
64 static cl::opt<bool>
65 FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true),
66                    cl::desc("Iterate to a fixed point when attempting to "
67                             "convert reg-reg instructions to reg-imm"));
68 
69 static cl::opt<bool>
70 ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true),
71               cl::desc("Convert eligible reg+reg instructions to reg+imm"));
72 
73 static cl::opt<bool>
74     EnableSExtElimination("ppc-eliminate-signext",
75                           cl::desc("enable elimination of sign-extensions"),
76                           cl::init(true), cl::Hidden);
77 
78 static cl::opt<bool>
79     EnableZExtElimination("ppc-eliminate-zeroext",
80                           cl::desc("enable elimination of zero-extensions"),
81                           cl::init(true), cl::Hidden);
82 
83 static cl::opt<bool>
84     EnableTrapOptimization("ppc-opt-conditional-trap",
85                            cl::desc("enable optimization of conditional traps"),
86                            cl::init(false), cl::Hidden);
87 
88 namespace {
89 
90 struct PPCMIPeephole : public MachineFunctionPass {
91 
92   static char ID;
93   const PPCInstrInfo *TII;
94   MachineFunction *MF;
95   MachineRegisterInfo *MRI;
96 
97   PPCMIPeephole() : MachineFunctionPass(ID) {
98     initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
99   }
100 
101 private:
102   MachineDominatorTree *MDT;
103   MachinePostDominatorTree *MPDT;
104   MachineBlockFrequencyInfo *MBFI;
105   uint64_t EntryFreq;
106 
107   // Initialize class variables.
108   void initialize(MachineFunction &MFParm);
109 
110   // Perform peepholes.
111   bool simplifyCode();
112 
113   // Perform peepholes.
114   bool eliminateRedundantCompare();
115   bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves);
116   bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase);
117   bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI);
118   void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves,
119                       MachineInstr *MI);
120 
121 public:
122 
123   void getAnalysisUsage(AnalysisUsage &AU) const override {
124     AU.addRequired<MachineDominatorTree>();
125     AU.addRequired<MachinePostDominatorTree>();
126     AU.addRequired<MachineBlockFrequencyInfo>();
127     AU.addPreserved<MachineDominatorTree>();
128     AU.addPreserved<MachinePostDominatorTree>();
129     AU.addPreserved<MachineBlockFrequencyInfo>();
130     MachineFunctionPass::getAnalysisUsage(AU);
131   }
132 
133   // Main entry point for this pass.
134   bool runOnMachineFunction(MachineFunction &MF) override {
135     initialize(MF);
136     // At this point, TOC pointer should not be used in a function that uses
137     // PC-Relative addressing.
138     assert((MF.getRegInfo().use_empty(PPC::X2) ||
139             !MF.getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) &&
140            "TOC pointer used in a function using PC-Relative addressing!");
141     if (skipFunction(MF.getFunction()))
142       return false;
143     return simplifyCode();
144   }
145 };
146 
147 // Initialize class variables.
148 void PPCMIPeephole::initialize(MachineFunction &MFParm) {
149   MF = &MFParm;
150   MRI = &MF->getRegInfo();
151   MDT = &getAnalysis<MachineDominatorTree>();
152   MPDT = &getAnalysis<MachinePostDominatorTree>();
153   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
154   EntryFreq = MBFI->getEntryFreq();
155   TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
156   LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
157   LLVM_DEBUG(MF->dump());
158 }
159 
160 static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
161                                       MachineRegisterInfo *MRI) {
162   assert(Op && "Invalid Operand!");
163   if (!Op->isReg())
164     return nullptr;
165 
166   Register Reg = Op->getReg();
167   if (!Reg.isVirtual())
168     return nullptr;
169 
170   return MRI->getVRegDef(Reg);
171 }
172 
173 // This function returns number of known zero bits in output of MI
174 // starting from the most significant bit.
175 static unsigned getKnownLeadingZeroCount(const unsigned Reg,
176                                          const PPCInstrInfo *TII,
177                                          const MachineRegisterInfo *MRI) {
178   MachineInstr *MI = MRI->getVRegDef(Reg);
179   unsigned Opcode = MI->getOpcode();
180   if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
181       Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec)
182     return MI->getOperand(3).getImm();
183 
184   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
185       MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
186     return MI->getOperand(3).getImm();
187 
188   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
189        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
190        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
191       MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
192     return 32 + MI->getOperand(3).getImm();
193 
194   if (Opcode == PPC::ANDI_rec) {
195     uint16_t Imm = MI->getOperand(2).getImm();
196     return 48 + llvm::countl_zero(Imm);
197   }
198 
199   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
200       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
201       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
202     // The result ranges from 0 to 32.
203     return 58;
204 
205   if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
206       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec)
207     // The result ranges from 0 to 64.
208     return 57;
209 
210   if (Opcode == PPC::LHZ   || Opcode == PPC::LHZX  ||
211       Opcode == PPC::LHZ8  || Opcode == PPC::LHZX8 ||
212       Opcode == PPC::LHZU  || Opcode == PPC::LHZUX ||
213       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
214     return 48;
215 
216   if (Opcode == PPC::LBZ   || Opcode == PPC::LBZX  ||
217       Opcode == PPC::LBZ8  || Opcode == PPC::LBZX8 ||
218       Opcode == PPC::LBZU  || Opcode == PPC::LBZUX ||
219       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
220     return 56;
221 
222   if (TII->isZeroExtended(Reg, MRI))
223     return 32;
224 
225   return 0;
226 }
227 
228 // This function maintains a map for the pairs <TOC Save Instr, Keep>
229 // Each time a new TOC save is encountered, it checks if any of the existing
230 // ones are dominated by the new one. If so, it marks the existing one as
231 // redundant by setting it's entry in the map as false. It then adds the new
232 // instruction to the map with either true or false depending on if any
233 // existing instructions dominated the new one.
234 void PPCMIPeephole::UpdateTOCSaves(
235   std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) {
236   assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here");
237   // FIXME: Saving TOC in prologue hasn't been implemented well in AIX ABI part,
238   // here only support it under ELFv2.
239   if (MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) {
240     PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
241 
242     MachineBasicBlock *Entry = &MF->front();
243     uint64_t CurrBlockFreq = MBFI->getBlockFreq(MI->getParent()).getFrequency();
244 
245     // If the block in which the TOC save resides is in a block that
246     // post-dominates Entry, or a block that is hotter than entry (keep in mind
247     // that early MachineLICM has already run so the TOC save won't be hoisted)
248     // we can just do the save in the prologue.
249     if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry))
250       FI->setMustSaveTOC(true);
251 
252     // If we are saving the TOC in the prologue, all the TOC saves can be
253     // removed from the code.
254     if (FI->mustSaveTOC()) {
255       for (auto &TOCSave : TOCSaves)
256         TOCSave.second = false;
257       // Add new instruction to map.
258       TOCSaves[MI] = false;
259       return;
260     }
261   }
262 
263   bool Keep = true;
264   for (auto &I : TOCSaves) {
265     MachineInstr *CurrInst = I.first;
266     // If new instruction dominates an existing one, mark existing one as
267     // redundant.
268     if (I.second && MDT->dominates(MI, CurrInst))
269       I.second = false;
270     // Check if the new instruction is redundant.
271     if (MDT->dominates(CurrInst, MI)) {
272       Keep = false;
273       break;
274     }
275   }
276   // Add new instruction to map.
277   TOCSaves[MI] = Keep;
278 }
279 
280 // This function returns a list of all PHI nodes in the tree starting from
281 // the RootPHI node. We perform a BFS traversal to get an ordered list of nodes.
282 // The list initially only contains the root PHI. When we visit a PHI node, we
283 // add it to the list. We continue to look for other PHI node operands while
284 // there are nodes to visit in the list. The function returns false if the
285 // optimization cannot be applied on this tree.
286 static bool collectUnprimedAccPHIs(MachineRegisterInfo *MRI,
287                                    MachineInstr *RootPHI,
288                                    SmallVectorImpl<MachineInstr *> &PHIs) {
289   PHIs.push_back(RootPHI);
290   unsigned VisitedIndex = 0;
291   while (VisitedIndex < PHIs.size()) {
292     MachineInstr *VisitedPHI = PHIs[VisitedIndex];
293     for (unsigned PHIOp = 1, NumOps = VisitedPHI->getNumOperands();
294          PHIOp != NumOps; PHIOp += 2) {
295       Register RegOp = VisitedPHI->getOperand(PHIOp).getReg();
296       if (!RegOp.isVirtual())
297         return false;
298       MachineInstr *Instr = MRI->getVRegDef(RegOp);
299       // While collecting the PHI nodes, we check if they can be converted (i.e.
300       // all the operands are either copies, implicit defs or PHI nodes).
301       unsigned Opcode = Instr->getOpcode();
302       if (Opcode == PPC::COPY) {
303         Register Reg = Instr->getOperand(1).getReg();
304         if (!Reg.isVirtual() || MRI->getRegClass(Reg) != &PPC::ACCRCRegClass)
305           return false;
306       } else if (Opcode != PPC::IMPLICIT_DEF && Opcode != PPC::PHI)
307         return false;
308       // If we detect a cycle in the PHI nodes, we exit. It would be
309       // possible to change cycles as well, but that would add a lot
310       // of complexity for a case that is unlikely to occur with MMA
311       // code.
312       if (Opcode != PPC::PHI)
313         continue;
314       if (llvm::is_contained(PHIs, Instr))
315         return false;
316       PHIs.push_back(Instr);
317     }
318     VisitedIndex++;
319   }
320   return true;
321 }
322 
323 // This function changes the unprimed accumulator PHI nodes in the PHIs list to
324 // primed accumulator PHI nodes. The list is traversed in reverse order to
325 // change all the PHI operands of a PHI node before changing the node itself.
326 // We keep a map to associate each changed PHI node to its non-changed form.
327 static void convertUnprimedAccPHIs(const PPCInstrInfo *TII,
328                                    MachineRegisterInfo *MRI,
329                                    SmallVectorImpl<MachineInstr *> &PHIs,
330                                    Register Dst) {
331   DenseMap<MachineInstr *, MachineInstr *> ChangedPHIMap;
332   for (MachineInstr *PHI : llvm::reverse(PHIs)) {
333     SmallVector<std::pair<MachineOperand, MachineOperand>, 4> PHIOps;
334     // We check if the current PHI node can be changed by looking at its
335     // operands. If all the operands are either copies from primed
336     // accumulators, implicit definitions or other unprimed accumulator
337     // PHI nodes, we change it.
338     for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps;
339          PHIOp += 2) {
340       Register RegOp = PHI->getOperand(PHIOp).getReg();
341       MachineInstr *PHIInput = MRI->getVRegDef(RegOp);
342       unsigned Opcode = PHIInput->getOpcode();
343       assert((Opcode == PPC::COPY || Opcode == PPC::IMPLICIT_DEF ||
344               Opcode == PPC::PHI) &&
345              "Unexpected instruction");
346       if (Opcode == PPC::COPY) {
347         assert(MRI->getRegClass(PHIInput->getOperand(1).getReg()) ==
348                    &PPC::ACCRCRegClass &&
349                "Unexpected register class");
350         PHIOps.push_back({PHIInput->getOperand(1), PHI->getOperand(PHIOp + 1)});
351       } else if (Opcode == PPC::IMPLICIT_DEF) {
352         Register AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
353         BuildMI(*PHIInput->getParent(), PHIInput, PHIInput->getDebugLoc(),
354                 TII->get(PPC::IMPLICIT_DEF), AccReg);
355         PHIOps.push_back({MachineOperand::CreateReg(AccReg, false),
356                           PHI->getOperand(PHIOp + 1)});
357       } else if (Opcode == PPC::PHI) {
358         // We found a PHI operand. At this point we know this operand
359         // has already been changed so we get its associated changed form
360         // from the map.
361         assert(ChangedPHIMap.count(PHIInput) == 1 &&
362                "This PHI node should have already been changed.");
363         MachineInstr *PrimedAccPHI = ChangedPHIMap.lookup(PHIInput);
364         PHIOps.push_back({MachineOperand::CreateReg(
365                               PrimedAccPHI->getOperand(0).getReg(), false),
366                           PHI->getOperand(PHIOp + 1)});
367       }
368     }
369     Register AccReg = Dst;
370     // If the PHI node we are changing is the root node, the register it defines
371     // will be the destination register of the original copy (of the PHI def).
372     // For all other PHI's in the list, we need to create another primed
373     // accumulator virtual register as the PHI will no longer define the
374     // unprimed accumulator.
375     if (PHI != PHIs[0])
376       AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass);
377     MachineInstrBuilder NewPHI = BuildMI(
378         *PHI->getParent(), PHI, PHI->getDebugLoc(), TII->get(PPC::PHI), AccReg);
379     for (auto RegMBB : PHIOps)
380       NewPHI.add(RegMBB.first).add(RegMBB.second);
381     ChangedPHIMap[PHI] = NewPHI.getInstr();
382     LLVM_DEBUG(dbgs() << "Converting PHI: ");
383     LLVM_DEBUG(PHI->dump());
384     LLVM_DEBUG(dbgs() << "To: ");
385     LLVM_DEBUG(NewPHI.getInstr()->dump());
386   }
387 }
388 
389 // Perform peephole optimizations.
390 bool PPCMIPeephole::simplifyCode() {
391   bool Simplified = false;
392   bool TrapOpt = false;
393   MachineInstr* ToErase = nullptr;
394   std::map<MachineInstr *, bool> TOCSaves;
395   const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
396   NumFunctionsEnteredInMIPeephole++;
397   if (ConvertRegReg) {
398     // Fixed-point conversion of reg/reg instructions fed by load-immediate
399     // into reg/imm instructions. FIXME: This is expensive, control it with
400     // an option.
401     bool SomethingChanged = false;
402     do {
403       NumFixedPointIterations++;
404       SomethingChanged = false;
405       for (MachineBasicBlock &MBB : *MF) {
406         for (MachineInstr &MI : MBB) {
407           if (MI.isDebugInstr())
408             continue;
409 
410           if (TII->convertToImmediateForm(MI)) {
411             // We don't erase anything in case the def has other uses. Let DCE
412             // remove it if it can be removed.
413             LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
414             LLVM_DEBUG(MI.dump());
415             NumConvertedToImmediateForm++;
416             SomethingChanged = true;
417             Simplified = true;
418             continue;
419           }
420         }
421       }
422     } while (SomethingChanged && FixedPointRegToImm);
423   }
424 
425   for (MachineBasicBlock &MBB : *MF) {
426     for (MachineInstr &MI : MBB) {
427 
428       // If the previous instruction was marked for elimination,
429       // remove it now.
430       if (ToErase) {
431         LLVM_DEBUG(dbgs() << "Deleting instruction: ");
432         LLVM_DEBUG(ToErase->dump());
433         ToErase->eraseFromParent();
434         ToErase = nullptr;
435       }
436       // If a conditional trap instruction got optimized to an
437       // unconditional trap, eliminate all the instructions after
438       // the trap.
439       if (EnableTrapOptimization && TrapOpt) {
440         ToErase = &MI;
441         continue;
442       }
443 
444       // Ignore debug instructions.
445       if (MI.isDebugInstr())
446         continue;
447 
448       // Per-opcode peepholes.
449       switch (MI.getOpcode()) {
450 
451       default:
452         break;
453       case PPC::COPY: {
454         Register Src = MI.getOperand(1).getReg();
455         Register Dst = MI.getOperand(0).getReg();
456         if (!Src.isVirtual() || !Dst.isVirtual())
457           break;
458         if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass ||
459             MRI->getRegClass(Dst) != &PPC::ACCRCRegClass)
460           break;
461 
462         // We are copying an unprimed accumulator to a primed accumulator.
463         // If the input to the copy is a PHI that is fed only by (i) copies in
464         // the other direction (ii) implicitly defined unprimed accumulators or
465         // (iii) other PHI nodes satisfying (i) and (ii), we can change
466         // the PHI to a PHI on primed accumulators (as long as we also change
467         // its operands). To detect and change such copies, we first get a list
468         // of all the PHI nodes starting from the root PHI node in BFS order.
469         // We then visit all these PHI nodes to check if they can be changed to
470         // primed accumulator PHI nodes and if so, we change them.
471         MachineInstr *RootPHI = MRI->getVRegDef(Src);
472         if (RootPHI->getOpcode() != PPC::PHI)
473           break;
474 
475         SmallVector<MachineInstr *, 4> PHIs;
476         if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs))
477           break;
478 
479         convertUnprimedAccPHIs(TII, MRI, PHIs, Dst);
480 
481         ToErase = &MI;
482         break;
483       }
484       case PPC::LI:
485       case PPC::LI8: {
486         // If we are materializing a zero, look for any use operands for which
487         // zero means immediate zero. All such operands can be replaced with
488         // PPC::ZERO.
489         if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0)
490           break;
491         Register MIDestReg = MI.getOperand(0).getReg();
492         for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg))
493           Simplified |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg);
494         if (MRI->use_nodbg_empty(MIDestReg)) {
495           ++NumLoadImmZeroFoldedAndRemoved;
496           ToErase = &MI;
497         }
498         break;
499       }
500       case PPC::STW:
501       case PPC::STD: {
502         MachineFrameInfo &MFI = MF->getFrameInfo();
503         if (MFI.hasVarSizedObjects() ||
504             (!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() &&
505              !MF->getSubtarget<PPCSubtarget>().isAIXABI()))
506           break;
507         // When encountering a TOC save instruction, call UpdateTOCSaves
508         // to add it to the TOCSaves map and mark any existing TOC saves
509         // it dominates as redundant.
510         if (TII->isTOCSaveMI(MI))
511           UpdateTOCSaves(TOCSaves, &MI);
512         break;
513       }
514       case PPC::XXPERMDI: {
515         // Perform simplifications of 2x64 vector swaps and splats.
516         // A swap is identified by an immediate value of 2, and a splat
517         // is identified by an immediate value of 0 or 3.
518         int Immed = MI.getOperand(3).getImm();
519 
520         if (Immed == 1)
521           break;
522 
523         // For each of these simplifications, we need the two source
524         // regs to match.  Unfortunately, MachineCSE ignores COPY and
525         // SUBREG_TO_REG, so for example we can see
526         //   XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
527         // We have to look through chains of COPY and SUBREG_TO_REG
528         // to find the real source values for comparison.
529         Register TrueReg1 =
530           TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
531         Register TrueReg2 =
532           TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
533 
534         if (!(TrueReg1 == TrueReg2 && TrueReg1.isVirtual()))
535           break;
536 
537         MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
538 
539         if (!DefMI)
540           break;
541 
542         unsigned DefOpc = DefMI->getOpcode();
543 
544         // If this is a splat fed by a splatting load, the splat is
545         // redundant. Replace with a copy. This doesn't happen directly due
546         // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
547         // a load of a double to a vector of 64-bit integers.
548         auto isConversionOfLoadAndSplat = [=]() -> bool {
549           if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
550             return false;
551           Register FeedReg1 =
552             TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
553           if (FeedReg1.isVirtual()) {
554             MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1);
555             if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
556               return true;
557           }
558           return false;
559         };
560         if ((Immed == 0 || Immed == 3) &&
561             (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) {
562           LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
563                                "to load-and-splat/copy: ");
564           LLVM_DEBUG(MI.dump());
565           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
566                   MI.getOperand(0).getReg())
567               .add(MI.getOperand(1));
568           ToErase = &MI;
569           Simplified = true;
570         }
571 
572         // If this is a splat or a swap fed by another splat, we
573         // can replace it with a copy.
574         if (DefOpc == PPC::XXPERMDI) {
575           Register DefReg1 = DefMI->getOperand(1).getReg();
576           Register DefReg2 = DefMI->getOperand(2).getReg();
577           unsigned DefImmed = DefMI->getOperand(3).getImm();
578 
579           // If the two inputs are not the same register, check to see if
580           // they originate from the same virtual register after only
581           // copy-like instructions.
582           if (DefReg1 != DefReg2) {
583             Register FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI);
584             Register FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI);
585 
586             if (!(FeedReg1 == FeedReg2 && FeedReg1.isVirtual()))
587               break;
588           }
589 
590           if (DefImmed == 0 || DefImmed == 3) {
591             LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
592                                  "to splat/copy: ");
593             LLVM_DEBUG(MI.dump());
594             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
595                     MI.getOperand(0).getReg())
596                 .add(MI.getOperand(1));
597             ToErase = &MI;
598             Simplified = true;
599           }
600 
601           // If this is a splat fed by a swap, we can simplify modify
602           // the splat to splat the other value from the swap's input
603           // parameter.
604           else if ((Immed == 0 || Immed == 3) && DefImmed == 2) {
605             LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
606             LLVM_DEBUG(MI.dump());
607             MI.getOperand(1).setReg(DefReg1);
608             MI.getOperand(2).setReg(DefReg2);
609             MI.getOperand(3).setImm(3 - Immed);
610             Simplified = true;
611           }
612 
613           // If this is a swap fed by a swap, we can replace it
614           // with a copy from the first swap's input.
615           else if (Immed == 2 && DefImmed == 2) {
616             LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
617             LLVM_DEBUG(MI.dump());
618             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
619                     MI.getOperand(0).getReg())
620                 .add(DefMI->getOperand(1));
621             ToErase = &MI;
622             Simplified = true;
623           }
624         } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
625                    DefOpc == PPC::XXPERMDIs &&
626                    (DefMI->getOperand(2).getImm() == 0 ||
627                     DefMI->getOperand(2).getImm() == 3)) {
628           ToErase = &MI;
629           Simplified = true;
630           // Swap of a splat, convert to copy.
631           if (Immed == 2) {
632             LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): ");
633             LLVM_DEBUG(MI.dump());
634             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
635                     MI.getOperand(0).getReg())
636                 .add(MI.getOperand(1));
637             break;
638           }
639           // Splat fed by another splat - switch the output of the first
640           // and remove the second.
641           DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
642           LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
643           LLVM_DEBUG(MI.dump());
644         } else if (Immed == 2 &&
645                    (DefOpc == PPC::VSPLTB || DefOpc == PPC::VSPLTH ||
646                     DefOpc == PPC::VSPLTW || DefOpc == PPC::XXSPLTW)) {
647           // Swap of various vector splats, convert to copy.
648           ToErase = &MI;
649           Simplified = true;
650           LLVM_DEBUG(dbgs() << "Optimizing swap(vsplt[b|h|w]|xxspltw) => "
651                                "copy(vsplt[b|h|w]|xxspltw): ");
652           LLVM_DEBUG(MI.dump());
653           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
654                   MI.getOperand(0).getReg())
655               .add(MI.getOperand(1));
656         } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
657                    TII->isLoadFromConstantPool(DefMI)) {
658           const Constant *C = TII->getConstantFromConstantPool(DefMI);
659           if (C && C->getType()->isVectorTy() && C->getSplatValue()) {
660             ToErase = &MI;
661             Simplified = true;
662             LLVM_DEBUG(dbgs()
663                        << "Optimizing swap(splat pattern from constant-pool) "
664                           "=> copy(splat pattern from constant-pool): ");
665             LLVM_DEBUG(MI.dump());
666             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
667                     MI.getOperand(0).getReg())
668                 .add(MI.getOperand(1));
669           }
670         }
671         break;
672       }
673       case PPC::VSPLTB:
674       case PPC::VSPLTH:
675       case PPC::XXSPLTW: {
676         unsigned MyOpcode = MI.getOpcode();
677         unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
678         Register TrueReg =
679           TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
680         if (!TrueReg.isVirtual())
681           break;
682         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
683         if (!DefMI)
684           break;
685         unsigned DefOpcode = DefMI->getOpcode();
686         auto isConvertOfSplat = [=]() -> bool {
687           if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
688             return false;
689           Register ConvReg = DefMI->getOperand(1).getReg();
690           if (!ConvReg.isVirtual())
691             return false;
692           MachineInstr *Splt = MRI->getVRegDef(ConvReg);
693           return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
694             Splt->getOpcode() == PPC::XXSPLTW);
695         };
696         bool AlreadySplat = (MyOpcode == DefOpcode) ||
697           (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
698           (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
699           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
700           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
701           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
702           (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
703         // If the instruction[s] that feed this splat have already splat
704         // the value, this splat is redundant.
705         if (AlreadySplat) {
706           LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
707           LLVM_DEBUG(MI.dump());
708           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
709                   MI.getOperand(0).getReg())
710               .add(MI.getOperand(OpNo));
711           ToErase = &MI;
712           Simplified = true;
713         }
714         // Splat fed by a shift. Usually when we align value to splat into
715         // vector element zero.
716         if (DefOpcode == PPC::XXSLDWI) {
717           Register ShiftRes = DefMI->getOperand(0).getReg();
718           Register ShiftOp1 = DefMI->getOperand(1).getReg();
719           Register ShiftOp2 = DefMI->getOperand(2).getReg();
720           unsigned ShiftImm = DefMI->getOperand(3).getImm();
721           unsigned SplatImm =
722               MI.getOperand(MyOpcode == PPC::XXSPLTW ? 2 : 1).getImm();
723           if (ShiftOp1 == ShiftOp2) {
724             unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
725             if (MRI->hasOneNonDBGUse(ShiftRes)) {
726               LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
727               LLVM_DEBUG(DefMI->dump());
728               ToErase = DefMI;
729             }
730             Simplified = true;
731             LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
732                               << " to " << NewElem << " in instruction: ");
733             LLVM_DEBUG(MI.dump());
734             MI.getOperand(1).setReg(ShiftOp1);
735             MI.getOperand(2).setImm(NewElem);
736           }
737         }
738         break;
739       }
740       case PPC::XVCVDPSP: {
741         // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
742         Register TrueReg =
743           TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
744         if (!TrueReg.isVirtual())
745           break;
746         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
747 
748         // This can occur when building a vector of single precision or integer
749         // values.
750         if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
751           Register DefsReg1 =
752             TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
753           Register DefsReg2 =
754             TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
755           if (!DefsReg1.isVirtual() || !DefsReg2.isVirtual())
756             break;
757           MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
758           MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
759 
760           if (!P1 || !P2)
761             break;
762 
763           // Remove the passed FRSP/XSRSP instruction if it only feeds this MI
764           // and set any uses of that FRSP/XSRSP (in this MI) to the source of
765           // the FRSP/XSRSP.
766           auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
767             unsigned Opc = RoundInstr->getOpcode();
768             if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) &&
769                 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
770               Simplified = true;
771               Register ConvReg1 = RoundInstr->getOperand(1).getReg();
772               Register FRSPDefines = RoundInstr->getOperand(0).getReg();
773               MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines));
774               for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
775                 if (Use.getOperand(i).isReg() &&
776                     Use.getOperand(i).getReg() == FRSPDefines)
777                   Use.getOperand(i).setReg(ConvReg1);
778               LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n");
779               LLVM_DEBUG(RoundInstr->dump());
780               LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
781               LLVM_DEBUG(MI.dump());
782               LLVM_DEBUG(dbgs() << "Through instruction:\n");
783               LLVM_DEBUG(DefMI->dump());
784               RoundInstr->eraseFromParent();
785             }
786           };
787 
788           // If the input to XVCVDPSP is a vector that was built (even
789           // partially) out of FRSP's, the FRSP(s) can safely be removed
790           // since this instruction performs the same operation.
791           if (P1 != P2) {
792             removeFRSPIfPossible(P1);
793             removeFRSPIfPossible(P2);
794             break;
795           }
796           removeFRSPIfPossible(P1);
797         }
798         break;
799       }
800       case PPC::EXTSH:
801       case PPC::EXTSH8:
802       case PPC::EXTSH8_32_64: {
803         if (!EnableSExtElimination) break;
804         Register NarrowReg = MI.getOperand(1).getReg();
805         if (!NarrowReg.isVirtual())
806           break;
807 
808         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
809         unsigned SrcOpcode = SrcMI->getOpcode();
810         // If we've used a zero-extending load that we will sign-extend,
811         // just do a sign-extending load.
812         if (SrcOpcode == PPC::LHZ || SrcOpcode == PPC::LHZX) {
813           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
814             break;
815           // Determine the new opcode. We need to make sure that if the original
816           // instruction has a 64 bit opcode we keep using a 64 bit opcode.
817           // Likewise if the source is X-Form the new opcode should also be
818           // X-Form.
819           unsigned Opc = PPC::LHA;
820           bool SourceIsXForm = SrcOpcode == PPC::LHZX;
821           bool MIIs64Bit = MI.getOpcode() == PPC::EXTSH8 ||
822             MI.getOpcode() == PPC::EXTSH8_32_64;
823 
824           if (SourceIsXForm && MIIs64Bit)
825             Opc = PPC::LHAX8;
826           else if (SourceIsXForm && !MIIs64Bit)
827             Opc = PPC::LHAX;
828           else if (MIIs64Bit)
829             Opc = PPC::LHA8;
830 
831           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
832           LLVM_DEBUG(SrcMI->dump());
833           LLVM_DEBUG(dbgs() << "and sign-extension\n");
834           LLVM_DEBUG(MI.dump());
835           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
836           SrcMI->setDesc(TII->get(Opc));
837           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
838           ToErase = &MI;
839           Simplified = true;
840           NumEliminatedSExt++;
841         }
842         break;
843       }
844       case PPC::EXTSW:
845       case PPC::EXTSW_32:
846       case PPC::EXTSW_32_64: {
847         if (!EnableSExtElimination) break;
848         Register NarrowReg = MI.getOperand(1).getReg();
849         if (!NarrowReg.isVirtual())
850           break;
851 
852         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
853         unsigned SrcOpcode = SrcMI->getOpcode();
854         // If we've used a zero-extending load that we will sign-extend,
855         // just do a sign-extending load.
856         if (SrcOpcode == PPC::LWZ || SrcOpcode == PPC::LWZX) {
857           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
858             break;
859 
860           // The transformation from a zero-extending load to a sign-extending
861           // load is only legal when the displacement is a multiple of 4.
862           // If the displacement is not at least 4 byte aligned, don't perform
863           // the transformation.
864           bool IsWordAligned = false;
865           if (SrcMI->getOperand(1).isGlobal()) {
866             const GlobalObject *GO =
867                 dyn_cast<GlobalObject>(SrcMI->getOperand(1).getGlobal());
868             if (GO && GO->getAlign() && *GO->getAlign() >= 4 &&
869                 (SrcMI->getOperand(1).getOffset() % 4 == 0))
870               IsWordAligned = true;
871           } else if (SrcMI->getOperand(1).isImm()) {
872             int64_t Value = SrcMI->getOperand(1).getImm();
873             if (Value % 4 == 0)
874               IsWordAligned = true;
875           }
876 
877           // Determine the new opcode. We need to make sure that if the original
878           // instruction has a 64 bit opcode we keep using a 64 bit opcode.
879           // Likewise if the source is X-Form the new opcode should also be
880           // X-Form.
881           unsigned Opc = PPC::LWA_32;
882           bool SourceIsXForm = SrcOpcode == PPC::LWZX;
883           bool MIIs64Bit = MI.getOpcode() == PPC::EXTSW ||
884             MI.getOpcode() == PPC::EXTSW_32_64;
885 
886           if (SourceIsXForm && MIIs64Bit)
887             Opc = PPC::LWAX;
888           else if (SourceIsXForm && !MIIs64Bit)
889             Opc = PPC::LWAX_32;
890           else if (MIIs64Bit)
891             Opc = PPC::LWA;
892 
893           if (!IsWordAligned && (Opc == PPC::LWA || Opc == PPC::LWA_32))
894             break;
895 
896           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
897           LLVM_DEBUG(SrcMI->dump());
898           LLVM_DEBUG(dbgs() << "and sign-extension\n");
899           LLVM_DEBUG(MI.dump());
900           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
901           SrcMI->setDesc(TII->get(Opc));
902           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
903           ToErase = &MI;
904           Simplified = true;
905           NumEliminatedSExt++;
906         } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
907                    TII->isSignExtended(NarrowReg, MRI)) {
908           // We can eliminate EXTSW if the input is known to be already
909           // sign-extended.
910           LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
911           Register TmpReg =
912               MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
913           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
914                   TmpReg);
915           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
916                   MI.getOperand(0).getReg())
917               .addReg(TmpReg)
918               .addReg(NarrowReg)
919               .addImm(PPC::sub_32);
920           ToErase = &MI;
921           Simplified = true;
922           NumEliminatedSExt++;
923         }
924         break;
925       }
926       case PPC::RLDICL: {
927         // We can eliminate RLDICL (e.g. for zero-extension)
928         // if all bits to clear are already zero in the input.
929         // This code assume following code sequence for zero-extension.
930         //   %6 = COPY %5:sub_32; (optional)
931         //   %8 = IMPLICIT_DEF;
932         //   %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
933         if (!EnableZExtElimination) break;
934 
935         if (MI.getOperand(2).getImm() != 0)
936           break;
937 
938         Register SrcReg = MI.getOperand(1).getReg();
939         if (!SrcReg.isVirtual())
940           break;
941 
942         MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
943         if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
944               SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
945           break;
946 
947         MachineInstr *ImpDefMI, *SubRegMI;
948         ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
949         SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
950         if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
951 
952         SrcMI = SubRegMI;
953         if (SubRegMI->getOpcode() == PPC::COPY) {
954           Register CopyReg = SubRegMI->getOperand(1).getReg();
955           if (CopyReg.isVirtual())
956             SrcMI = MRI->getVRegDef(CopyReg);
957         }
958         if (!SrcMI->getOperand(0).isReg())
959           break;
960 
961         unsigned KnownZeroCount =
962             getKnownLeadingZeroCount(SrcMI->getOperand(0).getReg(), TII, MRI);
963         if (MI.getOperand(3).getImm() <= KnownZeroCount) {
964           LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
965           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
966                   MI.getOperand(0).getReg())
967               .addReg(SrcReg);
968           ToErase = &MI;
969           Simplified = true;
970           NumEliminatedZExt++;
971         }
972         break;
973       }
974 
975       // TODO: Any instruction that has an immediate form fed only by a PHI
976       // whose operands are all load immediate can be folded away. We currently
977       // do this for ADD instructions, but should expand it to arithmetic and
978       // binary instructions with immediate forms in the future.
979       case PPC::ADD4:
980       case PPC::ADD8: {
981         auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
982           assert(PhiOp && "Invalid Operand!");
983           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
984 
985           return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
986                  MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
987         };
988 
989         auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
990                                             MachineOperand *PhiOp) {
991           assert(PhiOp && "Invalid Operand!");
992           assert(DominatorOp && "Invalid Operand!");
993           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
994           MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
995 
996           // Note: the vregs only show up at odd indices position of PHI Node,
997           // the even indices position save the BB info.
998           for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
999             MachineInstr *LiMI =
1000                 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
1001             if (!LiMI ||
1002                 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
1003                 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
1004                 !MDT->dominates(DefDomMI, LiMI))
1005               return false;
1006           }
1007 
1008           return true;
1009         };
1010 
1011         MachineOperand Op1 = MI.getOperand(1);
1012         MachineOperand Op2 = MI.getOperand(2);
1013         if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
1014           std::swap(Op1, Op2);
1015         else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
1016           break; // We don't have an ADD fed by LI's that can be transformed
1017 
1018         // Now we know that Op1 is the PHI node and Op2 is the dominator
1019         Register DominatorReg = Op2.getReg();
1020 
1021         const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
1022                                              ? &PPC::G8RC_and_G8RC_NOX0RegClass
1023                                              : &PPC::GPRC_and_GPRC_NOR0RegClass;
1024         MRI->setRegClass(DominatorReg, TRC);
1025 
1026         // replace LIs with ADDIs
1027         MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
1028         for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
1029           MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
1030           LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
1031           LLVM_DEBUG(LiMI->dump());
1032 
1033           // There could be repeated registers in the PHI, e.g: %1 =
1034           // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
1035           // already replaced the def instruction, skip.
1036           if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
1037             continue;
1038 
1039           assert((LiMI->getOpcode() == PPC::LI ||
1040                   LiMI->getOpcode() == PPC::LI8) &&
1041                  "Invalid Opcode!");
1042           auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
1043           LiMI->removeOperand(1);                    // remove the imm of LI
1044           LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
1045                                                               : PPC::ADDI8));
1046           MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
1047               .addReg(DominatorReg)
1048               .addImm(LiImm); // restore the imm of LI
1049           LLVM_DEBUG(LiMI->dump());
1050         }
1051 
1052         // Replace ADD with COPY
1053         LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
1054         LLVM_DEBUG(MI.dump());
1055         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
1056                 MI.getOperand(0).getReg())
1057             .add(Op1);
1058         ToErase = &MI;
1059         Simplified = true;
1060         NumOptADDLIs++;
1061         break;
1062       }
1063       case PPC::RLDICR: {
1064         Simplified |= emitRLDICWhenLoweringJumpTables(MI) ||
1065                       combineSEXTAndSHL(MI, ToErase);
1066         break;
1067       }
1068       case PPC::RLWINM:
1069       case PPC::RLWINM_rec:
1070       case PPC::RLWINM8:
1071       case PPC::RLWINM8_rec: {
1072         Simplified = TII->combineRLWINM(MI, &ToErase);
1073         if (Simplified)
1074           ++NumRotatesCollapsed;
1075         break;
1076       }
1077       // We will replace TD/TW/TDI/TWI with an unconditional trap if it will
1078       // always trap, we will delete the node if it will never trap.
1079       case PPC::TDI:
1080       case PPC::TWI:
1081       case PPC::TD:
1082       case PPC::TW: {
1083         if (!EnableTrapOptimization) break;
1084         MachineInstr *LiMI1 = getVRegDefOrNull(&MI.getOperand(1), MRI);
1085         MachineInstr *LiMI2 = getVRegDefOrNull(&MI.getOperand(2), MRI);
1086         bool IsOperand2Immediate = MI.getOperand(2).isImm();
1087         // We can only do the optimization if we can get immediates
1088         // from both operands
1089         if (!(LiMI1 && (LiMI1->getOpcode() == PPC::LI ||
1090                         LiMI1->getOpcode() == PPC::LI8)))
1091           break;
1092         if (!IsOperand2Immediate &&
1093             !(LiMI2 && (LiMI2->getOpcode() == PPC::LI ||
1094                         LiMI2->getOpcode() == PPC::LI8)))
1095           break;
1096 
1097         auto ImmOperand0 = MI.getOperand(0).getImm();
1098         auto ImmOperand1 = LiMI1->getOperand(1).getImm();
1099         auto ImmOperand2 = IsOperand2Immediate ? MI.getOperand(2).getImm()
1100                                                : LiMI2->getOperand(1).getImm();
1101 
1102         // We will replace the MI with an unconditional trap if it will always
1103         // trap.
1104         if ((ImmOperand0 == 31) ||
1105             ((ImmOperand0 & 0x10) &&
1106              ((int64_t)ImmOperand1 < (int64_t)ImmOperand2)) ||
1107             ((ImmOperand0 & 0x8) &&
1108              ((int64_t)ImmOperand1 > (int64_t)ImmOperand2)) ||
1109             ((ImmOperand0 & 0x2) &&
1110              ((uint64_t)ImmOperand1 < (uint64_t)ImmOperand2)) ||
1111             ((ImmOperand0 & 0x1) &&
1112              ((uint64_t)ImmOperand1 > (uint64_t)ImmOperand2)) ||
1113             ((ImmOperand0 & 0x4) && (ImmOperand1 == ImmOperand2))) {
1114           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::TRAP));
1115           TrapOpt = true;
1116         }
1117         // We will delete the MI if it will never trap.
1118         ToErase = &MI;
1119         Simplified = true;
1120         break;
1121       }
1122       }
1123     }
1124 
1125     // If the last instruction was marked for elimination,
1126     // remove it now.
1127     if (ToErase) {
1128       ToErase->eraseFromParent();
1129       ToErase = nullptr;
1130     }
1131     // Reset TrapOpt to false at the end of the basic block.
1132     if (EnableTrapOptimization)
1133       TrapOpt = false;
1134   }
1135 
1136   // Eliminate all the TOC save instructions which are redundant.
1137   Simplified |= eliminateRedundantTOCSaves(TOCSaves);
1138   PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
1139   if (FI->mustSaveTOC())
1140     NumTOCSavesInPrologue++;
1141 
1142   // We try to eliminate redundant compare instruction.
1143   Simplified |= eliminateRedundantCompare();
1144 
1145   return Simplified;
1146 }
1147 
1148 // helper functions for eliminateRedundantCompare
1149 static bool isEqOrNe(MachineInstr *BI) {
1150   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1151   unsigned PredCond = PPC::getPredicateCondition(Pred);
1152   return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
1153 }
1154 
1155 static bool isSupportedCmpOp(unsigned opCode) {
1156   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD  ||
1157           opCode == PPC::CMPLW  || opCode == PPC::CMPW  ||
1158           opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
1159           opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
1160 }
1161 
1162 static bool is64bitCmpOp(unsigned opCode) {
1163   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD ||
1164           opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
1165 }
1166 
1167 static bool isSignedCmpOp(unsigned opCode) {
1168   return (opCode == PPC::CMPD  || opCode == PPC::CMPW ||
1169           opCode == PPC::CMPDI || opCode == PPC::CMPWI);
1170 }
1171 
1172 static unsigned getSignedCmpOpCode(unsigned opCode) {
1173   if (opCode == PPC::CMPLD)  return PPC::CMPD;
1174   if (opCode == PPC::CMPLW)  return PPC::CMPW;
1175   if (opCode == PPC::CMPLDI) return PPC::CMPDI;
1176   if (opCode == PPC::CMPLWI) return PPC::CMPWI;
1177   return opCode;
1178 }
1179 
1180 // We can decrement immediate x in (GE x) by changing it to (GT x-1) or
1181 // (LT x) to (LE x-1)
1182 static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
1183   uint64_t Imm = CMPI->getOperand(2).getImm();
1184   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1185   if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
1186     return 0;
1187 
1188   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1189   unsigned PredCond = PPC::getPredicateCondition(Pred);
1190   unsigned PredHint = PPC::getPredicateHint(Pred);
1191   if (PredCond == PPC::PRED_GE)
1192     return PPC::getPredicate(PPC::PRED_GT, PredHint);
1193   if (PredCond == PPC::PRED_LT)
1194     return PPC::getPredicate(PPC::PRED_LE, PredHint);
1195 
1196   return 0;
1197 }
1198 
1199 // We can increment immediate x in (GT x) by changing it to (GE x+1) or
1200 // (LE x) to (LT x+1)
1201 static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
1202   uint64_t Imm = CMPI->getOperand(2).getImm();
1203   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1204   if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
1205     return 0;
1206 
1207   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1208   unsigned PredCond = PPC::getPredicateCondition(Pred);
1209   unsigned PredHint = PPC::getPredicateHint(Pred);
1210   if (PredCond == PPC::PRED_GT)
1211     return PPC::getPredicate(PPC::PRED_GE, PredHint);
1212   if (PredCond == PPC::PRED_LE)
1213     return PPC::getPredicate(PPC::PRED_LT, PredHint);
1214 
1215   return 0;
1216 }
1217 
1218 // This takes a Phi node and returns a register value for the specified BB.
1219 static unsigned getIncomingRegForBlock(MachineInstr *Phi,
1220                                        MachineBasicBlock *MBB) {
1221   for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
1222     MachineOperand &MO = Phi->getOperand(I);
1223     if (MO.getMBB() == MBB)
1224       return Phi->getOperand(I-1).getReg();
1225   }
1226   llvm_unreachable("invalid src basic block for this Phi node\n");
1227   return 0;
1228 }
1229 
1230 // This function tracks the source of the register through register copy.
1231 // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
1232 // assuming that the control comes from BB1 into BB2.
1233 static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
1234                            MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
1235   unsigned SrcReg = Reg;
1236   while (true) {
1237     unsigned NextReg = SrcReg;
1238     MachineInstr *Inst = MRI->getVRegDef(SrcReg);
1239     if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
1240       NextReg = getIncomingRegForBlock(Inst, BB1);
1241       // We track through PHI only once to avoid infinite loop.
1242       BB1 = nullptr;
1243     }
1244     else if (Inst->isFullCopy())
1245       NextReg = Inst->getOperand(1).getReg();
1246     if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg))
1247       break;
1248     SrcReg = NextReg;
1249   }
1250   return SrcReg;
1251 }
1252 
1253 static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
1254                                           MachineBasicBlock *&PredMBB,
1255                                           MachineBasicBlock *&MBBtoMoveCmp,
1256                                           MachineRegisterInfo *MRI) {
1257 
1258   auto isEligibleBB = [&](MachineBasicBlock &BB) {
1259     auto BII = BB.getFirstInstrTerminator();
1260     // We optimize BBs ending with a conditional branch.
1261     // We check only for BCC here, not BCCLR, because BCCLR
1262     // will be formed only later in the pipeline.
1263     if (BB.succ_size() == 2 &&
1264         BII != BB.instr_end() &&
1265         (*BII).getOpcode() == PPC::BCC &&
1266         (*BII).getOperand(1).isReg()) {
1267       // We optimize only if the condition code is used only by one BCC.
1268       Register CndReg = (*BII).getOperand(1).getReg();
1269       if (!CndReg.isVirtual() || !MRI->hasOneNonDBGUse(CndReg))
1270         return false;
1271 
1272       MachineInstr *CMPI = MRI->getVRegDef(CndReg);
1273       // We assume compare and branch are in the same BB for ease of analysis.
1274       if (CMPI->getParent() != &BB)
1275         return false;
1276 
1277       // We skip this BB if a physical register is used in comparison.
1278       for (MachineOperand &MO : CMPI->operands())
1279         if (MO.isReg() && !MO.getReg().isVirtual())
1280           return false;
1281 
1282       return true;
1283     }
1284     return false;
1285   };
1286 
1287   // If this BB has more than one successor, we can create a new BB and
1288   // move the compare instruction in the new BB.
1289   // So far, we do not move compare instruction to a BB having multiple
1290   // successors to avoid potentially increasing code size.
1291   auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
1292     return BB.succ_size() == 1;
1293   };
1294 
1295   if (!isEligibleBB(MBB))
1296     return false;
1297 
1298   unsigned NumPredBBs = MBB.pred_size();
1299   if (NumPredBBs == 1) {
1300     MachineBasicBlock *TmpMBB = *MBB.pred_begin();
1301     if (isEligibleBB(*TmpMBB)) {
1302       PredMBB = TmpMBB;
1303       MBBtoMoveCmp = nullptr;
1304       return true;
1305     }
1306   }
1307   else if (NumPredBBs == 2) {
1308     // We check for partially redundant case.
1309     // So far, we support cases with only two predecessors
1310     // to avoid increasing the number of instructions.
1311     MachineBasicBlock::pred_iterator PI = MBB.pred_begin();
1312     MachineBasicBlock *Pred1MBB = *PI;
1313     MachineBasicBlock *Pred2MBB = *(PI+1);
1314 
1315     if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
1316       // We assume Pred1MBB is the BB containing the compare to be merged and
1317       // Pred2MBB is the BB to which we will append a compare instruction.
1318       // Proceed as is if Pred1MBB is different from MBB.
1319     }
1320     else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
1321       // We need to swap Pred1MBB and Pred2MBB to canonicalize.
1322       std::swap(Pred1MBB, Pred2MBB);
1323     }
1324     else return false;
1325 
1326     if (Pred1MBB == &MBB)
1327       return false;
1328 
1329     // Here, Pred2MBB is the BB to which we need to append a compare inst.
1330     // We cannot move the compare instruction if operands are not available
1331     // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
1332     MachineInstr *BI = &*MBB.getFirstInstrTerminator();
1333     MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
1334     for (int I = 1; I <= 2; I++)
1335       if (CMPI->getOperand(I).isReg()) {
1336         MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
1337         if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
1338           return false;
1339       }
1340 
1341     PredMBB = Pred1MBB;
1342     MBBtoMoveCmp = Pred2MBB;
1343     return true;
1344   }
1345 
1346   return false;
1347 }
1348 
1349 // This function will iterate over the input map containing a pair of TOC save
1350 // instruction and a flag. The flag will be set to false if the TOC save is
1351 // proven redundant. This function will erase from the basic block all the TOC
1352 // saves marked as redundant.
1353 bool PPCMIPeephole::eliminateRedundantTOCSaves(
1354     std::map<MachineInstr *, bool> &TOCSaves) {
1355   bool Simplified = false;
1356   int NumKept = 0;
1357   for (auto TOCSave : TOCSaves) {
1358     if (!TOCSave.second) {
1359       TOCSave.first->eraseFromParent();
1360       RemoveTOCSave++;
1361       Simplified = true;
1362     } else {
1363       NumKept++;
1364     }
1365   }
1366 
1367   if (NumKept > 1)
1368     MultiTOCSaves++;
1369 
1370   return Simplified;
1371 }
1372 
1373 // If multiple conditional branches are executed based on the (essentially)
1374 // same comparison, we merge compare instructions into one and make multiple
1375 // conditional branches on this comparison.
1376 // For example,
1377 //   if (a == 0) { ... }
1378 //   else if (a < 0) { ... }
1379 // can be executed by one compare and two conditional branches instead of
1380 // two pairs of a compare and a conditional branch.
1381 //
1382 // This method merges two compare instructions in two MBBs and modifies the
1383 // compare and conditional branch instructions if needed.
1384 // For the above example, the input for this pass looks like:
1385 //   cmplwi r3, 0
1386 //   beq    0, .LBB0_3
1387 //   cmpwi  r3, -1
1388 //   bgt    0, .LBB0_4
1389 // So, before merging two compares, we need to modify these instructions as
1390 //   cmpwi  r3, 0       ; cmplwi and cmpwi yield same result for beq
1391 //   beq    0, .LBB0_3
1392 //   cmpwi  r3, 0       ; greather than -1 means greater or equal to 0
1393 //   bge    0, .LBB0_4
1394 
1395 bool PPCMIPeephole::eliminateRedundantCompare() {
1396   bool Simplified = false;
1397 
1398   for (MachineBasicBlock &MBB2 : *MF) {
1399     MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
1400 
1401     // For fully redundant case, we select two basic blocks MBB1 and MBB2
1402     // as an optimization target if
1403     // - both MBBs end with a conditional branch,
1404     // - MBB1 is the only predecessor of MBB2, and
1405     // - compare does not take a physical register as a operand in both MBBs.
1406     // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
1407     //
1408     // As partially redundant case, we additionally handle if MBB2 has one
1409     // additional predecessor, which has only one successor (MBB2).
1410     // In this case, we move the compare instruction originally in MBB2 into
1411     // MBBtoMoveCmp. This partially redundant case is typically appear by
1412     // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
1413     //
1414     // Overview of CFG of related basic blocks
1415     // Fully redundant case        Partially redundant case
1416     //   --------                   ----------------  --------
1417     //   | MBB1 | (w/ 2 succ)       | MBBtoMoveCmp |  | MBB1 | (w/ 2 succ)
1418     //   --------                   ----------------  --------
1419     //      |    \                     (w/ 1 succ) \     |    \
1420     //      |     \                                 \    |     \
1421     //      |                                        \   |
1422     //   --------                                     --------
1423     //   | MBB2 | (w/ 1 pred                          | MBB2 | (w/ 2 pred
1424     //   -------- and 2 succ)                         -------- and 2 succ)
1425     //      |    \                                       |    \
1426     //      |     \                                      |     \
1427     //
1428     if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
1429       continue;
1430 
1431     MachineInstr *BI1   = &*MBB1->getFirstInstrTerminator();
1432     MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
1433 
1434     MachineInstr *BI2   = &*MBB2.getFirstInstrTerminator();
1435     MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
1436     bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
1437 
1438     // We cannot optimize an unsupported compare opcode or
1439     // a mix of 32-bit and 64-bit comparisons
1440     if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
1441         !isSupportedCmpOp(CMPI2->getOpcode()) ||
1442         is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
1443       continue;
1444 
1445     unsigned NewOpCode = 0;
1446     unsigned NewPredicate1 = 0, NewPredicate2 = 0;
1447     int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
1448     bool SwapOperands = false;
1449 
1450     if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
1451       // Typically, unsigned comparison is used for equality check, but
1452       // we replace it with a signed comparison if the comparison
1453       // to be merged is a signed comparison.
1454       // In other cases of opcode mismatch, we cannot optimize this.
1455 
1456       // We cannot change opcode when comparing against an immediate
1457       // if the most significant bit of the immediate is one
1458       // due to the difference in sign extension.
1459       auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
1460         if (!I->getOperand(2).isImm())
1461           return false;
1462         int16_t Imm = (int16_t)I->getOperand(2).getImm();
1463         return Imm < 0;
1464       };
1465 
1466       if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
1467           CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
1468         NewOpCode = CMPI1->getOpcode();
1469       else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
1470                getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
1471         NewOpCode = CMPI2->getOpcode();
1472       else continue;
1473     }
1474 
1475     if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
1476       // In case of comparisons between two registers, these two registers
1477       // must be same to merge two comparisons.
1478       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1479                                          nullptr, nullptr, MRI);
1480       unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
1481                                          nullptr, nullptr, MRI);
1482       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1483                                          MBB1, &MBB2, MRI);
1484       unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
1485                                          MBB1, &MBB2, MRI);
1486 
1487       if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
1488         // Same pair of registers in the same order; ready to merge as is.
1489       }
1490       else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
1491         // Same pair of registers in different order.
1492         // We reverse the predicate to merge compare instructions.
1493         PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm();
1494         NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
1495         // In case of partial redundancy, we need to swap operands
1496         // in another compare instruction.
1497         SwapOperands = true;
1498       }
1499       else continue;
1500     }
1501     else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
1502       // In case of comparisons between a register and an immediate,
1503       // the operand register must be same for two compare instructions.
1504       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1505                                          nullptr, nullptr, MRI);
1506       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1507                                          MBB1, &MBB2, MRI);
1508       if (Cmp1Operand1 != Cmp2Operand1)
1509         continue;
1510 
1511       NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
1512       NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
1513 
1514       // If immediate are not same, we try to adjust by changing predicate;
1515       // e.g. GT imm means GE (imm+1).
1516       if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
1517         int Diff = Imm1 - Imm2;
1518         if (Diff < -2 || Diff > 2)
1519           continue;
1520 
1521         unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
1522         unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
1523         unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
1524         unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
1525         if (Diff == 2) {
1526           if (PredToInc2 && PredToDec1) {
1527             NewPredicate2 = PredToInc2;
1528             NewPredicate1 = PredToDec1;
1529             NewImm2++;
1530             NewImm1--;
1531           }
1532         }
1533         else if (Diff == 1) {
1534           if (PredToInc2) {
1535             NewImm2++;
1536             NewPredicate2 = PredToInc2;
1537           }
1538           else if (PredToDec1) {
1539             NewImm1--;
1540             NewPredicate1 = PredToDec1;
1541           }
1542         }
1543         else if (Diff == -1) {
1544           if (PredToDec2) {
1545             NewImm2--;
1546             NewPredicate2 = PredToDec2;
1547           }
1548           else if (PredToInc1) {
1549             NewImm1++;
1550             NewPredicate1 = PredToInc1;
1551           }
1552         }
1553         else if (Diff == -2) {
1554           if (PredToDec2 && PredToInc1) {
1555             NewPredicate2 = PredToDec2;
1556             NewPredicate1 = PredToInc1;
1557             NewImm2--;
1558             NewImm1++;
1559           }
1560         }
1561       }
1562 
1563       // We cannot merge two compares if the immediates are not same.
1564       if (NewImm2 != NewImm1)
1565         continue;
1566     }
1567 
1568     LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
1569     LLVM_DEBUG(CMPI1->dump());
1570     LLVM_DEBUG(BI1->dump());
1571     LLVM_DEBUG(CMPI2->dump());
1572     LLVM_DEBUG(BI2->dump());
1573 
1574     // We adjust opcode, predicates and immediate as we determined above.
1575     if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
1576       CMPI1->setDesc(TII->get(NewOpCode));
1577     }
1578     if (NewPredicate1) {
1579       BI1->getOperand(0).setImm(NewPredicate1);
1580     }
1581     if (NewPredicate2) {
1582       BI2->getOperand(0).setImm(NewPredicate2);
1583     }
1584     if (NewImm1 != Imm1) {
1585       CMPI1->getOperand(2).setImm(NewImm1);
1586     }
1587 
1588     if (IsPartiallyRedundant) {
1589       // We touch up the compare instruction in MBB2 and move it to
1590       // a previous BB to handle partially redundant case.
1591       if (SwapOperands) {
1592         Register Op1 = CMPI2->getOperand(1).getReg();
1593         Register Op2 = CMPI2->getOperand(2).getReg();
1594         CMPI2->getOperand(1).setReg(Op2);
1595         CMPI2->getOperand(2).setReg(Op1);
1596       }
1597       if (NewImm2 != Imm2)
1598         CMPI2->getOperand(2).setImm(NewImm2);
1599 
1600       for (int I = 1; I <= 2; I++) {
1601         if (CMPI2->getOperand(I).isReg()) {
1602           MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
1603           if (Inst->getParent() != &MBB2)
1604             continue;
1605 
1606           assert(Inst->getOpcode() == PPC::PHI &&
1607                  "We cannot support if an operand comes from this BB.");
1608           unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
1609           CMPI2->getOperand(I).setReg(SrcReg);
1610         }
1611       }
1612       auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
1613       MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
1614 
1615       DebugLoc DL = CMPI2->getDebugLoc();
1616       Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
1617       BuildMI(MBB2, MBB2.begin(), DL,
1618               TII->get(PPC::PHI), NewVReg)
1619         .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
1620         .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
1621       BI2->getOperand(1).setReg(NewVReg);
1622     }
1623     else {
1624       // We finally eliminate compare instruction in MBB2.
1625       BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
1626       CMPI2->eraseFromParent();
1627     }
1628     BI2->getOperand(1).setIsKill(true);
1629     BI1->getOperand(1).setIsKill(false);
1630 
1631     LLVM_DEBUG(dbgs() << "into a compare and two branches:\n");
1632     LLVM_DEBUG(CMPI1->dump());
1633     LLVM_DEBUG(BI1->dump());
1634     LLVM_DEBUG(BI2->dump());
1635     if (IsPartiallyRedundant) {
1636       LLVM_DEBUG(dbgs() << "The following compare is moved into "
1637                         << printMBBReference(*MBBtoMoveCmp)
1638                         << " to handle partial redundancy.\n");
1639       LLVM_DEBUG(CMPI2->dump());
1640     }
1641 
1642     Simplified = true;
1643   }
1644 
1645   return Simplified;
1646 }
1647 
1648 // We miss the opportunity to emit an RLDIC when lowering jump tables
1649 // since ISEL sees only a single basic block. When selecting, the clear
1650 // and shift left will be in different blocks.
1651 bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI) {
1652   if (MI.getOpcode() != PPC::RLDICR)
1653     return false;
1654 
1655   Register SrcReg = MI.getOperand(1).getReg();
1656   if (!SrcReg.isVirtual())
1657     return false;
1658 
1659   MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1660   if (SrcMI->getOpcode() != PPC::RLDICL)
1661     return false;
1662 
1663   MachineOperand MOpSHSrc = SrcMI->getOperand(2);
1664   MachineOperand MOpMBSrc = SrcMI->getOperand(3);
1665   MachineOperand MOpSHMI = MI.getOperand(2);
1666   MachineOperand MOpMEMI = MI.getOperand(3);
1667   if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() &&
1668         MOpMEMI.isImm()))
1669     return false;
1670 
1671   uint64_t SHSrc = MOpSHSrc.getImm();
1672   uint64_t MBSrc = MOpMBSrc.getImm();
1673   uint64_t SHMI = MOpSHMI.getImm();
1674   uint64_t MEMI = MOpMEMI.getImm();
1675   uint64_t NewSH = SHSrc + SHMI;
1676   uint64_t NewMB = MBSrc - SHMI;
1677   if (NewMB > 63 || NewSH > 63)
1678     return false;
1679 
1680   // The bits cleared with RLDICL are [0, MBSrc).
1681   // The bits cleared with RLDICR are (MEMI, 63].
1682   // After the sequence, the bits cleared are:
1683   // [0, MBSrc-SHMI) and (MEMI, 63).
1684   //
1685   // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63].
1686   if ((63 - NewSH) != MEMI)
1687     return false;
1688 
1689   LLVM_DEBUG(dbgs() << "Converting pair: ");
1690   LLVM_DEBUG(SrcMI->dump());
1691   LLVM_DEBUG(MI.dump());
1692 
1693   MI.setDesc(TII->get(PPC::RLDIC));
1694   MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
1695   MI.getOperand(2).setImm(NewSH);
1696   MI.getOperand(3).setImm(NewMB);
1697   MI.getOperand(1).setIsKill(SrcMI->getOperand(1).isKill());
1698   SrcMI->getOperand(1).setIsKill(false);
1699 
1700   LLVM_DEBUG(dbgs() << "To: ");
1701   LLVM_DEBUG(MI.dump());
1702   NumRotatesCollapsed++;
1703   // If SrcReg has no non-debug use it's safe to delete its def SrcMI.
1704   if (MRI->use_nodbg_empty(SrcReg)) {
1705     assert(!SrcMI->hasImplicitDef() &&
1706            "Not expecting an implicit def with this instr.");
1707     SrcMI->eraseFromParent();
1708   }
1709   return true;
1710 }
1711 
1712 // For case in LLVM IR
1713 // entry:
1714 //   %iconv = sext i32 %index to i64
1715 //   br i1 undef label %true, label %false
1716 // true:
1717 //   %ptr = getelementptr inbounds i32, i32* null, i64 %iconv
1718 // ...
1719 // PPCISelLowering::combineSHL fails to combine, because sext and shl are in
1720 // different BBs when conducting instruction selection. We can do a peephole
1721 // optimization to combine these two instructions into extswsli after
1722 // instruction selection.
1723 bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI,
1724                                       MachineInstr *&ToErase) {
1725   if (MI.getOpcode() != PPC::RLDICR)
1726     return false;
1727 
1728   if (!MF->getSubtarget<PPCSubtarget>().isISA3_0())
1729     return false;
1730 
1731   assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands");
1732 
1733   MachineOperand MOpSHMI = MI.getOperand(2);
1734   MachineOperand MOpMEMI = MI.getOperand(3);
1735   if (!(MOpSHMI.isImm() && MOpMEMI.isImm()))
1736     return false;
1737 
1738   uint64_t SHMI = MOpSHMI.getImm();
1739   uint64_t MEMI = MOpMEMI.getImm();
1740   if (SHMI + MEMI != 63)
1741     return false;
1742 
1743   Register SrcReg = MI.getOperand(1).getReg();
1744   if (!SrcReg.isVirtual())
1745     return false;
1746 
1747   MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1748   if (SrcMI->getOpcode() != PPC::EXTSW &&
1749       SrcMI->getOpcode() != PPC::EXTSW_32_64)
1750     return false;
1751 
1752   // If the register defined by extsw has more than one use, combination is not
1753   // needed.
1754   if (!MRI->hasOneNonDBGUse(SrcReg))
1755     return false;
1756 
1757   assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands");
1758   assert(SrcMI->getOperand(1).isReg() &&
1759          "EXTSW's second operand should be a register");
1760   if (!SrcMI->getOperand(1).getReg().isVirtual())
1761     return false;
1762 
1763   LLVM_DEBUG(dbgs() << "Combining pair: ");
1764   LLVM_DEBUG(SrcMI->dump());
1765   LLVM_DEBUG(MI.dump());
1766 
1767   MachineInstr *NewInstr =
1768       BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
1769               SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI)
1770                                                : TII->get(PPC::EXTSWSLI_32_64),
1771               MI.getOperand(0).getReg())
1772           .add(SrcMI->getOperand(1))
1773           .add(MOpSHMI);
1774   (void)NewInstr;
1775 
1776   LLVM_DEBUG(dbgs() << "TO: ");
1777   LLVM_DEBUG(NewInstr->dump());
1778   ++NumEXTSWAndSLDICombined;
1779   ToErase = &MI;
1780   // SrcMI, which is extsw, is of no use now, erase it.
1781   SrcMI->eraseFromParent();
1782   return true;
1783 }
1784 
1785 } // end default namespace
1786 
1787 INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
1788                       "PowerPC MI Peephole Optimization", false, false)
1789 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1790 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1791 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1792 INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
1793                     "PowerPC MI Peephole Optimization", false, false)
1794 
1795 char PPCMIPeephole::ID = 0;
1796 FunctionPass*
1797 llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
1798