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