1 //===-- PPCInstrInfo.h - PowerPC Instruction Information --------*- C++ -*-===//
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 file contains the PowerPC implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_TARGET_POWERPC_PPCINSTRINFO_H
14 #define LLVM_LIB_TARGET_POWERPC_PPCINSTRINFO_H
15 
16 #include "PPCRegisterInfo.h"
17 #include "llvm/CodeGen/TargetInstrInfo.h"
18 
19 #define GET_INSTRINFO_HEADER
20 #include "PPCGenInstrInfo.inc"
21 
22 namespace llvm {
23 
24 /// PPCII - This namespace holds all of the PowerPC target-specific
25 /// per-instruction flags.  These must match the corresponding definitions in
26 /// PPC.td and PPCInstrFormats.td.
27 namespace PPCII {
28 enum {
29   // PPC970 Instruction Flags.  These flags describe the characteristics of the
30   // PowerPC 970 (aka G5) dispatch groups and how they are formed out of
31   // raw machine instructions.
32 
33   /// PPC970_First - This instruction starts a new dispatch group, so it will
34   /// always be the first one in the group.
35   PPC970_First = 0x1,
36 
37   /// PPC970_Single - This instruction starts a new dispatch group and
38   /// terminates it, so it will be the sole instruction in the group.
39   PPC970_Single = 0x2,
40 
41   /// PPC970_Cracked - This instruction is cracked into two pieces, requiring
42   /// two dispatch pipes to be available to issue.
43   PPC970_Cracked = 0x4,
44 
45   /// PPC970_Mask/Shift - This is a bitmask that selects the pipeline type that
46   /// an instruction is issued to.
47   PPC970_Shift = 3,
48   PPC970_Mask = 0x07 << PPC970_Shift
49 };
50 enum PPC970_Unit {
51   /// These are the various PPC970 execution unit pipelines.  Each instruction
52   /// is one of these.
53   PPC970_Pseudo = 0 << PPC970_Shift,   // Pseudo instruction
54   PPC970_FXU    = 1 << PPC970_Shift,   // Fixed Point (aka Integer/ALU) Unit
55   PPC970_LSU    = 2 << PPC970_Shift,   // Load Store Unit
56   PPC970_FPU    = 3 << PPC970_Shift,   // Floating Point Unit
57   PPC970_CRU    = 4 << PPC970_Shift,   // Control Register Unit
58   PPC970_VALU   = 5 << PPC970_Shift,   // Vector ALU
59   PPC970_VPERM  = 6 << PPC970_Shift,   // Vector Permute Unit
60   PPC970_BRU    = 7 << PPC970_Shift    // Branch Unit
61 };
62 
63 enum {
64   /// Shift count to bypass PPC970 flags
65   NewDef_Shift = 6,
66 
67   /// This instruction is an X-Form memory operation.
68   XFormMemOp = 0x1 << NewDef_Shift,
69   /// This instruction is prefixed.
70   Prefixed = 0x1 << (NewDef_Shift+1)
71 };
72 } // end namespace PPCII
73 
74 // Instructions that have an immediate form might be convertible to that
75 // form if the correct input is a result of a load immediate. In order to
76 // know whether the transformation is special, we might need to know some
77 // of the details of the two forms.
78 struct ImmInstrInfo {
79   // Is the immediate field in the immediate form signed or unsigned?
80   uint64_t SignedImm : 1;
81   // Does the immediate need to be a multiple of some value?
82   uint64_t ImmMustBeMultipleOf : 5;
83   // Is R0/X0 treated specially by the original r+r instruction?
84   // If so, in which operand?
85   uint64_t ZeroIsSpecialOrig : 3;
86   // Is R0/X0 treated specially by the new r+i instruction?
87   // If so, in which operand?
88   uint64_t ZeroIsSpecialNew : 3;
89   // Is the operation commutative?
90   uint64_t IsCommutative : 1;
91   // The operand number to check for add-immediate def.
92   uint64_t OpNoForForwarding : 3;
93   // The operand number for the immediate.
94   uint64_t ImmOpNo : 3;
95   // The opcode of the new instruction.
96   uint64_t ImmOpcode : 16;
97   // The size of the immediate.
98   uint64_t ImmWidth : 5;
99   // The immediate should be truncated to N bits.
100   uint64_t TruncateImmTo : 5;
101   // Is the instruction summing the operand
102   uint64_t IsSummingOperands : 1;
103 };
104 
105 // Information required to convert an instruction to just a materialized
106 // immediate.
107 struct LoadImmediateInfo {
108   unsigned Imm : 16;
109   unsigned Is64Bit : 1;
110   unsigned SetCR : 1;
111 };
112 
113 // Index into the OpcodesForSpill array.
114 enum SpillOpcodeKey {
115   SOK_Int4Spill,
116   SOK_Int8Spill,
117   SOK_Float8Spill,
118   SOK_Float4Spill,
119   SOK_CRSpill,
120   SOK_CRBitSpill,
121   SOK_VRVectorSpill,
122   SOK_VSXVectorSpill,
123   SOK_VectorFloat8Spill,
124   SOK_VectorFloat4Spill,
125   SOK_SpillToVSR,
126   SOK_PairedVecSpill,
127   SOK_AccumulatorSpill,
128   SOK_UAccumulatorSpill,
129   SOK_SPESpill,
130   SOK_LastOpcodeSpill // This must be last on the enum.
131 };
132 
133 // Define list of load and store spill opcodes.
134 #define NoInstr PPC::INSTRUCTION_LIST_END
135 #define Pwr8LoadOpcodes                                                        \
136   {                                                                            \
137     PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,                    \
138         PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXVD2X, PPC::LXSDX, PPC::LXSSPX,    \
139         PPC::SPILLTOVSR_LD, NoInstr, NoInstr, NoInstr, PPC::EVLDD              \
140   }
141 
142 #define Pwr9LoadOpcodes                                                        \
143   {                                                                            \
144     PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,                    \
145         PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64,                \
146         PPC::DFLOADf32, PPC::SPILLTOVSR_LD, NoInstr, NoInstr, NoInstr, NoInstr \
147   }
148 
149 #define Pwr10LoadOpcodes                                                       \
150   {                                                                            \
151     PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,                    \
152         PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64,                \
153         PPC::DFLOADf32, PPC::SPILLTOVSR_LD, PPC::LXVP, PPC::RESTORE_ACC,       \
154         PPC::RESTORE_UACC, NoInstr                                             \
155   }
156 
157 #define Pwr8StoreOpcodes                                                       \
158   {                                                                            \
159     PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR, PPC::SPILL_CRBIT, \
160         PPC::STVX, PPC::STXVD2X, PPC::STXSDX, PPC::STXSSPX,                    \
161         PPC::SPILLTOVSR_ST, NoInstr, NoInstr, NoInstr, PPC::EVSTDD             \
162   }
163 
164 #define Pwr9StoreOpcodes                                                       \
165   {                                                                            \
166     PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR, PPC::SPILL_CRBIT, \
167         PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32,                \
168         PPC::SPILLTOVSR_ST, NoInstr, NoInstr, NoInstr, NoInstr                 \
169   }
170 
171 #define Pwr10StoreOpcodes                                                      \
172   {                                                                            \
173     PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR, PPC::SPILL_CRBIT, \
174         PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32,                \
175         PPC::SPILLTOVSR_ST, PPC::STXVP, PPC::SPILL_ACC, PPC::SPILL_UACC,       \
176         NoInstr                                                                \
177   }
178 
179 // Initialize arrays for load and store spill opcodes on supported subtargets.
180 #define StoreOpcodesForSpill                                                   \
181   { Pwr8StoreOpcodes, Pwr9StoreOpcodes, Pwr10StoreOpcodes }
182 #define LoadOpcodesForSpill                                                    \
183   { Pwr8LoadOpcodes, Pwr9LoadOpcodes, Pwr10LoadOpcodes }
184 
185 class PPCSubtarget;
186 class PPCInstrInfo : public PPCGenInstrInfo {
187   PPCSubtarget &Subtarget;
188   const PPCRegisterInfo RI;
189   const unsigned StoreSpillOpcodesArray[3][SOK_LastOpcodeSpill] =
190       StoreOpcodesForSpill;
191   const unsigned LoadSpillOpcodesArray[3][SOK_LastOpcodeSpill] =
192       LoadOpcodesForSpill;
193 
194   void StoreRegToStackSlot(MachineFunction &MF, unsigned SrcReg, bool isKill,
195                            int FrameIdx, const TargetRegisterClass *RC,
196                            SmallVectorImpl<MachineInstr *> &NewMIs) const;
197   void LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
198                             unsigned DestReg, int FrameIdx,
199                             const TargetRegisterClass *RC,
200                             SmallVectorImpl<MachineInstr *> &NewMIs) const;
201 
202   // Replace the instruction with single LI if possible. \p DefMI must be LI or
203   // LI8.
204   bool simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
205                     unsigned OpNoForForwarding, MachineInstr **KilledDef) const;
206   // If the inst is imm-form and its register operand is produced by a ADDI, put
207   // the imm into the inst directly and remove the ADDI if possible.
208   bool transformToNewImmFormFedByAdd(MachineInstr &MI, MachineInstr &DefMI,
209                                      unsigned OpNoForForwarding) const;
210   // If the inst is x-form and has imm-form and one of its operand is produced
211   // by a LI, put the imm into the inst directly and remove the LI if possible.
212   bool transformToImmFormFedByLI(MachineInstr &MI, const ImmInstrInfo &III,
213                                  unsigned ConstantOpNo,
214                                  MachineInstr &DefMI) const;
215   // If the inst is x-form and has imm-form and one of its operand is produced
216   // by an add-immediate, try to transform it when possible.
217   bool transformToImmFormFedByAdd(MachineInstr &MI, const ImmInstrInfo &III,
218                                   unsigned ConstantOpNo, MachineInstr &DefMI,
219                                   bool KillDefMI) const;
220   // Try to find that, if the instruction 'MI' contains any operand that
221   // could be forwarded from some inst that feeds it. If yes, return the
222   // Def of that operand. And OpNoForForwarding is the operand index in
223   // the 'MI' for that 'Def'. If we see another use of this Def between
224   // the Def and the MI, SeenIntermediateUse becomes 'true'.
225   MachineInstr *getForwardingDefMI(MachineInstr &MI,
226                                    unsigned &OpNoForForwarding,
227                                    bool &SeenIntermediateUse) const;
228 
229   // Can the user MI have it's source at index \p OpNoForForwarding
230   // forwarded from an add-immediate that feeds it?
231   bool isUseMIElgibleForForwarding(MachineInstr &MI, const ImmInstrInfo &III,
232                                    unsigned OpNoForForwarding) const;
233   bool isDefMIElgibleForForwarding(MachineInstr &DefMI,
234                                    const ImmInstrInfo &III,
235                                    MachineOperand *&ImmMO,
236                                    MachineOperand *&RegMO) const;
237   bool isImmElgibleForForwarding(const MachineOperand &ImmMO,
238                                  const MachineInstr &DefMI,
239                                  const ImmInstrInfo &III,
240                                  int64_t &Imm,
241                                  int64_t BaseImm = 0) const;
242   bool isRegElgibleForForwarding(const MachineOperand &RegMO,
243                                  const MachineInstr &DefMI,
244                                  const MachineInstr &MI, bool KillDefMI,
245                                  bool &IsFwdFeederRegKilled) const;
246   unsigned getSpillTarget() const;
247   const unsigned *getStoreOpcodesForSpillArray() const;
248   const unsigned *getLoadOpcodesForSpillArray() const;
249   unsigned getSpillIndex(const TargetRegisterClass *RC) const;
250   int16_t getFMAOpIdxInfo(unsigned Opcode) const;
251   void reassociateFMA(MachineInstr &Root, MachineCombinerPattern Pattern,
252                       SmallVectorImpl<MachineInstr *> &InsInstrs,
253                       SmallVectorImpl<MachineInstr *> &DelInstrs,
254                       DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
255   virtual void anchor();
256 
257 protected:
258   /// Commutes the operands in the given instruction.
259   /// The commutable operands are specified by their indices OpIdx1 and OpIdx2.
260   ///
261   /// Do not call this method for a non-commutable instruction or for
262   /// non-commutable pair of operand indices OpIdx1 and OpIdx2.
263   /// Even though the instruction is commutable, the method may still
264   /// fail to commute the operands, null pointer is returned in such cases.
265   ///
266   /// For example, we can commute rlwimi instructions, but only if the
267   /// rotate amt is zero.  We also have to munge the immediates a bit.
268   MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
269                                        unsigned OpIdx1,
270                                        unsigned OpIdx2) const override;
271 
272 public:
273   explicit PPCInstrInfo(PPCSubtarget &STI);
274 
275   /// getRegisterInfo - TargetInstrInfo is a superset of MRegister info.  As
276   /// such, whenever a client has an instance of instruction info, it should
277   /// always be able to get register info as well (through this method).
278   ///
279   const PPCRegisterInfo &getRegisterInfo() const { return RI; }
280 
281   bool isXFormMemOp(unsigned Opcode) const {
282     return get(Opcode).TSFlags & PPCII::XFormMemOp;
283   }
284   bool isPrefixed(unsigned Opcode) const {
285     return get(Opcode).TSFlags & PPCII::Prefixed;
286   }
287 
288   static bool isSameClassPhysRegCopy(unsigned Opcode) {
289     unsigned CopyOpcodes[] = {PPC::OR,        PPC::OR8,   PPC::FMR,
290                               PPC::VOR,       PPC::XXLOR, PPC::XXLORf,
291                               PPC::XSCPSGNDP, PPC::MCRF,  PPC::CROR,
292                               PPC::EVOR,      -1U};
293     for (int i = 0; CopyOpcodes[i] != -1U; i++)
294       if (Opcode == CopyOpcodes[i])
295         return true;
296     return false;
297   }
298 
299   ScheduleHazardRecognizer *
300   CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
301                                const ScheduleDAG *DAG) const override;
302   ScheduleHazardRecognizer *
303   CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
304                                      const ScheduleDAG *DAG) const override;
305 
306   unsigned getInstrLatency(const InstrItineraryData *ItinData,
307                            const MachineInstr &MI,
308                            unsigned *PredCost = nullptr) const override;
309 
310   int getOperandLatency(const InstrItineraryData *ItinData,
311                         const MachineInstr &DefMI, unsigned DefIdx,
312                         const MachineInstr &UseMI,
313                         unsigned UseIdx) const override;
314   int getOperandLatency(const InstrItineraryData *ItinData,
315                         SDNode *DefNode, unsigned DefIdx,
316                         SDNode *UseNode, unsigned UseIdx) const override {
317     return PPCGenInstrInfo::getOperandLatency(ItinData, DefNode, DefIdx,
318                                               UseNode, UseIdx);
319   }
320 
321   bool hasLowDefLatency(const TargetSchedModel &SchedModel,
322                         const MachineInstr &DefMI,
323                         unsigned DefIdx) const override {
324     // Machine LICM should hoist all instructions in low-register-pressure
325     // situations; none are sufficiently free to justify leaving in a loop
326     // body.
327     return false;
328   }
329 
330   bool useMachineCombiner() const override {
331     return true;
332   }
333 
334   /// When getMachineCombinerPatterns() finds patterns, this function generates
335   /// the instructions that could replace the original code sequence
336   void genAlternativeCodeSequence(
337       MachineInstr &Root, MachineCombinerPattern Pattern,
338       SmallVectorImpl<MachineInstr *> &InsInstrs,
339       SmallVectorImpl<MachineInstr *> &DelInstrs,
340       DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const override;
341 
342   /// Return true when there is potentially a faster code sequence for a fma
343   /// chain ending in \p Root. All potential patterns are output in the \p
344   /// P array.
345   bool getFMAPatterns(MachineInstr &Root,
346                       SmallVectorImpl<MachineCombinerPattern> &P) const;
347 
348   /// Return true when there is potentially a faster code sequence
349   /// for an instruction chain ending in <Root>. All potential patterns are
350   /// output in the <Pattern> array.
351   bool getMachineCombinerPatterns(
352       MachineInstr &Root,
353       SmallVectorImpl<MachineCombinerPattern> &P) const override;
354 
355   bool isAssociativeAndCommutative(const MachineInstr &Inst) const override;
356 
357   /// On PowerPC, we try to reassociate FMA chain which will increase
358   /// instruction size. Set extension resource length limit to 1 for edge case.
359   /// Resource Length is calculated by scaled resource usage in getCycles().
360   /// Because of the division in getCycles(), it returns different cycles due to
361   /// legacy scaled resource usage. So new resource length may be same with
362   /// legacy or 1 bigger than legacy.
363   /// We need to execlude the 1 bigger case even the resource length is not
364   /// perserved for more FMA chain reassociations on PowerPC.
365   int getExtendResourceLenLimit() const override { return 1; }
366 
367   void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
368                              MachineInstr &NewMI1,
369                              MachineInstr &NewMI2) const override;
370 
371   void setSpecialOperandAttr(MachineInstr &MI, uint16_t Flags) const override;
372 
373   bool isCoalescableExtInstr(const MachineInstr &MI,
374                              Register &SrcReg, Register &DstReg,
375                              unsigned &SubIdx) const override;
376   unsigned isLoadFromStackSlot(const MachineInstr &MI,
377                                int &FrameIndex) const override;
378   bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
379                                          AAResults *AA) const override;
380   unsigned isStoreToStackSlot(const MachineInstr &MI,
381                               int &FrameIndex) const override;
382 
383   bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1,
384                              unsigned &SrcOpIdx2) const override;
385 
386   void insertNoop(MachineBasicBlock &MBB,
387                   MachineBasicBlock::iterator MI) const override;
388 
389 
390   // Branch analysis.
391   bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
392                      MachineBasicBlock *&FBB,
393                      SmallVectorImpl<MachineOperand> &Cond,
394                      bool AllowModify) const override;
395   unsigned removeBranch(MachineBasicBlock &MBB,
396                         int *BytesRemoved = nullptr) const override;
397   unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
398                         MachineBasicBlock *FBB, ArrayRef<MachineOperand> Cond,
399                         const DebugLoc &DL,
400                         int *BytesAdded = nullptr) const override;
401 
402   // Select analysis.
403   bool canInsertSelect(const MachineBasicBlock &, ArrayRef<MachineOperand> Cond,
404                        Register, Register, Register, int &, int &,
405                        int &) const override;
406   void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
407                     const DebugLoc &DL, Register DstReg,
408                     ArrayRef<MachineOperand> Cond, Register TrueReg,
409                     Register FalseReg) const override;
410 
411   void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
412                    const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg,
413                    bool KillSrc) const override;
414 
415   void storeRegToStackSlot(MachineBasicBlock &MBB,
416                            MachineBasicBlock::iterator MBBI,
417                            Register SrcReg, bool isKill, int FrameIndex,
418                            const TargetRegisterClass *RC,
419                            const TargetRegisterInfo *TRI) const override;
420 
421   // Emits a register spill without updating the register class for vector
422   // registers. This ensures that when we spill a vector register the
423   // element order in the register is the same as it was in memory.
424   void storeRegToStackSlotNoUpd(MachineBasicBlock &MBB,
425                                 MachineBasicBlock::iterator MBBI,
426                                 unsigned SrcReg, bool isKill, int FrameIndex,
427                                 const TargetRegisterClass *RC,
428                                 const TargetRegisterInfo *TRI) const;
429 
430   void loadRegFromStackSlot(MachineBasicBlock &MBB,
431                             MachineBasicBlock::iterator MBBI,
432                             Register DestReg, int FrameIndex,
433                             const TargetRegisterClass *RC,
434                             const TargetRegisterInfo *TRI) const override;
435 
436   // Emits a register reload without updating the register class for vector
437   // registers. This ensures that when we reload a vector register the
438   // element order in the register is the same as it was in memory.
439   void loadRegFromStackSlotNoUpd(MachineBasicBlock &MBB,
440                                  MachineBasicBlock::iterator MBBI,
441                                  unsigned DestReg, int FrameIndex,
442                                  const TargetRegisterClass *RC,
443                                  const TargetRegisterInfo *TRI) const;
444 
445   unsigned getStoreOpcodeForSpill(const TargetRegisterClass *RC) const;
446 
447   unsigned getLoadOpcodeForSpill(const TargetRegisterClass *RC) const;
448 
449   bool
450   reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const override;
451 
452   bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg,
453                      MachineRegisterInfo *MRI) const override;
454 
455   bool onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
456                          Register Reg) const;
457 
458   // If conversion by predication (only supported by some branch instructions).
459   // All of the profitability checks always return true; it is always
460   // profitable to use the predicated branches.
461   bool isProfitableToIfCvt(MachineBasicBlock &MBB,
462                           unsigned NumCycles, unsigned ExtraPredCycles,
463                           BranchProbability Probability) const override {
464     return true;
465   }
466 
467   bool isProfitableToIfCvt(MachineBasicBlock &TMBB,
468                            unsigned NumT, unsigned ExtraT,
469                            MachineBasicBlock &FMBB,
470                            unsigned NumF, unsigned ExtraF,
471                            BranchProbability Probability) const override;
472 
473   bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
474                                  BranchProbability Probability) const override {
475     return true;
476   }
477 
478   bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
479                                  MachineBasicBlock &FMBB) const override {
480     return false;
481   }
482 
483   // Predication support.
484   bool isPredicated(const MachineInstr &MI) const override;
485 
486   bool isSchedulingBoundary(const MachineInstr &MI,
487                             const MachineBasicBlock *MBB,
488                             const MachineFunction &MF) const override;
489 
490   bool PredicateInstruction(MachineInstr &MI,
491                             ArrayRef<MachineOperand> Pred) const override;
492 
493   bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
494                          ArrayRef<MachineOperand> Pred2) const override;
495 
496   bool ClobbersPredicate(MachineInstr &MI, std::vector<MachineOperand> &Pred,
497                          bool SkipDead) const override;
498 
499   // Comparison optimization.
500 
501   bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
502                       Register &SrcReg2, int &Mask, int &Value) const override;
503 
504   bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
505                             Register SrcReg2, int Mask, int Value,
506                             const MachineRegisterInfo *MRI) const override;
507 
508 
509   /// Return true if get the base operand, byte offset of an instruction and
510   /// the memory width. Width is the size of memory that is being
511   /// loaded/stored (e.g. 1, 2, 4, 8).
512   bool getMemOperandWithOffsetWidth(const MachineInstr &LdSt,
513                                     const MachineOperand *&BaseOp,
514                                     int64_t &Offset, unsigned &Width,
515                                     const TargetRegisterInfo *TRI) const;
516 
517   /// Get the base operand and byte offset of an instruction that reads/writes
518   /// memory.
519   bool getMemOperandsWithOffsetWidth(
520       const MachineInstr &LdSt,
521       SmallVectorImpl<const MachineOperand *> &BaseOps, int64_t &Offset,
522       bool &OffsetIsScalable, unsigned &Width,
523       const TargetRegisterInfo *TRI) const override;
524 
525   /// Returns true if the two given memory operations should be scheduled
526   /// adjacent.
527   bool shouldClusterMemOps(ArrayRef<const MachineOperand *> BaseOps1,
528                            ArrayRef<const MachineOperand *> BaseOps2,
529                            unsigned NumLoads, unsigned NumBytes) const override;
530 
531   /// Return true if two MIs access different memory addresses and false
532   /// otherwise
533   bool
534   areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
535                                   const MachineInstr &MIb) const override;
536 
537   /// GetInstSize - Return the number of bytes of code the specified
538   /// instruction may be.  This returns the maximum number of bytes.
539   ///
540   unsigned getInstSizeInBytes(const MachineInstr &MI) const override;
541 
542   void getNoop(MCInst &NopInst) const override;
543 
544   std::pair<unsigned, unsigned>
545   decomposeMachineOperandsTargetFlags(unsigned TF) const override;
546 
547   ArrayRef<std::pair<unsigned, const char *>>
548   getSerializableDirectMachineOperandTargetFlags() const override;
549 
550   ArrayRef<std::pair<unsigned, const char *>>
551   getSerializableBitmaskMachineOperandTargetFlags() const override;
552 
553   // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
554   bool expandVSXMemPseudo(MachineInstr &MI) const;
555 
556   // Lower pseudo instructions after register allocation.
557   bool expandPostRAPseudo(MachineInstr &MI) const override;
558 
559   static bool isVFRegister(unsigned Reg) {
560     return Reg >= PPC::VF0 && Reg <= PPC::VF31;
561   }
562   static bool isVRRegister(unsigned Reg) {
563     return Reg >= PPC::V0 && Reg <= PPC::V31;
564   }
565   const TargetRegisterClass *updatedRC(const TargetRegisterClass *RC) const;
566   static int getRecordFormOpcode(unsigned Opcode);
567 
568   bool isTOCSaveMI(const MachineInstr &MI) const;
569 
570   bool isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
571                             const unsigned PhiDepth) const;
572 
573   /// Return true if the output of the instruction is always a sign-extended,
574   /// i.e. 0 to 31-th bits are same as 32-th bit.
575   bool isSignExtended(const MachineInstr &MI, const unsigned depth = 0) const {
576     return isSignOrZeroExtended(MI, true, depth);
577   }
578 
579   /// Return true if the output of the instruction is always zero-extended,
580   /// i.e. 0 to 31-th bits are all zeros
581   bool isZeroExtended(const MachineInstr &MI, const unsigned depth = 0) const {
582    return isSignOrZeroExtended(MI, false, depth);
583   }
584 
585   bool convertToImmediateForm(MachineInstr &MI,
586                               MachineInstr **KilledDef = nullptr) const;
587   bool foldFrameOffset(MachineInstr &MI) const;
588   bool simplifyRotateAndMaskInstr(MachineInstr &MI,
589                                   MachineInstr *&ToErase) const;
590   bool isADDIInstrEligibleForFolding(MachineInstr &ADDIMI, int64_t &Imm) const;
591   bool isADDInstrEligibleForFolding(MachineInstr &ADDMI) const;
592   bool isImmInstrEligibleForFolding(MachineInstr &MI, unsigned &BaseReg,
593                                     unsigned &XFormOpcode,
594                                     int64_t &OffsetOfImmInstr,
595                                     ImmInstrInfo &III) const;
596   bool isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
597                              MachineInstr *&ADDIMI, int64_t &OffsetAddi,
598                              int64_t OffsetImm) const;
599 
600   /// Fixup killed/dead flag for register \p RegNo between instructions [\p
601   /// StartMI, \p EndMI]. Some pre-RA or post-RA transformations may violate
602   /// register killed/dead flags semantics, this function can be called to fix
603   /// up. Before calling this function,
604   /// 1. Ensure that \p RegNo liveness is killed after instruction \p EndMI.
605   /// 2. Ensure that there is no new definition between (\p StartMI, \p EndMI)
606   ///    and possible definition for \p RegNo is \p StartMI or \p EndMI. For
607   ///    pre-RA cases, definition may be \p StartMI through COPY, \p StartMI
608   ///    will be adjust to true definition.
609   /// 3. We can do accurate fixup for the case when all instructions between
610   ///    [\p StartMI, \p EndMI] are in same basic block.
611   /// 4. For the case when \p StartMI and \p EndMI are not in same basic block,
612   ///    we conservatively clear kill flag for all uses of \p RegNo for pre-RA
613   ///    and for post-RA, we give an assertion as without reaching definition
614   ///    analysis post-RA, \p StartMI and \p EndMI are hard to keep right.
615   void fixupIsDeadOrKill(MachineInstr *StartMI, MachineInstr *EndMI,
616                          unsigned RegNo) const;
617   void replaceInstrWithLI(MachineInstr &MI, const LoadImmediateInfo &LII) const;
618   void replaceInstrOperandWithImm(MachineInstr &MI, unsigned OpNo,
619                                   int64_t Imm) const;
620 
621   bool instrHasImmForm(unsigned Opc, bool IsVFReg, ImmInstrInfo &III,
622                        bool PostRA) const;
623 
624   // In PostRA phase, try to find instruction defines \p Reg before \p MI.
625   // \p SeenIntermediate is set to true if uses between DefMI and \p MI exist.
626   MachineInstr *getDefMIPostRA(unsigned Reg, MachineInstr &MI,
627                                bool &SeenIntermediateUse) const;
628 
629   /// getRegNumForOperand - some operands use different numbering schemes
630   /// for the same registers. For example, a VSX instruction may have any of
631   /// vs0-vs63 allocated whereas an Altivec instruction could only have
632   /// vs32-vs63 allocated (numbered as v0-v31). This function returns the actual
633   /// register number needed for the opcode/operand number combination.
634   /// The operand number argument will be useful when we need to extend this
635   /// to instructions that use both Altivec and VSX numbering (for different
636   /// operands).
637   static unsigned getRegNumForOperand(const MCInstrDesc &Desc, unsigned Reg,
638                                       unsigned OpNo) {
639     int16_t regClass = Desc.OpInfo[OpNo].RegClass;
640     switch (regClass) {
641       // We store F0-F31, VF0-VF31 in MCOperand and it should be F0-F31,
642       // VSX32-VSX63 during encoding/disassembling
643       case PPC::VSSRCRegClassID:
644       case PPC::VSFRCRegClassID:
645         if (isVFRegister(Reg))
646           return PPC::VSX32 + (Reg - PPC::VF0);
647         break;
648       // We store VSL0-VSL31, V0-V31 in MCOperand and it should be VSL0-VSL31,
649       // VSX32-VSX63 during encoding/disassembling
650       case PPC::VSRCRegClassID:
651         if (isVRRegister(Reg))
652           return PPC::VSX32 + (Reg - PPC::V0);
653         break;
654       // Other RegClass doesn't need mapping
655       default:
656         break;
657     }
658     return Reg;
659   }
660 
661   /// Check \p Opcode is BDNZ (Decrement CTR and branch if it is still nonzero).
662   bool isBDNZ(unsigned Opcode) const;
663 
664   /// Find the hardware loop instruction used to set-up the specified loop.
665   /// On PPC, we have two instructions used to set-up the hardware loop
666   /// (MTCTRloop, MTCTR8loop) with corresponding endloop (BDNZ, BDNZ8)
667   /// instructions to indicate the end of a loop.
668   MachineInstr *
669   findLoopInstr(MachineBasicBlock &PreHeader,
670                 SmallPtrSet<MachineBasicBlock *, 8> &Visited) const;
671 
672   /// Analyze loop L, which must be a single-basic-block loop, and if the
673   /// conditions can be understood enough produce a PipelinerLoopInfo object.
674   std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
675   analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const override;
676 };
677 
678 }
679 
680 #endif
681