xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision 3cb390498eb3ba80f18672be4e91fef3f8150ba5)
1 //===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 /// \file
9 //===----------------------------------------------------------------------===//
10 //
11 
12 #include "AMDGPU.h"
13 #include "AMDGPUSubtarget.h"
14 #include "SIInstrInfo.h"
15 #include "SIMachineFunctionInfo.h"
16 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetMachine.h"
23 
24 #define DEBUG_TYPE "si-fold-operands"
25 using namespace llvm;
26 
27 namespace {
28 
29 struct FoldCandidate {
30   MachineInstr *UseMI;
31   union {
32     MachineOperand *OpToFold;
33     uint64_t ImmToFold;
34     int FrameIndexToFold;
35   };
36   unsigned char UseOpNo;
37   MachineOperand::MachineOperandType Kind;
38 
39   FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp) :
40     UseMI(MI), OpToFold(nullptr), UseOpNo(OpNo), Kind(FoldOp->getType()) {
41     if (FoldOp->isImm()) {
42       ImmToFold = FoldOp->getImm();
43     } else if (FoldOp->isFI()) {
44       FrameIndexToFold = FoldOp->getIndex();
45     } else {
46       assert(FoldOp->isReg());
47       OpToFold = FoldOp;
48     }
49   }
50 
51   bool isFI() const {
52     return Kind == MachineOperand::MO_FrameIndex;
53   }
54 
55   bool isImm() const {
56     return Kind == MachineOperand::MO_Immediate;
57   }
58 
59   bool isReg() const {
60     return Kind == MachineOperand::MO_Register;
61   }
62 };
63 
64 class SIFoldOperands : public MachineFunctionPass {
65 public:
66   static char ID;
67   MachineRegisterInfo *MRI;
68   const SIInstrInfo *TII;
69   const SIRegisterInfo *TRI;
70   const SISubtarget *ST;
71 
72   void foldOperand(MachineOperand &OpToFold,
73                    MachineInstr *UseMI,
74                    unsigned UseOpIdx,
75                    SmallVectorImpl<FoldCandidate> &FoldList,
76                    SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
77 
78   void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
79 
80   const MachineOperand *isClamp(const MachineInstr &MI) const;
81   bool tryFoldClamp(MachineInstr &MI);
82 
83   std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
84   bool tryFoldOMod(MachineInstr &MI);
85 
86 public:
87   SIFoldOperands() : MachineFunctionPass(ID) {
88     initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
89   }
90 
91   bool runOnMachineFunction(MachineFunction &MF) override;
92 
93   StringRef getPassName() const override { return "SI Fold Operands"; }
94 
95   void getAnalysisUsage(AnalysisUsage &AU) const override {
96     AU.setPreservesCFG();
97     MachineFunctionPass::getAnalysisUsage(AU);
98   }
99 };
100 
101 } // End anonymous namespace.
102 
103 INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
104                 "SI Fold Operands", false, false)
105 
106 char SIFoldOperands::ID = 0;
107 
108 char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
109 
110 // Wrapper around isInlineConstant that understands special cases when
111 // instruction types are replaced during operand folding.
112 static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
113                                      const MachineInstr &UseMI,
114                                      unsigned OpNo,
115                                      const MachineOperand &OpToFold) {
116   if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
117     return true;
118 
119   unsigned Opc = UseMI.getOpcode();
120   switch (Opc) {
121   case AMDGPU::V_MAC_F32_e64:
122   case AMDGPU::V_MAC_F16_e64: {
123     // Special case for mac. Since this is replaced with mad when folded into
124     // src2, we need to check the legality for the final instruction.
125     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
126     if (static_cast<int>(OpNo) == Src2Idx) {
127       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
128       const MCInstrDesc &MadDesc
129         = TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
130       return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
131     }
132   }
133   default:
134     return false;
135   }
136 }
137 
138 FunctionPass *llvm::createSIFoldOperandsPass() {
139   return new SIFoldOperands();
140 }
141 
142 static bool isFoldableCopy(const MachineInstr &MI) {
143   switch (MI.getOpcode()) {
144   case AMDGPU::V_MOV_B32_e32:
145   case AMDGPU::V_MOV_B32_e64:
146   case AMDGPU::V_MOV_B64_PSEUDO: {
147     // If there are additional implicit register operands, this may be used for
148     // register indexing so the source register operand isn't simply copied.
149     unsigned NumOps = MI.getDesc().getNumOperands() +
150       MI.getDesc().getNumImplicitUses();
151 
152     return MI.getNumOperands() == NumOps;
153   }
154   case AMDGPU::S_MOV_B32:
155   case AMDGPU::S_MOV_B64:
156   case AMDGPU::COPY:
157     return true;
158   default:
159     return false;
160   }
161 }
162 
163 static bool updateOperand(FoldCandidate &Fold,
164                           const TargetRegisterInfo &TRI) {
165   MachineInstr *MI = Fold.UseMI;
166   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
167   assert(Old.isReg());
168 
169   if (Fold.isImm()) {
170     Old.ChangeToImmediate(Fold.ImmToFold);
171     return true;
172   }
173 
174   if (Fold.isFI()) {
175     Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
176     return true;
177   }
178 
179   MachineOperand *New = Fold.OpToFold;
180   if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) &&
181       TargetRegisterInfo::isVirtualRegister(New->getReg())) {
182     Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
183     return true;
184   }
185 
186   // FIXME: Handle physical registers.
187 
188   return false;
189 }
190 
191 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
192                               const MachineInstr *MI) {
193   for (auto Candidate : FoldList) {
194     if (Candidate.UseMI == MI)
195       return true;
196   }
197   return false;
198 }
199 
200 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
201                              MachineInstr *MI, unsigned OpNo,
202                              MachineOperand *OpToFold,
203                              const SIInstrInfo *TII) {
204   if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
205 
206     // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
207     unsigned Opc = MI->getOpcode();
208     if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64) &&
209         (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
210       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
211 
212       // Check if changing this to a v_mad_{f16, f32} instruction will allow us
213       // to fold the operand.
214       MI->setDesc(TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16));
215       bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
216       if (FoldAsMAD) {
217         MI->untieRegOperand(OpNo);
218         return true;
219       }
220       MI->setDesc(TII->get(Opc));
221     }
222 
223     // Special case for s_setreg_b32
224     if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
225       MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
226       FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
227       return true;
228     }
229 
230     // If we are already folding into another operand of MI, then
231     // we can't commute the instruction, otherwise we risk making the
232     // other fold illegal.
233     if (isUseMIInFoldList(FoldList, MI))
234       return false;
235 
236     // Operand is not legal, so try to commute the instruction to
237     // see if this makes it possible to fold.
238     unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
239     unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
240     bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
241 
242     if (CanCommute) {
243       if (CommuteIdx0 == OpNo)
244         OpNo = CommuteIdx1;
245       else if (CommuteIdx1 == OpNo)
246         OpNo = CommuteIdx0;
247     }
248 
249     // One of operands might be an Imm operand, and OpNo may refer to it after
250     // the call of commuteInstruction() below. Such situations are avoided
251     // here explicitly as OpNo must be a register operand to be a candidate
252     // for memory folding.
253     if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
254                        !MI->getOperand(CommuteIdx1).isReg()))
255       return false;
256 
257     if (!CanCommute ||
258         !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
259       return false;
260 
261     if (!TII->isOperandLegal(*MI, OpNo, OpToFold))
262       return false;
263   }
264 
265   FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
266   return true;
267 }
268 
269 // If the use operand doesn't care about the value, this may be an operand only
270 // used for register indexing, in which case it is unsafe to fold.
271 static bool isUseSafeToFold(const MachineInstr &MI,
272                             const MachineOperand &UseMO) {
273   return !UseMO.isUndef();
274   //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
275 }
276 
277 void SIFoldOperands::foldOperand(
278   MachineOperand &OpToFold,
279   MachineInstr *UseMI,
280   unsigned UseOpIdx,
281   SmallVectorImpl<FoldCandidate> &FoldList,
282   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
283   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
284 
285   if (!isUseSafeToFold(*UseMI, UseOp))
286     return;
287 
288   // FIXME: Fold operands with subregs.
289   if (UseOp.isReg() && OpToFold.isReg()) {
290     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
291       return;
292 
293     // Don't fold subregister extracts into tied operands, only if it is a full
294     // copy since a subregister use tied to a full register def doesn't really
295     // make sense. e.g. don't fold:
296     //
297     // %vreg1 = COPY %vreg0:sub1
298     // %vreg2<tied3> = V_MAC_{F16, F32} %vreg3, %vreg4, %vreg1<tied0>
299     //
300     //  into
301     // %vreg2<tied3> = V_MAC_{F16, F32} %vreg3, %vreg4, %vreg0:sub1<tied0>
302     if (UseOp.isTied() && OpToFold.getSubReg() != AMDGPU::NoSubRegister)
303       return;
304   }
305 
306   // Special case for REG_SEQUENCE: We can't fold literals into
307   // REG_SEQUENCE instructions, so we have to fold them into the
308   // uses of REG_SEQUENCE.
309   if (UseMI->isRegSequence()) {
310     unsigned RegSeqDstReg = UseMI->getOperand(0).getReg();
311     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
312 
313     for (MachineRegisterInfo::use_iterator
314            RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end();
315          RSUse != RSE; ++RSUse) {
316 
317       MachineInstr *RSUseMI = RSUse->getParent();
318       if (RSUse->getSubReg() != RegSeqDstSubReg)
319         continue;
320 
321       foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
322                   CopiesToReplace);
323     }
324 
325     return;
326   }
327 
328 
329   bool FoldingImm = OpToFold.isImm();
330 
331   // In order to fold immediates into copies, we need to change the
332   // copy to a MOV.
333   if (FoldingImm && UseMI->isCopy()) {
334     unsigned DestReg = UseMI->getOperand(0).getReg();
335     const TargetRegisterClass *DestRC
336       = TargetRegisterInfo::isVirtualRegister(DestReg) ?
337       MRI->getRegClass(DestReg) :
338       TRI->getPhysRegClass(DestReg);
339 
340     unsigned MovOp = TII->getMovOpcode(DestRC);
341     if (MovOp == AMDGPU::COPY)
342       return;
343 
344     UseMI->setDesc(TII->get(MovOp));
345     CopiesToReplace.push_back(UseMI);
346   } else {
347     const MCInstrDesc &UseDesc = UseMI->getDesc();
348 
349     // Don't fold into target independent nodes.  Target independent opcodes
350     // don't have defined register classes.
351     if (UseDesc.isVariadic() ||
352         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
353       return;
354   }
355 
356   if (!FoldingImm) {
357     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
358 
359     // FIXME: We could try to change the instruction from 64-bit to 32-bit
360     // to enable more folding opportunites.  The shrink operands pass
361     // already does this.
362     return;
363   }
364 
365 
366   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
367   const TargetRegisterClass *FoldRC =
368     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
369 
370   APInt Imm(TII->operandBitWidth(FoldDesc.OpInfo[1].OperandType),
371             OpToFold.getImm());
372 
373   // Split 64-bit constants into 32-bits for folding.
374   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
375     unsigned UseReg = UseOp.getReg();
376     const TargetRegisterClass *UseRC
377       = TargetRegisterInfo::isVirtualRegister(UseReg) ?
378       MRI->getRegClass(UseReg) :
379       TRI->getPhysRegClass(UseReg);
380 
381     assert(Imm.getBitWidth() == 64);
382 
383     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
384       return;
385 
386     if (UseOp.getSubReg() == AMDGPU::sub0) {
387       Imm = Imm.getLoBits(32);
388     } else {
389       assert(UseOp.getSubReg() == AMDGPU::sub1);
390       Imm = Imm.getHiBits(32);
391     }
392   }
393 
394   MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
395   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
396 }
397 
398 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
399                                   uint32_t LHS, uint32_t RHS) {
400   switch (Opcode) {
401   case AMDGPU::V_AND_B32_e64:
402   case AMDGPU::V_AND_B32_e32:
403   case AMDGPU::S_AND_B32:
404     Result = LHS & RHS;
405     return true;
406   case AMDGPU::V_OR_B32_e64:
407   case AMDGPU::V_OR_B32_e32:
408   case AMDGPU::S_OR_B32:
409     Result = LHS | RHS;
410     return true;
411   case AMDGPU::V_XOR_B32_e64:
412   case AMDGPU::V_XOR_B32_e32:
413   case AMDGPU::S_XOR_B32:
414     Result = LHS ^ RHS;
415     return true;
416   case AMDGPU::V_LSHL_B32_e64:
417   case AMDGPU::V_LSHL_B32_e32:
418   case AMDGPU::S_LSHL_B32:
419     // The instruction ignores the high bits for out of bounds shifts.
420     Result = LHS << (RHS & 31);
421     return true;
422   case AMDGPU::V_LSHLREV_B32_e64:
423   case AMDGPU::V_LSHLREV_B32_e32:
424     Result = RHS << (LHS & 31);
425     return true;
426   case AMDGPU::V_LSHR_B32_e64:
427   case AMDGPU::V_LSHR_B32_e32:
428   case AMDGPU::S_LSHR_B32:
429     Result = LHS >> (RHS & 31);
430     return true;
431   case AMDGPU::V_LSHRREV_B32_e64:
432   case AMDGPU::V_LSHRREV_B32_e32:
433     Result = RHS >> (LHS & 31);
434     return true;
435   case AMDGPU::V_ASHR_I32_e64:
436   case AMDGPU::V_ASHR_I32_e32:
437   case AMDGPU::S_ASHR_I32:
438     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
439     return true;
440   case AMDGPU::V_ASHRREV_I32_e64:
441   case AMDGPU::V_ASHRREV_I32_e32:
442     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
443     return true;
444   default:
445     return false;
446   }
447 }
448 
449 static unsigned getMovOpc(bool IsScalar) {
450   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
451 }
452 
453 /// Remove any leftover implicit operands from mutating the instruction. e.g.
454 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
455 /// anymore.
456 static void stripExtraCopyOperands(MachineInstr &MI) {
457   const MCInstrDesc &Desc = MI.getDesc();
458   unsigned NumOps = Desc.getNumOperands() +
459                     Desc.getNumImplicitUses() +
460                     Desc.getNumImplicitDefs();
461 
462   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
463     MI.RemoveOperand(I);
464 }
465 
466 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
467   MI.setDesc(NewDesc);
468   stripExtraCopyOperands(MI);
469 }
470 
471 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
472                                                MachineOperand &Op) {
473   if (Op.isReg()) {
474     // If this has a subregister, it obviously is a register source.
475     if (Op.getSubReg() != AMDGPU::NoSubRegister)
476       return &Op;
477 
478     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
479     if (Def->isMoveImmediate()) {
480       MachineOperand &ImmSrc = Def->getOperand(1);
481       if (ImmSrc.isImm())
482         return &ImmSrc;
483     }
484   }
485 
486   return &Op;
487 }
488 
489 // Try to simplify operations with a constant that may appear after instruction
490 // selection.
491 // TODO: See if a frame index with a fixed offset can fold.
492 static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
493                               const SIInstrInfo *TII,
494                               MachineInstr *MI,
495                               MachineOperand *ImmOp) {
496   unsigned Opc = MI->getOpcode();
497   if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
498       Opc == AMDGPU::S_NOT_B32) {
499     MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
500     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
501     return true;
502   }
503 
504   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
505   if (Src1Idx == -1)
506     return false;
507 
508   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
509   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
510   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
511 
512   if (!Src0->isImm() && !Src1->isImm())
513     return false;
514 
515   // and k0, k1 -> v_mov_b32 (k0 & k1)
516   // or k0, k1 -> v_mov_b32 (k0 | k1)
517   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
518   if (Src0->isImm() && Src1->isImm()) {
519     int32_t NewImm;
520     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
521       return false;
522 
523     const SIRegisterInfo &TRI = TII->getRegisterInfo();
524     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
525 
526     // Be careful to change the right operand, src0 may belong to a different
527     // instruction.
528     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
529     MI->RemoveOperand(Src1Idx);
530     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
531     return true;
532   }
533 
534   if (!MI->isCommutable())
535     return false;
536 
537   if (Src0->isImm() && !Src1->isImm()) {
538     std::swap(Src0, Src1);
539     std::swap(Src0Idx, Src1Idx);
540   }
541 
542   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
543   if (Opc == AMDGPU::V_OR_B32_e64 ||
544       Opc == AMDGPU::V_OR_B32_e32 ||
545       Opc == AMDGPU::S_OR_B32) {
546     if (Src1Val == 0) {
547       // y = or x, 0 => y = copy x
548       MI->RemoveOperand(Src1Idx);
549       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
550     } else if (Src1Val == -1) {
551       // y = or x, -1 => y = v_mov_b32 -1
552       MI->RemoveOperand(Src1Idx);
553       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
554     } else
555       return false;
556 
557     return true;
558   }
559 
560   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
561       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
562       MI->getOpcode() == AMDGPU::S_AND_B32) {
563     if (Src1Val == 0) {
564       // y = and x, 0 => y = v_mov_b32 0
565       MI->RemoveOperand(Src0Idx);
566       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
567     } else if (Src1Val == -1) {
568       // y = and x, -1 => y = copy x
569       MI->RemoveOperand(Src1Idx);
570       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
571       stripExtraCopyOperands(*MI);
572     } else
573       return false;
574 
575     return true;
576   }
577 
578   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
579       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
580       MI->getOpcode() == AMDGPU::S_XOR_B32) {
581     if (Src1Val == 0) {
582       // y = xor x, 0 => y = copy x
583       MI->RemoveOperand(Src1Idx);
584       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
585       return true;
586     }
587   }
588 
589   return false;
590 }
591 
592 void SIFoldOperands::foldInstOperand(MachineInstr &MI,
593                                      MachineOperand &OpToFold) const {
594   // We need mutate the operands of new mov instructions to add implicit
595   // uses of EXEC, but adding them invalidates the use_iterator, so defer
596   // this.
597   SmallVector<MachineInstr *, 4> CopiesToReplace;
598   SmallVector<FoldCandidate, 4> FoldList;
599   MachineOperand &Dst = MI.getOperand(0);
600 
601   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
602   if (FoldingImm) {
603     unsigned NumLiteralUses = 0;
604     MachineOperand *NonInlineUse = nullptr;
605     int NonInlineUseOpNo = -1;
606 
607     MachineRegisterInfo::use_iterator NextUse, NextInstUse;
608     for (MachineRegisterInfo::use_iterator
609            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
610          Use != E; Use = NextUse) {
611       NextUse = std::next(Use);
612       MachineInstr *UseMI = Use->getParent();
613       unsigned OpNo = Use.getOperandNo();
614 
615       // Folding the immediate may reveal operations that can be constant
616       // folded or replaced with a copy. This can happen for example after
617       // frame indices are lowered to constants or from splitting 64-bit
618       // constants.
619       //
620       // We may also encounter cases where one or both operands are
621       // immediates materialized into a register, which would ordinarily not
622       // be folded due to multiple uses or operand constraints.
623 
624       if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
625         DEBUG(dbgs() << "Constant folded " << *UseMI <<'\n');
626 
627         // Some constant folding cases change the same immediate's use to a new
628         // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
629         // again. The same constant folded instruction could also have a second
630         // use operand.
631         NextUse = MRI->use_begin(Dst.getReg());
632         continue;
633       }
634 
635       // Try to fold any inline immediate uses, and then only fold other
636       // constants if they have one use.
637       //
638       // The legality of the inline immediate must be checked based on the use
639       // operand, not the defining instruction, because 32-bit instructions
640       // with 32-bit inline immediate sources may be used to materialize
641       // constants used in 16-bit operands.
642       //
643       // e.g. it is unsafe to fold:
644       //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
645       //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
646 
647       // Folding immediates with more than one use will increase program size.
648       // FIXME: This will also reduce register usage, which may be better
649       // in some cases. A better heuristic is needed.
650       if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
651         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
652       } else {
653         if (++NumLiteralUses == 1) {
654           NonInlineUse = &*Use;
655           NonInlineUseOpNo = OpNo;
656         }
657       }
658     }
659 
660     if (NumLiteralUses == 1) {
661       MachineInstr *UseMI = NonInlineUse->getParent();
662       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
663     }
664   } else {
665     // Folding register.
666     for (MachineRegisterInfo::use_iterator
667            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
668          Use != E; ++Use) {
669       MachineInstr *UseMI = Use->getParent();
670 
671       foldOperand(OpToFold, UseMI, Use.getOperandNo(),
672                   FoldList, CopiesToReplace);
673     }
674   }
675 
676   MachineFunction *MF = MI.getParent()->getParent();
677   // Make sure we add EXEC uses to any new v_mov instructions created.
678   for (MachineInstr *Copy : CopiesToReplace)
679     Copy->addImplicitDefUseOperands(*MF);
680 
681   for (FoldCandidate &Fold : FoldList) {
682     if (updateOperand(Fold, *TRI)) {
683       // Clear kill flags.
684       if (Fold.isReg()) {
685         assert(Fold.OpToFold && Fold.OpToFold->isReg());
686         // FIXME: Probably shouldn't bother trying to fold if not an
687         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
688         // copies.
689         MRI->clearKillFlags(Fold.OpToFold->getReg());
690       }
691       DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " <<
692             static_cast<int>(Fold.UseOpNo) << " of " << *Fold.UseMI << '\n');
693     }
694   }
695 }
696 
697 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
698   unsigned Op = MI.getOpcode();
699   switch (Op) {
700   case AMDGPU::V_MAX_F32_e64:
701   case AMDGPU::V_MAX_F16_e64:
702   case AMDGPU::V_MAX_F64: {
703     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
704       return nullptr;
705 
706     // Make sure sources are identical.
707     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
708     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
709     if (!Src0->isReg() || Src0->getSubReg() != Src1->getSubReg() ||
710         Src0->getSubReg() != AMDGPU::NoSubRegister)
711       return nullptr;
712 
713     // Can't fold up if we have modifiers.
714     if (TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
715         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
716         TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
717       return nullptr;
718     return Src0;
719   }
720   default:
721     return nullptr;
722   }
723 }
724 
725 // We obviously have multiple uses in a clamp since the register is used twice
726 // in the same instruction.
727 static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
728   int Count = 0;
729   for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
730        I != E; ++I) {
731     if (++Count > 1)
732       return false;
733   }
734 
735   return true;
736 }
737 
738 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
739   const MachineOperand *ClampSrc = isClamp(MI);
740   if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
741     return false;
742 
743   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
744   if (!TII->hasFPClamp(*Def))
745     return false;
746   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
747   if (!DefClamp)
748     return false;
749 
750   DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def << '\n');
751 
752   // Clamp is applied after omod, so it is OK if omod is set.
753   DefClamp->setImm(1);
754   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
755   MI.eraseFromParent();
756   return true;
757 }
758 
759 static int getOModValue(unsigned Opc, int64_t Val) {
760   switch (Opc) {
761   case AMDGPU::V_MUL_F32_e64: {
762     switch (static_cast<uint32_t>(Val)) {
763     case 0x3f000000: // 0.5
764       return SIOutMods::DIV2;
765     case 0x40000000: // 2.0
766       return SIOutMods::MUL2;
767     case 0x40800000: // 4.0
768       return SIOutMods::MUL4;
769     default:
770       return SIOutMods::NONE;
771     }
772   }
773   case AMDGPU::V_MUL_F16_e64: {
774     switch (static_cast<uint16_t>(Val)) {
775     case 0x3800: // 0.5
776       return SIOutMods::DIV2;
777     case 0x4000: // 2.0
778       return SIOutMods::MUL2;
779     case 0x4400: // 4.0
780       return SIOutMods::MUL4;
781     default:
782       return SIOutMods::NONE;
783     }
784   }
785   default:
786     llvm_unreachable("invalid mul opcode");
787   }
788 }
789 
790 // FIXME: Does this really not support denormals with f16?
791 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
792 // handled, so will anything other than that break?
793 std::pair<const MachineOperand *, int>
794 SIFoldOperands::isOMod(const MachineInstr &MI) const {
795   unsigned Op = MI.getOpcode();
796   switch (Op) {
797   case AMDGPU::V_MUL_F32_e64:
798   case AMDGPU::V_MUL_F16_e64: {
799     // If output denormals are enabled, omod is ignored.
800     if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) ||
801         (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals()))
802       return std::make_pair(nullptr, SIOutMods::NONE);
803 
804     const MachineOperand *RegOp = nullptr;
805     const MachineOperand *ImmOp = nullptr;
806     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
807     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
808     if (Src0->isImm()) {
809       ImmOp = Src0;
810       RegOp = Src1;
811     } else if (Src1->isImm()) {
812       ImmOp = Src1;
813       RegOp = Src0;
814     } else
815       return std::make_pair(nullptr, SIOutMods::NONE);
816 
817     int OMod = getOModValue(Op, ImmOp->getImm());
818     if (OMod == SIOutMods::NONE ||
819         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
820         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
821         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
822         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
823       return std::make_pair(nullptr, SIOutMods::NONE);
824 
825     return std::make_pair(RegOp, OMod);
826   }
827   case AMDGPU::V_ADD_F32_e64:
828   case AMDGPU::V_ADD_F16_e64: {
829     // If output denormals are enabled, omod is ignored.
830     if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) ||
831         (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals()))
832       return std::make_pair(nullptr, SIOutMods::NONE);
833 
834     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
835     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
836     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
837 
838     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
839         Src0->getSubReg() == Src1->getSubReg() &&
840         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
841         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
842         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
843         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
844       return std::make_pair(Src0, SIOutMods::MUL2);
845 
846     return std::make_pair(nullptr, SIOutMods::NONE);
847   }
848   default:
849     return std::make_pair(nullptr, SIOutMods::NONE);
850   }
851 }
852 
853 // FIXME: Does this need to check IEEE bit on function?
854 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
855   const MachineOperand *RegOp;
856   int OMod;
857   std::tie(RegOp, OMod) = isOMod(MI);
858   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
859       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
860       !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
861     return false;
862 
863   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
864   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
865   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
866     return false;
867 
868   // Clamp is applied after omod. If the source already has clamp set, don't
869   // fold it.
870   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
871     return false;
872 
873   DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
874 
875   DefOMod->setImm(OMod);
876   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
877   MI.eraseFromParent();
878   return true;
879 }
880 
881 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
882   if (skipFunction(*MF.getFunction()))
883     return false;
884 
885   MRI = &MF.getRegInfo();
886   ST = &MF.getSubtarget<SISubtarget>();
887   TII = ST->getInstrInfo();
888   TRI = &TII->getRegisterInfo();
889 
890   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
891 
892   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
893   // correctly handle signed zeros.
894   //
895   // TODO: Check nsz on instructions when fast math flags are preserved to MI
896   // level.
897   bool IsIEEEMode = ST->enableIEEEBit(MF) || !MFI->hasNoSignedZerosFPMath();
898 
899   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
900        BI != BE; ++BI) {
901 
902     MachineBasicBlock &MBB = *BI;
903     MachineBasicBlock::iterator I, Next;
904     for (I = MBB.begin(); I != MBB.end(); I = Next) {
905       Next = std::next(I);
906       MachineInstr &MI = *I;
907 
908       if (!isFoldableCopy(MI)) {
909         if (IsIEEEMode || !tryFoldOMod(MI))
910           tryFoldClamp(MI);
911         continue;
912       }
913 
914       MachineOperand &OpToFold = MI.getOperand(1);
915       bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
916 
917       // FIXME: We could also be folding things like TargetIndexes.
918       if (!FoldingImm && !OpToFold.isReg())
919         continue;
920 
921       if (OpToFold.isReg() &&
922           !TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()))
923         continue;
924 
925       // Prevent folding operands backwards in the function. For example,
926       // the COPY opcode must not be replaced by 1 in this example:
927       //
928       //    %vreg3<def> = COPY %VGPR0; VGPR_32:%vreg3
929       //    ...
930       //    %VGPR0<def> = V_MOV_B32_e32 1, %EXEC<imp-use>
931       MachineOperand &Dst = MI.getOperand(0);
932       if (Dst.isReg() &&
933           !TargetRegisterInfo::isVirtualRegister(Dst.getReg()))
934         continue;
935 
936       foldInstOperand(MI, OpToFold);
937     }
938   }
939   return false;
940 }
941