xref: /llvm-project/llvm/lib/Target/AMDGPU/SIModeRegister.cpp (revision 90777e2924ec7f99a3f1b718a636f47036012514)
1 //===-- SIModeRegister.cpp - Mode Register --------------------------------===//
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 /// \file
9 /// This pass inserts changes to the Mode register settings as required.
10 /// Note that currently it only deals with the Double Precision Floating Point
11 /// rounding mode setting, but is intended to be generic enough to be easily
12 /// expanded.
13 ///
14 //===----------------------------------------------------------------------===//
15 //
16 #include "AMDGPU.h"
17 #include "AMDGPUInstrInfo.h"
18 #include "AMDGPUSubtarget.h"
19 #include "SIInstrInfo.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include <queue>
32 
33 #define DEBUG_TYPE "si-mode-register"
34 
35 STATISTIC(NumSetregInserted, "Number of setreg of mode register inserted.");
36 
37 using namespace llvm;
38 
39 struct Status {
40   // Mask is a bitmask where a '1' indicates the corresponding Mode bit has a
41   // known value
42   unsigned Mask;
43   unsigned Mode;
44 
45   Status() : Mask(0), Mode(0){};
46 
47   Status(unsigned NewMask, unsigned NewMode) : Mask(NewMask), Mode(NewMode) {
48     Mode &= Mask;
49   };
50 
51   // merge two status values such that only values that don't conflict are
52   // preserved
53   Status merge(const Status &S) const {
54     return Status((Mask | S.Mask), ((Mode & ~S.Mask) | (S.Mode & S.Mask)));
55   }
56 
57   // merge an unknown value by using the unknown value's mask to remove bits
58   // from the result
59   Status mergeUnknown(unsigned newMask) {
60     return Status(Mask & ~newMask, Mode & ~newMask);
61   }
62 
63   // intersect two Status values to produce a mode and mask that is a subset
64   // of both values
65   Status intersect(const Status &S) const {
66     unsigned NewMask = (Mask & S.Mask) & (Mode ^ ~S.Mode);
67     unsigned NewMode = (Mode & NewMask);
68     return Status(NewMask, NewMode);
69   }
70 
71   // produce the delta required to change the Mode to the required Mode
72   Status delta(const Status &S) const {
73     return Status((S.Mask & (Mode ^ S.Mode)) | (~Mask & S.Mask), S.Mode);
74   }
75 
76   bool operator==(const Status &S) const {
77     return (Mask == S.Mask) && (Mode == S.Mode);
78   }
79 
80   bool operator!=(const Status &S) const { return !(*this == S); }
81 
82   bool isCompatible(Status &S) {
83     return ((Mask & S.Mask) == S.Mask) && ((Mode & S.Mask) == S.Mode);
84   }
85 
86   bool isCombinable(Status &S) { return !(Mask & S.Mask) || isCompatible(S); }
87 };
88 
89 class BlockData {
90 public:
91   // The Status that represents the mode register settings required by the
92   // FirstInsertionPoint (if any) in this block. Calculated in Phase 1.
93   Status Require;
94 
95   // The Status that represents the net changes to the Mode register made by
96   // this block, Calculated in Phase 1.
97   Status Change;
98 
99   // The Status that represents the mode register settings on exit from this
100   // block. Calculated in Phase 2.
101   Status Exit;
102 
103   // The Status that represents the intersection of exit Mode register settings
104   // from all predecessor blocks. Calculated in Phase 2, and used by Phase 3.
105   Status Pred;
106 
107   // In Phase 1 we record the first instruction that has a mode requirement,
108   // which is used in Phase 3 if we need to insert a mode change.
109   MachineInstr *FirstInsertionPoint;
110 
111   // A flag to indicate whether an Exit value has been set (we can't tell by
112   // examining the Exit value itself as all values may be valid results).
113   bool ExitSet;
114 
115   BlockData() : FirstInsertionPoint(nullptr), ExitSet(false){};
116 };
117 
118 namespace {
119 
120 class SIModeRegister : public MachineFunctionPass {
121 public:
122   static char ID;
123 
124   std::vector<std::unique_ptr<BlockData>> BlockInfo;
125   std::queue<MachineBasicBlock *> Phase2List;
126 
127   // The default mode register setting currently only caters for the floating
128   // point double precision rounding mode.
129   // We currently assume the default rounding mode is Round to Nearest
130   // NOTE: this should come from a per function rounding mode setting once such
131   // a setting exists.
132   unsigned DefaultMode = FP_ROUND_ROUND_TO_NEAREST;
133   Status DefaultStatus =
134       Status(FP_ROUND_MODE_DP(0x3), FP_ROUND_MODE_DP(DefaultMode));
135 
136   bool Changed = false;
137 
138 public:
139   SIModeRegister() : MachineFunctionPass(ID) {}
140 
141   bool runOnMachineFunction(MachineFunction &MF) override;
142 
143   void getAnalysisUsage(AnalysisUsage &AU) const override {
144     AU.setPreservesCFG();
145     MachineFunctionPass::getAnalysisUsage(AU);
146   }
147 
148   void processBlockPhase1(MachineBasicBlock &MBB, const SIInstrInfo *TII);
149 
150   void processBlockPhase2(MachineBasicBlock &MBB, const SIInstrInfo *TII);
151 
152   void processBlockPhase3(MachineBasicBlock &MBB, const SIInstrInfo *TII);
153 
154   Status getInstructionMode(MachineInstr &MI, const SIInstrInfo *TII);
155 
156   void insertSetreg(MachineBasicBlock &MBB, MachineInstr *I,
157                     const SIInstrInfo *TII, Status InstrMode);
158 };
159 } // End anonymous namespace.
160 
161 INITIALIZE_PASS(SIModeRegister, DEBUG_TYPE,
162                 "Insert required mode register values", false, false)
163 
164 char SIModeRegister::ID = 0;
165 
166 char &llvm::SIModeRegisterID = SIModeRegister::ID;
167 
168 FunctionPass *llvm::createSIModeRegisterPass() { return new SIModeRegister(); }
169 
170 // Determine the Mode register setting required for this instruction.
171 // Instructions which don't use the Mode register return a null Status.
172 // Note this currently only deals with instructions that use the floating point
173 // double precision setting.
174 Status SIModeRegister::getInstructionMode(MachineInstr &MI,
175                                           const SIInstrInfo *TII) {
176   if (TII->usesFPDPRounding(MI)) {
177     switch (MI.getOpcode()) {
178     case AMDGPU::V_INTERP_P1LL_F16:
179     case AMDGPU::V_INTERP_P1LV_F16:
180     case AMDGPU::V_INTERP_P2_F16:
181       // f16 interpolation instructions need double precision round to zero
182       return Status(FP_ROUND_MODE_DP(3),
183                     FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_ZERO));
184     default:
185       return DefaultStatus;
186     }
187   }
188   return Status();
189 }
190 
191 // Insert a setreg instruction to update the Mode register.
192 // It is possible (though unlikely) for an instruction to require a change to
193 // the value of disjoint parts of the Mode register when we don't know the
194 // value of the intervening bits. In that case we need to use more than one
195 // setreg instruction.
196 void SIModeRegister::insertSetreg(MachineBasicBlock &MBB, MachineInstr *MI,
197                                   const SIInstrInfo *TII, Status InstrMode) {
198   while (InstrMode.Mask) {
199     unsigned Offset = countTrailingZeros<unsigned>(InstrMode.Mask);
200     unsigned Width = countTrailingOnes<unsigned>(InstrMode.Mask >> Offset);
201     unsigned Value = (InstrMode.Mode >> Offset) & ((1 << Width) - 1);
202     BuildMI(MBB, MI, 0, TII->get(AMDGPU::S_SETREG_IMM32_B32))
203         .addImm(Value)
204         .addImm(((Width - 1) << AMDGPU::Hwreg::WIDTH_M1_SHIFT_) |
205                 (Offset << AMDGPU::Hwreg::OFFSET_SHIFT_) |
206                 (AMDGPU::Hwreg::ID_MODE << AMDGPU::Hwreg::ID_SHIFT_));
207     ++NumSetregInserted;
208     Changed = true;
209     InstrMode.Mask &= ~(((1 << Width) - 1) << Offset);
210   }
211 }
212 
213 // In Phase 1 we iterate through the instructions of the block and for each
214 // instruction we get its mode usage. If the instruction uses the Mode register
215 // we:
216 // - update the Change status, which tracks the changes to the Mode register
217 //   made by this block
218 // - if this instruction's requirements are compatible with the current setting
219 //   of the Mode register we merge the modes
220 // - if it isn't compatible and an InsertionPoint isn't set, then we set the
221 //   InsertionPoint to the current instruction, and we remember the current
222 //   mode
223 // - if it isn't compatible and InsertionPoint is set we insert a seteg before
224 //   that instruction (unless this instruction forms part of the block's
225 //   entry requirements in which case the insertion is deferred until Phase 3
226 //   when predecessor exit values are known), and move the insertion point to
227 //   this instruction
228 // - if this is a setreg instruction we treat it as an incompatible instruction.
229 //   This is sub-optimal but avoids some nasty corner cases, and is expected to
230 //   occur very rarely.
231 // - on exit we have set the Require, Change, and initial Exit modes.
232 void SIModeRegister::processBlockPhase1(MachineBasicBlock &MBB,
233                                         const SIInstrInfo *TII) {
234   auto NewInfo = std::make_unique<BlockData>();
235   MachineInstr *InsertionPoint = nullptr;
236   // RequirePending is used to indicate whether we are collecting the initial
237   // requirements for the block, and need to defer the first InsertionPoint to
238   // Phase 3. It is set to false once we have set FirstInsertionPoint, or when
239   // we discover an explict setreg that means this block doesn't have any
240   // initial requirements.
241   bool RequirePending = true;
242   Status IPChange;
243   for (MachineInstr &MI : MBB) {
244     Status InstrMode = getInstructionMode(MI, TII);
245     if (MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
246         MI.getOpcode() == AMDGPU::S_SETREG_B32_mode ||
247         MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
248         MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) {
249       // We preserve any explicit mode register setreg instruction we encounter,
250       // as we assume it has been inserted by a higher authority (this is
251       // likely to be a very rare occurrence).
252       unsigned Dst = TII->getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm();
253       if (((Dst & AMDGPU::Hwreg::ID_MASK_) >> AMDGPU::Hwreg::ID_SHIFT_) !=
254           AMDGPU::Hwreg::ID_MODE)
255         continue;
256 
257       unsigned Width = ((Dst & AMDGPU::Hwreg::WIDTH_M1_MASK_) >>
258                         AMDGPU::Hwreg::WIDTH_M1_SHIFT_) +
259                        1;
260       unsigned Offset =
261           (Dst & AMDGPU::Hwreg::OFFSET_MASK_) >> AMDGPU::Hwreg::OFFSET_SHIFT_;
262       unsigned Mask = ((1 << Width) - 1) << Offset;
263 
264       // If an InsertionPoint is set we will insert a setreg there.
265       if (InsertionPoint) {
266         insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change));
267         InsertionPoint = nullptr;
268       }
269       // If this is an immediate then we know the value being set, but if it is
270       // not an immediate then we treat the modified bits of the mode register
271       // as unknown.
272       if (MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
273           MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) {
274         unsigned Val = TII->getNamedOperand(MI, AMDGPU::OpName::imm)->getImm();
275         unsigned Mode = (Val << Offset) & Mask;
276         Status Setreg = Status(Mask, Mode);
277         // If we haven't already set the initial requirements for the block we
278         // don't need to as the requirements start from this explicit setreg.
279         RequirePending = false;
280         NewInfo->Change = NewInfo->Change.merge(Setreg);
281       } else {
282         NewInfo->Change = NewInfo->Change.mergeUnknown(Mask);
283       }
284     } else if (!NewInfo->Change.isCompatible(InstrMode)) {
285       // This instruction uses the Mode register and its requirements aren't
286       // compatible with the current mode.
287       if (InsertionPoint) {
288         // If the required mode change cannot be included in the current
289         // InsertionPoint changes, we need a setreg and start a new
290         // InsertionPoint.
291         if (!IPChange.delta(NewInfo->Change).isCombinable(InstrMode)) {
292           if (RequirePending) {
293             // This is the first insertionPoint in the block so we will defer
294             // the insertion of the setreg to Phase 3 where we know whether or
295             // not it is actually needed.
296             NewInfo->FirstInsertionPoint = InsertionPoint;
297             NewInfo->Require = NewInfo->Change;
298             RequirePending = false;
299           } else {
300             insertSetreg(MBB, InsertionPoint, TII,
301                          IPChange.delta(NewInfo->Change));
302             IPChange = NewInfo->Change;
303           }
304           // Set the new InsertionPoint
305           InsertionPoint = &MI;
306         }
307         NewInfo->Change = NewInfo->Change.merge(InstrMode);
308       } else {
309         // No InsertionPoint is currently set - this is either the first in
310         // the block or we have previously seen an explicit setreg.
311         InsertionPoint = &MI;
312         IPChange = NewInfo->Change;
313         NewInfo->Change = NewInfo->Change.merge(InstrMode);
314       }
315     }
316   }
317   if (RequirePending) {
318     // If we haven't yet set the initial requirements for the block we set them
319     // now.
320     NewInfo->FirstInsertionPoint = InsertionPoint;
321     NewInfo->Require = NewInfo->Change;
322   } else if (InsertionPoint) {
323     // We need to insert a setreg at the InsertionPoint
324     insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change));
325   }
326   NewInfo->Exit = NewInfo->Change;
327   BlockInfo[MBB.getNumber()] = std::move(NewInfo);
328 }
329 
330 // In Phase 2 we revisit each block and calculate the common Mode register
331 // value provided by all predecessor blocks. If the Exit value for the block
332 // is changed, then we add the successor blocks to the worklist so that the
333 // exit value is propagated.
334 void SIModeRegister::processBlockPhase2(MachineBasicBlock &MBB,
335                                         const SIInstrInfo *TII) {
336   bool RevisitRequired = false;
337   bool ExitSet = false;
338   unsigned ThisBlock = MBB.getNumber();
339   if (MBB.pred_empty()) {
340     // There are no predecessors, so use the default starting status.
341     BlockInfo[ThisBlock]->Pred = DefaultStatus;
342     ExitSet = true;
343   } else {
344     // Build a status that is common to all the predecessors by intersecting
345     // all the predecessor exit status values.
346     // Mask bits (which represent the Mode bits with a known value) can only be
347     // added by explicit SETREG instructions or the initial default value -
348     // the intersection process may remove Mask bits.
349     // If we find a predecessor that has not yet had an exit value determined
350     // (this can happen for example if a block is its own predecessor) we defer
351     // use of that value as the Mask will be all zero, and we will revisit this
352     // block again later (unless the only predecessor without an exit value is
353     // this block).
354     MachineBasicBlock::pred_iterator P = MBB.pred_begin(), E = MBB.pred_end();
355     MachineBasicBlock &PB = *(*P);
356     unsigned PredBlock = PB.getNumber();
357     if ((ThisBlock == PredBlock) && (std::next(P) == E)) {
358       BlockInfo[ThisBlock]->Pred = DefaultStatus;
359       ExitSet = true;
360     } else if (BlockInfo[PredBlock]->ExitSet) {
361       BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit;
362       ExitSet = true;
363     } else if (PredBlock != ThisBlock)
364       RevisitRequired = true;
365 
366     for (P = std::next(P); P != E; P = std::next(P)) {
367       MachineBasicBlock *Pred = *P;
368       unsigned PredBlock = Pred->getNumber();
369       if (BlockInfo[PredBlock]->ExitSet) {
370         if (BlockInfo[ThisBlock]->ExitSet) {
371           BlockInfo[ThisBlock]->Pred =
372               BlockInfo[ThisBlock]->Pred.intersect(BlockInfo[PredBlock]->Exit);
373         } else {
374           BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit;
375         }
376         ExitSet = true;
377       } else if (PredBlock != ThisBlock)
378         RevisitRequired = true;
379     }
380   }
381   Status TmpStatus =
382       BlockInfo[ThisBlock]->Pred.merge(BlockInfo[ThisBlock]->Change);
383   if (BlockInfo[ThisBlock]->Exit != TmpStatus) {
384     BlockInfo[ThisBlock]->Exit = TmpStatus;
385     // Add the successors to the work list so we can propagate the changed exit
386     // status.
387     for (MachineBasicBlock::succ_iterator S = MBB.succ_begin(),
388                                           E = MBB.succ_end();
389          S != E; S = std::next(S)) {
390       MachineBasicBlock &B = *(*S);
391       Phase2List.push(&B);
392     }
393   }
394   BlockInfo[ThisBlock]->ExitSet = ExitSet;
395   if (RevisitRequired)
396     Phase2List.push(&MBB);
397 }
398 
399 // In Phase 3 we revisit each block and if it has an insertion point defined we
400 // check whether the predecessor mode meets the block's entry requirements. If
401 // not we insert an appropriate setreg instruction to modify the Mode register.
402 void SIModeRegister::processBlockPhase3(MachineBasicBlock &MBB,
403                                         const SIInstrInfo *TII) {
404   unsigned ThisBlock = MBB.getNumber();
405   if (!BlockInfo[ThisBlock]->Pred.isCompatible(BlockInfo[ThisBlock]->Require)) {
406     Status Delta =
407         BlockInfo[ThisBlock]->Pred.delta(BlockInfo[ThisBlock]->Require);
408     if (BlockInfo[ThisBlock]->FirstInsertionPoint)
409       insertSetreg(MBB, BlockInfo[ThisBlock]->FirstInsertionPoint, TII, Delta);
410     else
411       insertSetreg(MBB, &MBB.instr_front(), TII, Delta);
412   }
413 }
414 
415 bool SIModeRegister::runOnMachineFunction(MachineFunction &MF) {
416   BlockInfo.resize(MF.getNumBlockIDs());
417   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
418   const SIInstrInfo *TII = ST.getInstrInfo();
419 
420   // Processing is performed in a number of phases
421 
422   // Phase 1 - determine the initial mode required by each block, and add setreg
423   // instructions for intra block requirements.
424   for (MachineBasicBlock &BB : MF)
425     processBlockPhase1(BB, TII);
426 
427   // Phase 2 - determine the exit mode from each block. We add all blocks to the
428   // list here, but will also add any that need to be revisited during Phase 2
429   // processing.
430   for (MachineBasicBlock &BB : MF)
431     Phase2List.push(&BB);
432   while (!Phase2List.empty()) {
433     processBlockPhase2(*Phase2List.front(), TII);
434     Phase2List.pop();
435   }
436 
437   // Phase 3 - add an initial setreg to each block where the required entry mode
438   // is not satisfied by the exit mode of all its predecessors.
439   for (MachineBasicBlock &BB : MF)
440     processBlockPhase3(BB, TII);
441 
442   BlockInfo.clear();
443 
444   return Changed;
445 }
446