LLVM 24.0.0git
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 (32 / 64-bit scalar registers). The pass assumes machine SSA
11// form 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 "SILowerI1Copies.h"
25#include "AMDGPU.h"
28
29#define DEBUG_TYPE "si-i1-copies"
30
31using namespace llvm;
32
33static Register
35 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs);
36
37namespace {
38
39class Vreg1LoweringHelper : public AMDGPU::PhiLoweringHelper {
40public:
41 Vreg1LoweringHelper(MachineFunction &MF, MachineDominatorTree &DT,
43
44private:
45 DenseSet<Register> ConstrainRegs;
46
47public:
48 void markAsLaneMask(Register DstReg) const override;
49 void getCandidatesForLowering(
50 SmallVectorImpl<MachineInstr *> &Vreg1Phis) const override;
51 void collectIncomingValuesFromPhi(
52 const MachineInstr *MI,
53 SmallVectorImpl<AMDGPU::Incoming> &Incomings) const override;
54 void replaceDstReg(Register NewReg, Register OldReg,
55 MachineBasicBlock *MBB) override;
56 void buildMergeLaneMasks(MachineBasicBlock &MBB,
58 Register DstReg, Register PrevReg,
59 Register CurReg) override;
60 void constrainAsLaneMask(AMDGPU::Incoming &In) override;
61
62 bool lowerCopiesFromI1();
63 bool lowerCopiesToI1();
64 bool cleanConstrainRegs(bool Changed);
65 bool isVreg1(Register Reg) const {
66 return Reg.isVirtual() && MRI->getRegClass(Reg) == &AMDGPU::VReg_1RegClass;
67 }
68};
69
70Vreg1LoweringHelper::Vreg1LoweringHelper(MachineFunction &MF,
73 : PhiLoweringHelper(MF, DT, PDT) {}
74
75bool Vreg1LoweringHelper::cleanConstrainRegs(bool Changed) {
76 assert(Changed || ConstrainRegs.empty());
77 for (Register Reg : ConstrainRegs)
78 MRI->constrainRegClass(Reg, TII->getRegisterInfo().getWaveMaskRegClass());
79 ConstrainRegs.clear();
80
81 return Changed;
82}
83
84} // end anonymous namespace
85
86namespace llvm {
87namespace AMDGPU {
88
89/// Helper class that determines the relationship between incoming values of a
90/// phi in the control flow graph to determine where an incoming value can
91/// simply be taken as a scalar lane mask as-is, and where it needs to be
92/// merged with another, previously defined lane mask.
93///
94/// The approach is as follows:
95/// - Determine all basic blocks which, starting from the incoming blocks,
96/// a wave may reach before entering the def block (the block containing the
97/// phi).
98/// - If an incoming block has no predecessors in this set, we can take the
99/// incoming value as a scalar lane mask as-is.
100/// -- A special case of this is when the def block has a self-loop.
101/// - Otherwise, the incoming value needs to be merged with a previously
102/// defined lane mask.
103/// - If there is a path into the set of reachable blocks that does _not_ go
104/// through an incoming block where we can take the scalar lane mask as-is,
105/// we need to invent an available value for the SSAUpdater. Choices are
106/// 0 and undef, with differing consequences for how to merge values etc.
107///
108/// TODO: We could use region analysis to quickly skip over SESE regions during
109/// the traversal.
110///
113 const SIInstrInfo *TII;
114
115 // For each reachable basic block, whether it is a source in the induced
116 // subgraph of the CFG.
120
121public:
123 : PDT(PDT), TII(TII) {}
124
125 /// Returns whether \p MBB is a source in the induced subgraph of reachable
126 /// blocks.
128 return ReachableMap.find(&MBB)->second;
129 }
130
131 ArrayRef<MachineBasicBlock *> predecessors() const { return Predecessors; }
132
134 ArrayRef<AMDGPU::Incoming> Incomings) {
135 assert(Stack.empty());
136 ReachableMap.clear();
137 Predecessors.clear();
138
139 // Insert the def block first, so that it acts as an end point for the
140 // traversal.
141 ReachableMap.try_emplace(&DefBlock, false);
142
143 for (auto Incoming : Incomings) {
145 if (MBB == &DefBlock) {
146 ReachableMap[&DefBlock] = true; // self-loop on DefBlock
147 continue;
148 }
149
150 // If this block has a divergent terminator and the def block is its
151 // post-dominator, the wave may first visit the other successors.
152 if (TII->hasDivergentBranch(MBB) && PDT.dominates(&DefBlock, MBB))
153 Stack.push_back(MBB);
154 }
155
156 while (!Stack.empty()) {
157 MachineBasicBlock *MBB = Stack.pop_back_val();
158 if (ReachableMap.try_emplace(MBB, false).second)
159 append_range(Stack, MBB->successors());
160 }
161
162 // Insert remaining incoming blocks.
163 for (auto Incoming : Incomings) {
165 ReachableMap.try_emplace(MBB, false);
166 }
167
168 for (auto &[MBB, IsSource] : ReachableMap) {
169 bool HaveReachablePred = false;
170 for (MachineBasicBlock *Pred : MBB->predecessors()) {
171 if (ReachableMap.count(Pred)) {
172 HaveReachablePred = true;
173 } else {
174 Stack.push_back(Pred);
175 }
176 }
177 if (!HaveReachablePred)
178 IsSource = true;
179 if (HaveReachablePred) {
180 for (MachineBasicBlock *UnreachablePred : Stack) {
181 if (!llvm::is_contained(Predecessors, UnreachablePred))
182 Predecessors.push_back(UnreachablePred);
183 }
184 }
185 Stack.clear();
186 }
187 }
188};
189
190/// Helper class that detects loops which require us to lower an i1 COPY into
191/// bitwise manipulation.
192///
193/// Unfortunately, we cannot use LoopInfo because LoopInfo does not distinguish
194/// between loops with the same header. Consider this example:
195///
196/// A-+-+
197/// | | |
198/// B-+ |
199/// | |
200/// C---+
201///
202/// A is the header of a loop containing A, B, and C as far as LoopInfo is
203/// concerned. However, an i1 COPY in B that is used in C must be lowered to
204/// bitwise operations to combine results from different loop iterations when
205/// B has a divergent branch (since by default we will compile this code such
206/// that threads in a wave are merged at the entry of C).
207///
208/// The following rule is implemented to determine whether bitwise operations
209/// are required: use the bitwise lowering for a def in block B if a backward
210/// edge to B is reachable without going through the nearest common
211/// post-dominator of B and all uses of the def.
212///
213/// TODO: This rule is conservative because it does not check whether the
214/// relevant branches are actually divergent.
215///
216/// The class is designed to cache the CFG traversal so that it can be re-used
217/// for multiple defs within the same basic block.
218///
219/// TODO: We could use region analysis to quickly skip over SESE regions during
220/// the traversal.
221///
225
226 // All visited / reachable block, tagged by level (level 0 is the def block,
227 // level 1 are all blocks reachable including but not going through the def
228 // block's IPDOM, etc.).
230
231 // Nearest common dominator of all visited blocks by level (level 0 is the
232 // def block). Used for seeding the SSAUpdater.
234
235 // Post-dominator of all visited blocks.
236 MachineBasicBlock *VisitedPostDom = nullptr;
237
238 // Level at which a loop was found: 0 is not possible; 1 = a backward edge is
239 // reachable without going through the IPDOM of the def block (if the IPDOM
240 // itself has an edge to the def block, the loop level is 2), etc.
241 unsigned FoundLoopLevel = ~0u;
242
243 MachineBasicBlock *DefBlock = nullptr;
246
247public:
249 : DT(DT), PDT(PDT) {}
250
252 Visited.clear();
253 CommonDominators.clear();
254 Stack.clear();
255 NextLevel.clear();
256 VisitedPostDom = nullptr;
257 FoundLoopLevel = ~0u;
258
259 DefBlock = &MBB;
260 }
261
262 /// Check whether a backward edge can be reached without going through the
263 /// given \p PostDom of the def block.
264 ///
265 /// Return the level of \p PostDom if a loop was found, or 0 otherwise.
266 unsigned findLoop(MachineBasicBlock *PostDom) {
267 MachineDomTreeNode *PDNode = PDT.getNode(DefBlock);
268
269 if (!VisitedPostDom)
270 advanceLevel();
271
272 unsigned Level = 0;
273 while (PDNode->getBlock() != PostDom) {
274 if (PDNode->getBlock() == VisitedPostDom)
275 advanceLevel();
276 PDNode = PDNode->getIDom();
277 Level++;
278 if (FoundLoopLevel == Level)
279 return Level;
280 }
281
282 return 0;
283 }
284
285 /// Add undef values dominating the loop and the optionally given additional
286 /// blocks, so that the SSA updater doesn't have to search all the way to the
287 /// function entry.
290 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs,
291 ArrayRef<AMDGPU::Incoming> Incomings = {}) {
292 assert(LoopLevel < CommonDominators.size());
293
294 MachineBasicBlock *Dom = CommonDominators[LoopLevel];
295 for (auto &Incoming : Incomings)
297
298 if (!inLoopLevel(*Dom, LoopLevel, Incomings)) {
299 SSAUpdater.addAvailableValue(
300 Dom, insertUndefLaneMask(Dom, &MRI, LaneMaskRegAttrs));
301 } else {
302 // The dominator is part of the loop or the given blocks, so add the
303 // undef value to unreachable predecessors instead.
304 for (MachineBasicBlock *Pred : Dom->predecessors()) {
305 if (!inLoopLevel(*Pred, LoopLevel, Incomings))
306 SSAUpdater.addAvailableValue(
307 Pred, insertUndefLaneMask(Pred, &MRI, LaneMaskRegAttrs));
308 }
309 }
310 }
311
312private:
313 bool inLoopLevel(MachineBasicBlock &MBB, unsigned LoopLevel,
314 ArrayRef<AMDGPU::Incoming> Incomings) const {
315 auto DomIt = Visited.find(&MBB);
316 if (DomIt != Visited.end() && DomIt->second <= LoopLevel)
317 return true;
318
319 for (auto &Incoming : Incomings)
320 if (Incoming.Block == &MBB)
321 return true;
322
323 return false;
324 }
325
326 void advanceLevel() {
327 MachineBasicBlock *VisitedDom;
328
329 if (!VisitedPostDom) {
330 VisitedPostDom = DefBlock;
331 VisitedDom = DefBlock;
332 Stack.push_back(DefBlock);
333 } else {
334 VisitedPostDom = PDT.getNode(VisitedPostDom)->getIDom()->getBlock();
335 VisitedDom = CommonDominators.back();
336
337 for (unsigned i = 0; i < NextLevel.size();) {
338 if (PDT.dominates(VisitedPostDom, NextLevel[i])) {
339 Stack.push_back(NextLevel[i]);
340
341 NextLevel[i] = NextLevel.back();
342 NextLevel.pop_back();
343 } else {
344 i++;
345 }
346 }
347 }
348
349 unsigned Level = CommonDominators.size();
350 while (!Stack.empty()) {
351 MachineBasicBlock *MBB = Stack.pop_back_val();
352 if (!PDT.dominates(VisitedPostDom, MBB))
353 NextLevel.push_back(MBB);
354
355 Visited[MBB] = Level;
356 VisitedDom = DT.findNearestCommonDominator(VisitedDom, MBB);
357
358 for (MachineBasicBlock *Succ : MBB->successors()) {
359 if (Succ == DefBlock) {
360 if (MBB == VisitedPostDom)
361 FoundLoopLevel = std::min(FoundLoopLevel, Level + 1);
362 else
363 FoundLoopLevel = std::min(FoundLoopLevel, Level);
364 continue;
365 }
366
367 if (Visited.try_emplace(Succ, ~0u).second) {
368 if (MBB == VisitedPostDom)
369 NextLevel.push_back(Succ);
370 else
371 Stack.push_back(Succ);
372 }
373 }
374 }
375
376 CommonDominators.push_back(VisitedDom);
377 }
378};
379
380} // namespace AMDGPU
381} // namespace llvm
382
385 return MRI->createVirtualRegister(LaneMaskRegAttrs);
386}
387
388static Register
390 MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs) {
391 MachineFunction &MF = *MBB->getParent();
392 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
393 const SIInstrInfo *TII = ST.getInstrInfo();
394 Register UndefReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
395 BuildMI(*MBB, MBB->getFirstTerminator(), {}, TII->get(AMDGPU::IMPLICIT_DEF),
396 UndefReg);
397 return UndefReg;
398}
399
400#ifndef NDEBUG
402 const MachineRegisterInfo &MRI,
403 Register Reg) {
404 unsigned Size = TRI.getRegSizeInBits(Reg, MRI);
405 return Size == 1 || Size == 32;
406}
407#endif
408
409bool Vreg1LoweringHelper::lowerCopiesFromI1() {
410 bool Changed = false;
411 SmallVector<MachineInstr *, 4> DeadCopies;
412
413 for (MachineBasicBlock &MBB : MF) {
414 for (MachineInstr &MI : MBB) {
415 if (MI.getOpcode() != AMDGPU::COPY)
416 continue;
417
418 Register DstReg = MI.getOperand(0).getReg();
419 Register SrcReg = MI.getOperand(1).getReg();
420 if (!isVreg1(SrcReg))
421 continue;
422
423 if (isLaneMaskReg(DstReg) || isVreg1(DstReg))
424 continue;
425
426 Changed = true;
427
428 // Copy into a 32-bit vector register.
429 LLVM_DEBUG(dbgs() << "Lower copy from i1: " << MI);
430 const DebugLoc &DL = MI.getDebugLoc();
431
433 assert(!MI.getOperand(0).getSubReg());
434
435 ConstrainRegs.insert(SrcReg);
436 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
437 .addImm(0)
438 .addImm(0)
439 .addImm(0)
440 .addImm(-1)
441 .addReg(SrcReg);
442 DeadCopies.push_back(&MI);
443 }
444
445 for (MachineInstr *MI : DeadCopies)
446 MI->eraseFromParent();
447 DeadCopies.clear();
448 }
449 return Changed;
450}
451
455 : MF(MF), DT(DT), PDT(PDT), ST(&MF.getSubtarget<GCNSubtarget>()),
457 MRI = &MF.getRegInfo();
458
459 TII = ST->getInstrInfo();
460}
461
466 LF.initialize(MBB);
467
468 // Sort the incomings such that incoming values that dominate other incoming
469 // values are sorted earlier. This allows us to do some amount of on-the-fly
470 // constant folding.
471 // Incoming with smaller DFSNumIn goes first, DFSNumIn is 0 for entry block.
472 llvm::sort(Incomings, [this](Incoming LHS, Incoming RHS) {
473 return DT.getNode(LHS.Block)->getDFSNumIn() <
474 DT.getNode(RHS.Block)->getDFSNumIn();
475 });
476
477 // Values in a loop that are observed outside the loop receive a simple but
478 // conservatively correct treatment.
480 for (MachineInstr &Use : MRI->use_instructions(DstReg))
481 DomBlocks.push_back(Use.getParent());
482
483 MachineBasicBlock *PostDomBound = PDT.findNearestCommonDominator(DomBlocks);
484
485 // FIXME: This fails to find irreducible cycles. If we have a def (other
486 // than a constant) in a pair of blocks that end up looping back to each
487 // other, it will be mishandle. Due to structurization this shouldn't occur
488 // in practice.
489 unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
490
491 SSAUpdater.addUseBlock(&MBB);
492
493 if (FoundLoopLevel) {
494 LF.addLoopEntries(FoundLoopLevel, SSAUpdater, *MRI, LaneMaskRegAttrs,
495 Incomings);
496
497 for (auto &Incoming : Incomings) {
498 SSAUpdater.addUseBlock(Incoming.Block);
500 SSAUpdater.addAvailableValue(Incoming.Block, Incoming.UpdatedReg);
501 }
502
503 SSAUpdater.calculate();
504
505 for (auto &Incoming : Incomings) {
509 SSAUpdater.getValueInMiddleOfBlock(&IMBB), Incoming.Reg);
510 }
511 } else {
512 // The value is not observed from outside a loop. Use a more accurate
513 // lowering.
514 PIA.analyze(MBB, Incomings);
515
516 for (MachineBasicBlock *PredMBB : PIA.predecessors())
517 SSAUpdater.addAvailableValue(
518 PredMBB, insertUndefLaneMask(PredMBB, MRI, LaneMaskRegAttrs));
519
520 for (auto &Incoming : Incomings) {
522 if (PIA.isSource(IMBB)) {
524 SSAUpdater.addAvailableValue(&IMBB, Incoming.Reg);
525 } else {
526 SSAUpdater.addUseBlock(&IMBB);
528 SSAUpdater.addAvailableValue(&IMBB, Incoming.UpdatedReg);
529 }
530 }
531
532 SSAUpdater.calculate();
533
534 for (auto &Incoming : Incomings) {
536 continue;
537
541 SSAUpdater.getValueInMiddleOfBlock(&IMBB), Incoming.Reg);
542 }
543 }
544}
545
548 SmallVector<Incoming, 4> Incomings;
549
550 getCandidatesForLowering(Vreg1Phis);
551 if (Vreg1Phis.empty())
552 return false;
553
554 LoopFinder LF(DT, PDT);
556
557 DT.updateDFSNumbers();
558 for (MachineInstr *MI : Vreg1Phis) {
559 MachineBasicBlock &MBB = *MI->getParent();
560 LLVM_DEBUG(dbgs() << "Lower PHI: " << *MI);
561
562 Register DstReg = MI->getOperand(0).getReg();
563 markAsLaneMask(DstReg);
565
567
568#ifndef NDEBUG
569 PhiRegisters.insert(DstReg);
570#endif
571
573 mergeIncomingLaneMasks(DstReg, MBB, Incomings, SSAUpdater, LF, PIA);
574
575 Register NewReg = SSAUpdater.getValueInMiddleOfBlock(&MBB);
576 if (NewReg != DstReg) {
577 replaceDstReg(NewReg, DstReg, &MBB);
578 MI->eraseFromParent();
579 }
580
581 Incomings.clear();
582 }
583 return true;
584}
585
586bool Vreg1LoweringHelper::lowerCopiesToI1() {
587 bool Changed = false;
588 AMDGPU::LoopFinder LF(DT, PDT);
590
591 for (MachineBasicBlock &MBB : MF) {
592 LF.initialize(MBB);
593
594 for (MachineInstr &MI : MBB) {
595 if (MI.getOpcode() != AMDGPU::IMPLICIT_DEF &&
596 MI.getOpcode() != AMDGPU::COPY)
597 continue;
598
599 Register DstReg = MI.getOperand(0).getReg();
600 if (!isVreg1(DstReg))
601 continue;
602
603 Changed = true;
604
605 if (MRI->use_empty(DstReg)) {
606 DeadCopies.push_back(&MI);
607 continue;
608 }
609
610 LLVM_DEBUG(dbgs() << "Lower Other: " << MI);
611
612 markAsLaneMask(DstReg);
613 initializeLaneMaskRegisterAttributes(DstReg);
614
615 if (MI.getOpcode() == AMDGPU::IMPLICIT_DEF)
616 continue;
617
618 const DebugLoc &DL = MI.getDebugLoc();
619 Register SrcReg = MI.getOperand(1).getReg();
620 assert(!MI.getOperand(1).getSubReg());
621
622 if (!SrcReg.isVirtual() || (!isLaneMaskReg(SrcReg) && !isVreg1(SrcReg))) {
623 assert(TII->getRegisterInfo().getRegSizeInBits(SrcReg, *MRI) == 32);
624 Register TmpReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
625 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_CMP_NE_U32_e64), TmpReg)
626 .addReg(SrcReg)
627 .addImm(0);
628 MI.getOperand(1).setReg(TmpReg);
629 SrcReg = TmpReg;
630 } else {
631 // SrcReg needs to be live beyond copy.
632 MI.getOperand(1).setIsKill(false);
633 }
634
635 // Defs in a loop that are observed outside the loop must be transformed
636 // into appropriate bit manipulation.
637 std::vector<MachineBasicBlock *> DomBlocks = {&MBB};
638 for (MachineInstr &Use : MRI->use_instructions(DstReg))
639 DomBlocks.push_back(Use.getParent());
640
641 MachineBasicBlock *PostDomBound =
642 PDT.findNearestCommonDominator(DomBlocks);
643 unsigned FoundLoopLevel = LF.findLoop(PostDomBound);
644 if (FoundLoopLevel) {
645 MachineIDFSSAUpdater SSAUpdater(DT, MF, DstReg);
646 SSAUpdater.addUseBlock(&MBB);
647 SSAUpdater.addAvailableValue(&MBB, DstReg);
648 LF.addLoopEntries(FoundLoopLevel, SSAUpdater, *MRI, LaneMaskRegAttrs);
649
650 SSAUpdater.calculate();
651 buildMergeLaneMasks(MBB, MI, DL, DstReg,
652 SSAUpdater.getValueInMiddleOfBlock(&MBB), SrcReg);
653 DeadCopies.push_back(&MI);
654 }
655 }
656
657 for (MachineInstr *MI : DeadCopies)
658 MI->eraseFromParent();
659 DeadCopies.clear();
660 }
661 return Changed;
662}
663
665 bool &Val) const {
666 const MachineInstr *MI;
667 for (;;) {
668 MI = MRI->getUniqueVRegDef(Reg);
669 if (MI->getOpcode() == AMDGPU::IMPLICIT_DEF)
670 return true;
671
672 if (MI->getOpcode() != AMDGPU::COPY)
673 break;
674
675 Reg = MI->getOperand(1).getReg();
676 if (!Reg.isVirtual())
677 return false;
678 if (!isLaneMaskReg(Reg))
679 return false;
680 }
681
682 if (MI->getOpcode() != LMC->MovOpc)
683 return false;
684
685 if (!MI->getOperand(1).isImm())
686 return false;
687
688 int64_t Imm = MI->getOperand(1).getImm();
689 if (Imm == 0) {
690 Val = false;
691 return true;
692 }
693 if (Imm == -1) {
694 Val = true;
695 return true;
696 }
697
698 return false;
699}
700
701static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use) {
702 Def = false;
703 Use = false;
704
705 for (const MachineOperand &MO : MI.operands()) {
706 if (MO.isReg() && MO.getReg() == AMDGPU::SCC) {
707 if (MO.isUse())
708 Use = true;
709 else
710 Def = true;
711 }
712 }
713}
714
715/// Return a point at the end of the given \p MBB to insert SALU instructions
716/// for lane mask calculation. Take terminators and SCC into account.
719 auto InsertionPt = MBB.getFirstTerminator();
720 bool TerminatorsUseSCC = false;
721 for (auto I = InsertionPt, E = MBB.end(); I != E; ++I) {
722 bool DefsSCC;
723 instrDefsUsesSCC(*I, DefsSCC, TerminatorsUseSCC);
724 if (TerminatorsUseSCC || DefsSCC)
725 break;
726 }
727
728 if (!TerminatorsUseSCC)
729 return InsertionPt;
730
731 while (InsertionPt != MBB.begin()) {
732 InsertionPt--;
733
734 bool DefSCC, UseSCC;
735 instrDefsUsesSCC(*InsertionPt, DefSCC, UseSCC);
736 if (DefSCC)
737 return InsertionPt;
738 }
739
740 // We should have at least seen an IMPLICIT_DEF or COPY
741 llvm_unreachable("SCC used by terminator but no def in block");
742}
743
744// VReg_1 -> SReg_32 or SReg_64
745void Vreg1LoweringHelper::markAsLaneMask(Register DstReg) const {
746 MRI->setRegClass(DstReg, ST->getBoolRC());
747}
748
749void Vreg1LoweringHelper::getCandidatesForLowering(
750 SmallVectorImpl<MachineInstr *> &Vreg1Phis) const {
751 for (MachineBasicBlock &MBB : MF) {
752 for (MachineInstr &MI : MBB.phis()) {
753 if (isVreg1(MI.getOperand(0).getReg()))
754 Vreg1Phis.push_back(&MI);
755 }
756 }
757}
758
759void Vreg1LoweringHelper::collectIncomingValuesFromPhi(
760 const MachineInstr *MI,
761 SmallVectorImpl<AMDGPU::Incoming> &Incomings) const {
762 for (unsigned i = 1; i < MI->getNumOperands(); i += 2) {
763 assert(i + 1 < MI->getNumOperands());
764 Register IncomingReg = MI->getOperand(i).getReg();
765 MachineBasicBlock *IncomingMBB = MI->getOperand(i + 1).getMBB();
766 MachineInstr *IncomingDef = MRI->getUniqueVRegDef(IncomingReg);
767
768 if (IncomingDef->getOpcode() == AMDGPU::COPY) {
769 IncomingReg = IncomingDef->getOperand(1).getReg();
770 assert(isLaneMaskReg(IncomingReg) || isVreg1(IncomingReg));
771 assert(!IncomingDef->getOperand(1).getSubReg());
772 } else if (IncomingDef->getOpcode() == AMDGPU::IMPLICIT_DEF) {
773 continue;
774 } else {
775 assert(IncomingDef->isPHI() || PhiRegisters.count(IncomingReg));
776 }
777
778 Incomings.emplace_back(IncomingReg, IncomingMBB, Register());
779 }
780}
781
782void Vreg1LoweringHelper::replaceDstReg(Register NewReg, Register OldReg,
783 MachineBasicBlock *MBB) {
784 MRI->replaceRegWith(NewReg, OldReg);
785}
786
787void Vreg1LoweringHelper::buildMergeLaneMasks(MachineBasicBlock &MBB,
789 const DebugLoc &DL,
790 Register DstReg, Register PrevReg,
791 Register CurReg) {
792 bool PrevVal = false;
793 bool PrevConstant = isConstantLaneMask(PrevReg, PrevVal);
794 bool CurVal = false;
795 bool CurConstant = isConstantLaneMask(CurReg, CurVal);
796
797 if (PrevConstant && CurConstant) {
798 if (PrevVal == CurVal) {
799 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(CurReg);
800 } else if (CurVal) {
801 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg).addReg(LMC->ExecReg);
802 } else {
803 BuildMI(MBB, I, DL, TII->get(LMC->XorOpc), DstReg)
804 .addReg(LMC->ExecReg)
805 .addImm(-1);
806 }
807 return;
808 }
809
810 Register PrevMaskedReg;
811 Register CurMaskedReg;
812 if (!PrevConstant) {
813 if (CurConstant && CurVal) {
814 PrevMaskedReg = PrevReg;
815 } else {
816 PrevMaskedReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
817 BuildMI(MBB, I, DL, TII->get(LMC->AndN2Opc), PrevMaskedReg)
818 .addReg(PrevReg)
819 .addReg(LMC->ExecReg);
820 }
821 }
822 if (!CurConstant) {
823 // TODO: check whether CurReg is already masked by EXEC
824 if (PrevConstant && PrevVal) {
825 CurMaskedReg = CurReg;
826 } else {
827 CurMaskedReg = AMDGPU::createLaneMaskReg(MRI, LaneMaskRegAttrs);
828 BuildMI(MBB, I, DL, TII->get(LMC->AndOpc), CurMaskedReg)
829 .addReg(CurReg)
830 .addReg(LMC->ExecReg);
831 }
832 }
833
834 if (PrevConstant && !PrevVal) {
835 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
836 .addReg(CurMaskedReg);
837 } else if (CurConstant && !CurVal) {
838 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), DstReg)
839 .addReg(PrevMaskedReg);
840 } else if (PrevConstant && PrevVal) {
841 BuildMI(MBB, I, DL, TII->get(LMC->OrN2Opc), DstReg)
842 .addReg(CurMaskedReg)
843 .addReg(LMC->ExecReg);
844 } else {
845 BuildMI(MBB, I, DL, TII->get(LMC->OrOpc), DstReg)
846 .addReg(PrevMaskedReg)
847 .addReg(CurMaskedReg ? CurMaskedReg : LMC->ExecReg);
848 }
849}
850
851void Vreg1LoweringHelper::constrainAsLaneMask(AMDGPU::Incoming &In) {}
852
853/// Lower all instructions that def or use vreg_1 registers.
854///
855/// In a first pass, we lower COPYs from vreg_1 to vector registers, as can
856/// occur around inline assembly. We do this first, before vreg_1 registers
857/// are changed to scalar mask registers.
858///
859/// Then we lower all defs of vreg_1 registers. Phi nodes are lowered before
860/// all others, because phi lowering looks through copies and can therefore
861/// often make copy lowering unnecessary.
864 // Only need to run this in SelectionDAG path.
865 if (MF.getProperties().hasSelected())
866 return false;
867
868 Vreg1LoweringHelper Helper(MF, MDT, MPDT);
869 bool Changed = false;
870 Changed |= Helper.lowerCopiesFromI1();
871 Changed |= Helper.lowerPhis();
872 Changed |= Helper.lowerCopiesToI1();
873 return Helper.cleanConstrainRegs(Changed);
874}
875
876PreservedAnalyses
889
891public:
892 static char ID;
893
895
896 bool runOnMachineFunction(MachineFunction &MF) override;
897
898 StringRef getPassName() const override { return "SI Lower i1 Copies"; }
899
906};
907
915
917 false, false)
922
923char SILowerI1CopiesLegacy::ID = 0;
924
926
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void instrDefsUsesSCC(const MachineInstr &MI, bool &Def, bool &Use)
static Register insertUndefLaneMask(MachineBasicBlock *MBB, MachineRegisterInfo *MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs)
static bool runFixI1Copies(MachineFunction &MF, MachineDominatorTree &MDT, MachinePostDominatorTree &MPDT)
Lower all instructions that def or use vreg_1 registers.
static bool isVRegCompatibleReg(const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI, Register Reg)
Interface definition of the PhiLoweringHelper class that implements lane mask merging algorithm for d...
#define LLVM_DEBUG(...)
Definition Debug.h:119
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Helper class that detects loops which require us to lower an i1 COPY into bitwise manipulation.
void initialize(MachineBasicBlock &MBB)
unsigned findLoop(MachineBasicBlock *PostDom)
Check whether a backward edge can be reached without going through the given PostDom of the def block...
LoopFinder(MachineDominatorTree &DT, MachinePostDominatorTree &PDT)
void addLoopEntries(unsigned LoopLevel, MachineIDFSSAUpdater &SSAUpdater, MachineRegisterInfo &MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs, ArrayRef< AMDGPU::Incoming > Incomings={})
Add undef values dominating the loop and the optionally given additional blocks, so that the SSA upda...
Helper class that determines the relationship between incoming values of a phi in the control flow gr...
bool isSource(MachineBasicBlock &MBB) const
Returns whether MBB is a source in the induced subgraph of reachable blocks.
ArrayRef< MachineBasicBlock * > predecessors() const
PhiIncomingAnalysis(MachinePostDominatorTree &PDT, const SIInstrInfo *TII)
void analyze(MachineBasicBlock &DefBlock, ArrayRef< AMDGPU::Incoming > Incomings)
bool isLaneMaskReg(Register Reg) const
virtual void replaceDstReg(Register NewReg, Register OldReg, MachineBasicBlock *MBB)=0
MachineBasicBlock::iterator getSaluInsertionAtEnd(MachineBasicBlock &MBB) const
Return a point at the end of the given MBB to insert SALU instructions for lane mask calculation.
bool isConstantLaneMask(Register Reg, bool &Val) const
MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs
void initializeLaneMaskRegisterAttributes(Register LaneMask)
virtual void buildMergeLaneMasks(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, Register PrevReg, Register CurReg)=0
virtual void getCandidatesForLowering(SmallVectorImpl< MachineInstr * > &Vreg1Phis) const =0
const AMDGPU::LaneMaskConstants * LMC
PhiLoweringHelper(MachineFunction &MF, MachineDominatorTree &DT, MachinePostDominatorTree &PDT)
DenseSet< Register > PhiRegisters
virtual void markAsLaneMask(Register DstReg) const =0
virtual void constrainAsLaneMask(Incoming &In)=0
virtual void collectIncomingValuesFromPhi(const MachineInstr *MI, SmallVectorImpl< Incoming > &Incomings) const =0
void mergeIncomingLaneMasks(Register DstReg, MachineBasicBlock &MBB, SmallVectorImpl< Incoming > &Incomings, MachineIDFSSAUpdater &SSAUpdater, LoopFinder &LF, PhiIncomingAnalysis &PIA)
Merge the Incomings lane masks into DstReg, the value owned by MBB.
MachinePostDominatorTree & PDT
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
iterator end()
Definition DenseMap.h:141
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const HexagonRegisterInfo & getRegisterInfo() const
void push_back(MachineInstr *MI)
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const MachineFunctionProperties & getProperties() const
Get the function properties.
LLVM_ABI Register getValueInMiddleOfBlock(MachineBasicBlock *BB)
See SSAUpdater::GetValueInMiddleOfBlock description.
void addAvailableValue(MachineBasicBlock *BB, Register V)
Indicate that a rewritten value is available in the specified block with the specified value.
LLVM_ABI void calculate()
Calculate and insert necessary PHI nodes for SSA form.
void addUseBlock(MachineBasicBlock *BB)
Record a basic block that uses the value.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
LLVM_ABI MachineBasicBlock * findNearestCommonDominator(ArrayRef< MachineBasicBlock * > Blocks) const
Returns the nearest common dominator of the given blocks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Register createLaneMaskReg(MachineRegisterInfo *MRI, MachineRegisterInfo::VRegAttrs LaneMaskRegAttrs)
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
ArrayRef(const T &OneElt) -> ArrayRef< T >
FunctionPass * createSILowerI1CopiesLegacyPass()
char & SILowerI1CopiesLegacyID
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Incoming for lane mask phi as machine instruction, incoming register Reg and incoming block Block are...
MachineBasicBlock * Block
All attributes(register class or bank and low-level type) a virtual register can have.