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