LLVM  9.0.0svn
SILowerI1Copies.cpp
Go to the documentation of this file.
1 //===-- SILowerI1Copies.cpp - Lower I1 Copies -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass lowers all occurrences of i1 values (with a vreg_1 register class)
10 // to lane masks (64-bit scalar registers). The pass assumes machine SSA form
11 // and a wave-level control flow graph.
12 //
13 // Before this pass, values that are semantically i1 and are defined and used
14 // within the same basic block are already represented as lane masks in scalar
15 // registers. However, values that cross basic blocks are always transferred
16 // between basic blocks in vreg_1 virtual registers and are lowered by this
17 // pass.
18 //
19 // The only instructions that use or define vreg_1 virtual registers are COPY,
20 // PHI, and IMPLICIT_DEF.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "AMDGPU.h"
25 #include "AMDGPUSubtarget.h"
27 #include "SIInstrInfo.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/Debug.h"
38 
39 #define DEBUG_TYPE "si-i1-copies"
40 
41 using namespace llvm;
42 
43 static unsigned createLaneMaskReg(MachineFunction &MF);
44 static unsigned insertUndefLaneMask(MachineBasicBlock &MBB);
45 
46 namespace {
47 
48 class SILowerI1Copies : public MachineFunctionPass {
49 public:
50  static char ID;
51 
52 private:
53  MachineFunction *MF = nullptr;
54  MachineDominatorTree *DT = nullptr;
55  MachinePostDominatorTree *PDT = nullptr;
56  MachineRegisterInfo *MRI = nullptr;
57  const GCNSubtarget *ST = nullptr;
58  const SIInstrInfo *TII = nullptr;
59 
60  DenseSet<unsigned> ConstrainRegs;
61 
62 public:
63  SILowerI1Copies() : MachineFunctionPass(ID) {
65  }
66 
67  bool runOnMachineFunction(MachineFunction &MF) override;
68 
69  StringRef getPassName() const override { return "SI Lower i1 Copies"; }
70 
71  void getAnalysisUsage(AnalysisUsage &AU) const override {
72  AU.setPreservesCFG();
76  }
77 
78 private:
79  void lowerCopiesFromI1();
80  void lowerPhis();
81  void lowerCopiesToI1();
82  bool isConstantLaneMask(unsigned Reg, bool &Val) const;
83  void buildMergeLaneMasks(MachineBasicBlock &MBB,
85  unsigned DstReg, unsigned PrevReg, unsigned CurReg);
87  getSaluInsertionAtEnd(MachineBasicBlock &MBB) const;
88 
89  bool isLaneMaskReg(unsigned Reg) const {
90  return TII->getRegisterInfo().isSGPRReg(*MRI, Reg) &&
91  TII->getRegisterInfo().getRegSizeInBits(Reg, *MRI) ==
92  ST->getWavefrontSize();
93  }
94 };
95 
96 /// Helper class that determines the relationship between incoming values of a
97 /// phi in the control flow graph to determine where an incoming value can
98 /// simply be taken as a scalar lane mask as-is, and where it needs to be
99 /// merged with another, previously defined lane mask.
100 ///
101 /// The approach is as follows:
102 /// - Determine all basic blocks which, starting from the incoming blocks,
103 /// a wave may reach before entering the def block (the block containing the
104 /// phi).
105 /// - If an incoming block has no predecessors in this set, we can take the
106 /// incoming value as a scalar lane mask as-is.
107 /// -- A special case of this is when the def block has a self-loop.
108 /// - Otherwise, the incoming value needs to be merged with a previously
109 /// defined lane mask.
110 /// - If there is a path into the set of reachable blocks that does _not_ go
111 /// through an incoming block where we can take the scalar lane mask as-is,
112 /// we need to invent an available value for the SSAUpdater. Choices are
113 /// 0 and undef, with differing consequences for how to merge values etc.
114 ///
115 /// TODO: We could use region analysis to quickly skip over SESE regions during
116 /// the traversal.
117 ///
118 class PhiIncomingAnalysis {
120 
121  // For each reachable basic block, whether it is a source in the induced
122  // subgraph of the CFG.
124  SmallVector<MachineBasicBlock *, 4> ReachableOrdered;
127 
128 public:
129  PhiIncomingAnalysis(MachinePostDominatorTree &PDT) : PDT(PDT) {}
130 
131  /// Returns whether \p MBB is a source in the induced subgraph of reachable
132  /// blocks.
133  bool isSource(MachineBasicBlock &MBB) const {
134  return ReachableMap.find(&MBB)->second;
135  }
136 
137  ArrayRef<MachineBasicBlock *> predecessors() const { return Predecessors; }
138 
139  void analyze(MachineBasicBlock &DefBlock,
140  ArrayRef<MachineBasicBlock *> IncomingBlocks) {
141  assert(Stack.empty());
142  ReachableMap.clear();
143  ReachableOrdered.clear();
144  Predecessors.clear();
145 
146  // Insert the def block first, so that it acts as an end point for the
147  // traversal.
148  ReachableMap.try_emplace(&DefBlock, false);
149  ReachableOrdered.push_back(&DefBlock);
150 
151  for (MachineBasicBlock *MBB : IncomingBlocks) {
152  if (MBB == &DefBlock) {
153  ReachableMap[&DefBlock] = true; // self-loop on DefBlock
154  continue;
155  }
156 
157  ReachableMap.try_emplace(MBB, false);
158  ReachableOrdered.push_back(MBB);
159 
160  // If this block has a divergent terminator and the def block is its
161  // post-dominator, the wave may first visit the other successors.
162  bool Divergent = false;
163  for (MachineInstr &MI : MBB->terminators()) {
164  if (MI.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO ||
165  MI.getOpcode() == AMDGPU::SI_IF ||
166  MI.getOpcode() == AMDGPU::SI_ELSE ||
167  MI.getOpcode() == AMDGPU::SI_LOOP) {
168  Divergent = true;
169  break;
170  }
171  }
172 
173  if (Divergent && PDT.dominates(&DefBlock, MBB)) {
174  for (MachineBasicBlock *Succ : MBB->successors())
175  Stack.push_back(Succ);
176  }
177  }
178 
179  while (!Stack.empty()) {
180  MachineBasicBlock *MBB = Stack.pop_back_val();
181  if (!ReachableMap.try_emplace(MBB, false).second)
182  continue;
183  ReachableOrdered.push_back(MBB);
184 
185  for (MachineBasicBlock *Succ : MBB->successors())
186  Stack.push_back(Succ);
187  }
188 
189  for (MachineBasicBlock *MBB : ReachableOrdered) {
190  bool HaveReachablePred = false;
191  for (MachineBasicBlock *Pred : MBB->predecessors()) {
192  if (ReachableMap.count(Pred)) {
193  HaveReachablePred = true;
194  } else {
195  Stack.push_back(Pred);
196  }
197  }
198  if (!HaveReachablePred)
199  ReachableMap[MBB] = true;
200  if (HaveReachablePred) {
201  for (MachineBasicBlock *UnreachablePred : Stack) {
202  if (llvm::find(Predecessors, UnreachablePred) == Predecessors.end())
203  Predecessors.push_back(UnreachablePred);
204  }
205  }
206  Stack.clear();
207  }
208  }
209 };
210 
211 /// Helper class that detects loops which require us to lower an i1 COPY into
212 /// bitwise manipulation.
213 ///
214 /// Unfortunately, we cannot use LoopInfo because LoopInfo does not distinguish
215 /// between loops with the same header. Consider this example:
216 ///
217 /// A-+-+
218 /// | | |
219 /// B-+ |
220 /// | |
221 /// C---+
222 ///
223 /// A is the header of a loop containing A, B, and C as far as LoopInfo is
224 /// concerned. However, an i1 COPY in B that is used in C must be lowered to
225 /// bitwise operations to combine results from different loop iterations when
226 /// B has a divergent branch (since by default we will compile this code such
227 /// that threads in a wave are merged at the entry of C).
228 ///
229 /// The following rule is implemented to determine whether bitwise operations
230 /// are required: use the bitwise lowering for a def in block B if a backward
231 /// edge to B is reachable without going through the nearest common
232 /// post-dominator of B and all uses of the def.
233 ///
234 /// TODO: This rule is conservative because it does not check whether the
235 /// relevant branches are actually divergent.
236 ///
237 /// The class is designed to cache the CFG traversal so that it can be re-used
238 /// for multiple defs within the same basic block.
239 ///
240 /// TODO: We could use region analysis to quickly skip over SESE regions during
241 /// the traversal.
242 ///
243 class LoopFinder {
246 
247  // All visited / reachable block, tagged by level (level 0 is the def block,
248  // level 1 are all blocks reachable including but not going through the def
249  // block's IPDOM, etc.).
251 
252  // Nearest common dominator of all visited blocks by level (level 0 is the
253  // def block). Used for seeding the SSAUpdater.
254  SmallVector<MachineBasicBlock *, 4> CommonDominators;
255 
256  // Post-dominator of all visited blocks.
257  MachineBasicBlock *VisitedPostDom = nullptr;
258 
259  // Level at which a loop was found: 0 is not possible; 1 = a backward edge is
260  // reachable without going through the IPDOM of the def block (if the IPDOM
261  // itself has an edge to the def block, the loop level is 2), etc.
262  unsigned FoundLoopLevel = ~0u;
263 
264  MachineBasicBlock *DefBlock = nullptr;
267 
268 public:
269  LoopFinder(MachineDominatorTree &DT, MachinePostDominatorTree &PDT)
270  : DT(DT), PDT(PDT) {}
271 
272  void initialize(MachineBasicBlock &MBB) {
273  Visited.clear();
274  CommonDominators.clear();
275  Stack.clear();
276  NextLevel.clear();
277  VisitedPostDom = nullptr;
278  FoundLoopLevel = ~0u;
279 
280  DefBlock = &MBB;
281  }
282 
283  /// Check whether a backward edge can be reached without going through the
284  /// given \p PostDom of the def block.
285  ///
286  /// Return the level of \p PostDom if a loop was found, or 0 otherwise.
287  unsigned findLoop(MachineBasicBlock *PostDom) {
288  MachineDomTreeNode *PDNode = PDT.getNode(DefBlock);
289 
290  if (!VisitedPostDom)
291  advanceLevel();
292 
293  unsigned Level = 0;
294  while (PDNode->getBlock() != PostDom) {
295  if (PDNode->getBlock() == VisitedPostDom)
296  advanceLevel();
297  PDNode = PDNode->getIDom();
298  Level++;
299  if (FoundLoopLevel == Level)
300  return Level;
301  }
302 
303  return 0;
304  }
305 
306  /// Add undef values dominating the loop and the optionally given additional
307  /// blocks, so that the SSA updater doesn't have to search all the way to the
308  /// function entry.
309  void addLoopEntries(unsigned LoopLevel, MachineSSAUpdater &SSAUpdater,
310  ArrayRef<MachineBasicBlock *> Blocks = {}) {
311  assert(LoopLevel < CommonDominators.size());
312 
313  MachineBasicBlock *Dom = CommonDominators[LoopLevel];
314  for (MachineBasicBlock *MBB : Blocks)
315  Dom = DT.findNearestCommonDominator(Dom, MBB);
316 
317  if (!inLoopLevel(*Dom, LoopLevel, Blocks)) {
318  SSAUpdater.AddAvailableValue(Dom, insertUndefLaneMask(*Dom));
319  } else {
320  // The dominator is part of the loop or the given blocks, so add the
321  // undef value to unreachable predecessors instead.
322  for (MachineBasicBlock *Pred : Dom->predecessors()) {
323  if (!inLoopLevel(*Pred, LoopLevel, Blocks))
324  SSAUpdater.AddAvailableValue(Pred, insertUndefLaneMask(*Pred));
325  }
326  }
327  }
328 
329 private:
330  bool inLoopLevel(MachineBasicBlock &MBB, unsigned LoopLevel,
331  ArrayRef<MachineBasicBlock *> Blocks) const {
332  auto DomIt = Visited.find(&MBB);
333  if (DomIt != Visited.end() && DomIt->second <= LoopLevel)
334  return true;
335 
336  if (llvm::find(Blocks, &MBB) != Blocks.end())
337  return true;
338 
339  return false;
340  }
341 
342  void advanceLevel() {
343  MachineBasicBlock *VisitedDom;
344 
345  if (!VisitedPostDom) {
346  VisitedPostDom = DefBlock;
347  VisitedDom = DefBlock;
348  Stack.push_back(DefBlock);
349  } else {
350  VisitedPostDom = PDT.getNode(VisitedPostDom)->getIDom()->getBlock();
351  VisitedDom = CommonDominators.back();
352 
353  for (unsigned i = 0; i < NextLevel.size();) {
354  if (PDT.dominates(VisitedPostDom, NextLevel[i])) {
355  Stack.push_back(NextLevel[i]);
356 
357  NextLevel[i] = NextLevel.back();
358  NextLevel.pop_back();
359  } else {
360  i++;
361  }
362  }
363  }
364 
365  unsigned Level = CommonDominators.size();
366  while (!Stack.empty()) {
367  MachineBasicBlock *MBB = Stack.pop_back_val();
368  if (!PDT.dominates(VisitedPostDom, MBB))
369  NextLevel.push_back(MBB);
370 
371  Visited[MBB] = Level;
372  VisitedDom = DT.findNearestCommonDominator(VisitedDom, MBB);
373 
374  for (MachineBasicBlock *Succ : MBB->successors()) {
375  if (Succ == DefBlock) {
376  if (MBB == VisitedPostDom)
377  FoundLoopLevel = std::min(FoundLoopLevel, Level + 1);
378  else
379  FoundLoopLevel = std::min(FoundLoopLevel, Level);
380  continue;
381  }
382 
383  if (Visited.try_emplace(Succ, ~0u).second) {
384  if (MBB == VisitedPostDom)
385  NextLevel.push_back(Succ);
386  else
387  Stack.push_back(Succ);
388  }
389  }
390  }
391 
392  CommonDominators.push_back(VisitedDom);
393  }
394 };
395 
396 } // End anonymous namespace.
397 
398 INITIALIZE_PASS_BEGIN(SILowerI1Copies, DEBUG_TYPE, "SI Lower i1 Copies", false,
399  false)
403  false)
404 
405 char SILowerI1Copies::ID = 0;
406 
407 char &llvm::SILowerI1CopiesID = SILowerI1Copies::ID;
408 
410  return new SILowerI1Copies();
411 }
412 
413 static unsigned createLaneMaskReg(MachineFunction &MF) {
414  MachineRegisterInfo &MRI = MF.getRegInfo();
415  return MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
416 }
417 
418 static unsigned insertUndefLaneMask(MachineBasicBlock &MBB) {
419  MachineFunction &MF = *MBB.getParent();
420  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
421  const SIInstrInfo *TII = ST.getInstrInfo();
422  unsigned UndefReg = createLaneMaskReg(MF);
423  BuildMI(MBB, MBB.getFirstTerminator(), {}, TII->get(AMDGPU::IMPLICIT_DEF),
424  UndefReg);
425  return UndefReg;
426 }
427 
428 /// Lower all instructions that def or use vreg_1 registers.
429 ///
430 /// In a first pass, we lower COPYs from vreg_1 to vector registers, as can
431 /// occur around inline assembly. We do this first, before vreg_1 registers
432 /// are changed to scalar mask registers.
433 ///
434 /// Then we lower all defs of vreg_1 registers. Phi nodes are lowered before
435 /// all others, because phi lowering looks through copies and can therefore
436 /// often make copy lowering unnecessary.
437 bool SILowerI1Copies::runOnMachineFunction(MachineFunction &TheMF) {
438  MF = &TheMF;
439  MRI = &MF->getRegInfo();
440  DT = &getAnalysis<MachineDominatorTree>();
441  PDT = &getAnalysis<MachinePostDominatorTree>();
442 
443  ST = &MF->getSubtarget<GCNSubtarget>();
444  TII = ST->getInstrInfo();
445 
446  lowerCopiesFromI1();
447  lowerPhis();
448  lowerCopiesToI1();
449 
450  for (unsigned Reg : ConstrainRegs)
451  MRI->constrainRegClass(Reg, &AMDGPU::SReg_64_XEXECRegClass);
452  ConstrainRegs.clear();
453 
454  return true;
455 }
456 
457 void SILowerI1Copies::lowerCopiesFromI1() {
459 
460  for (MachineBasicBlock &MBB : *MF) {
461  for (MachineInstr &MI : MBB) {
462  if (MI.getOpcode() != AMDGPU::COPY)
463  continue;
464 
465  unsigned DstReg = MI.getOperand(0).getReg();
466  unsigned SrcReg = MI.getOperand(1).getReg();
468  MRI->getRegClass(SrcReg) != &AMDGPU::VReg_1RegClass)
469  continue;
470 
471  if (isLaneMaskReg(DstReg) ||
473  MRI->getRegClass(DstReg) == &AMDGPU::VReg_1RegClass))
474  continue;
475 
476  // Copy into a 32-bit vector register.
477  LLVM_DEBUG(dbgs() << "Lower copy from i1: " << MI);
478  DebugLoc DL = MI.getDebugLoc();
479 
480  assert(TII->getRegisterInfo().getRegSizeInBits(DstReg, *MRI) == 32);
481  assert(!MI.getOperand(0).getSubReg());
482 
483  ConstrainRegs.insert(SrcReg);
484  BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
485  .addImm(0)
486  .addImm(0)
487  .addImm(0)
488  .addImm(-1)
489  .addReg(SrcReg);
490  DeadCopies.push_back(&MI);
491  }
492 
493  for (MachineInstr *MI : DeadCopies)
494  MI->eraseFromParent();
495  DeadCopies.clear();
496  }
497 }
498 
499 void SILowerI1Copies::lowerPhis() {
500  MachineSSAUpdater SSAUpdater(*MF);
501  LoopFinder LF(*DT, *PDT);
502  PhiIncomingAnalysis PIA(*PDT);
505  SmallVector<unsigned, 4> IncomingRegs;
506  SmallVector<unsigned, 4> IncomingUpdated;
507 
508  for (MachineBasicBlock &MBB : *MF) {
509  LF.initialize(MBB);
510 
511  for (MachineInstr &MI : MBB.phis()) {
512  unsigned DstReg = MI.getOperand(0).getReg();
513  if (MRI->getRegClass(DstReg) != &AMDGPU::VReg_1RegClass)
514  continue;
515 
516  LLVM_DEBUG(dbgs() << "Lower PHI: " << MI);
517 
518  MRI->setRegClass(DstReg, &AMDGPU::SReg_64RegClass);
519 
520  // Collect incoming values.
521  for (unsigned i = 1; i < MI.getNumOperands(); i += 2) {
522  assert(i + 1 < MI.getNumOperands());
523  unsigned IncomingReg = MI.getOperand(i).getReg();
524  MachineBasicBlock *IncomingMBB = MI.getOperand(i + 1).getMBB();
525  MachineInstr *IncomingDef = MRI->getUniqueVRegDef(IncomingReg);
526 
527  if (IncomingDef->getOpcode() == AMDGPU::COPY) {
528  IncomingReg = IncomingDef->getOperand(1).getReg();
529  assert(isLaneMaskReg(IncomingReg));
530  assert(!IncomingDef->getOperand(1).getSubReg());
531  } else if (IncomingDef->getOpcode() == AMDGPU::IMPLICIT_DEF) {
532  continue;
533  } else {
534  assert(IncomingDef->isPHI());
535  }
536 
537  IncomingBlocks.push_back(IncomingMBB);
538  IncomingRegs.push_back(IncomingReg);
539  }
540 
541  // Phis in a loop that are observed outside the loop receive a simple but
542  // conservatively correct treatment.
543  MachineBasicBlock *PostDomBound = &MBB;
544  for (MachineInstr &Use : MRI->use_instructions(DstReg)) {
545  PostDomBound =
546  PDT->findNearestCommonDominator(PostDomBound, Use.getParent());
547  }
548 
549  unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
550 
551  SSAUpdater.Initialize(DstReg);
552 
553  if (FoundLoopLevel) {
554  LF.addLoopEntries(FoundLoopLevel, SSAUpdater, IncomingBlocks);
555 
556  for (unsigned i = 0; i < IncomingRegs.size(); ++i) {
557  IncomingUpdated.push_back(createLaneMaskReg(*MF));
558  SSAUpdater.AddAvailableValue(IncomingBlocks[i],
559  IncomingUpdated.back());
560  }
561 
562  for (unsigned i = 0; i < IncomingRegs.size(); ++i) {
563  MachineBasicBlock &IMBB = *IncomingBlocks[i];
564  buildMergeLaneMasks(
565  IMBB, getSaluInsertionAtEnd(IMBB), {}, IncomingUpdated[i],
566  SSAUpdater.GetValueInMiddleOfBlock(&IMBB), IncomingRegs[i]);
567  }
568  } else {
569  // The phi is not observed from outside a loop. Use a more accurate
570  // lowering.
571  PIA.analyze(MBB, IncomingBlocks);
572 
573  for (MachineBasicBlock *MBB : PIA.predecessors())
574  SSAUpdater.AddAvailableValue(MBB, insertUndefLaneMask(*MBB));
575 
576  for (unsigned i = 0; i < IncomingRegs.size(); ++i) {
577  MachineBasicBlock &IMBB = *IncomingBlocks[i];
578  if (PIA.isSource(IMBB)) {
579  IncomingUpdated.push_back(0);
580  SSAUpdater.AddAvailableValue(&IMBB, IncomingRegs[i]);
581  } else {
582  IncomingUpdated.push_back(createLaneMaskReg(*MF));
583  SSAUpdater.AddAvailableValue(&IMBB, IncomingUpdated.back());
584  }
585  }
586 
587  for (unsigned i = 0; i < IncomingRegs.size(); ++i) {
588  if (!IncomingUpdated[i])
589  continue;
590 
591  MachineBasicBlock &IMBB = *IncomingBlocks[i];
592  buildMergeLaneMasks(
593  IMBB, getSaluInsertionAtEnd(IMBB), {}, IncomingUpdated[i],
594  SSAUpdater.GetValueInMiddleOfBlock(&IMBB), IncomingRegs[i]);
595  }
596  }
597 
598  unsigned NewReg = SSAUpdater.GetValueInMiddleOfBlock(&MBB);
599  if (NewReg != DstReg) {
600  MRI->replaceRegWith(NewReg, DstReg);
601 
602  // Ensure that DstReg has a single def and mark the old PHI node for
603  // deletion.
604  MI.getOperand(0).setReg(NewReg);
605  DeadPhis.push_back(&MI);
606  }
607 
608  IncomingBlocks.clear();
609  IncomingRegs.clear();
610  IncomingUpdated.clear();
611  }
612 
613  for (MachineInstr *MI : DeadPhis)
614  MI->eraseFromParent();
615  DeadPhis.clear();
616  }
617 }
618 
619 void SILowerI1Copies::lowerCopiesToI1() {
620  MachineSSAUpdater SSAUpdater(*MF);
621  LoopFinder LF(*DT, *PDT);
623 
624  for (MachineBasicBlock &MBB : *MF) {
625  LF.initialize(MBB);
626 
627  for (MachineInstr &MI : MBB) {
628  if (MI.getOpcode() != AMDGPU::IMPLICIT_DEF &&
629  MI.getOpcode() != AMDGPU::COPY)
630  continue;
631 
632  unsigned DstReg = MI.getOperand(0).getReg();
634  MRI->getRegClass(DstReg) != &AMDGPU::VReg_1RegClass)
635  continue;
636 
637  if (MRI->use_empty(DstReg)) {
638  DeadCopies.push_back(&MI);
639  continue;
640  }
641 
642  LLVM_DEBUG(dbgs() << "Lower Other: " << MI);
643 
644  MRI->setRegClass(DstReg, &AMDGPU::SReg_64RegClass);
645  if (MI.getOpcode() == AMDGPU::IMPLICIT_DEF)
646  continue;
647 
648  DebugLoc DL = MI.getDebugLoc();
649  unsigned SrcReg = MI.getOperand(1).getReg();
650  assert(!MI.getOperand(1).getSubReg());
651 
653  !isLaneMaskReg(SrcReg)) {
654  assert(TII->getRegisterInfo().getRegSizeInBits(SrcReg, *MRI) == 32);
655  unsigned TmpReg = createLaneMaskReg(*MF);
656  BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CMP_NE_U32_e64), TmpReg)
657  .addReg(SrcReg)
658  .addImm(0);
659  MI.getOperand(1).setReg(TmpReg);
660  SrcReg = TmpReg;
661  }
662 
663  // Defs in a loop that are observed outside the loop must be transformed
664  // into appropriate bit manipulation.
665  MachineBasicBlock *PostDomBound = &MBB;
666  for (MachineInstr &Use : MRI->use_instructions(DstReg)) {
667  PostDomBound =
668  PDT->findNearestCommonDominator(PostDomBound, Use.getParent());
669  }
670 
671  unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
672  if (FoundLoopLevel) {
673  SSAUpdater.Initialize(DstReg);
674  SSAUpdater.AddAvailableValue(&MBB, DstReg);
675  LF.addLoopEntries(FoundLoopLevel, SSAUpdater);
676 
677  buildMergeLaneMasks(MBB, MI, DL, DstReg,
678  SSAUpdater.GetValueInMiddleOfBlock(&MBB), SrcReg);
679  DeadCopies.push_back(&MI);
680  }
681  }
682 
683  for (MachineInstr *MI : DeadCopies)
684  MI->eraseFromParent();
685  DeadCopies.clear();
686  }
687 }
688 
689 bool SILowerI1Copies::isConstantLaneMask(unsigned Reg, bool &Val) const {
690  const MachineInstr *MI;
691  for (;;) {
692  MI = MRI->getUniqueVRegDef(Reg);
693  if (MI->getOpcode() != AMDGPU::COPY)
694  break;
695 
696  Reg = MI->getOperand(1).getReg();
698  return false;
699  if (!isLaneMaskReg(Reg))
700  return false;
701  }
702 
703  if (MI->getOpcode() != AMDGPU::S_MOV_B64)
704  return false;
705 
706  if (!MI->getOperand(1).isImm())
707  return false;
708 
709  int64_t Imm = MI->getOperand(1).getImm();
710  if (Imm == 0) {
711  Val = false;
712  return true;
713  }
714  if (Imm == -1) {
715  Val = true;
716  return true;
717  }
718 
719  return false;
720 }
721 
722 static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use) {
723  Def = false;
724  Use = false;
725 
726  for (const MachineOperand &MO : MI.operands()) {
727  if (MO.isReg() && MO.getReg() == AMDGPU::SCC) {
728  if (MO.isUse())
729  Use = true;
730  else
731  Def = true;
732  }
733  }
734 }
735 
736 /// Return a point at the end of the given \p MBB to insert SALU instructions
737 /// for lane mask calculation. Take terminators and SCC into account.
739 SILowerI1Copies::getSaluInsertionAtEnd(MachineBasicBlock &MBB) const {
740  auto InsertionPt = MBB.getFirstTerminator();
741  bool TerminatorsUseSCC = false;
742  for (auto I = InsertionPt, E = MBB.end(); I != E; ++I) {
743  bool DefsSCC;
744  instrDefsUsesSCC(*I, DefsSCC, TerminatorsUseSCC);
745  if (TerminatorsUseSCC || DefsSCC)
746  break;
747  }
748 
749  if (!TerminatorsUseSCC)
750  return InsertionPt;
751 
752  while (InsertionPt != MBB.begin()) {
753  InsertionPt--;
754 
755  bool DefSCC, UseSCC;
756  instrDefsUsesSCC(*InsertionPt, DefSCC, UseSCC);
757  if (DefSCC)
758  return InsertionPt;
759  }
760 
761  // We should have at least seen an IMPLICIT_DEF or COPY
762  llvm_unreachable("SCC used by terminator but no def in block");
763 }
764 
765 void SILowerI1Copies::buildMergeLaneMasks(MachineBasicBlock &MBB,
767  const DebugLoc &DL, unsigned DstReg,
768  unsigned PrevReg, unsigned CurReg) {
769  bool PrevVal;
770  bool PrevConstant = isConstantLaneMask(PrevReg, PrevVal);
771  bool CurVal;
772  bool CurConstant = isConstantLaneMask(CurReg, CurVal);
773 
774  if (PrevConstant && CurConstant) {
775  if (PrevVal == CurVal) {
776  BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(CurReg);
777  } else if (CurVal) {
778  BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(AMDGPU::EXEC);
779  } else {
780  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_XOR_B64), DstReg)
781  .addReg(AMDGPU::EXEC)
782  .addImm(-1);
783  }
784  return;
785  }
786 
787  unsigned PrevMaskedReg = 0;
788  unsigned CurMaskedReg = 0;
789  if (!PrevConstant) {
790  if (CurConstant && CurVal) {
791  PrevMaskedReg = PrevReg;
792  } else {
793  PrevMaskedReg = createLaneMaskReg(*MF);
794  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ANDN2_B64), PrevMaskedReg)
795  .addReg(PrevReg)
796  .addReg(AMDGPU::EXEC);
797  }
798  }
799  if (!CurConstant) {
800  // TODO: check whether CurReg is already masked by EXEC
801  if (PrevConstant && PrevVal) {
802  CurMaskedReg = CurReg;
803  } else {
804  CurMaskedReg = createLaneMaskReg(*MF);
805  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_AND_B64), CurMaskedReg)
806  .addReg(CurReg)
807  .addReg(AMDGPU::EXEC);
808  }
809  }
810 
811  if (PrevConstant && !PrevVal) {
812  BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
813  .addReg(CurMaskedReg);
814  } else if (CurConstant && !CurVal) {
815  BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
816  .addReg(PrevMaskedReg);
817  } else if (PrevConstant && PrevVal) {
818  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ORN2_B64), DstReg)
819  .addReg(CurMaskedReg)
820  .addReg(AMDGPU::EXEC);
821  } else {
822  BuildMI(MBB, I, DL, TII->get(AMDGPU::S_OR_B64), DstReg)
823  .addReg(PrevMaskedReg)
824  .addReg(CurMaskedReg ? CurMaskedReg : (unsigned)AMDGPU::EXEC);
825  }
826 }
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:38
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AMDGPU specific subclass of TargetSubtarget.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
MachineBasicBlock * findNearestCommonDominator(MachineBasicBlock *A, MachineBasicBlock *B)
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned getReg() const
getReg - Returns the register number.
#define DEBUG_TYPE
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
INITIALIZE_PASS_BEGIN(SILowerI1Copies, DEBUG_TYPE, "SI Lower i1 Copies", false, false) INITIALIZE_PASS_END(SILowerI1Copies
unsigned Reg
unsigned getSubReg() const
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
const SIInstrInfo * getInstrInfo() const override
A debug info location.
Definition: DebugLoc.h:33
static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use)
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:458
bool isPHI() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
MachineSSAUpdater - This class updates SSA form for a set of virtual registers defined in multiple bl...
const SIRegisterInfo & getRegisterInfo() const
Definition: SIInstrInfo.h:164
iterator_range< succ_iterator > successors()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
bool isSGPRReg(const MachineRegisterInfo &MRI, unsigned Reg) const
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
iterator_range< iterator > terminators()
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
static bool isSource(Value *V)
Return true if the given value is a source in the use-def chain, producing a narrow &#39;TypeSize&#39; value...
FunctionPass * createSILowerI1CopiesPass()
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
MachineBasicBlock * findNearestCommonDominator(MachineBasicBlock *A, MachineBasicBlock *B)
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
void Initialize(unsigned V)
Initialize - Reset this object to get ready for a new set of SSA updates.
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
NodeT * getBlock() const
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:187
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
iterator_range< pred_iterator > predecessors()
char & SILowerI1CopiesID
size_t size() const
Definition: SmallVector.h:52
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getWavefrontSize() const
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
iterator end() const
Definition: ArrayRef.h:137
SI Lower i1 Copies
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:124
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:301
int64_t getImm() const
MachineInstr * getUniqueVRegDef(unsigned Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef< StringRef > StandardNames)
Initialize the set of available library functions based on the specified target triple.
bool use_empty(unsigned RegNo) const
use_empty - Return true if there are no instructions using the specified register.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Provides AMDGPU specific target descriptions.
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
Interface definition for SIInstrInfo.
MachineDomTreeNode * getNode(MachineBasicBlock *BB) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
static unsigned createLaneMaskReg(MachineFunction &MF)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static unsigned insertUndefLaneMask(MachineBasicBlock &MBB)
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned GetValueInMiddleOfBlock(MachineBasicBlock *BB)
GetValueInMiddleOfBlock - Construct SSA form, materializing a value that is live in the middle of the...
void AddAvailableValue(MachineBasicBlock *BB, unsigned V)
AddAvailableValue - Indicate that a rewritten value is available at the end of the specified block wi...
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:171
iterator_range< use_instr_iterator > use_instructions(unsigned Reg) const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
IRTranslator LLVM IR MI
void setRegClass(unsigned Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
void initializeSILowerI1CopiesPass(PassRegistry &)
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
unsigned createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...