LLVM 20.0.0git
SILowerControlFlow.cpp
Go to the documentation of this file.
1//===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This pass lowers the pseudo control flow instructions to real
11/// machine instructions.
12///
13/// All control flow is handled using predicated instructions and
14/// a predicate stack. Each Scalar ALU controls the operations of 64 Vector
15/// ALUs. The Scalar ALU can update the predicate for any of the Vector ALUs
16/// by writing to the 64-bit EXEC register (each bit corresponds to a
17/// single vector ALU). Typically, for predicates, a vector ALU will write
18/// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each
19/// Vector ALU) and then the ScalarALU will AND the VCC register with the
20/// EXEC to update the predicates.
21///
22/// For example:
23/// %vcc = V_CMP_GT_F32 %vgpr1, %vgpr2
24/// %sgpr0 = SI_IF %vcc
25/// %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0
26/// %sgpr0 = SI_ELSE %sgpr0
27/// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr0
28/// SI_END_CF %sgpr0
29///
30/// becomes:
31///
32/// %sgpr0 = S_AND_SAVEEXEC_B64 %vcc // Save and update the exec mask
33/// %sgpr0 = S_XOR_B64 %sgpr0, %exec // Clear live bits from saved exec mask
34/// S_CBRANCH_EXECZ label0 // This instruction is an optional
35/// // optimization which allows us to
36/// // branch if all the bits of
37/// // EXEC are zero.
38/// %vgpr0 = V_ADD_F32 %vgpr0, %vgpr0 // Do the IF block of the branch
39///
40/// label0:
41/// %sgpr0 = S_OR_SAVEEXEC_B64 %sgpr0 // Restore the exec mask for the Then
42/// // block
43/// %exec = S_XOR_B64 %sgpr0, %exec // Update the exec mask
44/// S_CBRANCH_EXECZ label1 // Use our branch optimization
45/// // instruction again.
46/// %vgpr0 = V_SUB_F32 %vgpr0, %vgpr // Do the ELSE block
47/// label1:
48/// %exec = S_OR_B64 %exec, %sgpr0 // Re-enable saved exec mask bits
49//===----------------------------------------------------------------------===//
50
51#include "SILowerControlFlow.h"
52#include "AMDGPU.h"
53#include "GCNSubtarget.h"
55#include "llvm/ADT/SmallSet.h"
61
62using namespace llvm;
63
64#define DEBUG_TYPE "si-lower-control-flow"
65
66static cl::opt<bool>
67RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
69
70namespace {
71
72class SILowerControlFlow {
73private:
74 const SIRegisterInfo *TRI = nullptr;
75 const SIInstrInfo *TII = nullptr;
76 LiveIntervals *LIS = nullptr;
77 LiveVariables *LV = nullptr;
78 MachineDominatorTree *MDT = nullptr;
79 MachineRegisterInfo *MRI = nullptr;
80 SetVector<MachineInstr*> LoweredEndCf;
81 DenseSet<Register> LoweredIf;
83 SmallSet<Register, 8> RecomputeRegs;
84
85 const TargetRegisterClass *BoolRC = nullptr;
86 unsigned AndOpc;
87 unsigned OrOpc;
88 unsigned XorOpc;
89 unsigned MovTermOpc;
90 unsigned Andn2TermOpc;
91 unsigned XorTermrOpc;
92 unsigned OrTermrOpc;
93 unsigned OrSaveExecOpc;
94 unsigned Exec;
95
96 bool EnableOptimizeEndCf = false;
97
98 bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
99
100 void emitIf(MachineInstr &MI);
101 void emitElse(MachineInstr &MI);
102 void emitIfBreak(MachineInstr &MI);
103 void emitLoop(MachineInstr &MI);
104
105 MachineBasicBlock *emitEndCf(MachineInstr &MI);
106
107 void findMaskOperands(MachineInstr &MI, unsigned OpNo,
109
110 void combineMasks(MachineInstr &MI);
111
112 bool removeMBBifRedundant(MachineBasicBlock &MBB);
113
115
116 // Skip to the next instruction, ignoring debug instructions, and trivial
117 // block boundaries (blocks that have one (typically fallthrough) successor,
118 // and the successor has one predecessor.
120 skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
122
123 /// Find the insertion point for a new conditional branch.
125 skipToUncondBrOrEnd(MachineBasicBlock &MBB,
127 assert(I->isTerminator());
128
129 // FIXME: What if we had multiple pre-existing conditional branches?
131 while (I != End && !I->isUnconditionalBranch())
132 ++I;
133 return I;
134 }
135
136 // Remove redundant SI_END_CF instructions.
137 void optimizeEndCf();
138
139public:
140 SILowerControlFlow(LiveIntervals *LIS, LiveVariables *LV,
142 : LIS(LIS), LV(LV), MDT(MDT) {}
143 bool run(MachineFunction &MF);
144};
145
146class SILowerControlFlowLegacy : public MachineFunctionPass {
147public:
148 static char ID;
149
150 SILowerControlFlowLegacy() : MachineFunctionPass(ID) {}
151
152 bool runOnMachineFunction(MachineFunction &MF) override;
153
154 StringRef getPassName() const override {
155 return "SI Lower control flow pseudo instructions";
156 }
157
158 void getAnalysisUsage(AnalysisUsage &AU) const override {
160 // Should preserve the same set that TwoAddressInstructions does.
166 }
167};
168
169} // end anonymous namespace
170
171char SILowerControlFlowLegacy::ID = 0;
172
173INITIALIZE_PASS(SILowerControlFlowLegacy, DEBUG_TYPE, "SI lower control flow",
174 false, false)
175
176static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
177 MachineOperand &ImpDefSCC = MI.getOperand(3);
178 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
179
180 ImpDefSCC.setIsDead(IsDead);
181}
182
183char &llvm::SILowerControlFlowLegacyID = SILowerControlFlowLegacy::ID;
184
185bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
186 const MachineBasicBlock *End) {
189
190 while (!Worklist.empty()) {
191 MachineBasicBlock *MBB = Worklist.pop_back_val();
192
193 if (MBB == End || !Visited.insert(MBB).second)
194 continue;
195 if (KillBlocks.contains(MBB))
196 return true;
197
198 Worklist.append(MBB->succ_begin(), MBB->succ_end());
199 }
200
201 return false;
202}
203
204static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
205 Register SaveExecReg = MI.getOperand(0).getReg();
206 auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
207
208 if (U == MRI->use_instr_nodbg_end() ||
209 std::next(U) != MRI->use_instr_nodbg_end() ||
210 U->getOpcode() != AMDGPU::SI_END_CF)
211 return false;
212
213 return true;
214}
215
216void SILowerControlFlow::emitIf(MachineInstr &MI) {
217 MachineBasicBlock &MBB = *MI.getParent();
218 const DebugLoc &DL = MI.getDebugLoc();
220 Register SaveExecReg = MI.getOperand(0).getReg();
221 MachineOperand& Cond = MI.getOperand(1);
222 assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
223
224 MachineOperand &ImpDefSCC = MI.getOperand(4);
225 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
226
227 // If there is only one use of save exec register and that use is SI_END_CF,
228 // we can optimize SI_IF by returning the full saved exec mask instead of
229 // just cleared bits.
230 bool SimpleIf = isSimpleIf(MI, MRI);
231
232 if (SimpleIf) {
233 // Check for SI_KILL_*_TERMINATOR on path from if to endif.
234 // if there is any such terminator simplifications are not safe.
235 auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
236 SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
237 }
238
239 // Add an implicit def of exec to discourage scheduling VALU after this which
240 // will interfere with trying to form s_and_saveexec_b64 later.
241 Register CopyReg = SimpleIf ? SaveExecReg
242 : MRI->createVirtualRegister(BoolRC);
243 MachineInstr *CopyExec =
244 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
245 .addReg(Exec)
247 LoweredIf.insert(CopyReg);
248
249 Register Tmp = MRI->createVirtualRegister(BoolRC);
250
252 BuildMI(MBB, I, DL, TII->get(AndOpc), Tmp)
253 .addReg(CopyReg)
254 .add(Cond);
255 if (LV)
256 LV->replaceKillInstruction(Cond.getReg(), MI, *And);
257
258 setImpSCCDefDead(*And, true);
259
260 MachineInstr *Xor = nullptr;
261 if (!SimpleIf) {
262 Xor =
263 BuildMI(MBB, I, DL, TII->get(XorOpc), SaveExecReg)
264 .addReg(Tmp)
265 .addReg(CopyReg);
266 setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
267 }
268
269 // Use a copy that is a terminator to get correct spill code placement it with
270 // fast regalloc.
271 MachineInstr *SetExec =
272 BuildMI(MBB, I, DL, TII->get(MovTermOpc), Exec)
273 .addReg(Tmp, RegState::Kill);
274 if (LV)
275 LV->getVarInfo(Tmp).Kills.push_back(SetExec);
276
277 // Skip ahead to the unconditional branch in case there are other terminators
278 // present.
279 I = skipToUncondBrOrEnd(MBB, I);
280
281 // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
282 // during SIPreEmitPeephole.
283 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
284 .add(MI.getOperand(2));
285
286 if (!LIS) {
287 MI.eraseFromParent();
288 return;
289 }
290
291 LIS->InsertMachineInstrInMaps(*CopyExec);
292
293 // Replace with and so we don't need to fix the live interval for condition
294 // register.
296
297 if (!SimpleIf)
299 LIS->InsertMachineInstrInMaps(*SetExec);
300 LIS->InsertMachineInstrInMaps(*NewBr);
301
302 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
303 MI.eraseFromParent();
304
305 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
306 // hard to add another def here but I'm not sure how to correctly update the
307 // valno.
308 RecomputeRegs.insert(SaveExecReg);
310 if (!SimpleIf)
312}
313
314void SILowerControlFlow::emitElse(MachineInstr &MI) {
315 MachineBasicBlock &MBB = *MI.getParent();
316 const DebugLoc &DL = MI.getDebugLoc();
317
318 Register DstReg = MI.getOperand(0).getReg();
319 Register SrcReg = MI.getOperand(1).getReg();
320
322
323 // This must be inserted before phis and any spill code inserted before the
324 // else.
325 Register SaveReg = MRI->createVirtualRegister(BoolRC);
326 MachineInstr *OrSaveExec =
327 BuildMI(MBB, Start, DL, TII->get(OrSaveExecOpc), SaveReg)
328 .add(MI.getOperand(1)); // Saved EXEC
329 if (LV)
330 LV->replaceKillInstruction(SrcReg, MI, *OrSaveExec);
331
332 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
333
335
336 // This accounts for any modification of the EXEC mask within the block and
337 // can be optimized out pre-RA when not required.
338 MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(AndOpc), DstReg)
339 .addReg(Exec)
340 .addReg(SaveReg);
341
343 BuildMI(MBB, ElsePt, DL, TII->get(XorTermrOpc), Exec)
344 .addReg(Exec)
345 .addReg(DstReg);
346
347 // Skip ahead to the unconditional branch in case there are other terminators
348 // present.
349 ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
350
352 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
353 .addMBB(DestBB);
354
355 if (!LIS) {
356 MI.eraseFromParent();
357 return;
358 }
359
361 MI.eraseFromParent();
362
363 LIS->InsertMachineInstrInMaps(*OrSaveExec);
365
367 LIS->InsertMachineInstrInMaps(*Branch);
368
369 RecomputeRegs.insert(SrcReg);
370 RecomputeRegs.insert(DstReg);
372
373 // Let this be recomputed.
374 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
375}
376
377void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
378 MachineBasicBlock &MBB = *MI.getParent();
379 const DebugLoc &DL = MI.getDebugLoc();
380 auto Dst = MI.getOperand(0).getReg();
381
382 // Skip ANDing with exec if the break condition is already masked by exec
383 // because it is a V_CMP in the same basic block. (We know the break
384 // condition operand was an i1 in IR, so if it is a VALU instruction it must
385 // be one with a carry-out.)
386 bool SkipAnding = false;
387 if (MI.getOperand(1).isReg()) {
388 if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
389 SkipAnding = Def->getParent() == MI.getParent()
390 && SIInstrInfo::isVALU(*Def);
391 }
392 }
393
394 // AND the break condition operand with exec, then OR that into the "loop
395 // exit" mask.
396 MachineInstr *And = nullptr, *Or = nullptr;
397 Register AndReg;
398 if (!SkipAnding) {
399 AndReg = MRI->createVirtualRegister(BoolRC);
400 And = BuildMI(MBB, &MI, DL, TII->get(AndOpc), AndReg)
401 .addReg(Exec)
402 .add(MI.getOperand(1));
403 if (LV)
404 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *And);
405 Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
406 .addReg(AndReg)
407 .add(MI.getOperand(2));
408 } else {
409 Or = BuildMI(MBB, &MI, DL, TII->get(OrOpc), Dst)
410 .add(MI.getOperand(1))
411 .add(MI.getOperand(2));
412 if (LV)
413 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *Or);
414 }
415 if (LV)
416 LV->replaceKillInstruction(MI.getOperand(2).getReg(), MI, *Or);
417
418 if (LIS) {
420 if (And) {
421 // Read of original operand 1 is on And now not Or.
422 RecomputeRegs.insert(And->getOperand(2).getReg());
425 }
426 }
427
428 MI.eraseFromParent();
429}
430
431void SILowerControlFlow::emitLoop(MachineInstr &MI) {
432 MachineBasicBlock &MBB = *MI.getParent();
433 const DebugLoc &DL = MI.getDebugLoc();
434
435 MachineInstr *AndN2 =
436 BuildMI(MBB, &MI, DL, TII->get(Andn2TermOpc), Exec)
437 .addReg(Exec)
438 .add(MI.getOperand(0));
439 if (LV)
440 LV->replaceKillInstruction(MI.getOperand(0).getReg(), MI, *AndN2);
441
442 auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
444 BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
445 .add(MI.getOperand(1));
446
447 if (LIS) {
448 RecomputeRegs.insert(MI.getOperand(0).getReg());
449 LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
450 LIS->InsertMachineInstrInMaps(*Branch);
451 }
452
453 MI.eraseFromParent();
454}
455
457SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
459
462 do {
463 if (!Visited.insert(B).second)
464 return MBB.end();
465
466 auto E = B->end();
467 for ( ; It != E; ++It) {
468 if (TII->mayReadEXEC(*MRI, *It))
469 break;
470 }
471
472 if (It != E)
473 return It;
474
475 if (B->succ_size() != 1)
476 return MBB.end();
477
478 // If there is one trivial successor, advance to the next block.
479 MachineBasicBlock *Succ = *B->succ_begin();
480
481 It = Succ->begin();
482 B = Succ;
483 } while (true);
484}
485
486MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
487 MachineBasicBlock &MBB = *MI.getParent();
488 const DebugLoc &DL = MI.getDebugLoc();
489
491
492 // If we have instructions that aren't prolog instructions, split the block
493 // and emit a terminator instruction. This ensures correct spill placement.
494 // FIXME: We should unconditionally split the block here.
495 bool NeedBlockSplit = false;
496 Register DataReg = MI.getOperand(0).getReg();
497 for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
498 I != E; ++I) {
499 if (I->modifiesRegister(DataReg, TRI)) {
500 NeedBlockSplit = true;
501 break;
502 }
503 }
504
505 unsigned Opcode = OrOpc;
506 MachineBasicBlock *SplitBB = &MBB;
507 if (NeedBlockSplit) {
508 SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
509 if (MDT && SplitBB != &MBB) {
510 MachineDomTreeNode *MBBNode = (*MDT)[&MBB];
512 MBBNode->end());
513 MachineDomTreeNode *SplitBBNode = MDT->addNewBlock(SplitBB, &MBB);
514 for (MachineDomTreeNode *Child : Children)
515 MDT->changeImmediateDominator(Child, SplitBBNode);
516 }
517 Opcode = OrTermrOpc;
518 InsPt = MI;
519 }
520
521 MachineInstr *NewMI =
522 BuildMI(MBB, InsPt, DL, TII->get(Opcode), Exec)
523 .addReg(Exec)
524 .add(MI.getOperand(0));
525 if (LV) {
526 LV->replaceKillInstruction(DataReg, MI, *NewMI);
527
528 if (SplitBB != &MBB) {
529 // Track the set of registers defined in the original block so we don't
530 // accidentally add the original block to AliveBlocks. AliveBlocks only
531 // includes blocks which are live through, which excludes live outs and
532 // local defs.
533 DenseSet<Register> DefInOrigBlock;
534
535 for (MachineBasicBlock *BlockPiece : {&MBB, SplitBB}) {
536 for (MachineInstr &X : *BlockPiece) {
537 for (MachineOperand &Op : X.all_defs()) {
538 if (Op.getReg().isVirtual())
539 DefInOrigBlock.insert(Op.getReg());
540 }
541 }
542 }
543
544 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
547
548 if (VI.AliveBlocks.test(MBB.getNumber()))
549 VI.AliveBlocks.set(SplitBB->getNumber());
550 else {
551 for (MachineInstr *Kill : VI.Kills) {
552 if (Kill->getParent() == SplitBB && !DefInOrigBlock.contains(Reg))
553 VI.AliveBlocks.set(MBB.getNumber());
554 }
555 }
556 }
557 }
558 }
559
560 LoweredEndCf.insert(NewMI);
561
562 if (LIS)
563 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
564
565 MI.eraseFromParent();
566
567 if (LIS)
568 LIS->handleMove(*NewMI);
569 return SplitBB;
570}
571
572// Returns replace operands for a logical operation, either single result
573// for exec or two operands if source was another equivalent operation.
574void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
576 MachineOperand &Op = MI.getOperand(OpNo);
577 if (!Op.isReg() || !Op.getReg().isVirtual()) {
578 Src.push_back(Op);
579 return;
580 }
581
582 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
583 if (!Def || Def->getParent() != MI.getParent() ||
584 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
585 return;
586
587 // Make sure we do not modify exec between def and use.
588 // A copy with implicitly defined exec inserted earlier is an exclusion, it
589 // does not really modify exec.
590 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
591 if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
592 !(I->isCopy() && I->getOperand(0).getReg() != Exec))
593 return;
594
595 for (const auto &SrcOp : Def->explicit_operands())
596 if (SrcOp.isReg() && SrcOp.isUse() &&
597 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == Exec))
598 Src.push_back(SrcOp);
599}
600
601// Search and combine pairs of equivalent instructions, like
602// S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
603// S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y
604// One of the operands is exec mask.
605void SILowerControlFlow::combineMasks(MachineInstr &MI) {
606 assert(MI.getNumExplicitOperands() == 3);
608 unsigned OpToReplace = 1;
609 findMaskOperands(MI, 1, Ops);
610 if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
611 findMaskOperands(MI, 2, Ops);
612 if (Ops.size() != 3) return;
613
614 unsigned UniqueOpndIdx;
615 if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
616 else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
617 else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
618 else return;
619
620 Register Reg = MI.getOperand(OpToReplace).getReg();
621 MI.removeOperand(OpToReplace);
622 MI.addOperand(Ops[UniqueOpndIdx]);
623 if (MRI->use_empty(Reg))
624 MRI->getUniqueVRegDef(Reg)->eraseFromParent();
625}
626
627void SILowerControlFlow::optimizeEndCf() {
628 // If the only instruction immediately following this END_CF is another
629 // END_CF in the only successor we can avoid emitting exec mask restore here.
630 if (!EnableOptimizeEndCf)
631 return;
632
633 for (MachineInstr *MI : reverse(LoweredEndCf)) {
634 MachineBasicBlock &MBB = *MI->getParent();
635 auto Next =
636 skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
637 if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
638 continue;
639 // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
640 // If that belongs to SI_ELSE then saved mask has an inverted value.
641 Register SavedExec
642 = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
643 assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
644
645 const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
646 if (Def && LoweredIf.count(SavedExec)) {
647 LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
648 if (LIS)
651 if (LV)
652 Reg = TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
653 MI->eraseFromParent();
654 if (LV)
656 removeMBBifRedundant(MBB);
657 }
658 }
659}
660
661MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
662 MachineBasicBlock &MBB = *MI.getParent();
664 MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
665
666 MachineBasicBlock *SplitBB = &MBB;
667
668 switch (MI.getOpcode()) {
669 case AMDGPU::SI_IF:
670 emitIf(MI);
671 break;
672
673 case AMDGPU::SI_ELSE:
674 emitElse(MI);
675 break;
676
677 case AMDGPU::SI_IF_BREAK:
678 emitIfBreak(MI);
679 break;
680
681 case AMDGPU::SI_LOOP:
682 emitLoop(MI);
683 break;
684
685 case AMDGPU::SI_WATERFALL_LOOP:
686 MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
687 break;
688
689 case AMDGPU::SI_END_CF:
690 SplitBB = emitEndCf(MI);
691 break;
692
693 default:
694 assert(false && "Attempt to process unsupported instruction");
695 break;
696 }
697
699 for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
700 Next = std::next(I);
701 MachineInstr &MaskMI = *I;
702 switch (MaskMI.getOpcode()) {
703 case AMDGPU::S_AND_B64:
704 case AMDGPU::S_OR_B64:
705 case AMDGPU::S_AND_B32:
706 case AMDGPU::S_OR_B32:
707 // Cleanup bit manipulations on exec mask
708 combineMasks(MaskMI);
709 break;
710 default:
711 I = MBB.end();
712 break;
713 }
714 }
715
716 return SplitBB;
717}
718
719bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
720 for (auto &I : MBB.instrs()) {
721 if (!I.isDebugInstr() && !I.isUnconditionalBranch())
722 return false;
723 }
724
725 assert(MBB.succ_size() == 1 && "MBB has more than one successor");
726
728 MachineBasicBlock *FallThrough = nullptr;
729
730 while (!MBB.predecessors().empty()) {
732 if (P->getFallThrough(false) == &MBB)
733 FallThrough = P;
734 P->ReplaceUsesOfBlockWith(&MBB, Succ);
735 }
736 MBB.removeSuccessor(Succ);
737 if (LIS) {
738 for (auto &I : MBB.instrs())
740 }
741 if (MDT) {
742 // If Succ, the single successor of MBB, is dominated by MBB, MDT needs
743 // updating by changing Succ's idom to the one of MBB; otherwise, MBB must
744 // be a leaf node in MDT and could be erased directly.
745 if (MDT->dominates(&MBB, Succ))
746 MDT->changeImmediateDominator(MDT->getNode(Succ),
747 MDT->getNode(&MBB)->getIDom());
748 MDT->eraseNode(&MBB);
749 }
750 MBB.clear();
752 if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
753 // Note: we cannot update block layout and preserve live intervals;
754 // hence we must insert a branch.
755 MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
756 FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
757 .addMBB(Succ);
758 if (LIS)
759 LIS->InsertMachineInstrInMaps(*BranchMI);
760 }
761
762 return true;
763}
764
765bool SILowerControlFlow::run(MachineFunction &MF) {
767 TII = ST.getInstrInfo();
768 TRI = &TII->getRegisterInfo();
769 EnableOptimizeEndCf = RemoveRedundantEndcf &&
770 MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
771
772 MRI = &MF.getRegInfo();
773 BoolRC = TRI->getBoolRC();
774
775 if (ST.isWave32()) {
776 AndOpc = AMDGPU::S_AND_B32;
777 OrOpc = AMDGPU::S_OR_B32;
778 XorOpc = AMDGPU::S_XOR_B32;
779 MovTermOpc = AMDGPU::S_MOV_B32_term;
780 Andn2TermOpc = AMDGPU::S_ANDN2_B32_term;
781 XorTermrOpc = AMDGPU::S_XOR_B32_term;
782 OrTermrOpc = AMDGPU::S_OR_B32_term;
783 OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B32;
784 Exec = AMDGPU::EXEC_LO;
785 } else {
786 AndOpc = AMDGPU::S_AND_B64;
787 OrOpc = AMDGPU::S_OR_B64;
788 XorOpc = AMDGPU::S_XOR_B64;
789 MovTermOpc = AMDGPU::S_MOV_B64_term;
790 Andn2TermOpc = AMDGPU::S_ANDN2_B64_term;
791 XorTermrOpc = AMDGPU::S_XOR_B64_term;
792 OrTermrOpc = AMDGPU::S_OR_B64_term;
793 OrSaveExecOpc = AMDGPU::S_OR_SAVEEXEC_B64;
794 Exec = AMDGPU::EXEC;
795 }
796
797 // Compute set of blocks with kills
798 const bool CanDemote =
800 for (auto &MBB : MF) {
801 bool IsKillBlock = false;
802 for (auto &Term : MBB.terminators()) {
803 if (TII->isKillTerminator(Term.getOpcode())) {
804 KillBlocks.insert(&MBB);
805 IsKillBlock = true;
806 break;
807 }
808 }
809 if (CanDemote && !IsKillBlock) {
810 for (auto &MI : MBB) {
811 if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
812 KillBlocks.insert(&MBB);
813 break;
814 }
815 }
816 }
817 }
818
819 bool Changed = false;
821 for (MachineFunction::iterator BI = MF.begin();
822 BI != MF.end(); BI = NextBB) {
823 NextBB = std::next(BI);
824 MachineBasicBlock *MBB = &*BI;
825
827 E = MBB->end();
828 for (I = MBB->begin(); I != E; I = Next) {
829 Next = std::next(I);
830 MachineInstr &MI = *I;
831 MachineBasicBlock *SplitMBB = MBB;
832
833 switch (MI.getOpcode()) {
834 case AMDGPU::SI_IF:
835 case AMDGPU::SI_ELSE:
836 case AMDGPU::SI_IF_BREAK:
837 case AMDGPU::SI_WATERFALL_LOOP:
838 case AMDGPU::SI_LOOP:
839 case AMDGPU::SI_END_CF:
840 SplitMBB = process(MI);
841 Changed = true;
842 break;
843 }
844
845 if (SplitMBB != MBB) {
846 MBB = Next->getParent();
847 E = MBB->end();
848 }
849 }
850 }
851
852 optimizeEndCf();
853
854 if (LIS) {
855 for (Register Reg : RecomputeRegs) {
856 LIS->removeInterval(Reg);
858 }
859 }
860
861 RecomputeRegs.clear();
862 LoweredEndCf.clear();
863 LoweredIf.clear();
864 KillBlocks.clear();
865
866 return Changed;
867}
868
869bool SILowerControlFlowLegacy::runOnMachineFunction(MachineFunction &MF) {
870 // This doesn't actually need LiveIntervals, but we can preserve them.
871 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
872 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
873 // This doesn't actually need LiveVariables, but we can preserve them.
874 auto *LVWrapper = getAnalysisIfAvailable<LiveVariablesWrapperPass>();
875 LiveVariables *LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
876 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
877 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
878 return SILowerControlFlow(LIS, LV, MDT).run(MF);
879}
880
888
889 bool Changed = SILowerControlFlow(LIS, LV, MDT).run(MF);
890 if (!Changed)
891 return PreservedAnalyses::all();
892
894 PA.preserve<MachineDominatorTreeAnalysis>();
895 PA.preserve<SlotIndexesAnalysis>();
896 PA.preserve<LiveIntervalsAnalysis>();
897 PA.preserve<LiveVariablesAnalysis>();
898 return PA;
899}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DEBUG(...)
Definition: Debug.h:106
bool End
Definition: ELF_riscv.cpp:480
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< bool > RemoveRedundantEndcf("amdgpu-remove-redundant-endcf", cl::init(true), cl::ReallyHidden)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool IsDead
static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI)
#define DEBUG_TYPE
This file defines the SmallSet class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:429
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Base class for the actual dominator tree node.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:277
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
void removeInterval(Register Reg)
Interval removal.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
void recomputeForSingleDefVirtReg(Register Reg)
Recompute liveness from scratch for a virtual register Reg that is known to have a single def that do...
VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
unsigned succ_size() const
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
iterator_range< iterator > terminators()
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
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 TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:575
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:347
MachineOperand class - Representation of each machine instruction operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void dump() const
Definition: Pass.cpp:136
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
static bool isVALU(const MachineInstr &MI)
Definition: SIInstrInfo.h:424
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
Definition: SetVector.h:57
void clear()
Completely clear the SetVector.
Definition: SetVector.h:273
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:264
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:132
void clear()
Definition: SmallSet.h:204
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition: SmallSet.h:222
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:181
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:683
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
Register getReg() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:193
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:95
self_iterator getIterator()
Definition: ilist_node.h:132
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ Kill
The last use of a register.
Reg
All possible values of the reg field in the ModR/M byte.
@ ReallyHidden
Definition: CommandLine.h:138
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition: RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
char & SILowerControlFlowLegacyID
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
VarInfo - This represents the regions where a virtual register is live in the program.
Definition: LiveVariables.h:78
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
Definition: LiveVariables.h:88