1 //===-- SIWholeQuadMode.cpp - enter and suspend whole quad mode -----------===//
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 /// \file
10 /// This pass adds instructions to enable whole quad mode for pixel
11 /// shaders, and whole wavefront mode for all programs.
12 ///
13 /// Whole quad mode is required for derivative computations, but it interferes
14 /// with shader side effects (stores and atomics). This pass is run on the
15 /// scheduled machine IR but before register coalescing, so that machine SSA is
16 /// available for analysis. It ensures that WQM is enabled when necessary, but
17 /// disabled around stores and atomics.
18 ///
19 /// When necessary, this pass creates a function prolog
20 ///
21 ///   S_MOV_B64 LiveMask, EXEC
22 ///   S_WQM_B64 EXEC, EXEC
23 ///
24 /// to enter WQM at the top of the function and surrounds blocks of Exact
25 /// instructions by
26 ///
27 ///   S_AND_SAVEEXEC_B64 Tmp, LiveMask
28 ///   ...
29 ///   S_MOV_B64 EXEC, Tmp
30 ///
31 /// We also compute when a sequence of instructions requires Whole Wavefront
32 /// Mode (WWM) and insert instructions to save and restore it:
33 ///
34 /// S_OR_SAVEEXEC_B64 Tmp, -1
35 /// ...
36 /// S_MOV_B64 EXEC, Tmp
37 ///
38 /// In order to avoid excessive switching during sequences of Exact
39 /// instructions, the pass first analyzes which instructions must be run in WQM
40 /// (aka which instructions produce values that lead to derivative
41 /// computations).
42 ///
43 /// Basic blocks are always exited in WQM as long as some successor needs WQM.
44 ///
45 /// There is room for improvement given better control flow analysis:
46 ///
47 ///  (1) at the top level (outside of control flow statements, and as long as
48 ///      kill hasn't been used), one SGPR can be saved by recovering WQM from
49 ///      the LiveMask (this is implemented for the entry block).
50 ///
51 ///  (2) when entire regions (e.g. if-else blocks or entire loops) only
52 ///      consist of exact and don't-care instructions, the switch only has to
53 ///      be done at the entry and exit points rather than potentially in each
54 ///      block of the region.
55 ///
56 //===----------------------------------------------------------------------===//
57 
58 #include "AMDGPU.h"
59 #include "AMDGPUSubtarget.h"
60 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
61 #include "SIInstrInfo.h"
62 #include "SIMachineFunctionInfo.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/PostOrderIterator.h"
65 #include "llvm/ADT/SmallVector.h"
66 #include "llvm/ADT/StringRef.h"
67 #include "llvm/CodeGen/LiveInterval.h"
68 #include "llvm/CodeGen/LiveIntervals.h"
69 #include "llvm/CodeGen/MachineBasicBlock.h"
70 #include "llvm/CodeGen/MachineFunction.h"
71 #include "llvm/CodeGen/MachineFunctionPass.h"
72 #include "llvm/CodeGen/MachineInstr.h"
73 #include "llvm/CodeGen/MachineInstrBuilder.h"
74 #include "llvm/CodeGen/MachineOperand.h"
75 #include "llvm/CodeGen/MachineRegisterInfo.h"
76 #include "llvm/CodeGen/SlotIndexes.h"
77 #include "llvm/CodeGen/TargetRegisterInfo.h"
78 #include "llvm/IR/CallingConv.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/InitializePasses.h"
81 #include "llvm/MC/MCRegisterInfo.h"
82 #include "llvm/Pass.h"
83 #include "llvm/Support/Debug.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include <cassert>
86 #include <vector>
87 
88 using namespace llvm;
89 
90 #define DEBUG_TYPE "si-wqm"
91 
92 namespace {
93 
94 enum {
95   StateWQM = 0x1,
96   StateWWM = 0x2,
97   StateExact = 0x4,
98 };
99 
100 struct PrintState {
101 public:
102   int State;
103 
104   explicit PrintState(int State) : State(State) {}
105 };
106 
107 #ifndef NDEBUG
108 static raw_ostream &operator<<(raw_ostream &OS, const PrintState &PS) {
109   if (PS.State & StateWQM)
110     OS << "WQM";
111   if (PS.State & StateWWM) {
112     if (PS.State & StateWQM)
113       OS << '|';
114     OS << "WWM";
115   }
116   if (PS.State & StateExact) {
117     if (PS.State & (StateWQM | StateWWM))
118       OS << '|';
119     OS << "Exact";
120   }
121 
122   return OS;
123 }
124 #endif
125 
126 struct InstrInfo {
127   char Needs = 0;
128   char Disabled = 0;
129   char OutNeeds = 0;
130 };
131 
132 struct BlockInfo {
133   char Needs = 0;
134   char InNeeds = 0;
135   char OutNeeds = 0;
136 };
137 
138 struct WorkItem {
139   MachineBasicBlock *MBB = nullptr;
140   MachineInstr *MI = nullptr;
141 
142   WorkItem() = default;
143   WorkItem(MachineBasicBlock *MBB) : MBB(MBB) {}
144   WorkItem(MachineInstr *MI) : MI(MI) {}
145 };
146 
147 class SIWholeQuadMode : public MachineFunctionPass {
148 private:
149   CallingConv::ID CallingConv;
150   const SIInstrInfo *TII;
151   const SIRegisterInfo *TRI;
152   const GCNSubtarget *ST;
153   MachineRegisterInfo *MRI;
154   LiveIntervals *LIS;
155 
156   DenseMap<const MachineInstr *, InstrInfo> Instructions;
157   DenseMap<MachineBasicBlock *, BlockInfo> Blocks;
158   SmallVector<MachineInstr *, 1> LiveMaskQueries;
159   SmallVector<MachineInstr *, 4> LowerToMovInstrs;
160   SmallVector<MachineInstr *, 4> LowerToCopyInstrs;
161 
162   void printInfo();
163 
164   void markInstruction(MachineInstr &MI, char Flag,
165                        std::vector<WorkItem> &Worklist);
166   void markInstructionUses(const MachineInstr &MI, char Flag,
167                            std::vector<WorkItem> &Worklist);
168   char scanInstructions(MachineFunction &MF, std::vector<WorkItem> &Worklist);
169   void propagateInstruction(MachineInstr &MI, std::vector<WorkItem> &Worklist);
170   void propagateBlock(MachineBasicBlock &MBB, std::vector<WorkItem> &Worklist);
171   char analyzeFunction(MachineFunction &MF);
172 
173   bool requiresCorrectState(const MachineInstr &MI) const;
174 
175   MachineBasicBlock::iterator saveSCC(MachineBasicBlock &MBB,
176                                       MachineBasicBlock::iterator Before);
177   MachineBasicBlock::iterator
178   prepareInsertion(MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
179                    MachineBasicBlock::iterator Last, bool PreferLast,
180                    bool SaveSCC);
181   void toExact(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
182                unsigned SaveWQM, unsigned LiveMaskReg);
183   void toWQM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
184              unsigned SavedWQM);
185   void toWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
186              unsigned SaveOrig);
187   void fromWWM(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
188                unsigned SavedOrig);
189   void processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg, bool isEntry);
190 
191   void lowerLiveMaskQueries(unsigned LiveMaskReg);
192   void lowerCopyInstrs();
193 
194 public:
195   static char ID;
196 
197   SIWholeQuadMode() :
198     MachineFunctionPass(ID) { }
199 
200   bool runOnMachineFunction(MachineFunction &MF) override;
201 
202   StringRef getPassName() const override { return "SI Whole Quad Mode"; }
203 
204   void getAnalysisUsage(AnalysisUsage &AU) const override {
205     AU.addRequired<LiveIntervals>();
206     AU.addPreserved<SlotIndexes>();
207     AU.addPreserved<LiveIntervals>();
208     AU.setPreservesCFG();
209     MachineFunctionPass::getAnalysisUsage(AU);
210   }
211 };
212 
213 } // end anonymous namespace
214 
215 char SIWholeQuadMode::ID = 0;
216 
217 INITIALIZE_PASS_BEGIN(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
218                       false)
219 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
220 INITIALIZE_PASS_END(SIWholeQuadMode, DEBUG_TYPE, "SI Whole Quad Mode", false,
221                     false)
222 
223 char &llvm::SIWholeQuadModeID = SIWholeQuadMode::ID;
224 
225 FunctionPass *llvm::createSIWholeQuadModePass() {
226   return new SIWholeQuadMode;
227 }
228 
229 #ifndef NDEBUG
230 LLVM_DUMP_METHOD void SIWholeQuadMode::printInfo() {
231   for (const auto &BII : Blocks) {
232     dbgs() << "\n"
233            << printMBBReference(*BII.first) << ":\n"
234            << "  InNeeds = " << PrintState(BII.second.InNeeds)
235            << ", Needs = " << PrintState(BII.second.Needs)
236            << ", OutNeeds = " << PrintState(BII.second.OutNeeds) << "\n\n";
237 
238     for (const MachineInstr &MI : *BII.first) {
239       auto III = Instructions.find(&MI);
240       if (III == Instructions.end())
241         continue;
242 
243       dbgs() << "  " << MI << "    Needs = " << PrintState(III->second.Needs)
244              << ", OutNeeds = " << PrintState(III->second.OutNeeds) << '\n';
245     }
246   }
247 }
248 #endif
249 
250 void SIWholeQuadMode::markInstruction(MachineInstr &MI, char Flag,
251                                       std::vector<WorkItem> &Worklist) {
252   InstrInfo &II = Instructions[&MI];
253 
254   assert(!(Flag & StateExact) && Flag != 0);
255 
256   // Remove any disabled states from the flag. The user that required it gets
257   // an undefined value in the helper lanes. For example, this can happen if
258   // the result of an atomic is used by instruction that requires WQM, where
259   // ignoring the request for WQM is correct as per the relevant specs.
260   Flag &= ~II.Disabled;
261 
262   // Ignore if the flag is already encompassed by the existing needs, or we
263   // just disabled everything.
264   if ((II.Needs & Flag) == Flag)
265     return;
266 
267   II.Needs |= Flag;
268   Worklist.push_back(&MI);
269 }
270 
271 /// Mark all instructions defining the uses in \p MI with \p Flag.
272 void SIWholeQuadMode::markInstructionUses(const MachineInstr &MI, char Flag,
273                                           std::vector<WorkItem> &Worklist) {
274   for (const MachineOperand &Use : MI.uses()) {
275     if (!Use.isReg() || !Use.isUse())
276       continue;
277 
278     Register Reg = Use.getReg();
279 
280     // Handle physical registers that we need to track; this is mostly relevant
281     // for VCC, which can appear as the (implicit) input of a uniform branch,
282     // e.g. when a loop counter is stored in a VGPR.
283     if (!Register::isVirtualRegister(Reg)) {
284       if (Reg == AMDGPU::EXEC || Reg == AMDGPU::EXEC_LO)
285         continue;
286 
287       for (MCRegUnitIterator RegUnit(Reg, TRI); RegUnit.isValid(); ++RegUnit) {
288         LiveRange &LR = LIS->getRegUnit(*RegUnit);
289         const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn();
290         if (!Value)
291           continue;
292 
293         // Since we're in machine SSA, we do not need to track physical
294         // registers across basic blocks.
295         if (Value->isPHIDef())
296           continue;
297 
298         markInstruction(*LIS->getInstructionFromIndex(Value->def), Flag,
299                         Worklist);
300       }
301 
302       continue;
303     }
304 
305     for (MachineInstr &DefMI : MRI->def_instructions(Use.getReg()))
306       markInstruction(DefMI, Flag, Worklist);
307   }
308 }
309 
310 // Scan instructions to determine which ones require an Exact execmask and
311 // which ones seed WQM requirements.
312 char SIWholeQuadMode::scanInstructions(MachineFunction &MF,
313                                        std::vector<WorkItem> &Worklist) {
314   char GlobalFlags = 0;
315   bool WQMOutputs = MF.getFunction().hasFnAttribute("amdgpu-ps-wqm-outputs");
316   SmallVector<MachineInstr *, 4> SetInactiveInstrs;
317   SmallVector<MachineInstr *, 4> SoftWQMInstrs;
318 
319   // We need to visit the basic blocks in reverse post-order so that we visit
320   // defs before uses, in particular so that we don't accidentally mark an
321   // instruction as needing e.g. WQM before visiting it and realizing it needs
322   // WQM disabled.
323   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
324   for (auto BI = RPOT.begin(), BE = RPOT.end(); BI != BE; ++BI) {
325     MachineBasicBlock &MBB = **BI;
326     BlockInfo &BBI = Blocks[&MBB];
327 
328     for (auto II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
329       MachineInstr &MI = *II;
330       InstrInfo &III = Instructions[&MI];
331       unsigned Opcode = MI.getOpcode();
332       char Flags = 0;
333 
334       if (TII->isWQM(Opcode)) {
335         // Sampling instructions don't need to produce results for all pixels
336         // in a quad, they just require all inputs of a quad to have been
337         // computed for derivatives.
338         markInstructionUses(MI, StateWQM, Worklist);
339         GlobalFlags |= StateWQM;
340         continue;
341       } else if (Opcode == AMDGPU::WQM) {
342         // The WQM intrinsic requires its output to have all the helper lanes
343         // correct, so we need it to be in WQM.
344         Flags = StateWQM;
345         LowerToCopyInstrs.push_back(&MI);
346       } else if (Opcode == AMDGPU::SOFT_WQM) {
347         LowerToCopyInstrs.push_back(&MI);
348         SoftWQMInstrs.push_back(&MI);
349         continue;
350       } else if (Opcode == AMDGPU::WWM) {
351         // The WWM intrinsic doesn't make the same guarantee, and plus it needs
352         // to be executed in WQM or Exact so that its copy doesn't clobber
353         // inactive lanes.
354         markInstructionUses(MI, StateWWM, Worklist);
355         GlobalFlags |= StateWWM;
356         LowerToMovInstrs.push_back(&MI);
357         continue;
358       } else if (Opcode == AMDGPU::V_SET_INACTIVE_B32 ||
359                  Opcode == AMDGPU::V_SET_INACTIVE_B64) {
360         III.Disabled = StateWWM;
361         MachineOperand &Inactive = MI.getOperand(2);
362         if (Inactive.isReg()) {
363           if (Inactive.isUndef()) {
364             LowerToCopyInstrs.push_back(&MI);
365           } else {
366             Register Reg = Inactive.getReg();
367             if (Register::isVirtualRegister(Reg)) {
368               for (MachineInstr &DefMI : MRI->def_instructions(Reg))
369                 markInstruction(DefMI, StateWWM, Worklist);
370             }
371           }
372         }
373         SetInactiveInstrs.push_back(&MI);
374         continue;
375       } else if (TII->isDisableWQM(MI)) {
376         BBI.Needs |= StateExact;
377         if (!(BBI.InNeeds & StateExact)) {
378           BBI.InNeeds |= StateExact;
379           Worklist.push_back(&MBB);
380         }
381         GlobalFlags |= StateExact;
382         III.Disabled = StateWQM | StateWWM;
383         continue;
384       } else {
385         if (Opcode == AMDGPU::SI_PS_LIVE) {
386           LiveMaskQueries.push_back(&MI);
387         } else if (WQMOutputs) {
388           // The function is in machine SSA form, which means that physical
389           // VGPRs correspond to shader inputs and outputs. Inputs are
390           // only used, outputs are only defined.
391           for (const MachineOperand &MO : MI.defs()) {
392             if (!MO.isReg())
393               continue;
394 
395             Register Reg = MO.getReg();
396 
397             if (!Register::isVirtualRegister(Reg) &&
398                 TRI->hasVectorRegisters(TRI->getPhysRegClass(Reg))) {
399               Flags = StateWQM;
400               break;
401             }
402           }
403         }
404 
405         if (!Flags)
406           continue;
407       }
408 
409       markInstruction(MI, Flags, Worklist);
410       GlobalFlags |= Flags;
411     }
412   }
413 
414   // Mark sure that any SET_INACTIVE instructions are computed in WQM if WQM is
415   // ever used anywhere in the function. This implements the corresponding
416   // semantics of @llvm.amdgcn.set.inactive.
417   // Similarly for SOFT_WQM instructions, implementing @llvm.amdgcn.softwqm.
418   if (GlobalFlags & StateWQM) {
419     for (MachineInstr *MI : SetInactiveInstrs)
420       markInstruction(*MI, StateWQM, Worklist);
421     for (MachineInstr *MI : SoftWQMInstrs)
422       markInstruction(*MI, StateWQM, Worklist);
423   }
424 
425   return GlobalFlags;
426 }
427 
428 void SIWholeQuadMode::propagateInstruction(MachineInstr &MI,
429                                            std::vector<WorkItem>& Worklist) {
430   MachineBasicBlock *MBB = MI.getParent();
431   InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references
432   BlockInfo &BI = Blocks[MBB];
433 
434   // Control flow-type instructions and stores to temporary memory that are
435   // followed by WQM computations must themselves be in WQM.
436   if ((II.OutNeeds & StateWQM) && !(II.Disabled & StateWQM) &&
437       (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) {
438     Instructions[&MI].Needs = StateWQM;
439     II.Needs = StateWQM;
440   }
441 
442   // Propagate to block level
443   if (II.Needs & StateWQM) {
444     BI.Needs |= StateWQM;
445     if (!(BI.InNeeds & StateWQM)) {
446       BI.InNeeds |= StateWQM;
447       Worklist.push_back(MBB);
448     }
449   }
450 
451   // Propagate backwards within block
452   if (MachineInstr *PrevMI = MI.getPrevNode()) {
453     char InNeeds = (II.Needs & ~StateWWM) | II.OutNeeds;
454     if (!PrevMI->isPHI()) {
455       InstrInfo &PrevII = Instructions[PrevMI];
456       if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
457         PrevII.OutNeeds |= InNeeds;
458         Worklist.push_back(PrevMI);
459       }
460     }
461   }
462 
463   // Propagate WQM flag to instruction inputs
464   assert(!(II.Needs & StateExact));
465 
466   if (II.Needs != 0)
467     markInstructionUses(MI, II.Needs, Worklist);
468 
469   // Ensure we process a block containing WWM, even if it does not require any
470   // WQM transitions.
471   if (II.Needs & StateWWM)
472     BI.Needs |= StateWWM;
473 }
474 
475 void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB,
476                                      std::vector<WorkItem>& Worklist) {
477   BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references.
478 
479   // Propagate through instructions
480   if (!MBB.empty()) {
481     MachineInstr *LastMI = &*MBB.rbegin();
482     InstrInfo &LastII = Instructions[LastMI];
483     if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
484       LastII.OutNeeds |= BI.OutNeeds;
485       Worklist.push_back(LastMI);
486     }
487   }
488 
489   // Predecessor blocks must provide for our WQM/Exact needs.
490   for (MachineBasicBlock *Pred : MBB.predecessors()) {
491     BlockInfo &PredBI = Blocks[Pred];
492     if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
493       continue;
494 
495     PredBI.OutNeeds |= BI.InNeeds;
496     PredBI.InNeeds |= BI.InNeeds;
497     Worklist.push_back(Pred);
498   }
499 
500   // All successors must be prepared to accept the same set of WQM/Exact data.
501   for (MachineBasicBlock *Succ : MBB.successors()) {
502     BlockInfo &SuccBI = Blocks[Succ];
503     if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
504       continue;
505 
506     SuccBI.InNeeds |= BI.OutNeeds;
507     Worklist.push_back(Succ);
508   }
509 }
510 
511 char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) {
512   std::vector<WorkItem> Worklist;
513   char GlobalFlags = scanInstructions(MF, Worklist);
514 
515   while (!Worklist.empty()) {
516     WorkItem WI = Worklist.back();
517     Worklist.pop_back();
518 
519     if (WI.MI)
520       propagateInstruction(*WI.MI, Worklist);
521     else
522       propagateBlock(*WI.MBB, Worklist);
523   }
524 
525   return GlobalFlags;
526 }
527 
528 /// Whether \p MI really requires the exec state computed during analysis.
529 ///
530 /// Scalar instructions must occasionally be marked WQM for correct propagation
531 /// (e.g. thread masks leading up to branches), but when it comes to actual
532 /// execution, they don't care about EXEC.
533 bool SIWholeQuadMode::requiresCorrectState(const MachineInstr &MI) const {
534   if (MI.isTerminator())
535     return true;
536 
537   // Skip instructions that are not affected by EXEC
538   if (TII->isScalarUnit(MI))
539     return false;
540 
541   // Generic instructions such as COPY will either disappear by register
542   // coalescing or be lowered to SALU or VALU instructions.
543   if (MI.isTransient()) {
544     if (MI.getNumExplicitOperands() >= 1) {
545       const MachineOperand &Op = MI.getOperand(0);
546       if (Op.isReg()) {
547         if (TRI->isSGPRReg(*MRI, Op.getReg())) {
548           // SGPR instructions are not affected by EXEC
549           return false;
550         }
551       }
552     }
553   }
554 
555   return true;
556 }
557 
558 MachineBasicBlock::iterator
559 SIWholeQuadMode::saveSCC(MachineBasicBlock &MBB,
560                          MachineBasicBlock::iterator Before) {
561   Register SaveReg = MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
562 
563   MachineInstr *Save =
564       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), SaveReg)
565           .addReg(AMDGPU::SCC);
566   MachineInstr *Restore =
567       BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::SCC)
568           .addReg(SaveReg);
569 
570   LIS->InsertMachineInstrInMaps(*Save);
571   LIS->InsertMachineInstrInMaps(*Restore);
572   LIS->createAndComputeVirtRegInterval(SaveReg);
573 
574   return Restore;
575 }
576 
577 // Return an iterator in the (inclusive) range [First, Last] at which
578 // instructions can be safely inserted, keeping in mind that some of the
579 // instructions we want to add necessarily clobber SCC.
580 MachineBasicBlock::iterator SIWholeQuadMode::prepareInsertion(
581     MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
582     MachineBasicBlock::iterator Last, bool PreferLast, bool SaveSCC) {
583   if (!SaveSCC)
584     return PreferLast ? Last : First;
585 
586   LiveRange &LR = LIS->getRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
587   auto MBBE = MBB.end();
588   SlotIndex FirstIdx = First != MBBE ? LIS->getInstructionIndex(*First)
589                                      : LIS->getMBBEndIdx(&MBB);
590   SlotIndex LastIdx =
591       Last != MBBE ? LIS->getInstructionIndex(*Last) : LIS->getMBBEndIdx(&MBB);
592   SlotIndex Idx = PreferLast ? LastIdx : FirstIdx;
593   const LiveRange::Segment *S;
594 
595   for (;;) {
596     S = LR.getSegmentContaining(Idx);
597     if (!S)
598       break;
599 
600     if (PreferLast) {
601       SlotIndex Next = S->start.getBaseIndex();
602       if (Next < FirstIdx)
603         break;
604       Idx = Next;
605     } else {
606       SlotIndex Next = S->end.getNextIndex().getBaseIndex();
607       if (Next > LastIdx)
608         break;
609       Idx = Next;
610     }
611   }
612 
613   MachineBasicBlock::iterator MBBI;
614 
615   if (MachineInstr *MI = LIS->getInstructionFromIndex(Idx))
616     MBBI = MI;
617   else {
618     assert(Idx == LIS->getMBBEndIdx(&MBB));
619     MBBI = MBB.end();
620   }
621 
622   if (S)
623     MBBI = saveSCC(MBB, MBBI);
624 
625   return MBBI;
626 }
627 
628 void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
629                               MachineBasicBlock::iterator Before,
630                               unsigned SaveWQM, unsigned LiveMaskReg) {
631   MachineInstr *MI;
632 
633   if (SaveWQM) {
634     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
635                    AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64),
636                  SaveWQM)
637              .addReg(LiveMaskReg);
638   } else {
639     unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
640     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
641                    AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64),
642                  Exec)
643              .addReg(Exec)
644              .addReg(LiveMaskReg);
645   }
646 
647   LIS->InsertMachineInstrInMaps(*MI);
648 }
649 
650 void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
651                             MachineBasicBlock::iterator Before,
652                             unsigned SavedWQM) {
653   MachineInstr *MI;
654 
655   unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
656   if (SavedWQM) {
657     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), Exec)
658              .addReg(SavedWQM);
659   } else {
660     MI = BuildMI(MBB, Before, DebugLoc(), TII->get(ST->isWave32() ?
661                    AMDGPU::S_WQM_B32 : AMDGPU::S_WQM_B64),
662                  Exec)
663              .addReg(Exec);
664   }
665 
666   LIS->InsertMachineInstrInMaps(*MI);
667 }
668 
669 void SIWholeQuadMode::toWWM(MachineBasicBlock &MBB,
670                             MachineBasicBlock::iterator Before,
671                             unsigned SaveOrig) {
672   MachineInstr *MI;
673 
674   assert(SaveOrig);
675   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::ENTER_WWM), SaveOrig)
676            .addImm(-1);
677   LIS->InsertMachineInstrInMaps(*MI);
678 }
679 
680 void SIWholeQuadMode::fromWWM(MachineBasicBlock &MBB,
681                               MachineBasicBlock::iterator Before,
682                               unsigned SavedOrig) {
683   MachineInstr *MI;
684 
685   assert(SavedOrig);
686   MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::EXIT_WWM),
687                ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC)
688            .addReg(SavedOrig);
689   LIS->InsertMachineInstrInMaps(*MI);
690 }
691 
692 void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, unsigned LiveMaskReg,
693                                    bool isEntry) {
694   auto BII = Blocks.find(&MBB);
695   if (BII == Blocks.end())
696     return;
697 
698   const BlockInfo &BI = BII->second;
699 
700   // This is a non-entry block that is WQM throughout, so no need to do
701   // anything.
702   if (!isEntry && BI.Needs == StateWQM && BI.OutNeeds != StateExact)
703     return;
704 
705   LLVM_DEBUG(dbgs() << "\nProcessing block " << printMBBReference(MBB)
706                     << ":\n");
707 
708   unsigned SavedWQMReg = 0;
709   unsigned SavedNonWWMReg = 0;
710   bool WQMFromExec = isEntry;
711   char State = (isEntry || !(BI.InNeeds & StateWQM)) ? StateExact : StateWQM;
712   char NonWWMState = 0;
713   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
714 
715   auto II = MBB.getFirstNonPHI(), IE = MBB.end();
716   if (isEntry)
717     ++II; // Skip the instruction that saves LiveMask
718 
719   // This stores the first instruction where it's safe to switch from WQM to
720   // Exact or vice versa.
721   MachineBasicBlock::iterator FirstWQM = IE;
722 
723   // This stores the first instruction where it's safe to switch from WWM to
724   // Exact/WQM or to switch to WWM. It must always be the same as, or after,
725   // FirstWQM since if it's safe to switch to/from WWM, it must be safe to
726   // switch to/from WQM as well.
727   MachineBasicBlock::iterator FirstWWM = IE;
728   for (;;) {
729     MachineBasicBlock::iterator Next = II;
730     char Needs = StateExact | StateWQM; // WWM is disabled by default
731     char OutNeeds = 0;
732 
733     if (FirstWQM == IE)
734       FirstWQM = II;
735 
736     if (FirstWWM == IE)
737       FirstWWM = II;
738 
739     // First, figure out the allowed states (Needs) based on the propagated
740     // flags.
741     if (II != IE) {
742       MachineInstr &MI = *II;
743 
744       if (requiresCorrectState(MI)) {
745         auto III = Instructions.find(&MI);
746         if (III != Instructions.end()) {
747           if (III->second.Needs & StateWWM)
748             Needs = StateWWM;
749           else if (III->second.Needs & StateWQM)
750             Needs = StateWQM;
751           else
752             Needs &= ~III->second.Disabled;
753           OutNeeds = III->second.OutNeeds;
754         }
755       } else {
756         // If the instruction doesn't actually need a correct EXEC, then we can
757         // safely leave WWM enabled.
758         Needs = StateExact | StateWQM | StateWWM;
759       }
760 
761       if (MI.isTerminator() && OutNeeds == StateExact)
762         Needs = StateExact;
763 
764       if (MI.getOpcode() == AMDGPU::SI_ELSE && BI.OutNeeds == StateExact)
765         MI.getOperand(3).setImm(1);
766 
767       ++Next;
768     } else {
769       // End of basic block
770       if (BI.OutNeeds & StateWQM)
771         Needs = StateWQM;
772       else if (BI.OutNeeds == StateExact)
773         Needs = StateExact;
774       else
775         Needs = StateWQM | StateExact;
776     }
777 
778     // Now, transition if necessary.
779     if (!(Needs & State)) {
780       MachineBasicBlock::iterator First;
781       if (State == StateWWM || Needs == StateWWM) {
782         // We must switch to or from WWM
783         First = FirstWWM;
784       } else {
785         // We only need to switch to/from WQM, so we can use FirstWQM
786         First = FirstWQM;
787       }
788 
789       MachineBasicBlock::iterator Before =
790           prepareInsertion(MBB, First, II, Needs == StateWQM,
791                            Needs == StateExact || WQMFromExec);
792 
793       if (State == StateWWM) {
794         assert(SavedNonWWMReg);
795         fromWWM(MBB, Before, SavedNonWWMReg);
796         State = NonWWMState;
797       }
798 
799       if (Needs == StateWWM) {
800         NonWWMState = State;
801         SavedNonWWMReg = MRI->createVirtualRegister(BoolRC);
802         toWWM(MBB, Before, SavedNonWWMReg);
803         State = StateWWM;
804       } else {
805         if (State == StateWQM && (Needs & StateExact) && !(Needs & StateWQM)) {
806           if (!WQMFromExec && (OutNeeds & StateWQM))
807             SavedWQMReg = MRI->createVirtualRegister(BoolRC);
808 
809           toExact(MBB, Before, SavedWQMReg, LiveMaskReg);
810           State = StateExact;
811         } else if (State == StateExact && (Needs & StateWQM) &&
812                    !(Needs & StateExact)) {
813           assert(WQMFromExec == (SavedWQMReg == 0));
814 
815           toWQM(MBB, Before, SavedWQMReg);
816 
817           if (SavedWQMReg) {
818             LIS->createAndComputeVirtRegInterval(SavedWQMReg);
819             SavedWQMReg = 0;
820           }
821           State = StateWQM;
822         } else {
823           // We can get here if we transitioned from WWM to a non-WWM state that
824           // already matches our needs, but we shouldn't need to do anything.
825           assert(Needs & State);
826         }
827       }
828     }
829 
830     if (Needs != (StateExact | StateWQM | StateWWM)) {
831       if (Needs != (StateExact | StateWQM))
832         FirstWQM = IE;
833       FirstWWM = IE;
834     }
835 
836     if (II == IE)
837       break;
838     II = Next;
839   }
840 }
841 
842 void SIWholeQuadMode::lowerLiveMaskQueries(unsigned LiveMaskReg) {
843   for (MachineInstr *MI : LiveMaskQueries) {
844     const DebugLoc &DL = MI->getDebugLoc();
845     Register Dest = MI->getOperand(0).getReg();
846     MachineInstr *Copy =
847         BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest)
848             .addReg(LiveMaskReg);
849 
850     LIS->ReplaceMachineInstrInMaps(*MI, *Copy);
851     MI->eraseFromParent();
852   }
853 }
854 
855 void SIWholeQuadMode::lowerCopyInstrs() {
856   for (MachineInstr *MI : LowerToMovInstrs) {
857     assert(MI->getNumExplicitOperands() == 2);
858 
859     const Register Reg = MI->getOperand(0).getReg();
860 
861     if (TRI->isVGPR(*MRI, Reg)) {
862       const TargetRegisterClass *regClass = Register::isVirtualRegister(Reg)
863                                                 ? MRI->getRegClass(Reg)
864                                                 : TRI->getPhysRegClass(Reg);
865 
866       const unsigned MovOp = TII->getMovOpcode(regClass);
867       MI->setDesc(TII->get(MovOp));
868 
869       // And make it implicitly depend on exec (like all VALU movs should do).
870       MI->addOperand(MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
871     } else {
872       MI->setDesc(TII->get(AMDGPU::COPY));
873     }
874   }
875   for (MachineInstr *MI : LowerToCopyInstrs) {
876     if (MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B32 ||
877         MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B64) {
878       assert(MI->getNumExplicitOperands() == 3);
879       // the only reason we should be here is V_SET_INACTIVE has
880       // an undef input so it is being replaced by a simple copy.
881       // There should be a second undef source that we should remove.
882       assert(MI->getOperand(2).isUndef());
883       MI->RemoveOperand(2);
884       MI->untieRegOperand(1);
885     } else {
886       assert(MI->getNumExplicitOperands() == 2);
887     }
888 
889     MI->setDesc(TII->get(AMDGPU::COPY));
890   }
891 }
892 
893 bool SIWholeQuadMode::runOnMachineFunction(MachineFunction &MF) {
894   Instructions.clear();
895   Blocks.clear();
896   LiveMaskQueries.clear();
897   LowerToCopyInstrs.clear();
898   LowerToMovInstrs.clear();
899   CallingConv = MF.getFunction().getCallingConv();
900 
901   ST = &MF.getSubtarget<GCNSubtarget>();
902 
903   TII = ST->getInstrInfo();
904   TRI = &TII->getRegisterInfo();
905   MRI = &MF.getRegInfo();
906   LIS = &getAnalysis<LiveIntervals>();
907 
908   char GlobalFlags = analyzeFunction(MF);
909   unsigned LiveMaskReg = 0;
910   unsigned Exec = ST->isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
911   if (!(GlobalFlags & StateWQM)) {
912     lowerLiveMaskQueries(Exec);
913     if (!(GlobalFlags & StateWWM) && LowerToCopyInstrs.empty() && LowerToMovInstrs.empty())
914       return !LiveMaskQueries.empty();
915   } else {
916     // Store a copy of the original live mask when required
917     MachineBasicBlock &Entry = MF.front();
918     MachineBasicBlock::iterator EntryMI = Entry.getFirstNonPHI();
919 
920     if (GlobalFlags & StateExact || !LiveMaskQueries.empty()) {
921       LiveMaskReg = MRI->createVirtualRegister(TRI->getBoolRC());
922       MachineInstr *MI = BuildMI(Entry, EntryMI, DebugLoc(),
923                                  TII->get(AMDGPU::COPY), LiveMaskReg)
924                              .addReg(Exec);
925       LIS->InsertMachineInstrInMaps(*MI);
926     }
927 
928     lowerLiveMaskQueries(LiveMaskReg);
929 
930     if (GlobalFlags == StateWQM) {
931       // For a shader that needs only WQM, we can just set it once.
932       BuildMI(Entry, EntryMI, DebugLoc(), TII->get(ST->isWave32() ?
933                 AMDGPU::S_WQM_B32 : AMDGPU::S_WQM_B64),
934               Exec)
935           .addReg(Exec);
936 
937       lowerCopyInstrs();
938       // EntryMI may become invalid here
939       return true;
940     }
941   }
942 
943   LLVM_DEBUG(printInfo());
944 
945   lowerCopyInstrs();
946 
947   // Handle the general case
948   for (auto BII : Blocks)
949     processBlock(*BII.first, LiveMaskReg, BII.first == &*MF.begin());
950 
951   // Physical registers like SCC aren't tracked by default anyway, so just
952   // removing the ranges we computed is the simplest option for maintaining
953   // the analysis results.
954   LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::SCC, TRI));
955 
956   return true;
957 }
958