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