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