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