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