LLVM 24.0.0git
SIOptimizeExecMasking.cpp
Go to the documentation of this file.
1//===-- SIOptimizeExecMasking.cpp -----------------------------------------===//
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
10#include "AMDGPU.h"
11#include "AMDGPULaneMaskUtils.h"
12#include "GCNSubtarget.h"
13#include "SIRegisterInfo.h"
20
21using namespace llvm;
22
23#define DEBUG_TYPE "si-optimize-exec-masking"
24
25namespace {
26
27class SIOptimizeExecMasking {
28public:
29 SIOptimizeExecMasking(MachineFunction *MF)
30 : MF(MF), ST(&MF->getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
31 TRI(&TII->getRegisterInfo()), MRI(&MF->getRegInfo()),
33 bool run();
34
35private:
37 const GCNSubtarget *ST;
38 const SIInstrInfo *TII;
39 const SIRegisterInfo *TRI;
42
46 NotSaveExecs;
47
48 Register isCopyFromExec(const MachineInstr &MI) const;
49 Register isCopyToExec(const MachineInstr &MI) const;
50 bool removeTerminatorBit(MachineInstr &MI) const;
52 fixTerminators(MachineBasicBlock &MBB) const;
54 findExecCopy(MachineBasicBlock &MBB,
56 bool isRegisterInUseBetween(MachineInstr &Stop, MachineInstr &Start,
57 MCRegister Reg, bool UseLiveOuts = false,
58 bool IgnoreStart = false) const;
59 bool isRegisterInUseAfter(MachineInstr &Stop, MCRegister Reg) const;
60 MachineInstr *findInstrBackwards(
61 MachineInstr &Origin, std::function<bool(MachineInstr *)> Pred,
62 ArrayRef<MCRegister> NonModifiableRegs,
63 unsigned MaxInstructions = 20) const;
64 bool optimizeExecSequence();
65 bool blocksAndN2Sink(const MachineInstr &MI, Register Dst) const;
66 bool optimizeAndN2WrExecSequence(MachineInstr &CopyToExecInst,
67 Register Dst) const;
68 void tryRecordVCmpxAndSaveexecSequence(MachineInstr &MI);
69 bool optimizeVCMPSaveExecSequence(MachineInstr &SaveExecInstr,
70 MachineInstr &VCmp) const;
71
72 void tryRecordOrSaveexecXorSequence(MachineInstr &MI);
73 bool optimizeOrSaveexecXorSequences();
74
75 void tryRecordNotAndSaveexecSequence(MachineInstr &MI);
76 bool optimizeNotAndSaveexecSequences();
77};
78
79class SIOptimizeExecMaskingLegacy : public MachineFunctionPass {
80public:
81 static char ID;
82
83 SIOptimizeExecMaskingLegacy() : MachineFunctionPass(ID) {}
84
85 bool runOnMachineFunction(MachineFunction &MF) override;
86
87 StringRef getPassName() const override {
88 return "SI optimize exec mask operations";
89 }
90
91 void getAnalysisUsage(AnalysisUsage &AU) const override {
92 AU.setPreservesCFG();
94 }
95};
96
97} // End anonymous namespace.
98
102 SIOptimizeExecMasking Impl(&MF);
103
104 if (!Impl.run())
105 return PreservedAnalyses::all();
106
108 PA.preserveSet<CFGAnalyses>();
109 return PA;
110}
111
112INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingLegacy, DEBUG_TYPE,
113 "SI optimize exec mask operations", false, false)
115INITIALIZE_PASS_END(SIOptimizeExecMaskingLegacy, DEBUG_TYPE,
116 "SI optimize exec mask operations", false, false)
117
118char SIOptimizeExecMaskingLegacy::ID = 0;
119
120char &llvm::SIOptimizeExecMaskingLegacyID = SIOptimizeExecMaskingLegacy::ID;
121
122/// If \p MI is a copy from exec, return the register copied to.
123Register SIOptimizeExecMasking::isCopyFromExec(const MachineInstr &MI) const {
124 switch (MI.getOpcode()) {
125 case AMDGPU::COPY:
126 case AMDGPU::S_MOV_B64:
127 case AMDGPU::S_MOV_B64_term:
128 case AMDGPU::S_MOV_B32:
129 case AMDGPU::S_MOV_B32_term: {
130 const MachineOperand &Src = MI.getOperand(1);
131 if (Src.isReg() && Src.getReg() == LMC.ExecReg)
132 return MI.getOperand(0).getReg();
133 }
134 }
135
136 return AMDGPU::NoRegister;
137}
138
139/// If \p MI is a copy to exec, return the register copied from.
140Register SIOptimizeExecMasking::isCopyToExec(const MachineInstr &MI) const {
141 switch (MI.getOpcode()) {
142 case AMDGPU::COPY:
143 case AMDGPU::S_MOV_B64:
144 case AMDGPU::S_MOV_B32: {
145 const MachineOperand &Dst = MI.getOperand(0);
146 if (Dst.isReg() && Dst.getReg() == LMC.ExecReg && MI.getOperand(1).isReg())
147 return MI.getOperand(1).getReg();
148 break;
149 }
150 case AMDGPU::S_MOV_B64_term:
151 case AMDGPU::S_MOV_B32_term:
152 llvm_unreachable("should have been replaced");
153 }
154
155 return Register();
156}
157
158/// If \p MI is a logical operation on an exec value,
159/// return the register copied to.
161 switch (MI.getOpcode()) {
162 case AMDGPU::S_AND_B64:
163 case AMDGPU::S_OR_B64:
164 case AMDGPU::S_XOR_B64:
165 case AMDGPU::S_ANDN2_B64:
166 case AMDGPU::S_ORN2_B64:
167 case AMDGPU::S_NAND_B64:
168 case AMDGPU::S_NOR_B64:
169 case AMDGPU::S_XNOR_B64: {
170 const MachineOperand &Src1 = MI.getOperand(1);
171 if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC)
172 return MI.getOperand(0).getReg();
173 const MachineOperand &Src2 = MI.getOperand(2);
174 if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC)
175 return MI.getOperand(0).getReg();
176 break;
177 }
178 case AMDGPU::S_AND_B32:
179 case AMDGPU::S_OR_B32:
180 case AMDGPU::S_XOR_B32:
181 case AMDGPU::S_ANDN2_B32:
182 case AMDGPU::S_ORN2_B32:
183 case AMDGPU::S_NAND_B32:
184 case AMDGPU::S_NOR_B32:
185 case AMDGPU::S_XNOR_B32: {
186 const MachineOperand &Src1 = MI.getOperand(1);
187 if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC_LO)
188 return MI.getOperand(0).getReg();
189 const MachineOperand &Src2 = MI.getOperand(2);
190 if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC_LO)
191 return MI.getOperand(0).getReg();
192 break;
193 }
194 }
195
196 return AMDGPU::NoRegister;
197}
198
199static unsigned getSaveExecOp(unsigned Opc) {
200 switch (Opc) {
201 case AMDGPU::S_AND_B64:
202 return AMDGPU::S_AND_SAVEEXEC_B64;
203 case AMDGPU::S_OR_B64:
204 return AMDGPU::S_OR_SAVEEXEC_B64;
205 case AMDGPU::S_XOR_B64:
206 return AMDGPU::S_XOR_SAVEEXEC_B64;
207 case AMDGPU::S_ANDN2_B64:
208 return AMDGPU::S_ANDN2_SAVEEXEC_B64;
209 case AMDGPU::S_ORN2_B64:
210 return AMDGPU::S_ORN2_SAVEEXEC_B64;
211 case AMDGPU::S_NAND_B64:
212 return AMDGPU::S_NAND_SAVEEXEC_B64;
213 case AMDGPU::S_NOR_B64:
214 return AMDGPU::S_NOR_SAVEEXEC_B64;
215 case AMDGPU::S_XNOR_B64:
216 return AMDGPU::S_XNOR_SAVEEXEC_B64;
217 case AMDGPU::S_AND_B32:
218 return AMDGPU::S_AND_SAVEEXEC_B32;
219 case AMDGPU::S_OR_B32:
220 return AMDGPU::S_OR_SAVEEXEC_B32;
221 case AMDGPU::S_XOR_B32:
222 return AMDGPU::S_XOR_SAVEEXEC_B32;
223 case AMDGPU::S_ANDN2_B32:
224 return AMDGPU::S_ANDN2_SAVEEXEC_B32;
225 case AMDGPU::S_ORN2_B32:
226 return AMDGPU::S_ORN2_SAVEEXEC_B32;
227 case AMDGPU::S_NAND_B32:
228 return AMDGPU::S_NAND_SAVEEXEC_B32;
229 case AMDGPU::S_NOR_B32:
230 return AMDGPU::S_NOR_SAVEEXEC_B32;
231 case AMDGPU::S_XNOR_B32:
232 return AMDGPU::S_XNOR_SAVEEXEC_B32;
233 default:
234 return AMDGPU::INSTRUCTION_LIST_END;
235 }
236}
237
238// These are only terminators to get correct spill code placement during
239// register allocation, so turn them back into normal instructions.
240bool SIOptimizeExecMasking::removeTerminatorBit(MachineInstr &MI) const {
241 switch (MI.getOpcode()) {
242 case AMDGPU::S_MOV_B32_term: {
243 bool RegSrc = MI.getOperand(1).isReg();
244 MI.setDesc(TII->get(RegSrc ? AMDGPU::COPY : AMDGPU::S_MOV_B32));
245 return true;
246 }
247 case AMDGPU::S_MOV_B64_term: {
248 bool RegSrc = MI.getOperand(1).isReg();
249 MI.setDesc(TII->get(RegSrc ? AMDGPU::COPY : AMDGPU::S_MOV_B64));
250 return true;
251 }
252 case AMDGPU::S_XOR_B64_term: {
253 // This is only a terminator to get the correct spill code placement during
254 // register allocation.
255 MI.setDesc(TII->get(AMDGPU::S_XOR_B64));
256 return true;
257 }
258 case AMDGPU::S_XOR_B32_term: {
259 // This is only a terminator to get the correct spill code placement during
260 // register allocation.
261 MI.setDesc(TII->get(AMDGPU::S_XOR_B32));
262 return true;
263 }
264 case AMDGPU::S_OR_B64_term: {
265 // This is only a terminator to get the correct spill code placement during
266 // register allocation.
267 MI.setDesc(TII->get(AMDGPU::S_OR_B64));
268 return true;
269 }
270 case AMDGPU::S_OR_B32_term: {
271 // This is only a terminator to get the correct spill code placement during
272 // register allocation.
273 MI.setDesc(TII->get(AMDGPU::S_OR_B32));
274 return true;
275 }
276 case AMDGPU::S_ANDN2_B64_term: {
277 // This is only a terminator to get the correct spill code placement during
278 // register allocation.
279 MI.setDesc(TII->get(AMDGPU::S_ANDN2_B64));
280 return true;
281 }
282 case AMDGPU::S_ANDN2_B32_term: {
283 // This is only a terminator to get the correct spill code placement during
284 // register allocation.
285 MI.setDesc(TII->get(AMDGPU::S_ANDN2_B32));
286 return true;
287 }
288 case AMDGPU::S_AND_B64_term: {
289 // This is only a terminator to get the correct spill code placement during
290 // register allocation.
291 MI.setDesc(TII->get(AMDGPU::S_AND_B64));
292 return true;
293 }
294 case AMDGPU::S_AND_B32_term: {
295 // This is only a terminator to get the correct spill code placement during
296 // register allocation.
297 MI.setDesc(TII->get(AMDGPU::S_AND_B32));
298 return true;
299 }
300 case AMDGPU::V_CMPX_EQ_U32_nosdst_e32_term:
301 MI.setDesc(TII->get(AMDGPU::V_CMPX_EQ_U32_nosdst_e32));
302 return true;
303 case AMDGPU::V_CMPX_EQ_U64_nosdst_e32_term:
304 MI.setDesc(TII->get(AMDGPU::V_CMPX_EQ_U64_nosdst_e32));
305 return true;
306 default:
307 return false;
308 }
309}
310
311// Turn all pseudoterminators in the block into their equivalent non-terminator
312// instructions. Returns the reverse iterator to the first non-terminator
313// instruction in the block.
315SIOptimizeExecMasking::fixTerminators(MachineBasicBlock &MBB) const {
317
318 bool Seen = false;
320 for (; I != E; ++I) {
321 if (!I->isTerminator())
322 return Seen ? FirstNonTerm : I;
323
324 if (removeTerminatorBit(*I)) {
325 if (!Seen) {
326 FirstNonTerm = I;
327 Seen = true;
328 }
329 }
330 }
331
332 return FirstNonTerm;
333}
334
335MachineBasicBlock::reverse_iterator SIOptimizeExecMasking::findExecCopy(
337 const unsigned InstLimit = 25;
338
339 auto E = MBB.rend();
340 for (unsigned N = 0; N <= InstLimit && I != E; ++I) {
341 if (I->isDebugInstr())
342 continue;
343 ++N;
344
345 Register CopyFromExec = isCopyFromExec(*I);
346 if (CopyFromExec.isValid())
347 return I;
348 }
349
350 return E;
351}
352
353// XXX - Seems LiveRegUnits doesn't work correctly since it will incorrectly
354// report the register as unavailable because a super-register with a lane mask
355// is unavailable.
356static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg) {
357 for (MachineBasicBlock *Succ : MBB.successors()) {
358 if (Succ->isLiveIn(Reg))
359 return true;
360 }
361
362 return false;
363}
364
365// Backwards-iterate from Origin (for n=MaxInstructions iterations) until either
366// the beginning of the BB is reached or Pred evaluates to true - which can be
367// an arbitrary condition based on the current MachineInstr, for instance an
368// target instruction. Breaks prematurely by returning nullptr if one of the
369// registers given in NonModifiableRegs is modified by the current instruction.
370MachineInstr *SIOptimizeExecMasking::findInstrBackwards(
371 MachineInstr &Origin, std::function<bool(MachineInstr *)> Pred,
372 ArrayRef<MCRegister> NonModifiableRegs, unsigned MaxInstructions) const {
374 E = Origin.getParent()->rend();
375 unsigned CurrentIteration = 0;
376
377 for (++A; CurrentIteration < MaxInstructions && A != E; ++A) {
378 if (A->isDebugInstr())
379 continue;
380
381 if (Pred(&*A))
382 return &*A;
383
384 for (MCRegister Reg : NonModifiableRegs) {
385 if (A->modifiesRegister(Reg, TRI))
386 return nullptr;
387 }
388
389 ++CurrentIteration;
390 }
391
392 return nullptr;
393}
394
395// Determine if a register Reg is not re-defined and still in use
396// in the range (Stop..Start].
397// It does so by backwards calculating liveness from the end of the BB until
398// either Stop or the beginning of the BB is reached.
399// After liveness is calculated, we can determine if Reg is still in use and not
400// defined inbetween the instructions.
401bool SIOptimizeExecMasking::isRegisterInUseBetween(MachineInstr &Stop,
402 MachineInstr &Start,
404 bool UseLiveOuts,
405 bool IgnoreStart) const {
406 LiveRegUnits LR(*TRI);
407 if (UseLiveOuts)
408 LR.addLiveOuts(*Stop.getParent());
409
411
412 if (IgnoreStart)
413 ++A;
414
415 for (; A != Stop.getParent()->rend() && A != Stop; ++A) {
416 if (!A->isDebugInstr())
417 LR.stepBackward(*A);
418 }
419
420 return !LR.available(Reg) || MRI->isReserved(Reg);
421}
422
423// Determine if a register Reg is not re-defined and still in use
424// in the range (Stop..BB.end].
425bool SIOptimizeExecMasking::isRegisterInUseAfter(MachineInstr &Stop,
426 MCRegister Reg) const {
427 return isRegisterInUseBetween(Stop, *Stop.getParent()->rbegin(), Reg, true);
428}
429
430// Optimize sequences emitted for control flow lowering. They are originally
431// emitted as the separate operations because spill code may need to be
432// inserted for the saved copy of exec.
433//
434// x = copy exec
435// z = s_<op>_b64 x, y
436// exec = copy z
437// =>
438// x = s_<op>_saveexec_b64 y
439//
440bool SIOptimizeExecMasking::optimizeExecSequence() {
441 bool Changed = false;
442 for (MachineBasicBlock &MBB : *MF) {
443 MachineBasicBlock::reverse_iterator I = fixTerminators(MBB);
445 if (I == E)
446 continue;
447
448 // It's possible to see other terminator copies after the exec copy. This
449 // can happen if control flow pseudos had their outputs used by phis.
450 Register CopyToExec;
451
452 for (unsigned SearchCount = 0, SearchLimit = 5;
453 I != E && SearchCount < SearchLimit; ++I) {
454 if (I->isDebugInstr())
455 continue;
456 ++SearchCount;
457 CopyToExec = isCopyToExec(*I);
458 if (CopyToExec)
459 break;
460 }
461
462 if (!CopyToExec)
463 continue;
464
465 // Scan backwards to find the def.
466 auto *CopyToExecInst = &*I;
467 auto CopyFromExecInst = findExecCopy(MBB, I);
468 if (CopyFromExecInst == E) {
469 auto PrepareExecInst = next_nodbg(I, E);
470 if (PrepareExecInst == E)
471 continue;
472 // Fold exec = COPY (S_AND_B64 reg, exec) -> exec = S_AND_B64 reg, exec
473 if (CopyToExecInst->getOperand(1).isKill() &&
474 isLogicalOpOnExec(*PrepareExecInst) == CopyToExec) {
475 LLVM_DEBUG(dbgs() << "Fold exec copy: " << *PrepareExecInst);
476
477 PrepareExecInst->getOperand(0).setReg(LMC.ExecReg);
478
479 LLVM_DEBUG(dbgs() << "into: " << *PrepareExecInst << '\n');
480
481 CopyToExecInst->eraseFromParent();
482 Changed = true;
483 } else if (optimizeAndN2WrExecSequence(*CopyToExecInst, CopyToExec)) {
484 Changed = true;
485 }
486
487 continue;
488 }
489
490 if (isLiveOut(MBB, CopyToExec)) {
491 // The copied register is live out and has a second use in another block.
492 LLVM_DEBUG(dbgs() << "Exec copy source register is live out\n");
493 continue;
494 }
495
496 Register CopyFromExec = CopyFromExecInst->getOperand(0).getReg();
497 MachineInstr *SaveExecInst = nullptr;
498 SmallVector<MachineInstr *, 4> OtherUseInsts;
499
501 J = std::next(CopyFromExecInst->getIterator()),
502 JE = I->getIterator();
503 J != JE; ++J) {
504 if (J->isDebugInstr())
505 continue;
506
507 if (SaveExecInst && J->readsRegister(LMC.ExecReg, TRI)) {
508 LLVM_DEBUG(dbgs() << "exec read prevents saveexec: " << *J << '\n');
509 // Make sure this is inserted after any VALU ops that may have been
510 // scheduled in between.
511 SaveExecInst = nullptr;
512 break;
513 }
514
515 bool ReadsCopyFromExec = J->readsRegister(CopyFromExec, TRI);
516
517 if (J->modifiesRegister(CopyToExec, TRI)) {
518 if (SaveExecInst) {
519 LLVM_DEBUG(dbgs() << "Multiple instructions modify "
520 << printReg(CopyToExec, TRI) << '\n');
521 SaveExecInst = nullptr;
522 break;
523 }
524
525 unsigned SaveExecOp = getSaveExecOp(J->getOpcode());
526 if (SaveExecOp == AMDGPU::INSTRUCTION_LIST_END)
527 break;
528
529 if (ReadsCopyFromExec) {
530 SaveExecInst = &*J;
531 LLVM_DEBUG(dbgs() << "Found save exec op: " << *SaveExecInst << '\n');
532 continue;
533 }
534 LLVM_DEBUG(dbgs() << "Instruction does not read exec copy: " << *J
535 << '\n');
536 break;
537 }
538 if (ReadsCopyFromExec && !SaveExecInst) {
539 // Make sure no other instruction is trying to use this copy, before it
540 // will be rewritten by the saveexec, i.e. hasOneUse. There may have
541 // been another use, such as an inserted spill. For example:
542 //
543 // %sgpr0_sgpr1 = COPY %exec
544 // spill %sgpr0_sgpr1
545 // %sgpr2_sgpr3 = S_AND_B64 %sgpr0_sgpr1
546 //
547 LLVM_DEBUG(dbgs() << "Found second use of save inst candidate: " << *J
548 << '\n');
549 break;
550 }
551
552 if (SaveExecInst && J->readsRegister(CopyToExec, TRI)) {
553 assert(SaveExecInst != &*J);
554 OtherUseInsts.push_back(&*J);
555 }
556 }
557
558 if (!SaveExecInst)
559 continue;
560
561 LLVM_DEBUG(dbgs() << "Insert save exec op: " << *SaveExecInst << '\n');
562
563 MachineOperand &Src0 = SaveExecInst->getOperand(1);
564 MachineOperand &Src1 = SaveExecInst->getOperand(2);
565
566 MachineOperand *OtherOp = nullptr;
567
568 if (Src0.isReg() && Src0.getReg() == CopyFromExec) {
569 OtherOp = &Src1;
570 } else if (Src1.isReg() && Src1.getReg() == CopyFromExec) {
571 if (!SaveExecInst->isCommutable())
572 break;
573
574 OtherOp = &Src0;
575 } else
576 llvm_unreachable("unexpected");
577
578 CopyFromExecInst->eraseFromParent();
579
580 auto InsPt = SaveExecInst->getIterator();
581 const DebugLoc &DL = SaveExecInst->getDebugLoc();
582
583 BuildMI(MBB, InsPt, DL, TII->get(getSaveExecOp(SaveExecInst->getOpcode())),
584 CopyFromExec)
585 .addReg(OtherOp->getReg());
586 SaveExecInst->eraseFromParent();
587
588 CopyToExecInst->eraseFromParent();
589
590 for (MachineInstr *OtherInst : OtherUseInsts) {
591 OtherInst->substituteRegister(CopyToExec, LMC.ExecReg,
592 AMDGPU::NoSubRegister, *TRI);
593 }
594
595 Changed = true;
596 }
597
598 return Changed;
599}
600
601bool SIOptimizeExecMasking::blocksAndN2Sink(const MachineInstr &MI,
602 Register Dst) const {
603 for (const MachineOperand &MO : MI.operands()) {
604 if (!MO.isReg())
605 continue;
606 // Any access to Dst would see a stale value once the def sinks past it,
607 // and a use of SCC would see the s_andn2 result.
608 if (TRI->regsOverlap(MO.getReg(), Dst))
609 return true;
610 if (MO.isUse() && MO.getReg() == AMDGPU::SCC)
611 return true;
612 }
613 return false;
614}
615
616// Fold
617//
618// sdst = S_ANDN2_B32 ssrc, exec
619// exec = COPY sdst
620// =>
621// sdst = S_ANDN2_WREXEC_B32 ssrc
622//
623// The waterfall loop emits the two operations separately so that spill code
624// for sdst can be inserted before exec is narrowed.
625bool SIOptimizeExecMasking::optimizeAndN2WrExecSequence(
626 MachineInstr &CopyToExecInst, Register Dst) const {
627 if (!ST->hasNoSdstCMPX() || TII->pseudoToMCOpcode(LMC.AndN2WrExecOpc) == -1)
628 return false;
629
630 MachineBasicBlock &MBB = *CopyToExecInst.getParent();
631
632 // Keep the fused instruction ahead of any trailing debug instructions, so
633 // DBG_VALUEs of Dst stay after its def.
635 if (InsertPt != MBB.begin())
636 InsertPt = std::next(prev_nodbg(InsertPt, MBB.begin()));
637
638 // Scan back for the s_andn2 computing the new exec value. The scheduler may
639 // have moved it away from the exec write, so allow instructions in between
640 // as long as sinking the s_andn2 past them is safe.
641 auto IsAndN2Def = [&](const MachineInstr &MI) {
642 return MI.getOpcode() == LMC.AndN2Opc && MI.getOperand(0).getReg() == Dst;
643 };
644 MachineInstr *AndN2Inst = findInstrBackwards(
645 CopyToExecInst,
646 [&](MachineInstr *Check) {
647 return IsAndN2Def(*Check) || blocksAndN2Sink(*Check, Dst);
648 },
649 /*NonModifiableRegs=*/{});
650 if (!AndN2Inst || !IsAndN2Def(*AndN2Inst))
651 return false;
652
653 const MachineOperand &Src = AndN2Inst->getOperand(1);
654 const MachineOperand &Mask = AndN2Inst->getOperand(2);
655 if (!Src.isReg() || !Mask.isReg() || Mask.getReg() != LMC.ExecReg)
656 return false;
657
658 for (MachineInstr &MI : make_range(
659 std::next(MachineBasicBlock::iterator(AndN2Inst)), InsertPt)) {
660 if (MI.modifiesRegister(Src.getReg(), TRI))
661 return false;
662 }
663
664 // The fused form also clobbers SCC, at the point the s_andn2 is moved to.
665 if (isRegisterInUseAfter(CopyToExecInst, AMDGPU::SCC))
666 return false;
667
668 LLVM_DEBUG(dbgs() << "Fold exec write: " << *AndN2Inst);
669
670 BuildMI(MBB, InsertPt, AndN2Inst->getDebugLoc(), TII->get(LMC.AndN2WrExecOpc),
671 Dst)
672 .addReg(Src.getReg());
673
674 AndN2Inst->eraseFromParent();
675 CopyToExecInst.eraseFromParent();
676 return true;
677}
678
679// Inserts the optimized s_mov_b32 / v_cmpx sequence based on the
680// operands extracted from a v_cmp ..., s_and_saveexec pattern.
681bool SIOptimizeExecMasking::optimizeVCMPSaveExecSequence(
682 MachineInstr &SaveExecInstr, MachineInstr &VCmp) const {
683 const int NewOpcode = AMDGPU::getVCMPXOpFromVCMP(VCmp.getOpcode());
684
685 if (NewOpcode == -1)
686 return false;
687
688 MachineOperand *Src0 = TII->getNamedOperand(VCmp, AMDGPU::OpName::src0);
689 MachineOperand *Src1 = TII->getNamedOperand(VCmp, AMDGPU::OpName::src1);
690
691 // Kills of the sources between the v_cmp and the saveexec are no longer
692 // valid once the compare is moved to the saveexec.
693 for (MachineInstr &MI :
694 make_range(std::next(VCmp.getIterator()), SaveExecInstr.getIterator())) {
695 for (MachineOperand &MO : MI.all_uses()) {
696 if (MO.isKill() &&
697 any_of(std::array{Src0, Src1}, [&](const MachineOperand *Src) {
698 return Src->isReg() && TRI->regsOverlap(MO.getReg(), Src->getReg());
699 }))
700 MO.setIsKill(false);
701 }
702 }
703
704 Register MoveDest = SaveExecInstr.getOperand(0).getReg();
705
706 MachineBasicBlock::instr_iterator InsertPosIt = SaveExecInstr.getIterator();
707 if (!SaveExecInstr.uses().empty()) {
708 bool IsSGPR32 = TRI->getRegSizeInBits(MoveDest, *MRI) == 32;
709 unsigned MovOpcode = IsSGPR32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
710 BuildMI(*SaveExecInstr.getParent(), InsertPosIt,
711 SaveExecInstr.getDebugLoc(), TII->get(MovOpcode), MoveDest)
712 .addReg(LMC.ExecReg);
713 }
714
715 // Omit dst as V_CMPX is implicitly writing to EXEC.
716 // Add dummy src and clamp modifiers, if needed.
717 auto Builder = BuildMI(*VCmp.getParent(), std::next(InsertPosIt),
718 VCmp.getDebugLoc(), TII->get(NewOpcode));
719
720 auto TryAddImmediateValueFromNamedOperand =
721 [&](AMDGPU::OpName OperandName) -> void {
722 if (auto *Mod = TII->getNamedOperand(VCmp, OperandName))
723 Builder.addImm(Mod->getImm());
724 };
725
726 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::src0_modifiers);
727 Builder.add(*Src0);
728
729 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::src1_modifiers);
730 Builder.add(*Src1);
731
732 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::clamp);
733
734 TryAddImmediateValueFromNamedOperand(AMDGPU::OpName::op_sel);
735
736 SaveExecInstr.eraseFromParent();
737 VCmp.eraseFromParent();
738
739 return true;
740}
741
742// Record (on GFX10.3 and later) occurences of
743// v_cmp_* SGPR, IMM, VGPR
744// s_and_saveexec_b32 EXEC_SGPR_DEST, SGPR
745// to be replaced with
746// s_mov_b32 EXEC_SGPR_DEST, exec_lo
747// v_cmpx_* IMM, VGPR
748// to reduce pipeline stalls.
749void SIOptimizeExecMasking::tryRecordVCmpxAndSaveexecSequence(
750 MachineInstr &MI) {
751 if (!ST->hasGFX10_3Insts())
752 return;
753
754 if (MI.getOpcode() != LMC.AndSaveExecOpc)
755 return;
756
757 Register SaveExecDest = MI.getOperand(0).getReg();
758 if (!TRI->isSGPRReg(*MRI, SaveExecDest))
759 return;
760
761 MachineOperand *SaveExecSrc0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
762 if (!SaveExecSrc0->isReg())
763 return;
764
765 // Tries to find a possibility to optimize a v_cmp ..., s_and_saveexec
766 // sequence by looking at an instance of an s_and_saveexec instruction.
767 // Returns a pointer to the v_cmp instruction if it is safe to replace the
768 // sequence (see the conditions in the function body). This is after register
769 // allocation, so some checks on operand dependencies need to be considered.
770 MachineInstr *VCmp = nullptr;
771
772 // Try to find the last v_cmp instruction that defs the saveexec input
773 // operand without any write to Exec or the saveexec input operand inbetween.
774 VCmp = findInstrBackwards(
775 MI,
776 [&](MachineInstr *Check) {
777 return AMDGPU::getVCMPXOpFromVCMP(Check->getOpcode()) != -1 &&
778 Check->modifiesRegister(SaveExecSrc0->getReg(), TRI);
779 },
780 {LMC.ExecReg, SaveExecSrc0->getReg()});
781
782 if (!VCmp)
783 return;
784
785 MachineOperand *VCmpDest = TII->getNamedOperand(*VCmp, AMDGPU::OpName::sdst);
786 assert(VCmpDest && "Should have an sdst operand!");
787
788 // Check if any of the v_cmp source operands is written by the saveexec.
789 MachineOperand *Src0 = TII->getNamedOperand(*VCmp, AMDGPU::OpName::src0);
790 if (Src0->isReg() && TRI->isSGPRReg(*MRI, Src0->getReg()) &&
791 MI.modifiesRegister(Src0->getReg(), TRI))
792 return;
793
794 MachineOperand *Src1 = TII->getNamedOperand(*VCmp, AMDGPU::OpName::src1);
795 if (Src1->isReg() && TRI->isSGPRReg(*MRI, Src1->getReg()) &&
796 MI.modifiesRegister(Src1->getReg(), TRI))
797 return;
798
799 // Don't do the transformation if the destination operand is included in
800 // it's MBB Live-outs, meaning it's used in any of its successors, leading
801 // to incorrect code if the v_cmp and therefore the def of
802 // the dest operand is removed.
803 if (isLiveOut(*VCmp->getParent(), VCmpDest->getReg()))
804 return;
805
806 // If the v_cmp target is in use between v_cmp and s_and_saveexec or after the
807 // s_and_saveexec, skip the optimization.
808 if (isRegisterInUseBetween(*VCmp, MI, VCmpDest->getReg(), false, true) ||
809 isRegisterInUseAfter(MI, VCmpDest->getReg()))
810 return;
811
812 // Try to determine if there is a write to any of the VCmp
813 // operands between the saveexec and the vcmp.
814 // If yes, additional VGPR spilling might need to be inserted. In this case,
815 // it's not worth replacing the instruction sequence.
817 if (Src0->isReg())
818 NonDefRegs.push_back(Src0->getReg());
819
820 if (Src1->isReg())
821 NonDefRegs.push_back(Src1->getReg());
822
823 if (!findInstrBackwards(
824 MI, [&](MachineInstr *Check) { return Check == VCmp; }, NonDefRegs))
825 return;
826
827 SaveExecVCmpMapping[&MI] = VCmp;
828}
829
830// Record occurences of
831// s_or_saveexec s_o, s_i
832// s_xor exec, exec, s_o
833// to be replaced with
834// s_andn2_saveexec s_o, s_i.
835void SIOptimizeExecMasking::tryRecordOrSaveexecXorSequence(MachineInstr &MI) {
836 if (MI.getOpcode() == LMC.XorOpc && &MI != &MI.getParent()->front()) {
837 const MachineOperand &XorDst = MI.getOperand(0);
838 const MachineOperand &XorSrc0 = MI.getOperand(1);
839 const MachineOperand &XorSrc1 = MI.getOperand(2);
840
841 if (XorDst.isReg() && XorDst.getReg() == LMC.ExecReg && XorSrc0.isReg() &&
842 XorSrc1.isReg() &&
843 (XorSrc0.getReg() == LMC.ExecReg || XorSrc1.getReg() == LMC.ExecReg)) {
844
845 // Peek at the previous instruction, ignoring meta instructions such as
846 // debug instructions and IMPLICIT_DEFs, and check if this is a relevant
847 // s_or_saveexec instruction.
848 auto It = skipMetaInstructionsBackward(std::prev(MI.getIterator()),
849 MI.getParent()->instr_begin());
850 MachineInstr &PossibleOrSaveexec = *It;
851 if (PossibleOrSaveexec.getOpcode() != LMC.OrSaveExecOpc)
852 return;
853
854 const MachineOperand &OrDst = PossibleOrSaveexec.getOperand(0);
855 const MachineOperand &OrSrc0 = PossibleOrSaveexec.getOperand(1);
856 if (OrDst.isReg() && OrSrc0.isReg()) {
857 if ((XorSrc0.getReg() == LMC.ExecReg &&
858 XorSrc1.getReg() == OrDst.getReg()) ||
859 (XorSrc0.getReg() == OrDst.getReg() &&
860 XorSrc1.getReg() == LMC.ExecReg)) {
861 OrXors.emplace_back(&PossibleOrSaveexec, &MI);
862 }
863 }
864 }
865 }
866}
867
868bool SIOptimizeExecMasking::optimizeOrSaveexecXorSequences() {
869 if (OrXors.empty()) {
870 return false;
871 }
872
873 bool Changed = false;
874
875 for (const auto &Pair : OrXors) {
876 MachineInstr *Or = nullptr;
877 MachineInstr *Xor = nullptr;
878 std::tie(Or, Xor) = Pair;
879 BuildMI(*Or->getParent(), Or->getIterator(), Or->getDebugLoc(),
880 TII->get(LMC.AndN2SaveExecOpc), Or->getOperand(0).getReg())
881 .addReg(Or->getOperand(1).getReg());
882
883 Or->eraseFromParent();
884 Xor->eraseFromParent();
885
886 Changed = true;
887 }
888
889 return Changed;
890}
891
892// Record occurrences of
893// s_n = s_not s_i
894// s_o = s_and_saveexec s_n
895// to be replaced with
896// s_o = s_andn1_saveexec s_i.
897void SIOptimizeExecMasking::tryRecordNotAndSaveexecSequence(MachineInstr &MI) {
898 if (MI.getOpcode() != LMC.AndSaveExecOpc ||
899 ST->getGeneration() < AMDGPUSubtarget::GFX9)
900 return;
901
902 const MachineOperand &SaveExecSrc = MI.getOperand(1);
903 if (!SaveExecSrc.isReg())
904 return;
905 Register NotDst = SaveExecSrc.getReg();
906
907 // Find the instruction that defines the saveexec input operand and check
908 // that it is a NOT.
909 MachineInstr *Not = findInstrBackwards(
910 MI,
911 [&](MachineInstr *Check) { return Check->modifiesRegister(NotDst, TRI); },
912 {});
913 if (!Not)
914 return;
915
916 // A NOT is either an s_not or an s_xor with -1 as either operand.
917 const MachineOperand *NotSrcOp = nullptr;
918 if (Not->getOpcode() == LMC.NotOpc) {
919 NotSrcOp = &Not->getOperand(1);
920 } else if (Not->getOpcode() == LMC.XorOpc) {
921 auto IsAllOnes = [](const MachineOperand &MO) {
922 return MO.isImm() && MO.getImm() == -1;
923 };
924 if (IsAllOnes(Not->getOperand(2)))
925 NotSrcOp = &Not->getOperand(1);
926 else if (IsAllOnes(Not->getOperand(1)))
927 NotSrcOp = &Not->getOperand(2);
928 }
929 if (!NotSrcOp || !NotSrcOp->isReg() || Not->getOperand(0).getReg() != NotDst)
930 return;
931
932 // The NOT input must still hold the same value at the saveexec. If the NOT
933 // overwrites its input then removing it leaves the input in the register,
934 // which is fine because the checks below ensure that the result has no other
935 // uses.
936 Register NotSrc = NotSrcOp->getReg();
937 if (!findInstrBackwards(MI, [&](MachineInstr *Check) { return Check == Not; },
938 {NotSrc}))
939 return;
940
941 // The NOT is removed, so nothing else may use its result or the value that
942 // it leaves in SCC. The saveexec may overwrite the result itself.
943 if (isRegisterInUseBetween(*Not, MI, NotDst, false, true) ||
944 isRegisterInUseBetween(*Not, MI, AMDGPU::SCC, false, true))
945 return;
946 if (!MI.definesRegister(NotDst, TRI) && isRegisterInUseAfter(MI, NotDst))
947 return;
948
949 NotSaveExecs.emplace_back(Not, NotSrc, &MI);
950}
951
952bool SIOptimizeExecMasking::optimizeNotAndSaveexecSequences() {
953 for (auto [Not, NotSrc, SaveExec] : NotSaveExecs) {
954 // Kills of the NOT input between the NOT and the saveexec are no longer
955 // valid once it is used by the saveexec. If the NOT overwrites its input
956 // then there are no uses in between.
957 if (NotSrc != Not->getOperand(0).getReg()) {
958 for (MachineInstr &MI :
959 make_range(std::next(Not->getIterator()), SaveExec->getIterator()))
960 MI.clearRegisterKills(NotSrc, TRI);
961 }
962
963 SaveExec->setDesc(TII->get(LMC.AndN1SaveExecOpc));
964 MachineOperand &Src = SaveExec->getOperand(1);
965 Src.setReg(NotSrc);
966 Src.setIsKill(false);
967 Not->eraseFromParent();
968 }
969
970 return !NotSaveExecs.empty();
971}
972
973bool SIOptimizeExecMaskingLegacy::runOnMachineFunction(MachineFunction &MF) {
974 if (skipFunction(MF.getFunction()))
975 return false;
976
977 return SIOptimizeExecMasking(&MF).run();
978}
979
980bool SIOptimizeExecMasking::run() {
981 bool Changed = optimizeExecSequence();
982
983 OrXors.clear();
984 NotSaveExecs.clear();
985 SaveExecVCmpMapping.clear();
986 static unsigned SearchWindow = 10;
987 for (MachineBasicBlock &MBB : *MF) {
988 unsigned SearchCount = 0;
989
990 for (auto &MI : llvm::reverse(MBB)) {
991 if (MI.isDebugInstr())
992 continue;
993
994 if (SearchCount >= SearchWindow) {
995 break;
996 }
997
998 tryRecordOrSaveexecXorSequence(MI);
999 tryRecordVCmpxAndSaveexecSequence(MI);
1000 tryRecordNotAndSaveexecSequence(MI);
1001
1002 if (MI.modifiesRegister(LMC.ExecReg, TRI)) {
1003 break;
1004 }
1005
1006 ++SearchCount;
1007 }
1008 }
1009
1010 Changed |= optimizeOrSaveexecXorSequences();
1011 Changed |= optimizeNotAndSaveexecSequences();
1012 for (const auto &Entry : SaveExecVCmpMapping) {
1013 MachineInstr *SaveExecInstr = Entry.getFirst();
1014 MachineInstr *VCmpInstr = Entry.getSecond();
1015
1016 Changed |= optimizeVCMPSaveExecSequence(*SaveExecInstr, *VCmpInstr);
1017 }
1018
1019 return Changed;
1020}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
A set of register units.
unsigned Opc
#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
MachineRegisterInfo & MRI
static unsigned getSaveExecOp(unsigned Opc)
static Register isLogicalOpOnExec(const MachineInstr &MI)
If MI is a logical operation on an exec value, return the register copied to.
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
Interface definition for SIRegisterInfo.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const LaneMaskConstants & get(const GCNSubtarget &ST)
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
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
A set of register units used to track register liveness.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
reverse_iterator rbegin()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z,...
mop_range uses()
Returns all operands which may be register uses.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READONLY int32_t getVCMPXOpFromVCMP(uint32_t Opcode)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
Not(const Pred &P) -> Not< Pred >
std::reverse_iterator< iterator > rend() const
Definition BasicBlock.h:96
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
char & SIOptimizeExecMaskingLegacyID
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IterT skipMetaInstructionsBackward(IterT It, IterT Begin)
Decrement It until it points to a non-meta instruction or to Begin and return the resulting iterator.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ Xor
Bitwise or logical XOR of integers.
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
#define N