xref: /llvm-project/llvm/lib/Target/PowerPC/PPCMIPeephole.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
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 "PPC.h"
22 #include "PPCInstrBuilder.h"
23 #include "PPCInstrInfo.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/Support/Debug.h"
31 #include "MCTargetDesc/PPCPredicates.h"
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "ppc-mi-peepholes"
36 
37 STATISTIC(RemoveTOCSave, "Number of TOC saves removed");
38 STATISTIC(MultiTOCSaves,
39           "Number of functions with multiple TOC saves that must be kept");
40 STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions");
41 STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions");
42 STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI");
43 STATISTIC(NumConvertedToImmediateForm,
44           "Number of instructions converted to their immediate form");
45 STATISTIC(NumFunctionsEnteredInMIPeephole,
46           "Number of functions entered in PPC MI Peepholes");
47 STATISTIC(NumFixedPointIterations,
48           "Number of fixed-point iterations converting reg-reg instructions "
49           "to reg-imm ones");
50 
51 static cl::opt<bool>
52 FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true),
53                    cl::desc("Iterate to a fixed point when attempting to "
54                             "convert reg-reg instructions to reg-imm"));
55 
56 static cl::opt<bool>
57 ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true),
58               cl::desc("Convert eligible reg+reg instructions to reg+imm"));
59 
60 static cl::opt<bool>
61     EnableSExtElimination("ppc-eliminate-signext",
62                           cl::desc("enable elimination of sign-extensions"),
63                           cl::init(false), cl::Hidden);
64 
65 static cl::opt<bool>
66     EnableZExtElimination("ppc-eliminate-zeroext",
67                           cl::desc("enable elimination of zero-extensions"),
68                           cl::init(false), cl::Hidden);
69 
70 namespace {
71 
72 struct PPCMIPeephole : public MachineFunctionPass {
73 
74   static char ID;
75   const PPCInstrInfo *TII;
76   MachineFunction *MF;
77   MachineRegisterInfo *MRI;
78 
79   PPCMIPeephole() : MachineFunctionPass(ID) {
80     initializePPCMIPeepholePass(*PassRegistry::getPassRegistry());
81   }
82 
83 private:
84   MachineDominatorTree *MDT;
85 
86   // Initialize class variables.
87   void initialize(MachineFunction &MFParm);
88 
89   // Perform peepholes.
90   bool simplifyCode(void);
91 
92   // Perform peepholes.
93   bool eliminateRedundantCompare(void);
94   bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves);
95   void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves,
96                       MachineInstr *MI);
97 
98 public:
99 
100   void getAnalysisUsage(AnalysisUsage &AU) const override {
101     AU.addRequired<MachineDominatorTree>();
102     AU.addPreserved<MachineDominatorTree>();
103     MachineFunctionPass::getAnalysisUsage(AU);
104   }
105 
106   // Main entry point for this pass.
107   bool runOnMachineFunction(MachineFunction &MF) override {
108     if (skipFunction(MF.getFunction()))
109       return false;
110     initialize(MF);
111     return simplifyCode();
112   }
113 };
114 
115 // Initialize class variables.
116 void PPCMIPeephole::initialize(MachineFunction &MFParm) {
117   MF = &MFParm;
118   MRI = &MF->getRegInfo();
119   MDT = &getAnalysis<MachineDominatorTree>();
120   TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
121   LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n");
122   LLVM_DEBUG(MF->dump());
123 }
124 
125 static MachineInstr *getVRegDefOrNull(MachineOperand *Op,
126                                       MachineRegisterInfo *MRI) {
127   assert(Op && "Invalid Operand!");
128   if (!Op->isReg())
129     return nullptr;
130 
131   unsigned Reg = Op->getReg();
132   if (!TargetRegisterInfo::isVirtualRegister(Reg))
133     return nullptr;
134 
135   return MRI->getVRegDef(Reg);
136 }
137 
138 // This function returns number of known zero bits in output of MI
139 // starting from the most significant bit.
140 static unsigned
141 getKnownLeadingZeroCount(MachineInstr *MI, const PPCInstrInfo *TII) {
142   unsigned Opcode = MI->getOpcode();
143   if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICLo ||
144       Opcode == PPC::RLDCL  || Opcode == PPC::RLDCLo)
145     return MI->getOperand(3).getImm();
146 
147   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDICo) &&
148        MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm())
149     return MI->getOperand(3).getImm();
150 
151   if ((Opcode == PPC::RLWINM  || Opcode == PPC::RLWINMo ||
152        Opcode == PPC::RLWNM   || Opcode == PPC::RLWNMo  ||
153        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
154        MI->getOperand(3).getImm() <= MI->getOperand(4).getImm())
155     return 32 + MI->getOperand(3).getImm();
156 
157   if (Opcode == PPC::ANDIo) {
158     uint16_t Imm = MI->getOperand(2).getImm();
159     return 48 + countLeadingZeros(Imm);
160   }
161 
162   if (Opcode == PPC::CNTLZW  || Opcode == PPC::CNTLZWo ||
163       Opcode == PPC::CNTTZW  || Opcode == PPC::CNTTZWo ||
164       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8)
165     // The result ranges from 0 to 32.
166     return 58;
167 
168   if (Opcode == PPC::CNTLZD  || Opcode == PPC::CNTLZDo ||
169       Opcode == PPC::CNTTZD  || Opcode == PPC::CNTTZDo)
170     // The result ranges from 0 to 64.
171     return 57;
172 
173   if (Opcode == PPC::LHZ   || Opcode == PPC::LHZX  ||
174       Opcode == PPC::LHZ8  || Opcode == PPC::LHZX8 ||
175       Opcode == PPC::LHZU  || Opcode == PPC::LHZUX ||
176       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8)
177     return 48;
178 
179   if (Opcode == PPC::LBZ   || Opcode == PPC::LBZX  ||
180       Opcode == PPC::LBZ8  || Opcode == PPC::LBZX8 ||
181       Opcode == PPC::LBZU  || Opcode == PPC::LBZUX ||
182       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8)
183     return 56;
184 
185   if (TII->isZeroExtended(*MI))
186     return 32;
187 
188   return 0;
189 }
190 
191 // This function maintains a map for the pairs <TOC Save Instr, Keep>
192 // Each time a new TOC save is encountered, it checks if any of the existing
193 // ones are dominated by the new one. If so, it marks the existing one as
194 // redundant by setting it's entry in the map as false. It then adds the new
195 // instruction to the map with either true or false depending on if any
196 // existing instructions dominated the new one.
197 void PPCMIPeephole::UpdateTOCSaves(
198   std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) {
199   assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here");
200   bool Keep = true;
201   for (auto It = TOCSaves.begin(); It != TOCSaves.end(); It++ ) {
202     MachineInstr *CurrInst = It->first;
203     // If new instruction dominates an existing one, mark existing one as
204     // redundant.
205     if (It->second && MDT->dominates(MI, CurrInst))
206       It->second = false;
207     // Check if the new instruction is redundant.
208     if (MDT->dominates(CurrInst, MI)) {
209       Keep = false;
210       break;
211     }
212   }
213   // Add new instruction to map.
214   TOCSaves[MI] = Keep;
215 }
216 
217 // Perform peephole optimizations.
218 bool PPCMIPeephole::simplifyCode(void) {
219   bool Simplified = false;
220   MachineInstr* ToErase = nullptr;
221   std::map<MachineInstr *, bool> TOCSaves;
222   const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
223   NumFunctionsEnteredInMIPeephole++;
224   if (ConvertRegReg) {
225     // Fixed-point conversion of reg/reg instructions fed by load-immediate
226     // into reg/imm instructions. FIXME: This is expensive, control it with
227     // an option.
228     bool SomethingChanged = false;
229     do {
230       NumFixedPointIterations++;
231       SomethingChanged = false;
232       for (MachineBasicBlock &MBB : *MF) {
233         for (MachineInstr &MI : MBB) {
234           if (MI.isDebugInstr())
235             continue;
236 
237           if (TII->convertToImmediateForm(MI)) {
238             // We don't erase anything in case the def has other uses. Let DCE
239             // remove it if it can be removed.
240             LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
241             LLVM_DEBUG(MI.dump());
242             NumConvertedToImmediateForm++;
243             SomethingChanged = true;
244             Simplified = true;
245             continue;
246           }
247         }
248       }
249     } while (SomethingChanged && FixedPointRegToImm);
250   }
251 
252   for (MachineBasicBlock &MBB : *MF) {
253     for (MachineInstr &MI : MBB) {
254 
255       // If the previous instruction was marked for elimination,
256       // remove it now.
257       if (ToErase) {
258         ToErase->eraseFromParent();
259         ToErase = nullptr;
260       }
261 
262       // Ignore debug instructions.
263       if (MI.isDebugInstr())
264         continue;
265 
266       // Per-opcode peepholes.
267       switch (MI.getOpcode()) {
268 
269       default:
270         break;
271 
272       case PPC::STD: {
273         MachineFrameInfo &MFI = MF->getFrameInfo();
274         if (MFI.hasVarSizedObjects() ||
275             !MF->getSubtarget<PPCSubtarget>().isELFv2ABI())
276           break;
277         // When encountering a TOC save instruction, call UpdateTOCSaves
278         // to add it to the TOCSaves map and mark any existing TOC saves
279         // it dominates as redundant.
280         if (TII->isTOCSaveMI(MI))
281           UpdateTOCSaves(TOCSaves, &MI);
282         break;
283       }
284       case PPC::XXPERMDI: {
285         // Perform simplifications of 2x64 vector swaps and splats.
286         // A swap is identified by an immediate value of 2, and a splat
287         // is identified by an immediate value of 0 or 3.
288         int Immed = MI.getOperand(3).getImm();
289 
290         if (Immed != 1) {
291 
292           // For each of these simplifications, we need the two source
293           // regs to match.  Unfortunately, MachineCSE ignores COPY and
294           // SUBREG_TO_REG, so for example we can see
295           //   XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
296           // We have to look through chains of COPY and SUBREG_TO_REG
297           // to find the real source values for comparison.
298           unsigned TrueReg1 =
299             TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
300           unsigned TrueReg2 =
301             TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
302 
303           if (TrueReg1 == TrueReg2
304               && TargetRegisterInfo::isVirtualRegister(TrueReg1)) {
305             MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
306             unsigned DefOpc = DefMI ? DefMI->getOpcode() : 0;
307 
308             // If this is a splat fed by a splatting load, the splat is
309             // redundant. Replace with a copy. This doesn't happen directly due
310             // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
311             // a load of a double to a vector of 64-bit integers.
312             auto isConversionOfLoadAndSplat = [=]() -> bool {
313               if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
314                 return false;
315               unsigned DefReg =
316                 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
317               if (TargetRegisterInfo::isVirtualRegister(DefReg)) {
318                 MachineInstr *LoadMI = MRI->getVRegDef(DefReg);
319                 if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
320                   return true;
321               }
322               return false;
323             };
324             if (DefMI && (Immed == 0 || Immed == 3)) {
325               if (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat()) {
326                 LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
327                                      "to load-and-splat/copy: ");
328                 LLVM_DEBUG(MI.dump());
329                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
330                         MI.getOperand(0).getReg())
331                     .add(MI.getOperand(1));
332                 ToErase = &MI;
333                 Simplified = true;
334               }
335             }
336 
337             // If this is a splat or a swap fed by another splat, we
338             // can replace it with a copy.
339             if (DefOpc == PPC::XXPERMDI) {
340               unsigned FeedImmed = DefMI->getOperand(3).getImm();
341               unsigned FeedReg1 =
342                 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
343               unsigned FeedReg2 =
344                 TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
345 
346               if ((FeedImmed == 0 || FeedImmed == 3) && FeedReg1 == FeedReg2) {
347                 LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
348                                      "to splat/copy: ");
349                 LLVM_DEBUG(MI.dump());
350                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
351                         MI.getOperand(0).getReg())
352                     .add(MI.getOperand(1));
353                 ToErase = &MI;
354                 Simplified = true;
355               }
356 
357               // If this is a splat fed by a swap, we can simplify modify
358               // the splat to splat the other value from the swap's input
359               // parameter.
360               else if ((Immed == 0 || Immed == 3)
361                        && FeedImmed == 2 && FeedReg1 == FeedReg2) {
362                 LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
363                 LLVM_DEBUG(MI.dump());
364                 MI.getOperand(1).setReg(DefMI->getOperand(1).getReg());
365                 MI.getOperand(2).setReg(DefMI->getOperand(2).getReg());
366                 MI.getOperand(3).setImm(3 - Immed);
367                 Simplified = true;
368               }
369 
370               // If this is a swap fed by a swap, we can replace it
371               // with a copy from the first swap's input.
372               else if (Immed == 2 && FeedImmed == 2 && FeedReg1 == FeedReg2) {
373                 LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
374                 LLVM_DEBUG(MI.dump());
375                 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
376                         MI.getOperand(0).getReg())
377                     .add(DefMI->getOperand(1));
378                 ToErase = &MI;
379                 Simplified = true;
380               }
381             } else if ((Immed == 0 || Immed == 3) && DefOpc == PPC::XXPERMDIs &&
382                        (DefMI->getOperand(2).getImm() == 0 ||
383                         DefMI->getOperand(2).getImm() == 3)) {
384               // Splat fed by another splat - switch the output of the first
385               // and remove the second.
386               DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
387               ToErase = &MI;
388               Simplified = true;
389               LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
390               LLVM_DEBUG(MI.dump());
391             }
392           }
393         }
394         break;
395       }
396       case PPC::VSPLTB:
397       case PPC::VSPLTH:
398       case PPC::XXSPLTW: {
399         unsigned MyOpcode = MI.getOpcode();
400         unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
401         unsigned TrueReg =
402           TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
403         if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
404           break;
405         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
406         if (!DefMI)
407           break;
408         unsigned DefOpcode = DefMI->getOpcode();
409         auto isConvertOfSplat = [=]() -> bool {
410           if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
411             return false;
412           unsigned ConvReg = DefMI->getOperand(1).getReg();
413           if (!TargetRegisterInfo::isVirtualRegister(ConvReg))
414             return false;
415           MachineInstr *Splt = MRI->getVRegDef(ConvReg);
416           return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
417             Splt->getOpcode() == PPC::XXSPLTW);
418         };
419         bool AlreadySplat = (MyOpcode == DefOpcode) ||
420           (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
421           (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
422           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
423           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
424           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
425           (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
426         // If the instruction[s] that feed this splat have already splat
427         // the value, this splat is redundant.
428         if (AlreadySplat) {
429           LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
430           LLVM_DEBUG(MI.dump());
431           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
432                   MI.getOperand(0).getReg())
433               .add(MI.getOperand(OpNo));
434           ToErase = &MI;
435           Simplified = true;
436         }
437         // Splat fed by a shift. Usually when we align value to splat into
438         // vector element zero.
439         if (DefOpcode == PPC::XXSLDWI) {
440           unsigned ShiftRes = DefMI->getOperand(0).getReg();
441           unsigned ShiftOp1 = DefMI->getOperand(1).getReg();
442           unsigned ShiftOp2 = DefMI->getOperand(2).getReg();
443           unsigned ShiftImm = DefMI->getOperand(3).getImm();
444           unsigned SplatImm = MI.getOperand(2).getImm();
445           if (ShiftOp1 == ShiftOp2) {
446             unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
447             if (MRI->hasOneNonDBGUse(ShiftRes)) {
448               LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
449               LLVM_DEBUG(DefMI->dump());
450               ToErase = DefMI;
451             }
452             Simplified = true;
453             LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
454                               << " to " << NewElem << " in instruction: ");
455             LLVM_DEBUG(MI.dump());
456             MI.getOperand(1).setReg(ShiftOp1);
457             MI.getOperand(2).setImm(NewElem);
458           }
459         }
460         break;
461       }
462       case PPC::XVCVDPSP: {
463         // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
464         unsigned TrueReg =
465           TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
466         if (!TargetRegisterInfo::isVirtualRegister(TrueReg))
467           break;
468         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
469 
470         // This can occur when building a vector of single precision or integer
471         // values.
472         if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
473           unsigned DefsReg1 =
474             TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
475           unsigned DefsReg2 =
476             TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
477           if (!TargetRegisterInfo::isVirtualRegister(DefsReg1) ||
478               !TargetRegisterInfo::isVirtualRegister(DefsReg2))
479             break;
480           MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
481           MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
482 
483           if (!P1 || !P2)
484             break;
485 
486           // Remove the passed FRSP instruction if it only feeds this MI and
487           // set any uses of that FRSP (in this MI) to the source of the FRSP.
488           auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
489             if (RoundInstr->getOpcode() == PPC::FRSP &&
490                 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
491               Simplified = true;
492               unsigned ConvReg1 = RoundInstr->getOperand(1).getReg();
493               unsigned FRSPDefines = RoundInstr->getOperand(0).getReg();
494               MachineInstr &Use = *(MRI->use_instr_begin(FRSPDefines));
495               for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
496                 if (Use.getOperand(i).isReg() &&
497                     Use.getOperand(i).getReg() == FRSPDefines)
498                   Use.getOperand(i).setReg(ConvReg1);
499               LLVM_DEBUG(dbgs() << "Removing redundant FRSP:\n");
500               LLVM_DEBUG(RoundInstr->dump());
501               LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
502               LLVM_DEBUG(MI.dump());
503               LLVM_DEBUG(dbgs() << "Through instruction:\n");
504               LLVM_DEBUG(DefMI->dump());
505               RoundInstr->eraseFromParent();
506             }
507           };
508 
509           // If the input to XVCVDPSP is a vector that was built (even
510           // partially) out of FRSP's, the FRSP(s) can safely be removed
511           // since this instruction performs the same operation.
512           if (P1 != P2) {
513             removeFRSPIfPossible(P1);
514             removeFRSPIfPossible(P2);
515             break;
516           }
517           removeFRSPIfPossible(P1);
518         }
519         break;
520       }
521       case PPC::EXTSH:
522       case PPC::EXTSH8:
523       case PPC::EXTSH8_32_64: {
524         if (!EnableSExtElimination) break;
525         unsigned NarrowReg = MI.getOperand(1).getReg();
526         if (!TargetRegisterInfo::isVirtualRegister(NarrowReg))
527           break;
528 
529         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
530         // If we've used a zero-extending load that we will sign-extend,
531         // just do a sign-extending load.
532         if (SrcMI->getOpcode() == PPC::LHZ ||
533             SrcMI->getOpcode() == PPC::LHZX) {
534           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
535             break;
536           auto is64Bit = [] (unsigned Opcode) {
537             return Opcode == PPC::EXTSH8;
538           };
539           auto isXForm = [] (unsigned Opcode) {
540             return Opcode == PPC::LHZX;
541           };
542           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
543             if (is64Bit)
544               if (isXForm) return PPC::LHAX8;
545               else         return PPC::LHA8;
546             else
547               if (isXForm) return PPC::LHAX;
548               else         return PPC::LHA;
549           };
550           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
551                                        isXForm(SrcMI->getOpcode()));
552           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
553           LLVM_DEBUG(SrcMI->dump());
554           LLVM_DEBUG(dbgs() << "and sign-extension\n");
555           LLVM_DEBUG(MI.dump());
556           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
557           SrcMI->setDesc(TII->get(Opc));
558           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
559           ToErase = &MI;
560           Simplified = true;
561           NumEliminatedSExt++;
562         }
563         break;
564       }
565       case PPC::EXTSW:
566       case PPC::EXTSW_32:
567       case PPC::EXTSW_32_64: {
568         if (!EnableSExtElimination) break;
569         unsigned NarrowReg = MI.getOperand(1).getReg();
570         if (!TargetRegisterInfo::isVirtualRegister(NarrowReg))
571           break;
572 
573         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
574         // If we've used a zero-extending load that we will sign-extend,
575         // just do a sign-extending load.
576         if (SrcMI->getOpcode() == PPC::LWZ ||
577             SrcMI->getOpcode() == PPC::LWZX) {
578           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
579             break;
580           auto is64Bit = [] (unsigned Opcode) {
581             return Opcode == PPC::EXTSW || Opcode == PPC::EXTSW_32_64;
582           };
583           auto isXForm = [] (unsigned Opcode) {
584             return Opcode == PPC::LWZX;
585           };
586           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
587             if (is64Bit)
588               if (isXForm) return PPC::LWAX;
589               else         return PPC::LWA;
590             else
591               if (isXForm) return PPC::LWAX_32;
592               else         return PPC::LWA_32;
593           };
594           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
595                                        isXForm(SrcMI->getOpcode()));
596           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
597           LLVM_DEBUG(SrcMI->dump());
598           LLVM_DEBUG(dbgs() << "and sign-extension\n");
599           LLVM_DEBUG(MI.dump());
600           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
601           SrcMI->setDesc(TII->get(Opc));
602           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
603           ToErase = &MI;
604           Simplified = true;
605           NumEliminatedSExt++;
606         } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
607                    TII->isSignExtended(*SrcMI)) {
608           // We can eliminate EXTSW if the input is known to be already
609           // sign-extended.
610           LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
611           unsigned TmpReg =
612             MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
613           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
614                   TmpReg);
615           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
616                   MI.getOperand(0).getReg())
617               .addReg(TmpReg)
618               .addReg(NarrowReg)
619               .addImm(PPC::sub_32);
620           ToErase = &MI;
621           Simplified = true;
622           NumEliminatedSExt++;
623         }
624         break;
625       }
626       case PPC::RLDICL: {
627         // We can eliminate RLDICL (e.g. for zero-extension)
628         // if all bits to clear are already zero in the input.
629         // This code assume following code sequence for zero-extension.
630         //   %6 = COPY %5:sub_32; (optional)
631         //   %8 = IMPLICIT_DEF;
632         //   %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
633         if (!EnableZExtElimination) break;
634 
635         if (MI.getOperand(2).getImm() != 0)
636           break;
637 
638         unsigned SrcReg = MI.getOperand(1).getReg();
639         if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
640           break;
641 
642         MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
643         if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
644               SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
645           break;
646 
647         MachineInstr *ImpDefMI, *SubRegMI;
648         ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
649         SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
650         if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
651 
652         SrcMI = SubRegMI;
653         if (SubRegMI->getOpcode() == PPC::COPY) {
654           unsigned CopyReg = SubRegMI->getOperand(1).getReg();
655           if (TargetRegisterInfo::isVirtualRegister(CopyReg))
656             SrcMI = MRI->getVRegDef(CopyReg);
657         }
658 
659         unsigned KnownZeroCount = getKnownLeadingZeroCount(SrcMI, TII);
660         if (MI.getOperand(3).getImm() <= KnownZeroCount) {
661           LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
662           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
663                   MI.getOperand(0).getReg())
664               .addReg(SrcReg);
665           ToErase = &MI;
666           Simplified = true;
667           NumEliminatedZExt++;
668         }
669         break;
670       }
671 
672       // TODO: Any instruction that has an immediate form fed only by a PHI
673       // whose operands are all load immediate can be folded away. We currently
674       // do this for ADD instructions, but should expand it to arithmetic and
675       // binary instructions with immediate forms in the future.
676       case PPC::ADD4:
677       case PPC::ADD8: {
678         auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
679           assert(PhiOp && "Invalid Operand!");
680           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
681 
682           return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
683                  MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
684         };
685 
686         auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
687                                             MachineOperand *PhiOp) {
688           assert(PhiOp && "Invalid Operand!");
689           assert(DominatorOp && "Invalid Operand!");
690           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
691           MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
692 
693           // Note: the vregs only show up at odd indices position of PHI Node,
694           // the even indices position save the BB info.
695           for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
696             MachineInstr *LiMI =
697                 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
698             if (!LiMI ||
699                 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
700                 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
701                 !MDT->dominates(DefDomMI, LiMI))
702               return false;
703           }
704 
705           return true;
706         };
707 
708         MachineOperand Op1 = MI.getOperand(1);
709         MachineOperand Op2 = MI.getOperand(2);
710         if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
711           std::swap(Op1, Op2);
712         else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
713           break; // We don't have an ADD fed by LI's that can be transformed
714 
715         // Now we know that Op1 is the PHI node and Op2 is the dominator
716         unsigned DominatorReg = Op2.getReg();
717 
718         const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
719                                              ? &PPC::G8RC_and_G8RC_NOX0RegClass
720                                              : &PPC::GPRC_and_GPRC_NOR0RegClass;
721         MRI->setRegClass(DominatorReg, TRC);
722 
723         // replace LIs with ADDIs
724         MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
725         for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
726           MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
727           LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
728           LLVM_DEBUG(LiMI->dump());
729 
730           // There could be repeated registers in the PHI, e.g: %1 =
731           // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
732           // already replaced the def instruction, skip.
733           if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
734             continue;
735 
736           assert((LiMI->getOpcode() == PPC::LI ||
737                   LiMI->getOpcode() == PPC::LI8) &&
738                  "Invalid Opcode!");
739           auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
740           LiMI->RemoveOperand(1);                    // remove the imm of LI
741           LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
742                                                               : PPC::ADDI8));
743           MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
744               .addReg(DominatorReg)
745               .addImm(LiImm); // restore the imm of LI
746           LLVM_DEBUG(LiMI->dump());
747         }
748 
749         // Replace ADD with COPY
750         LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
751         LLVM_DEBUG(MI.dump());
752         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
753                 MI.getOperand(0).getReg())
754             .add(Op1);
755         ToErase = &MI;
756         Simplified = true;
757         NumOptADDLIs++;
758         break;
759       }
760       }
761     }
762 
763     // If the last instruction was marked for elimination,
764     // remove it now.
765     if (ToErase) {
766       ToErase->eraseFromParent();
767       ToErase = nullptr;
768     }
769   }
770 
771   // Eliminate all the TOC save instructions which are redundant.
772   Simplified |= eliminateRedundantTOCSaves(TOCSaves);
773   // We try to eliminate redundant compare instruction.
774   Simplified |= eliminateRedundantCompare();
775 
776   return Simplified;
777 }
778 
779 // helper functions for eliminateRedundantCompare
780 static bool isEqOrNe(MachineInstr *BI) {
781   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
782   unsigned PredCond = PPC::getPredicateCondition(Pred);
783   return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
784 }
785 
786 static bool isSupportedCmpOp(unsigned opCode) {
787   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD  ||
788           opCode == PPC::CMPLW  || opCode == PPC::CMPW  ||
789           opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
790           opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
791 }
792 
793 static bool is64bitCmpOp(unsigned opCode) {
794   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD ||
795           opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
796 }
797 
798 static bool isSignedCmpOp(unsigned opCode) {
799   return (opCode == PPC::CMPD  || opCode == PPC::CMPW ||
800           opCode == PPC::CMPDI || opCode == PPC::CMPWI);
801 }
802 
803 static unsigned getSignedCmpOpCode(unsigned opCode) {
804   if (opCode == PPC::CMPLD)  return PPC::CMPD;
805   if (opCode == PPC::CMPLW)  return PPC::CMPW;
806   if (opCode == PPC::CMPLDI) return PPC::CMPDI;
807   if (opCode == PPC::CMPLWI) return PPC::CMPWI;
808   return opCode;
809 }
810 
811 // We can decrement immediate x in (GE x) by changing it to (GT x-1) or
812 // (LT x) to (LE x-1)
813 static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
814   uint64_t Imm = CMPI->getOperand(2).getImm();
815   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
816   if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
817     return 0;
818 
819   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
820   unsigned PredCond = PPC::getPredicateCondition(Pred);
821   unsigned PredHint = PPC::getPredicateHint(Pred);
822   if (PredCond == PPC::PRED_GE)
823     return PPC::getPredicate(PPC::PRED_GT, PredHint);
824   if (PredCond == PPC::PRED_LT)
825     return PPC::getPredicate(PPC::PRED_LE, PredHint);
826 
827   return 0;
828 }
829 
830 // We can increment immediate x in (GT x) by changing it to (GE x+1) or
831 // (LE x) to (LT x+1)
832 static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
833   uint64_t Imm = CMPI->getOperand(2).getImm();
834   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
835   if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
836     return 0;
837 
838   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
839   unsigned PredCond = PPC::getPredicateCondition(Pred);
840   unsigned PredHint = PPC::getPredicateHint(Pred);
841   if (PredCond == PPC::PRED_GT)
842     return PPC::getPredicate(PPC::PRED_GE, PredHint);
843   if (PredCond == PPC::PRED_LE)
844     return PPC::getPredicate(PPC::PRED_LT, PredHint);
845 
846   return 0;
847 }
848 
849 // This takes a Phi node and returns a register value for the specified BB.
850 static unsigned getIncomingRegForBlock(MachineInstr *Phi,
851                                        MachineBasicBlock *MBB) {
852   for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
853     MachineOperand &MO = Phi->getOperand(I);
854     if (MO.getMBB() == MBB)
855       return Phi->getOperand(I-1).getReg();
856   }
857   llvm_unreachable("invalid src basic block for this Phi node\n");
858   return 0;
859 }
860 
861 // This function tracks the source of the register through register copy.
862 // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
863 // assuming that the control comes from BB1 into BB2.
864 static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
865                            MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
866   unsigned SrcReg = Reg;
867   while (1) {
868     unsigned NextReg = SrcReg;
869     MachineInstr *Inst = MRI->getVRegDef(SrcReg);
870     if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
871       NextReg = getIncomingRegForBlock(Inst, BB1);
872       // We track through PHI only once to avoid infinite loop.
873       BB1 = nullptr;
874     }
875     else if (Inst->isFullCopy())
876       NextReg = Inst->getOperand(1).getReg();
877     if (NextReg == SrcReg || !TargetRegisterInfo::isVirtualRegister(NextReg))
878       break;
879     SrcReg = NextReg;
880   }
881   return SrcReg;
882 }
883 
884 static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
885                                           MachineBasicBlock *&PredMBB,
886                                           MachineBasicBlock *&MBBtoMoveCmp,
887                                           MachineRegisterInfo *MRI) {
888 
889   auto isEligibleBB = [&](MachineBasicBlock &BB) {
890     auto BII = BB.getFirstInstrTerminator();
891     // We optimize BBs ending with a conditional branch.
892     // We check only for BCC here, not BCCLR, because BCCLR
893     // will be formed only later in the pipeline.
894     if (BB.succ_size() == 2 &&
895         BII != BB.instr_end() &&
896         (*BII).getOpcode() == PPC::BCC &&
897         (*BII).getOperand(1).isReg()) {
898       // We optimize only if the condition code is used only by one BCC.
899       unsigned CndReg = (*BII).getOperand(1).getReg();
900       if (!TargetRegisterInfo::isVirtualRegister(CndReg) ||
901           !MRI->hasOneNonDBGUse(CndReg))
902         return false;
903 
904       MachineInstr *CMPI = MRI->getVRegDef(CndReg);
905       // We assume compare and branch are in the same BB for ease of analysis.
906       if (CMPI->getParent() != &BB)
907         return false;
908 
909       // We skip this BB if a physical register is used in comparison.
910       for (MachineOperand &MO : CMPI->operands())
911         if (MO.isReg() && !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
912           return false;
913 
914       return true;
915     }
916     return false;
917   };
918 
919   // If this BB has more than one successor, we can create a new BB and
920   // move the compare instruction in the new BB.
921   // So far, we do not move compare instruction to a BB having multiple
922   // successors to avoid potentially increasing code size.
923   auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
924     return BB.succ_size() == 1;
925   };
926 
927   if (!isEligibleBB(MBB))
928     return false;
929 
930   unsigned NumPredBBs = MBB.pred_size();
931   if (NumPredBBs == 1) {
932     MachineBasicBlock *TmpMBB = *MBB.pred_begin();
933     if (isEligibleBB(*TmpMBB)) {
934       PredMBB = TmpMBB;
935       MBBtoMoveCmp = nullptr;
936       return true;
937     }
938   }
939   else if (NumPredBBs == 2) {
940     // We check for partially redundant case.
941     // So far, we support cases with only two predecessors
942     // to avoid increasing the number of instructions.
943     MachineBasicBlock::pred_iterator PI = MBB.pred_begin();
944     MachineBasicBlock *Pred1MBB = *PI;
945     MachineBasicBlock *Pred2MBB = *(PI+1);
946 
947     if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
948       // We assume Pred1MBB is the BB containing the compare to be merged and
949       // Pred2MBB is the BB to which we will append a compare instruction.
950       // Hence we can proceed as is.
951     }
952     else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
953       // We need to swap Pred1MBB and Pred2MBB to canonicalize.
954       std::swap(Pred1MBB, Pred2MBB);
955     }
956     else return false;
957 
958     // Here, Pred2MBB is the BB to which we need to append a compare inst.
959     // We cannot move the compare instruction if operands are not available
960     // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
961     MachineInstr *BI = &*MBB.getFirstInstrTerminator();
962     MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
963     for (int I = 1; I <= 2; I++)
964       if (CMPI->getOperand(I).isReg()) {
965         MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
966         if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
967           return false;
968       }
969 
970     PredMBB = Pred1MBB;
971     MBBtoMoveCmp = Pred2MBB;
972     return true;
973   }
974 
975   return false;
976 }
977 
978 // This function will iterate over the input map containing a pair of TOC save
979 // instruction and a flag. The flag will be set to false if the TOC save is
980 // proven redundant. This function will erase from the basic block all the TOC
981 // saves marked as redundant.
982 bool PPCMIPeephole::eliminateRedundantTOCSaves(
983     std::map<MachineInstr *, bool> &TOCSaves) {
984   bool Simplified = false;
985   int NumKept = 0;
986   for (auto TOCSave : TOCSaves) {
987     if (!TOCSave.second) {
988       TOCSave.first->eraseFromParent();
989       RemoveTOCSave++;
990       Simplified = true;
991     } else {
992       NumKept++;
993     }
994   }
995 
996   if (NumKept > 1)
997     MultiTOCSaves++;
998 
999   return Simplified;
1000 }
1001 
1002 // If multiple conditional branches are executed based on the (essentially)
1003 // same comparison, we merge compare instructions into one and make multiple
1004 // conditional branches on this comparison.
1005 // For example,
1006 //   if (a == 0) { ... }
1007 //   else if (a < 0) { ... }
1008 // can be executed by one compare and two conditional branches instead of
1009 // two pairs of a compare and a conditional branch.
1010 //
1011 // This method merges two compare instructions in two MBBs and modifies the
1012 // compare and conditional branch instructions if needed.
1013 // For the above example, the input for this pass looks like:
1014 //   cmplwi r3, 0
1015 //   beq    0, .LBB0_3
1016 //   cmpwi  r3, -1
1017 //   bgt    0, .LBB0_4
1018 // So, before merging two compares, we need to modify these instructions as
1019 //   cmpwi  r3, 0       ; cmplwi and cmpwi yield same result for beq
1020 //   beq    0, .LBB0_3
1021 //   cmpwi  r3, 0       ; greather than -1 means greater or equal to 0
1022 //   bge    0, .LBB0_4
1023 
1024 bool PPCMIPeephole::eliminateRedundantCompare(void) {
1025   bool Simplified = false;
1026 
1027   for (MachineBasicBlock &MBB2 : *MF) {
1028     MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
1029 
1030     // For fully redundant case, we select two basic blocks MBB1 and MBB2
1031     // as an optimization target if
1032     // - both MBBs end with a conditional branch,
1033     // - MBB1 is the only predecessor of MBB2, and
1034     // - compare does not take a physical register as a operand in both MBBs.
1035     // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
1036     //
1037     // As partially redundant case, we additionally handle if MBB2 has one
1038     // additional predecessor, which has only one successor (MBB2).
1039     // In this case, we move the compare instruction originally in MBB2 into
1040     // MBBtoMoveCmp. This partially redundant case is typically appear by
1041     // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
1042     //
1043     // Overview of CFG of related basic blocks
1044     // Fully redundant case        Partially redundant case
1045     //   --------                   ----------------  --------
1046     //   | MBB1 | (w/ 2 succ)       | MBBtoMoveCmp |  | MBB1 | (w/ 2 succ)
1047     //   --------                   ----------------  --------
1048     //      |    \                     (w/ 1 succ) \     |    \
1049     //      |     \                                 \    |     \
1050     //      |                                        \   |
1051     //   --------                                     --------
1052     //   | MBB2 | (w/ 1 pred                          | MBB2 | (w/ 2 pred
1053     //   -------- and 2 succ)                         -------- and 2 succ)
1054     //      |    \                                       |    \
1055     //      |     \                                      |     \
1056     //
1057     if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
1058       continue;
1059 
1060     MachineInstr *BI1   = &*MBB1->getFirstInstrTerminator();
1061     MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
1062 
1063     MachineInstr *BI2   = &*MBB2.getFirstInstrTerminator();
1064     MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
1065     bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
1066 
1067     // We cannot optimize an unsupported compare opcode or
1068     // a mix of 32-bit and 64-bit comaprisons
1069     if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
1070         !isSupportedCmpOp(CMPI2->getOpcode()) ||
1071         is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
1072       continue;
1073 
1074     unsigned NewOpCode = 0;
1075     unsigned NewPredicate1 = 0, NewPredicate2 = 0;
1076     int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
1077     bool SwapOperands = false;
1078 
1079     if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
1080       // Typically, unsigned comparison is used for equality check, but
1081       // we replace it with a signed comparison if the comparison
1082       // to be merged is a signed comparison.
1083       // In other cases of opcode mismatch, we cannot optimize this.
1084 
1085       // We cannot change opcode when comparing against an immediate
1086       // if the most significant bit of the immediate is one
1087       // due to the difference in sign extension.
1088       auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
1089         if (!I->getOperand(2).isImm())
1090           return false;
1091         int16_t Imm = (int16_t)I->getOperand(2).getImm();
1092         return Imm < 0;
1093       };
1094 
1095       if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
1096           CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
1097         NewOpCode = CMPI1->getOpcode();
1098       else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
1099                getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
1100         NewOpCode = CMPI2->getOpcode();
1101       else continue;
1102     }
1103 
1104     if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
1105       // In case of comparisons between two registers, these two registers
1106       // must be same to merge two comparisons.
1107       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1108                                          nullptr, nullptr, MRI);
1109       unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
1110                                          nullptr, nullptr, MRI);
1111       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1112                                          MBB1, &MBB2, MRI);
1113       unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
1114                                          MBB1, &MBB2, MRI);
1115 
1116       if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
1117         // Same pair of registers in the same order; ready to merge as is.
1118       }
1119       else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
1120         // Same pair of registers in different order.
1121         // We reverse the predicate to merge compare instructions.
1122         PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm();
1123         NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
1124         // In case of partial redundancy, we need to swap operands
1125         // in another compare instruction.
1126         SwapOperands = true;
1127       }
1128       else continue;
1129     }
1130     else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
1131       // In case of comparisons between a register and an immediate,
1132       // the operand register must be same for two compare instructions.
1133       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1134                                          nullptr, nullptr, MRI);
1135       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1136                                          MBB1, &MBB2, MRI);
1137       if (Cmp1Operand1 != Cmp2Operand1)
1138         continue;
1139 
1140       NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
1141       NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
1142 
1143       // If immediate are not same, we try to adjust by changing predicate;
1144       // e.g. GT imm means GE (imm+1).
1145       if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
1146         int Diff = Imm1 - Imm2;
1147         if (Diff < -2 || Diff > 2)
1148           continue;
1149 
1150         unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
1151         unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
1152         unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
1153         unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
1154         if (Diff == 2) {
1155           if (PredToInc2 && PredToDec1) {
1156             NewPredicate2 = PredToInc2;
1157             NewPredicate1 = PredToDec1;
1158             NewImm2++;
1159             NewImm1--;
1160           }
1161         }
1162         else if (Diff == 1) {
1163           if (PredToInc2) {
1164             NewImm2++;
1165             NewPredicate2 = PredToInc2;
1166           }
1167           else if (PredToDec1) {
1168             NewImm1--;
1169             NewPredicate1 = PredToDec1;
1170           }
1171         }
1172         else if (Diff == -1) {
1173           if (PredToDec2) {
1174             NewImm2--;
1175             NewPredicate2 = PredToDec2;
1176           }
1177           else if (PredToInc1) {
1178             NewImm1++;
1179             NewPredicate1 = PredToInc1;
1180           }
1181         }
1182         else if (Diff == -2) {
1183           if (PredToDec2 && PredToInc1) {
1184             NewPredicate2 = PredToDec2;
1185             NewPredicate1 = PredToInc1;
1186             NewImm2--;
1187             NewImm1++;
1188           }
1189         }
1190       }
1191 
1192       // We cannot merge two compares if the immediates are not same.
1193       if (NewImm2 != NewImm1)
1194         continue;
1195     }
1196 
1197     LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
1198     LLVM_DEBUG(CMPI1->dump());
1199     LLVM_DEBUG(BI1->dump());
1200     LLVM_DEBUG(CMPI2->dump());
1201     LLVM_DEBUG(BI2->dump());
1202 
1203     // We adjust opcode, predicates and immediate as we determined above.
1204     if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
1205       CMPI1->setDesc(TII->get(NewOpCode));
1206     }
1207     if (NewPredicate1) {
1208       BI1->getOperand(0).setImm(NewPredicate1);
1209     }
1210     if (NewPredicate2) {
1211       BI2->getOperand(0).setImm(NewPredicate2);
1212     }
1213     if (NewImm1 != Imm1) {
1214       CMPI1->getOperand(2).setImm(NewImm1);
1215     }
1216 
1217     if (IsPartiallyRedundant) {
1218       // We touch up the compare instruction in MBB2 and move it to
1219       // a previous BB to handle partially redundant case.
1220       if (SwapOperands) {
1221         unsigned Op1 = CMPI2->getOperand(1).getReg();
1222         unsigned Op2 = CMPI2->getOperand(2).getReg();
1223         CMPI2->getOperand(1).setReg(Op2);
1224         CMPI2->getOperand(2).setReg(Op1);
1225       }
1226       if (NewImm2 != Imm2)
1227         CMPI2->getOperand(2).setImm(NewImm2);
1228 
1229       for (int I = 1; I <= 2; I++) {
1230         if (CMPI2->getOperand(I).isReg()) {
1231           MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
1232           if (Inst->getParent() != &MBB2)
1233             continue;
1234 
1235           assert(Inst->getOpcode() == PPC::PHI &&
1236                  "We cannot support if an operand comes from this BB.");
1237           unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
1238           CMPI2->getOperand(I).setReg(SrcReg);
1239         }
1240       }
1241       auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
1242       MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
1243 
1244       DebugLoc DL = CMPI2->getDebugLoc();
1245       unsigned NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
1246       BuildMI(MBB2, MBB2.begin(), DL,
1247               TII->get(PPC::PHI), NewVReg)
1248         .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
1249         .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
1250       BI2->getOperand(1).setReg(NewVReg);
1251     }
1252     else {
1253       // We finally eliminate compare instruction in MBB2.
1254       BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
1255       CMPI2->eraseFromParent();
1256     }
1257     BI2->getOperand(1).setIsKill(true);
1258     BI1->getOperand(1).setIsKill(false);
1259 
1260     LLVM_DEBUG(dbgs() << "into a compare and two branches:\n");
1261     LLVM_DEBUG(CMPI1->dump());
1262     LLVM_DEBUG(BI1->dump());
1263     LLVM_DEBUG(BI2->dump());
1264     if (IsPartiallyRedundant) {
1265       LLVM_DEBUG(dbgs() << "The following compare is moved into "
1266                         << printMBBReference(*MBBtoMoveCmp)
1267                         << " to handle partial redundancy.\n");
1268       LLVM_DEBUG(CMPI2->dump());
1269     }
1270 
1271     Simplified = true;
1272   }
1273 
1274   return Simplified;
1275 }
1276 
1277 } // end default namespace
1278 
1279 INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
1280                       "PowerPC MI Peephole Optimization", false, false)
1281 INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
1282                     "PowerPC MI Peephole Optimization", false, false)
1283 
1284 char PPCMIPeephole::ID = 0;
1285 FunctionPass*
1286 llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
1287 
1288