xref: /llvm-project/llvm/lib/Target/PowerPC/PPCMIPeephole.cpp (revision 14d656b3d8057c4f8fa5901ad92d80b3a04fd545)
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   MachineInstr* ToErase = nullptr;
382   std::map<MachineInstr *, bool> TOCSaves;
383   const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
384   NumFunctionsEnteredInMIPeephole++;
385   if (ConvertRegReg) {
386     // Fixed-point conversion of reg/reg instructions fed by load-immediate
387     // into reg/imm instructions. FIXME: This is expensive, control it with
388     // an option.
389     bool SomethingChanged = false;
390     do {
391       NumFixedPointIterations++;
392       SomethingChanged = false;
393       for (MachineBasicBlock &MBB : *MF) {
394         for (MachineInstr &MI : MBB) {
395           if (MI.isDebugInstr())
396             continue;
397 
398           if (TII->convertToImmediateForm(MI)) {
399             // We don't erase anything in case the def has other uses. Let DCE
400             // remove it if it can be removed.
401             LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
402             LLVM_DEBUG(MI.dump());
403             NumConvertedToImmediateForm++;
404             SomethingChanged = true;
405             Simplified = true;
406             continue;
407           }
408         }
409       }
410     } while (SomethingChanged && FixedPointRegToImm);
411   }
412 
413   for (MachineBasicBlock &MBB : *MF) {
414     for (MachineInstr &MI : MBB) {
415 
416       // If the previous instruction was marked for elimination,
417       // remove it now.
418       if (ToErase) {
419         ToErase->eraseFromParent();
420         ToErase = nullptr;
421       }
422 
423       // Ignore debug instructions.
424       if (MI.isDebugInstr())
425         continue;
426 
427       // Per-opcode peepholes.
428       switch (MI.getOpcode()) {
429 
430       default:
431         break;
432       case PPC::COPY: {
433         Register Src = MI.getOperand(1).getReg();
434         Register Dst = MI.getOperand(0).getReg();
435         if (!Register::isVirtualRegister(Src) ||
436             !Register::isVirtualRegister(Dst))
437           break;
438         if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass ||
439             MRI->getRegClass(Dst) != &PPC::ACCRCRegClass)
440           break;
441 
442         // We are copying an unprimed accumulator to a primed accumulator.
443         // If the input to the copy is a PHI that is fed only by (i) copies in
444         // the other direction (ii) implicitly defined unprimed accumulators or
445         // (iii) other PHI nodes satisfying (i) and (ii), we can change
446         // the PHI to a PHI on primed accumulators (as long as we also change
447         // its operands). To detect and change such copies, we first get a list
448         // of all the PHI nodes starting from the root PHI node in BFS order.
449         // We then visit all these PHI nodes to check if they can be changed to
450         // primed accumulator PHI nodes and if so, we change them.
451         MachineInstr *RootPHI = MRI->getVRegDef(Src);
452         if (RootPHI->getOpcode() != PPC::PHI)
453           break;
454 
455         SmallVector<MachineInstr *, 4> PHIs;
456         if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs))
457           break;
458 
459         convertUnprimedAccPHIs(TII, MRI, PHIs, Dst);
460 
461         ToErase = &MI;
462         break;
463       }
464       case PPC::LI:
465       case PPC::LI8: {
466         // If we are materializing a zero, look for any use operands for which
467         // zero means immediate zero. All such operands can be replaced with
468         // PPC::ZERO.
469         if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0)
470           break;
471         unsigned MIDestReg = MI.getOperand(0).getReg();
472         for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg))
473           Simplified |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg);
474         if (MRI->use_nodbg_empty(MIDestReg)) {
475           ++NumLoadImmZeroFoldedAndRemoved;
476           ToErase = &MI;
477         }
478         break;
479       }
480       case PPC::STW:
481       case PPC::STD: {
482         MachineFrameInfo &MFI = MF->getFrameInfo();
483         if (MFI.hasVarSizedObjects() ||
484             (!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() &&
485              !MF->getSubtarget<PPCSubtarget>().isAIXABI()))
486           break;
487         // When encountering a TOC save instruction, call UpdateTOCSaves
488         // to add it to the TOCSaves map and mark any existing TOC saves
489         // it dominates as redundant.
490         if (TII->isTOCSaveMI(MI))
491           UpdateTOCSaves(TOCSaves, &MI);
492         break;
493       }
494       case PPC::XXPERMDI: {
495         // Perform simplifications of 2x64 vector swaps and splats.
496         // A swap is identified by an immediate value of 2, and a splat
497         // is identified by an immediate value of 0 or 3.
498         int Immed = MI.getOperand(3).getImm();
499 
500         if (Immed == 1)
501           break;
502 
503         // For each of these simplifications, we need the two source
504         // regs to match.  Unfortunately, MachineCSE ignores COPY and
505         // SUBREG_TO_REG, so for example we can see
506         //   XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed.
507         // We have to look through chains of COPY and SUBREG_TO_REG
508         // to find the real source values for comparison.
509         unsigned TrueReg1 =
510           TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
511         unsigned TrueReg2 =
512           TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI);
513 
514         if (!(TrueReg1 == TrueReg2 && Register::isVirtualRegister(TrueReg1)))
515           break;
516 
517         MachineInstr *DefMI = MRI->getVRegDef(TrueReg1);
518 
519         if (!DefMI)
520           break;
521 
522         unsigned DefOpc = DefMI->getOpcode();
523 
524         // If this is a splat fed by a splatting load, the splat is
525         // redundant. Replace with a copy. This doesn't happen directly due
526         // to code in PPCDAGToDAGISel.cpp, but it can happen when converting
527         // a load of a double to a vector of 64-bit integers.
528         auto isConversionOfLoadAndSplat = [=]() -> bool {
529           if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS)
530             return false;
531           unsigned FeedReg1 =
532             TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
533           if (Register::isVirtualRegister(FeedReg1)) {
534             MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1);
535             if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX)
536               return true;
537           }
538           return false;
539         };
540         if ((Immed == 0 || Immed == 3) &&
541             (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) {
542           LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat "
543                                "to load-and-splat/copy: ");
544           LLVM_DEBUG(MI.dump());
545           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
546                   MI.getOperand(0).getReg())
547               .add(MI.getOperand(1));
548           ToErase = &MI;
549           Simplified = true;
550         }
551 
552         // If this is a splat or a swap fed by another splat, we
553         // can replace it with a copy.
554         if (DefOpc == PPC::XXPERMDI) {
555           unsigned DefReg1 = DefMI->getOperand(1).getReg();
556           unsigned DefReg2 = DefMI->getOperand(2).getReg();
557           unsigned DefImmed = DefMI->getOperand(3).getImm();
558 
559           // If the two inputs are not the same register, check to see if
560           // they originate from the same virtual register after only
561           // copy-like instructions.
562           if (DefReg1 != DefReg2) {
563             unsigned FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI);
564             unsigned FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI);
565 
566             if (!(FeedReg1 == FeedReg2 &&
567                   Register::isVirtualRegister(FeedReg1)))
568               break;
569           }
570 
571           if (DefImmed == 0 || DefImmed == 3) {
572             LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat "
573                                  "to splat/copy: ");
574             LLVM_DEBUG(MI.dump());
575             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
576                     MI.getOperand(0).getReg())
577                 .add(MI.getOperand(1));
578             ToErase = &MI;
579             Simplified = true;
580           }
581 
582           // If this is a splat fed by a swap, we can simplify modify
583           // the splat to splat the other value from the swap's input
584           // parameter.
585           else if ((Immed == 0 || Immed == 3) && DefImmed == 2) {
586             LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: ");
587             LLVM_DEBUG(MI.dump());
588             MI.getOperand(1).setReg(DefReg1);
589             MI.getOperand(2).setReg(DefReg2);
590             MI.getOperand(3).setImm(3 - Immed);
591             Simplified = true;
592           }
593 
594           // If this is a swap fed by a swap, we can replace it
595           // with a copy from the first swap's input.
596           else if (Immed == 2 && DefImmed == 2) {
597             LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: ");
598             LLVM_DEBUG(MI.dump());
599             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
600                     MI.getOperand(0).getReg())
601                 .add(DefMI->getOperand(1));
602             ToErase = &MI;
603             Simplified = true;
604           }
605         } else if ((Immed == 0 || Immed == 3 || Immed == 2) &&
606                    DefOpc == PPC::XXPERMDIs &&
607                    (DefMI->getOperand(2).getImm() == 0 ||
608                     DefMI->getOperand(2).getImm() == 3)) {
609           ToErase = &MI;
610           Simplified = true;
611           // Swap of a splat, convert to copy.
612           if (Immed == 2) {
613             LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): ");
614             LLVM_DEBUG(MI.dump());
615             BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
616                     MI.getOperand(0).getReg())
617                 .add(MI.getOperand(1));
618             break;
619           }
620           // Splat fed by another splat - switch the output of the first
621           // and remove the second.
622           DefMI->getOperand(0).setReg(MI.getOperand(0).getReg());
623           LLVM_DEBUG(dbgs() << "Removing redundant splat: ");
624           LLVM_DEBUG(MI.dump());
625         }
626         break;
627       }
628       case PPC::VSPLTB:
629       case PPC::VSPLTH:
630       case PPC::XXSPLTW: {
631         unsigned MyOpcode = MI.getOpcode();
632         unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2;
633         unsigned TrueReg =
634           TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI);
635         if (!Register::isVirtualRegister(TrueReg))
636           break;
637         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
638         if (!DefMI)
639           break;
640         unsigned DefOpcode = DefMI->getOpcode();
641         auto isConvertOfSplat = [=]() -> bool {
642           if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS)
643             return false;
644           Register ConvReg = DefMI->getOperand(1).getReg();
645           if (!Register::isVirtualRegister(ConvReg))
646             return false;
647           MachineInstr *Splt = MRI->getVRegDef(ConvReg);
648           return Splt && (Splt->getOpcode() == PPC::LXVWSX ||
649             Splt->getOpcode() == PPC::XXSPLTW);
650         };
651         bool AlreadySplat = (MyOpcode == DefOpcode) ||
652           (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) ||
653           (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) ||
654           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) ||
655           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) ||
656           (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)||
657           (MyOpcode == PPC::XXSPLTW && isConvertOfSplat());
658         // If the instruction[s] that feed this splat have already splat
659         // the value, this splat is redundant.
660         if (AlreadySplat) {
661           LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: ");
662           LLVM_DEBUG(MI.dump());
663           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
664                   MI.getOperand(0).getReg())
665               .add(MI.getOperand(OpNo));
666           ToErase = &MI;
667           Simplified = true;
668         }
669         // Splat fed by a shift. Usually when we align value to splat into
670         // vector element zero.
671         if (DefOpcode == PPC::XXSLDWI) {
672           Register ShiftRes = DefMI->getOperand(0).getReg();
673           Register ShiftOp1 = DefMI->getOperand(1).getReg();
674           Register ShiftOp2 = DefMI->getOperand(2).getReg();
675           unsigned ShiftImm = DefMI->getOperand(3).getImm();
676           unsigned SplatImm =
677               MI.getOperand(MyOpcode == PPC::XXSPLTW ? 2 : 1).getImm();
678           if (ShiftOp1 == ShiftOp2) {
679             unsigned NewElem = (SplatImm + ShiftImm) & 0x3;
680             if (MRI->hasOneNonDBGUse(ShiftRes)) {
681               LLVM_DEBUG(dbgs() << "Removing redundant shift: ");
682               LLVM_DEBUG(DefMI->dump());
683               ToErase = DefMI;
684             }
685             Simplified = true;
686             LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm
687                               << " to " << NewElem << " in instruction: ");
688             LLVM_DEBUG(MI.dump());
689             MI.getOperand(1).setReg(ShiftOp1);
690             MI.getOperand(2).setImm(NewElem);
691           }
692         }
693         break;
694       }
695       case PPC::XVCVDPSP: {
696         // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant.
697         unsigned TrueReg =
698           TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI);
699         if (!Register::isVirtualRegister(TrueReg))
700           break;
701         MachineInstr *DefMI = MRI->getVRegDef(TrueReg);
702 
703         // This can occur when building a vector of single precision or integer
704         // values.
705         if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) {
706           unsigned DefsReg1 =
707             TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI);
708           unsigned DefsReg2 =
709             TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI);
710           if (!Register::isVirtualRegister(DefsReg1) ||
711               !Register::isVirtualRegister(DefsReg2))
712             break;
713           MachineInstr *P1 = MRI->getVRegDef(DefsReg1);
714           MachineInstr *P2 = MRI->getVRegDef(DefsReg2);
715 
716           if (!P1 || !P2)
717             break;
718 
719           // Remove the passed FRSP/XSRSP instruction if it only feeds this MI
720           // and set any uses of that FRSP/XSRSP (in this MI) to the source of
721           // the FRSP/XSRSP.
722           auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) {
723             unsigned Opc = RoundInstr->getOpcode();
724             if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) &&
725                 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) {
726               Simplified = true;
727               Register ConvReg1 = RoundInstr->getOperand(1).getReg();
728               Register FRSPDefines = RoundInstr->getOperand(0).getReg();
729               MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines));
730               for (int i = 0, e = Use.getNumOperands(); i < e; ++i)
731                 if (Use.getOperand(i).isReg() &&
732                     Use.getOperand(i).getReg() == FRSPDefines)
733                   Use.getOperand(i).setReg(ConvReg1);
734               LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n");
735               LLVM_DEBUG(RoundInstr->dump());
736               LLVM_DEBUG(dbgs() << "As it feeds instruction:\n");
737               LLVM_DEBUG(MI.dump());
738               LLVM_DEBUG(dbgs() << "Through instruction:\n");
739               LLVM_DEBUG(DefMI->dump());
740               RoundInstr->eraseFromParent();
741             }
742           };
743 
744           // If the input to XVCVDPSP is a vector that was built (even
745           // partially) out of FRSP's, the FRSP(s) can safely be removed
746           // since this instruction performs the same operation.
747           if (P1 != P2) {
748             removeFRSPIfPossible(P1);
749             removeFRSPIfPossible(P2);
750             break;
751           }
752           removeFRSPIfPossible(P1);
753         }
754         break;
755       }
756       case PPC::EXTSH:
757       case PPC::EXTSH8:
758       case PPC::EXTSH8_32_64: {
759         if (!EnableSExtElimination) break;
760         Register NarrowReg = MI.getOperand(1).getReg();
761         if (!Register::isVirtualRegister(NarrowReg))
762           break;
763 
764         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
765         // If we've used a zero-extending load that we will sign-extend,
766         // just do a sign-extending load.
767         if (SrcMI->getOpcode() == PPC::LHZ ||
768             SrcMI->getOpcode() == PPC::LHZX) {
769           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
770             break;
771           auto is64Bit = [] (unsigned Opcode) {
772             return Opcode == PPC::EXTSH8;
773           };
774           auto isXForm = [] (unsigned Opcode) {
775             return Opcode == PPC::LHZX;
776           };
777           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
778             if (is64Bit)
779               if (isXForm) return PPC::LHAX8;
780               else         return PPC::LHA8;
781             else
782               if (isXForm) return PPC::LHAX;
783               else         return PPC::LHA;
784           };
785           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
786                                        isXForm(SrcMI->getOpcode()));
787           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
788           LLVM_DEBUG(SrcMI->dump());
789           LLVM_DEBUG(dbgs() << "and sign-extension\n");
790           LLVM_DEBUG(MI.dump());
791           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
792           SrcMI->setDesc(TII->get(Opc));
793           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
794           ToErase = &MI;
795           Simplified = true;
796           NumEliminatedSExt++;
797         }
798         break;
799       }
800       case PPC::EXTSW:
801       case PPC::EXTSW_32:
802       case PPC::EXTSW_32_64: {
803         if (!EnableSExtElimination) break;
804         Register NarrowReg = MI.getOperand(1).getReg();
805         if (!Register::isVirtualRegister(NarrowReg))
806           break;
807 
808         MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg);
809         // If we've used a zero-extending load that we will sign-extend,
810         // just do a sign-extending load.
811         if (SrcMI->getOpcode() == PPC::LWZ ||
812             SrcMI->getOpcode() == PPC::LWZX) {
813           if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg()))
814             break;
815           auto is64Bit = [] (unsigned Opcode) {
816             return Opcode == PPC::EXTSW || Opcode == PPC::EXTSW_32_64;
817           };
818           auto isXForm = [] (unsigned Opcode) {
819             return Opcode == PPC::LWZX;
820           };
821           auto getSextLoadOp = [] (bool is64Bit, bool isXForm) {
822             if (is64Bit)
823               if (isXForm) return PPC::LWAX;
824               else         return PPC::LWA;
825             else
826               if (isXForm) return PPC::LWAX_32;
827               else         return PPC::LWA_32;
828           };
829           unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()),
830                                        isXForm(SrcMI->getOpcode()));
831           LLVM_DEBUG(dbgs() << "Zero-extending load\n");
832           LLVM_DEBUG(SrcMI->dump());
833           LLVM_DEBUG(dbgs() << "and sign-extension\n");
834           LLVM_DEBUG(MI.dump());
835           LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n");
836           SrcMI->setDesc(TII->get(Opc));
837           SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg());
838           ToErase = &MI;
839           Simplified = true;
840           NumEliminatedSExt++;
841         } else if (MI.getOpcode() == PPC::EXTSW_32_64 &&
842                    TII->isSignExtended(*SrcMI)) {
843           // We can eliminate EXTSW if the input is known to be already
844           // sign-extended.
845           LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n");
846           Register TmpReg =
847               MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
848           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF),
849                   TmpReg);
850           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG),
851                   MI.getOperand(0).getReg())
852               .addReg(TmpReg)
853               .addReg(NarrowReg)
854               .addImm(PPC::sub_32);
855           ToErase = &MI;
856           Simplified = true;
857           NumEliminatedSExt++;
858         }
859         break;
860       }
861       case PPC::RLDICL: {
862         // We can eliminate RLDICL (e.g. for zero-extension)
863         // if all bits to clear are already zero in the input.
864         // This code assume following code sequence for zero-extension.
865         //   %6 = COPY %5:sub_32; (optional)
866         //   %8 = IMPLICIT_DEF;
867         //   %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32;
868         if (!EnableZExtElimination) break;
869 
870         if (MI.getOperand(2).getImm() != 0)
871           break;
872 
873         Register SrcReg = MI.getOperand(1).getReg();
874         if (!Register::isVirtualRegister(SrcReg))
875           break;
876 
877         MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
878         if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG &&
879               SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg()))
880           break;
881 
882         MachineInstr *ImpDefMI, *SubRegMI;
883         ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg());
884         SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg());
885         if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break;
886 
887         SrcMI = SubRegMI;
888         if (SubRegMI->getOpcode() == PPC::COPY) {
889           Register CopyReg = SubRegMI->getOperand(1).getReg();
890           if (Register::isVirtualRegister(CopyReg))
891             SrcMI = MRI->getVRegDef(CopyReg);
892         }
893 
894         unsigned KnownZeroCount = getKnownLeadingZeroCount(SrcMI, TII);
895         if (MI.getOperand(3).getImm() <= KnownZeroCount) {
896           LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n");
897           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
898                   MI.getOperand(0).getReg())
899               .addReg(SrcReg);
900           ToErase = &MI;
901           Simplified = true;
902           NumEliminatedZExt++;
903         }
904         break;
905       }
906 
907       // TODO: Any instruction that has an immediate form fed only by a PHI
908       // whose operands are all load immediate can be folded away. We currently
909       // do this for ADD instructions, but should expand it to arithmetic and
910       // binary instructions with immediate forms in the future.
911       case PPC::ADD4:
912       case PPC::ADD8: {
913         auto isSingleUsePHI = [&](MachineOperand *PhiOp) {
914           assert(PhiOp && "Invalid Operand!");
915           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
916 
917           return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) &&
918                  MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg());
919         };
920 
921         auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp,
922                                             MachineOperand *PhiOp) {
923           assert(PhiOp && "Invalid Operand!");
924           assert(DominatorOp && "Invalid Operand!");
925           MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI);
926           MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI);
927 
928           // Note: the vregs only show up at odd indices position of PHI Node,
929           // the even indices position save the BB info.
930           for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
931             MachineInstr *LiMI =
932                 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
933             if (!LiMI ||
934                 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8)
935                 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) ||
936                 !MDT->dominates(DefDomMI, LiMI))
937               return false;
938           }
939 
940           return true;
941         };
942 
943         MachineOperand Op1 = MI.getOperand(1);
944         MachineOperand Op2 = MI.getOperand(2);
945         if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2))
946           std::swap(Op1, Op2);
947         else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1))
948           break; // We don't have an ADD fed by LI's that can be transformed
949 
950         // Now we know that Op1 is the PHI node and Op2 is the dominator
951         Register DominatorReg = Op2.getReg();
952 
953         const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8
954                                              ? &PPC::G8RC_and_G8RC_NOX0RegClass
955                                              : &PPC::GPRC_and_GPRC_NOR0RegClass;
956         MRI->setRegClass(DominatorReg, TRC);
957 
958         // replace LIs with ADDIs
959         MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI);
960         for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) {
961           MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI);
962           LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: ");
963           LLVM_DEBUG(LiMI->dump());
964 
965           // There could be repeated registers in the PHI, e.g: %1 =
966           // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've
967           // already replaced the def instruction, skip.
968           if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8)
969             continue;
970 
971           assert((LiMI->getOpcode() == PPC::LI ||
972                   LiMI->getOpcode() == PPC::LI8) &&
973                  "Invalid Opcode!");
974           auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI
975           LiMI->RemoveOperand(1);                    // remove the imm of LI
976           LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI
977                                                               : PPC::ADDI8));
978           MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI)
979               .addReg(DominatorReg)
980               .addImm(LiImm); // restore the imm of LI
981           LLVM_DEBUG(LiMI->dump());
982         }
983 
984         // Replace ADD with COPY
985         LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: ");
986         LLVM_DEBUG(MI.dump());
987         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY),
988                 MI.getOperand(0).getReg())
989             .add(Op1);
990         ToErase = &MI;
991         Simplified = true;
992         NumOptADDLIs++;
993         break;
994       }
995       case PPC::RLDICR: {
996         Simplified |= emitRLDICWhenLoweringJumpTables(MI) ||
997                       combineSEXTAndSHL(MI, ToErase);
998         break;
999       }
1000       case PPC::RLWINM:
1001       case PPC::RLWINM_rec:
1002       case PPC::RLWINM8:
1003       case PPC::RLWINM8_rec: {
1004         Simplified = TII->combineRLWINM(MI, &ToErase);
1005         if (Simplified)
1006           ++NumRotatesCollapsed;
1007         break;
1008       }
1009       }
1010     }
1011 
1012     // If the last instruction was marked for elimination,
1013     // remove it now.
1014     if (ToErase) {
1015       ToErase->eraseFromParent();
1016       ToErase = nullptr;
1017     }
1018   }
1019 
1020   // Eliminate all the TOC save instructions which are redundant.
1021   Simplified |= eliminateRedundantTOCSaves(TOCSaves);
1022   PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
1023   if (FI->mustSaveTOC())
1024     NumTOCSavesInPrologue++;
1025 
1026   // We try to eliminate redundant compare instruction.
1027   Simplified |= eliminateRedundantCompare();
1028 
1029   return Simplified;
1030 }
1031 
1032 // helper functions for eliminateRedundantCompare
1033 static bool isEqOrNe(MachineInstr *BI) {
1034   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1035   unsigned PredCond = PPC::getPredicateCondition(Pred);
1036   return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE);
1037 }
1038 
1039 static bool isSupportedCmpOp(unsigned opCode) {
1040   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD  ||
1041           opCode == PPC::CMPLW  || opCode == PPC::CMPW  ||
1042           opCode == PPC::CMPLDI || opCode == PPC::CMPDI ||
1043           opCode == PPC::CMPLWI || opCode == PPC::CMPWI);
1044 }
1045 
1046 static bool is64bitCmpOp(unsigned opCode) {
1047   return (opCode == PPC::CMPLD  || opCode == PPC::CMPD ||
1048           opCode == PPC::CMPLDI || opCode == PPC::CMPDI);
1049 }
1050 
1051 static bool isSignedCmpOp(unsigned opCode) {
1052   return (opCode == PPC::CMPD  || opCode == PPC::CMPW ||
1053           opCode == PPC::CMPDI || opCode == PPC::CMPWI);
1054 }
1055 
1056 static unsigned getSignedCmpOpCode(unsigned opCode) {
1057   if (opCode == PPC::CMPLD)  return PPC::CMPD;
1058   if (opCode == PPC::CMPLW)  return PPC::CMPW;
1059   if (opCode == PPC::CMPLDI) return PPC::CMPDI;
1060   if (opCode == PPC::CMPLWI) return PPC::CMPWI;
1061   return opCode;
1062 }
1063 
1064 // We can decrement immediate x in (GE x) by changing it to (GT x-1) or
1065 // (LT x) to (LE x-1)
1066 static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) {
1067   uint64_t Imm = CMPI->getOperand(2).getImm();
1068   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1069   if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000))
1070     return 0;
1071 
1072   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1073   unsigned PredCond = PPC::getPredicateCondition(Pred);
1074   unsigned PredHint = PPC::getPredicateHint(Pred);
1075   if (PredCond == PPC::PRED_GE)
1076     return PPC::getPredicate(PPC::PRED_GT, PredHint);
1077   if (PredCond == PPC::PRED_LT)
1078     return PPC::getPredicate(PPC::PRED_LE, PredHint);
1079 
1080   return 0;
1081 }
1082 
1083 // We can increment immediate x in (GT x) by changing it to (GE x+1) or
1084 // (LE x) to (LT x+1)
1085 static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) {
1086   uint64_t Imm = CMPI->getOperand(2).getImm();
1087   bool SignedCmp = isSignedCmpOp(CMPI->getOpcode());
1088   if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF))
1089     return 0;
1090 
1091   PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm();
1092   unsigned PredCond = PPC::getPredicateCondition(Pred);
1093   unsigned PredHint = PPC::getPredicateHint(Pred);
1094   if (PredCond == PPC::PRED_GT)
1095     return PPC::getPredicate(PPC::PRED_GE, PredHint);
1096   if (PredCond == PPC::PRED_LE)
1097     return PPC::getPredicate(PPC::PRED_LT, PredHint);
1098 
1099   return 0;
1100 }
1101 
1102 // This takes a Phi node and returns a register value for the specified BB.
1103 static unsigned getIncomingRegForBlock(MachineInstr *Phi,
1104                                        MachineBasicBlock *MBB) {
1105   for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) {
1106     MachineOperand &MO = Phi->getOperand(I);
1107     if (MO.getMBB() == MBB)
1108       return Phi->getOperand(I-1).getReg();
1109   }
1110   llvm_unreachable("invalid src basic block for this Phi node\n");
1111   return 0;
1112 }
1113 
1114 // This function tracks the source of the register through register copy.
1115 // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2
1116 // assuming that the control comes from BB1 into BB2.
1117 static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1,
1118                            MachineBasicBlock *BB2, MachineRegisterInfo *MRI) {
1119   unsigned SrcReg = Reg;
1120   while (1) {
1121     unsigned NextReg = SrcReg;
1122     MachineInstr *Inst = MRI->getVRegDef(SrcReg);
1123     if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) {
1124       NextReg = getIncomingRegForBlock(Inst, BB1);
1125       // We track through PHI only once to avoid infinite loop.
1126       BB1 = nullptr;
1127     }
1128     else if (Inst->isFullCopy())
1129       NextReg = Inst->getOperand(1).getReg();
1130     if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg))
1131       break;
1132     SrcReg = NextReg;
1133   }
1134   return SrcReg;
1135 }
1136 
1137 static bool eligibleForCompareElimination(MachineBasicBlock &MBB,
1138                                           MachineBasicBlock *&PredMBB,
1139                                           MachineBasicBlock *&MBBtoMoveCmp,
1140                                           MachineRegisterInfo *MRI) {
1141 
1142   auto isEligibleBB = [&](MachineBasicBlock &BB) {
1143     auto BII = BB.getFirstInstrTerminator();
1144     // We optimize BBs ending with a conditional branch.
1145     // We check only for BCC here, not BCCLR, because BCCLR
1146     // will be formed only later in the pipeline.
1147     if (BB.succ_size() == 2 &&
1148         BII != BB.instr_end() &&
1149         (*BII).getOpcode() == PPC::BCC &&
1150         (*BII).getOperand(1).isReg()) {
1151       // We optimize only if the condition code is used only by one BCC.
1152       Register CndReg = (*BII).getOperand(1).getReg();
1153       if (!Register::isVirtualRegister(CndReg) || !MRI->hasOneNonDBGUse(CndReg))
1154         return false;
1155 
1156       MachineInstr *CMPI = MRI->getVRegDef(CndReg);
1157       // We assume compare and branch are in the same BB for ease of analysis.
1158       if (CMPI->getParent() != &BB)
1159         return false;
1160 
1161       // We skip this BB if a physical register is used in comparison.
1162       for (MachineOperand &MO : CMPI->operands())
1163         if (MO.isReg() && !Register::isVirtualRegister(MO.getReg()))
1164           return false;
1165 
1166       return true;
1167     }
1168     return false;
1169   };
1170 
1171   // If this BB has more than one successor, we can create a new BB and
1172   // move the compare instruction in the new BB.
1173   // So far, we do not move compare instruction to a BB having multiple
1174   // successors to avoid potentially increasing code size.
1175   auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) {
1176     return BB.succ_size() == 1;
1177   };
1178 
1179   if (!isEligibleBB(MBB))
1180     return false;
1181 
1182   unsigned NumPredBBs = MBB.pred_size();
1183   if (NumPredBBs == 1) {
1184     MachineBasicBlock *TmpMBB = *MBB.pred_begin();
1185     if (isEligibleBB(*TmpMBB)) {
1186       PredMBB = TmpMBB;
1187       MBBtoMoveCmp = nullptr;
1188       return true;
1189     }
1190   }
1191   else if (NumPredBBs == 2) {
1192     // We check for partially redundant case.
1193     // So far, we support cases with only two predecessors
1194     // to avoid increasing the number of instructions.
1195     MachineBasicBlock::pred_iterator PI = MBB.pred_begin();
1196     MachineBasicBlock *Pred1MBB = *PI;
1197     MachineBasicBlock *Pred2MBB = *(PI+1);
1198 
1199     if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) {
1200       // We assume Pred1MBB is the BB containing the compare to be merged and
1201       // Pred2MBB is the BB to which we will append a compare instruction.
1202       // Hence we can proceed as is.
1203     }
1204     else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) {
1205       // We need to swap Pred1MBB and Pred2MBB to canonicalize.
1206       std::swap(Pred1MBB, Pred2MBB);
1207     }
1208     else return false;
1209 
1210     // Here, Pred2MBB is the BB to which we need to append a compare inst.
1211     // We cannot move the compare instruction if operands are not available
1212     // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI).
1213     MachineInstr *BI = &*MBB.getFirstInstrTerminator();
1214     MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg());
1215     for (int I = 1; I <= 2; I++)
1216       if (CMPI->getOperand(I).isReg()) {
1217         MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg());
1218         if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI)
1219           return false;
1220       }
1221 
1222     PredMBB = Pred1MBB;
1223     MBBtoMoveCmp = Pred2MBB;
1224     return true;
1225   }
1226 
1227   return false;
1228 }
1229 
1230 // This function will iterate over the input map containing a pair of TOC save
1231 // instruction and a flag. The flag will be set to false if the TOC save is
1232 // proven redundant. This function will erase from the basic block all the TOC
1233 // saves marked as redundant.
1234 bool PPCMIPeephole::eliminateRedundantTOCSaves(
1235     std::map<MachineInstr *, bool> &TOCSaves) {
1236   bool Simplified = false;
1237   int NumKept = 0;
1238   for (auto TOCSave : TOCSaves) {
1239     if (!TOCSave.second) {
1240       TOCSave.first->eraseFromParent();
1241       RemoveTOCSave++;
1242       Simplified = true;
1243     } else {
1244       NumKept++;
1245     }
1246   }
1247 
1248   if (NumKept > 1)
1249     MultiTOCSaves++;
1250 
1251   return Simplified;
1252 }
1253 
1254 // If multiple conditional branches are executed based on the (essentially)
1255 // same comparison, we merge compare instructions into one and make multiple
1256 // conditional branches on this comparison.
1257 // For example,
1258 //   if (a == 0) { ... }
1259 //   else if (a < 0) { ... }
1260 // can be executed by one compare and two conditional branches instead of
1261 // two pairs of a compare and a conditional branch.
1262 //
1263 // This method merges two compare instructions in two MBBs and modifies the
1264 // compare and conditional branch instructions if needed.
1265 // For the above example, the input for this pass looks like:
1266 //   cmplwi r3, 0
1267 //   beq    0, .LBB0_3
1268 //   cmpwi  r3, -1
1269 //   bgt    0, .LBB0_4
1270 // So, before merging two compares, we need to modify these instructions as
1271 //   cmpwi  r3, 0       ; cmplwi and cmpwi yield same result for beq
1272 //   beq    0, .LBB0_3
1273 //   cmpwi  r3, 0       ; greather than -1 means greater or equal to 0
1274 //   bge    0, .LBB0_4
1275 
1276 bool PPCMIPeephole::eliminateRedundantCompare(void) {
1277   bool Simplified = false;
1278 
1279   for (MachineBasicBlock &MBB2 : *MF) {
1280     MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr;
1281 
1282     // For fully redundant case, we select two basic blocks MBB1 and MBB2
1283     // as an optimization target if
1284     // - both MBBs end with a conditional branch,
1285     // - MBB1 is the only predecessor of MBB2, and
1286     // - compare does not take a physical register as a operand in both MBBs.
1287     // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr.
1288     //
1289     // As partially redundant case, we additionally handle if MBB2 has one
1290     // additional predecessor, which has only one successor (MBB2).
1291     // In this case, we move the compare instruction originally in MBB2 into
1292     // MBBtoMoveCmp. This partially redundant case is typically appear by
1293     // compiling a while loop; here, MBBtoMoveCmp is the loop preheader.
1294     //
1295     // Overview of CFG of related basic blocks
1296     // Fully redundant case        Partially redundant case
1297     //   --------                   ----------------  --------
1298     //   | MBB1 | (w/ 2 succ)       | MBBtoMoveCmp |  | MBB1 | (w/ 2 succ)
1299     //   --------                   ----------------  --------
1300     //      |    \                     (w/ 1 succ) \     |    \
1301     //      |     \                                 \    |     \
1302     //      |                                        \   |
1303     //   --------                                     --------
1304     //   | MBB2 | (w/ 1 pred                          | MBB2 | (w/ 2 pred
1305     //   -------- and 2 succ)                         -------- and 2 succ)
1306     //      |    \                                       |    \
1307     //      |     \                                      |     \
1308     //
1309     if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI))
1310       continue;
1311 
1312     MachineInstr *BI1   = &*MBB1->getFirstInstrTerminator();
1313     MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg());
1314 
1315     MachineInstr *BI2   = &*MBB2.getFirstInstrTerminator();
1316     MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg());
1317     bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr);
1318 
1319     // We cannot optimize an unsupported compare opcode or
1320     // a mix of 32-bit and 64-bit comaprisons
1321     if (!isSupportedCmpOp(CMPI1->getOpcode()) ||
1322         !isSupportedCmpOp(CMPI2->getOpcode()) ||
1323         is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode()))
1324       continue;
1325 
1326     unsigned NewOpCode = 0;
1327     unsigned NewPredicate1 = 0, NewPredicate2 = 0;
1328     int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0;
1329     bool SwapOperands = false;
1330 
1331     if (CMPI1->getOpcode() != CMPI2->getOpcode()) {
1332       // Typically, unsigned comparison is used for equality check, but
1333       // we replace it with a signed comparison if the comparison
1334       // to be merged is a signed comparison.
1335       // In other cases of opcode mismatch, we cannot optimize this.
1336 
1337       // We cannot change opcode when comparing against an immediate
1338       // if the most significant bit of the immediate is one
1339       // due to the difference in sign extension.
1340       auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
1341         if (!I->getOperand(2).isImm())
1342           return false;
1343         int16_t Imm = (int16_t)I->getOperand(2).getImm();
1344         return Imm < 0;
1345       };
1346 
1347       if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
1348           CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
1349         NewOpCode = CMPI1->getOpcode();
1350       else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
1351                getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
1352         NewOpCode = CMPI2->getOpcode();
1353       else continue;
1354     }
1355 
1356     if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) {
1357       // In case of comparisons between two registers, these two registers
1358       // must be same to merge two comparisons.
1359       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1360                                          nullptr, nullptr, MRI);
1361       unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(),
1362                                          nullptr, nullptr, MRI);
1363       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1364                                          MBB1, &MBB2, MRI);
1365       unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(),
1366                                          MBB1, &MBB2, MRI);
1367 
1368       if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) {
1369         // Same pair of registers in the same order; ready to merge as is.
1370       }
1371       else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) {
1372         // Same pair of registers in different order.
1373         // We reverse the predicate to merge compare instructions.
1374         PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm();
1375         NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred);
1376         // In case of partial redundancy, we need to swap operands
1377         // in another compare instruction.
1378         SwapOperands = true;
1379       }
1380       else continue;
1381     }
1382     else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) {
1383       // In case of comparisons between a register and an immediate,
1384       // the operand register must be same for two compare instructions.
1385       unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(),
1386                                          nullptr, nullptr, MRI);
1387       unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(),
1388                                          MBB1, &MBB2, MRI);
1389       if (Cmp1Operand1 != Cmp2Operand1)
1390         continue;
1391 
1392       NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm();
1393       NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm();
1394 
1395       // If immediate are not same, we try to adjust by changing predicate;
1396       // e.g. GT imm means GE (imm+1).
1397       if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) {
1398         int Diff = Imm1 - Imm2;
1399         if (Diff < -2 || Diff > 2)
1400           continue;
1401 
1402         unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1);
1403         unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1);
1404         unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2);
1405         unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2);
1406         if (Diff == 2) {
1407           if (PredToInc2 && PredToDec1) {
1408             NewPredicate2 = PredToInc2;
1409             NewPredicate1 = PredToDec1;
1410             NewImm2++;
1411             NewImm1--;
1412           }
1413         }
1414         else if (Diff == 1) {
1415           if (PredToInc2) {
1416             NewImm2++;
1417             NewPredicate2 = PredToInc2;
1418           }
1419           else if (PredToDec1) {
1420             NewImm1--;
1421             NewPredicate1 = PredToDec1;
1422           }
1423         }
1424         else if (Diff == -1) {
1425           if (PredToDec2) {
1426             NewImm2--;
1427             NewPredicate2 = PredToDec2;
1428           }
1429           else if (PredToInc1) {
1430             NewImm1++;
1431             NewPredicate1 = PredToInc1;
1432           }
1433         }
1434         else if (Diff == -2) {
1435           if (PredToDec2 && PredToInc1) {
1436             NewPredicate2 = PredToDec2;
1437             NewPredicate1 = PredToInc1;
1438             NewImm2--;
1439             NewImm1++;
1440           }
1441         }
1442       }
1443 
1444       // We cannot merge two compares if the immediates are not same.
1445       if (NewImm2 != NewImm1)
1446         continue;
1447     }
1448 
1449     LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n");
1450     LLVM_DEBUG(CMPI1->dump());
1451     LLVM_DEBUG(BI1->dump());
1452     LLVM_DEBUG(CMPI2->dump());
1453     LLVM_DEBUG(BI2->dump());
1454 
1455     // We adjust opcode, predicates and immediate as we determined above.
1456     if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) {
1457       CMPI1->setDesc(TII->get(NewOpCode));
1458     }
1459     if (NewPredicate1) {
1460       BI1->getOperand(0).setImm(NewPredicate1);
1461     }
1462     if (NewPredicate2) {
1463       BI2->getOperand(0).setImm(NewPredicate2);
1464     }
1465     if (NewImm1 != Imm1) {
1466       CMPI1->getOperand(2).setImm(NewImm1);
1467     }
1468 
1469     if (IsPartiallyRedundant) {
1470       // We touch up the compare instruction in MBB2 and move it to
1471       // a previous BB to handle partially redundant case.
1472       if (SwapOperands) {
1473         Register Op1 = CMPI2->getOperand(1).getReg();
1474         Register Op2 = CMPI2->getOperand(2).getReg();
1475         CMPI2->getOperand(1).setReg(Op2);
1476         CMPI2->getOperand(2).setReg(Op1);
1477       }
1478       if (NewImm2 != Imm2)
1479         CMPI2->getOperand(2).setImm(NewImm2);
1480 
1481       for (int I = 1; I <= 2; I++) {
1482         if (CMPI2->getOperand(I).isReg()) {
1483           MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg());
1484           if (Inst->getParent() != &MBB2)
1485             continue;
1486 
1487           assert(Inst->getOpcode() == PPC::PHI &&
1488                  "We cannot support if an operand comes from this BB.");
1489           unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp);
1490           CMPI2->getOperand(I).setReg(SrcReg);
1491         }
1492       }
1493       auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator());
1494       MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2));
1495 
1496       DebugLoc DL = CMPI2->getDebugLoc();
1497       Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass);
1498       BuildMI(MBB2, MBB2.begin(), DL,
1499               TII->get(PPC::PHI), NewVReg)
1500         .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1)
1501         .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp);
1502       BI2->getOperand(1).setReg(NewVReg);
1503     }
1504     else {
1505       // We finally eliminate compare instruction in MBB2.
1506       BI2->getOperand(1).setReg(BI1->getOperand(1).getReg());
1507       CMPI2->eraseFromParent();
1508     }
1509     BI2->getOperand(1).setIsKill(true);
1510     BI1->getOperand(1).setIsKill(false);
1511 
1512     LLVM_DEBUG(dbgs() << "into a compare and two branches:\n");
1513     LLVM_DEBUG(CMPI1->dump());
1514     LLVM_DEBUG(BI1->dump());
1515     LLVM_DEBUG(BI2->dump());
1516     if (IsPartiallyRedundant) {
1517       LLVM_DEBUG(dbgs() << "The following compare is moved into "
1518                         << printMBBReference(*MBBtoMoveCmp)
1519                         << " to handle partial redundancy.\n");
1520       LLVM_DEBUG(CMPI2->dump());
1521     }
1522 
1523     Simplified = true;
1524   }
1525 
1526   return Simplified;
1527 }
1528 
1529 // We miss the opportunity to emit an RLDIC when lowering jump tables
1530 // since ISEL sees only a single basic block. When selecting, the clear
1531 // and shift left will be in different blocks.
1532 bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI) {
1533   if (MI.getOpcode() != PPC::RLDICR)
1534     return false;
1535 
1536   Register SrcReg = MI.getOperand(1).getReg();
1537   if (!Register::isVirtualRegister(SrcReg))
1538     return false;
1539 
1540   MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1541   if (SrcMI->getOpcode() != PPC::RLDICL)
1542     return false;
1543 
1544   MachineOperand MOpSHSrc = SrcMI->getOperand(2);
1545   MachineOperand MOpMBSrc = SrcMI->getOperand(3);
1546   MachineOperand MOpSHMI = MI.getOperand(2);
1547   MachineOperand MOpMEMI = MI.getOperand(3);
1548   if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() &&
1549         MOpMEMI.isImm()))
1550     return false;
1551 
1552   uint64_t SHSrc = MOpSHSrc.getImm();
1553   uint64_t MBSrc = MOpMBSrc.getImm();
1554   uint64_t SHMI = MOpSHMI.getImm();
1555   uint64_t MEMI = MOpMEMI.getImm();
1556   uint64_t NewSH = SHSrc + SHMI;
1557   uint64_t NewMB = MBSrc - SHMI;
1558   if (NewMB > 63 || NewSH > 63)
1559     return false;
1560 
1561   // The bits cleared with RLDICL are [0, MBSrc).
1562   // The bits cleared with RLDICR are (MEMI, 63].
1563   // After the sequence, the bits cleared are:
1564   // [0, MBSrc-SHMI) and (MEMI, 63).
1565   //
1566   // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63].
1567   if ((63 - NewSH) != MEMI)
1568     return false;
1569 
1570   LLVM_DEBUG(dbgs() << "Converting pair: ");
1571   LLVM_DEBUG(SrcMI->dump());
1572   LLVM_DEBUG(MI.dump());
1573 
1574   MI.setDesc(TII->get(PPC::RLDIC));
1575   MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg());
1576   MI.getOperand(2).setImm(NewSH);
1577   MI.getOperand(3).setImm(NewMB);
1578   MI.getOperand(1).setIsKill(SrcMI->getOperand(1).isKill());
1579   SrcMI->getOperand(1).setIsKill(false);
1580 
1581   LLVM_DEBUG(dbgs() << "To: ");
1582   LLVM_DEBUG(MI.dump());
1583   NumRotatesCollapsed++;
1584   // If SrcReg has no non-debug use it's safe to delete its def SrcMI.
1585   if (MRI->use_nodbg_empty(SrcReg)) {
1586     assert(!SrcMI->hasImplicitDef() &&
1587            "Not expecting an implicit def with this instr.");
1588     SrcMI->eraseFromParent();
1589   }
1590   return true;
1591 }
1592 
1593 // For case in LLVM IR
1594 // entry:
1595 //   %iconv = sext i32 %index to i64
1596 //   br i1 undef label %true, label %false
1597 // true:
1598 //   %ptr = getelementptr inbounds i32, i32* null, i64 %iconv
1599 // ...
1600 // PPCISelLowering::combineSHL fails to combine, because sext and shl are in
1601 // different BBs when conducting instruction selection. We can do a peephole
1602 // optimization to combine these two instructions into extswsli after
1603 // instruction selection.
1604 bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI,
1605                                       MachineInstr *&ToErase) {
1606   if (MI.getOpcode() != PPC::RLDICR)
1607     return false;
1608 
1609   if (!MF->getSubtarget<PPCSubtarget>().isISA3_0())
1610     return false;
1611 
1612   assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands");
1613 
1614   MachineOperand MOpSHMI = MI.getOperand(2);
1615   MachineOperand MOpMEMI = MI.getOperand(3);
1616   if (!(MOpSHMI.isImm() && MOpMEMI.isImm()))
1617     return false;
1618 
1619   uint64_t SHMI = MOpSHMI.getImm();
1620   uint64_t MEMI = MOpMEMI.getImm();
1621   if (SHMI + MEMI != 63)
1622     return false;
1623 
1624   Register SrcReg = MI.getOperand(1).getReg();
1625   if (!Register::isVirtualRegister(SrcReg))
1626     return false;
1627 
1628   MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
1629   if (SrcMI->getOpcode() != PPC::EXTSW &&
1630       SrcMI->getOpcode() != PPC::EXTSW_32_64)
1631     return false;
1632 
1633   // If the register defined by extsw has more than one use, combination is not
1634   // needed.
1635   if (!MRI->hasOneNonDBGUse(SrcReg))
1636     return false;
1637 
1638   assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands");
1639   assert(SrcMI->getOperand(1).isReg() &&
1640          "EXTSW's second operand should be a register");
1641   if (!Register::isVirtualRegister(SrcMI->getOperand(1).getReg()))
1642     return false;
1643 
1644   LLVM_DEBUG(dbgs() << "Combining pair: ");
1645   LLVM_DEBUG(SrcMI->dump());
1646   LLVM_DEBUG(MI.dump());
1647 
1648   MachineInstr *NewInstr =
1649       BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(),
1650               SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI)
1651                                                : TII->get(PPC::EXTSWSLI_32_64),
1652               MI.getOperand(0).getReg())
1653           .add(SrcMI->getOperand(1))
1654           .add(MOpSHMI);
1655   (void)NewInstr;
1656 
1657   LLVM_DEBUG(dbgs() << "TO: ");
1658   LLVM_DEBUG(NewInstr->dump());
1659   ++NumEXTSWAndSLDICombined;
1660   ToErase = &MI;
1661   // SrcMI, which is extsw, is of no use now, erase it.
1662   SrcMI->eraseFromParent();
1663   return true;
1664 }
1665 
1666 } // end default namespace
1667 
1668 INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE,
1669                       "PowerPC MI Peephole Optimization", false, false)
1670 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1671 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1672 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1673 INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE,
1674                     "PowerPC MI Peephole Optimization", false, false)
1675 
1676 char PPCMIPeephole::ID = 0;
1677 FunctionPass*
1678 llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); }
1679 
1680