LLVM 24.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 "AMDGPULaneMaskUtils.h"
54#include "GCNSubtarget.h"
56#include "llvm/ADT/SmallSet.h"
65
66using namespace llvm;
67
68#define DEBUG_TYPE "si-lower-control-flow"
69
70static cl::opt<bool>
71RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
73
74namespace {
75
76class SILowerControlFlow {
77private:
78 const SIRegisterInfo *TRI = nullptr;
79 const SIInstrInfo *TII = nullptr;
80 LiveIntervals *LIS = nullptr;
81 LiveVariables *LV = nullptr;
82 MachineDominatorTree *MDT = nullptr;
83 MachinePostDominatorTree *PDT = nullptr;
84 MachineRegisterInfo *MRI = nullptr;
85 SetVector<MachineInstr*> LoweredEndCf;
86 DenseSet<Register> LoweredIf;
88 SmallSet<Register, 8> RecomputeRegs;
89
90 const TargetRegisterClass *BoolRC = nullptr;
92
93 bool EnableOptimizeEndCf = false;
94
95 bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
96
97 void emitIf(MachineInstr &MI);
98 void emitElse(MachineInstr &MI);
99 void emitIfBreak(MachineInstr &MI);
100 void emitLoop(MachineInstr &MI);
101
102 MachineBasicBlock *emitEndCf(MachineInstr &MI);
103
104 void findMaskOperands(MachineInstr &MI, unsigned OpNo,
106
107 void combineMasks(MachineInstr &MI);
108
109 bool removeMBBifRedundant(MachineBasicBlock &MBB);
110
112
113 // Skip to the next instruction, ignoring debug instructions, and trivial
114 // block boundaries (blocks that have one (typically fallthrough) successor,
115 // and the successor has one predecessor.
117 skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
119
120 /// Find the insertion point for a new conditional branch.
122 skipToUncondBrOrEnd(MachineBasicBlock &MBB,
124 assert(I->isTerminator());
125
126 // FIXME: What if we had multiple pre-existing conditional branches?
128 while (I != End && !I->isUnconditionalBranch())
129 ++I;
130 return I;
131 }
132
133 // Remove redundant SI_END_CF instructions.
134 void optimizeEndCf();
135
136public:
137 SILowerControlFlow(const GCNSubtarget *ST, LiveIntervals *LIS,
138 LiveVariables *LV, MachineDominatorTree *MDT,
139 MachinePostDominatorTree *PDT)
140 : LIS(LIS), LV(LV), MDT(MDT), PDT(PDT),
141 LMC(AMDGPU::LaneMaskConstants::get(*ST)) {}
142 bool run(MachineFunction &MF);
143};
144
145class SILowerControlFlowLegacy : public MachineFunctionPass {
146public:
147 static char ID;
148
149 SILowerControlFlowLegacy() : MachineFunctionPass(ID) {}
150
151 bool runOnMachineFunction(MachineFunction &MF) override;
152
153 StringRef getPassName() const override {
154 return "SI Lower control flow pseudo instructions";
155 }
156
157 void getAnalysisUsage(AnalysisUsage &AU) const override {
158 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
159 // Should preserve the same set that TwoAddressInstructions does.
160 AU.addPreserved<MachineDominatorTreeWrapperPass>();
161 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
162 AU.addPreserved<SlotIndexesWrapperPass>();
163 AU.addPreserved<LiveIntervalsWrapperPass>();
164 AU.addPreserved<LiveVariablesWrapperPass>();
165 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
166 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
168 }
169};
170
171} // end anonymous namespace
172
173char SILowerControlFlowLegacy::ID = 0;
174
175INITIALIZE_PASS(SILowerControlFlowLegacy, DEBUG_TYPE, "SI lower control flow",
176 false, false)
177
178static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) {
179 MachineOperand &ImpDefSCC = MI.getOperand(3);
180 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
181
182 ImpDefSCC.setIsDead(IsDead);
183}
184
185char &llvm::SILowerControlFlowLegacyID = SILowerControlFlowLegacy::ID;
186
187bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
188 const MachineBasicBlock *End) {
191
192 while (!Worklist.empty()) {
193 MachineBasicBlock *MBB = Worklist.pop_back_val();
194
195 if (MBB == End || !Visited.insert(MBB).second)
196 continue;
197 if (KillBlocks.contains(MBB))
198 return true;
199
200 Worklist.append(MBB->succ_begin(), MBB->succ_end());
201 }
202
203 return false;
204}
205
206static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
207 Register SaveExecReg = MI.getOperand(0).getReg();
208 auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
209
210 if (U == MRI->use_instr_nodbg_end() ||
211 std::next(U) != MRI->use_instr_nodbg_end() ||
212 U->getOpcode() != AMDGPU::SI_END_CF)
213 return false;
214
215 return true;
216}
217
218void SILowerControlFlow::emitIf(MachineInstr &MI) {
219 MachineBasicBlock &MBB = *MI.getParent();
220 const DebugLoc &DL = MI.getDebugLoc();
222 Register SaveExecReg = MI.getOperand(0).getReg();
223 MachineOperand& Cond = MI.getOperand(1);
224 assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
225
226 MachineOperand &ImpDefSCC = MI.getOperand(4);
227 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
228
229 // If there is only one use of save exec register and that use is SI_END_CF,
230 // we can optimize SI_IF by returning the full saved exec mask instead of
231 // just cleared bits.
232 bool SimpleIf = isSimpleIf(MI, MRI);
233
234 if (SimpleIf) {
235 // Check for SI_KILL_*_TERMINATOR on path from if to endif.
236 // if there is any such terminator simplifications are not safe.
237 auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
238 SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
239 }
240
241 // Add an implicit def of exec to discourage scheduling VALU after this which
242 // will interfere with trying to form s_and_saveexec_b64 later.
243 Register CopyReg = SimpleIf ? SaveExecReg
244 : MRI->createVirtualRegister(BoolRC);
245 MachineInstr *CopyExec = BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
246 .addReg(LMC.ExecReg)
247 .addReg(LMC.ExecReg, RegState::ImplicitDefine);
248 LoweredIf.insert(CopyReg);
249
250 Register Tmp = MRI->createVirtualRegister(BoolRC);
251
252 MachineInstr *And =
253 BuildMI(MBB, I, DL, TII->get(LMC.AndOpc), Tmp).addReg(CopyReg).add(Cond);
254 if (LV)
255 LV->replaceKillInstruction(Cond.getReg(), MI, *And);
256
257 setImpSCCDefDead(*And, true);
258
259 MachineInstr *Xor = nullptr;
260 if (!SimpleIf) {
261 Xor = BuildMI(MBB, I, DL, TII->get(LMC.XorOpc), SaveExecReg)
262 .addReg(Tmp)
263 .addReg(CopyReg);
264 setImpSCCDefDead(*Xor, ImpDefSCC.isDead());
265 }
266
267 // Use a copy that is a terminator to get correct spill code placement it with
268 // fast regalloc.
269 MachineInstr *SetExec =
270 BuildMI(MBB, I, DL, TII->get(LMC.MovTermOpc), LMC.ExecReg)
271 .addReg(Tmp, RegState::Kill);
272 if (LV)
273 LV->getVarInfo(Tmp).Kills.push_back(SetExec);
274
275 // Skip ahead to the unconditional branch in case there are other terminators
276 // present.
277 I = skipToUncondBrOrEnd(MBB, I);
278
279 // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
280 // during SIPreEmitPeephole.
281 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
282 .add(MI.getOperand(2));
283
284 if (!LIS) {
285 MI.eraseFromParent();
286 return;
287 }
288
289 LIS->InsertMachineInstrInMaps(*CopyExec);
290
291 // Replace with and so we don't need to fix the live interval for condition
292 // register.
294
295 if (!SimpleIf)
297 LIS->InsertMachineInstrInMaps(*SetExec);
298 LIS->InsertMachineInstrInMaps(*NewBr);
299
300 MI.eraseFromParent();
301
302 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
303 // hard to add another def here but I'm not sure how to correctly update the
304 // valno.
305 RecomputeRegs.insert(SaveExecReg);
307 if (!SimpleIf)
309}
310
311void SILowerControlFlow::emitElse(MachineInstr &MI) {
312 MachineBasicBlock &MBB = *MI.getParent();
313 const DebugLoc &DL = MI.getDebugLoc();
314
315 Register DstReg = MI.getOperand(0).getReg();
316 Register SrcReg = MI.getOperand(1).getReg();
317
319
320 // This must be inserted before phis and any spill code inserted before the
321 // else.
322 Register SaveReg = MRI->createVirtualRegister(BoolRC);
323 MachineInstr *OrSaveExec =
324 BuildMI(MBB, Start, DL, TII->get(LMC.OrSaveExecOpc), SaveReg)
325 .add(MI.getOperand(1)); // Saved EXEC
326 if (LV)
327 LV->replaceKillInstruction(SrcReg, MI, *OrSaveExec);
328
329 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
330
332
333 // This accounts for any modification of the EXEC mask within the block and
334 // can be optimized out pre-RA when not required.
335 MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(LMC.AndOpc), DstReg)
336 .addReg(LMC.ExecReg)
337 .addReg(SaveReg);
338
339 MachineInstr *Xor =
340 BuildMI(MBB, ElsePt, DL, TII->get(LMC.XorTermOpc), LMC.ExecReg)
341 .addReg(LMC.ExecReg)
342 .addReg(DstReg);
343
344 // Skip ahead to the unconditional branch in case there are other terminators
345 // present.
346 ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
347
348 MachineInstr *Branch =
349 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
350 .addMBB(DestBB);
351
352 if (!LIS) {
353 MI.eraseFromParent();
354 return;
355 }
356
358 MI.eraseFromParent();
359
360 LIS->InsertMachineInstrInMaps(*OrSaveExec);
362
364 LIS->InsertMachineInstrInMaps(*Branch);
365
366 RecomputeRegs.insert(SrcReg);
367 RecomputeRegs.insert(DstReg);
369}
370
371void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
372 MachineBasicBlock &MBB = *MI.getParent();
373 const DebugLoc &DL = MI.getDebugLoc();
374 auto Dst = MI.getOperand(0).getReg();
375
376 // Skip ANDing with exec if the break condition is already masked by exec
377 // because it is a V_CMP in the same basic block. (We know the break
378 // condition operand was an i1 in IR, so if it is a VALU instruction it must
379 // be one with a carry-out.)
380 bool SkipAnding = false;
381 if (MI.getOperand(1).isReg()) {
382 if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
383 SkipAnding = Def->getParent() == MI.getParent() &&
384 SIInstrInfo::isVALU(*Def, /*AllowLDSDMA=*/true);
385 }
386 }
387
388 // AND the break condition operand with exec, then OR that into the "loop
389 // exit" mask.
390 MachineInstr *And = nullptr, *Or = nullptr;
391 Register AndReg;
392 if (!SkipAnding) {
393 AndReg = MRI->createVirtualRegister(BoolRC);
394 And = BuildMI(MBB, &MI, DL, TII->get(LMC.AndOpc), AndReg)
395 .addReg(LMC.ExecReg)
396 .add(MI.getOperand(1));
397 if (LV)
398 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *And);
399 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
400 .addReg(AndReg)
401 .add(MI.getOperand(2));
402 } else {
403 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
404 .add(MI.getOperand(1))
405 .add(MI.getOperand(2));
406 if (LV)
407 LV->replaceKillInstruction(MI.getOperand(1).getReg(), MI, *Or);
408 }
409 if (LV)
410 LV->replaceKillInstruction(MI.getOperand(2).getReg(), MI, *Or);
411
412 if (LIS) {
414 if (And) {
415 // Read of original operand 1 is on And now not Or.
416 RecomputeRegs.insert(And->getOperand(2).getReg());
419 }
420 }
421
422 MI.eraseFromParent();
423}
424
425void SILowerControlFlow::emitLoop(MachineInstr &MI) {
426 MachineBasicBlock &MBB = *MI.getParent();
427 const DebugLoc &DL = MI.getDebugLoc();
428
429 MachineInstr *AndN2 =
430 BuildMI(MBB, &MI, DL, TII->get(LMC.AndN2TermOpc), LMC.ExecReg)
431 .addReg(LMC.ExecReg)
432 .add(MI.getOperand(0));
433 if (LV)
434 LV->replaceKillInstruction(MI.getOperand(0).getReg(), MI, *AndN2);
435
436 auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
437 MachineInstr *Branch =
438 BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
439 .add(MI.getOperand(1));
440
441 if (LIS) {
442 RecomputeRegs.insert(MI.getOperand(0).getReg());
443 LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
444 LIS->InsertMachineInstrInMaps(*Branch);
445 }
446
447 MI.eraseFromParent();
448}
449
451SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
452 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
453
454 SmallPtrSet<const MachineBasicBlock *, 4> Visited;
455 MachineBasicBlock *B = &MBB;
456 do {
457 if (!Visited.insert(B).second)
458 return MBB.end();
459
460 auto E = B->end();
461 for ( ; It != E; ++It) {
462 if (TII->mayReadEXEC(*MRI, *It))
463 break;
464 }
465
466 if (It != E)
467 return It;
468
469 if (B->succ_size() != 1)
470 return MBB.end();
471
472 // If there is one trivial successor, advance to the next block.
473 MachineBasicBlock *Succ = *B->succ_begin();
474
475 It = Succ->begin();
476 B = Succ;
477 } while (true);
478}
479
480MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
481 MachineBasicBlock &MBB = *MI.getParent();
482 const DebugLoc &DL = MI.getDebugLoc();
483
485
486 // If we have instructions that aren't prolog instructions, split the block
487 // and emit a terminator instruction. This ensures correct spill placement.
488 // FIXME: We should unconditionally split the block here.
489 bool NeedBlockSplit = false;
490 Register DataReg = MI.getOperand(0).getReg();
491 for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
492 I != E; ++I) {
493 if (I->modifiesRegister(DataReg, TRI)) {
494 NeedBlockSplit = true;
495 break;
496 }
497 }
498
499 unsigned Opcode = LMC.OrOpc;
500 MachineBasicBlock *SplitBB = &MBB;
501 if (NeedBlockSplit) {
502 SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
503 if (SplitBB != &MBB && (MDT || PDT)) {
504 using DomTreeT = DomTreeBase<MachineBasicBlock>;
506 for (MachineBasicBlock *Succ : SplitBB->successors()) {
507 DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
508 DTUpdates.push_back({DomTreeT::Delete, &MBB, Succ});
509 }
510 DTUpdates.push_back({DomTreeT::Insert, &MBB, SplitBB});
511 if (MDT)
512 MDT->applyUpdates(DTUpdates);
513 if (PDT)
514 PDT->applyUpdates(DTUpdates);
515 }
516 Opcode = LMC.OrTermOpc;
517 InsPt = MI;
518 }
519
520 MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(Opcode), LMC.ExecReg)
521 .addReg(LMC.ExecReg)
522 .add(MI.getOperand(0));
523 if (LV) {
524 LV->replaceKillInstruction(DataReg, MI, *NewMI);
525
526 if (SplitBB != &MBB) {
527 // Track the set of registers defined in the original block so we don't
528 // accidentally add the original block to AliveBlocks. AliveBlocks only
529 // includes blocks which are live through, which excludes live outs and
530 // local defs.
531 DenseSet<Register> DefInOrigBlock;
532
533 for (MachineBasicBlock *BlockPiece : {&MBB, SplitBB}) {
534 for (MachineInstr &X : *BlockPiece) {
535 for (MachineOperand &Op : X.all_defs()) {
536 if (Op.getReg().isVirtual())
537 DefInOrigBlock.insert(Op.getReg());
538 }
539 }
540 }
541
542 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
543 Register Reg = Register::index2VirtReg(i);
544 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
545
546 if (VI.AliveBlocks.test(MBB.getNumber()))
547 VI.AliveBlocks.set(SplitBB->getNumber());
548 else {
549 for (MachineInstr *Kill : VI.Kills) {
550 if (Kill->getParent() == SplitBB && !DefInOrigBlock.contains(Reg))
551 VI.AliveBlocks.set(MBB.getNumber());
552 }
553 }
554 }
555 }
556 }
557
558 LoweredEndCf.insert(NewMI);
559
560 if (LIS)
561 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
562
563 MI.eraseFromParent();
564
565 if (LIS)
566 LIS->handleMove(*NewMI);
567 return SplitBB;
568}
569
570// Returns replace operands for a logical operation, either single result
571// for exec or two operands if source was another equivalent operation.
572void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo,
573 SmallVectorImpl<MachineOperand> &Src) const {
574 MachineOperand &Op = MI.getOperand(OpNo);
575 if (!Op.isReg() || !Op.getReg().isVirtual()) {
576 Src.push_back(Op);
577 return;
578 }
579
580 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
581 if (!Def || Def->getParent() != MI.getParent() ||
582 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
583 return;
584
585 // Make sure we do not modify exec between def and use.
586 // A copy with implicitly defined exec inserted earlier is an exclusion, it
587 // does not really modify exec.
588 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
589 if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
590 !(I->isCopy() && I->getOperand(0).getReg() != LMC.ExecReg))
591 return;
592
593 for (const auto &SrcOp : Def->explicit_operands())
594 if (SrcOp.isReg() && SrcOp.isUse() &&
595 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == LMC.ExecReg))
596 Src.push_back(SrcOp);
597}
598
599// Search and combine pairs of equivalent instructions, like
600// S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
601// S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y
602// One of the operands is exec mask.
603void SILowerControlFlow::combineMasks(MachineInstr &MI) {
604 assert(MI.getNumExplicitOperands() == 3);
606 unsigned OpToReplace = 1;
607 findMaskOperands(MI, 1, Ops);
608 if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy
609 findMaskOperands(MI, 2, Ops);
610 if (Ops.size() != 3) return;
611
612 unsigned UniqueOpndIdx;
613 if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2;
614 else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
615 else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1;
616 else return;
617
618 Register Reg = MI.getOperand(OpToReplace).getReg();
619 MI.removeOperand(OpToReplace);
620 MI.addOperand(Ops[UniqueOpndIdx]);
621 if (MRI->use_empty(Reg))
623}
624
625void SILowerControlFlow::optimizeEndCf() {
626 // If the only instruction immediately following this END_CF is another
627 // END_CF in the only successor we can avoid emitting exec mask restore here.
628 if (!EnableOptimizeEndCf)
629 return;
630
631 for (MachineInstr *MI : reverse(LoweredEndCf)) {
632 MachineBasicBlock &MBB = *MI->getParent();
633 auto Next =
634 skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
635 if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
636 continue;
637 // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
638 // If that belongs to SI_ELSE then saved mask has an inverted value.
639 Register SavedExec
640 = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
641 assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
642
643 const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
644 if (Def && LoweredIf.count(SavedExec)) {
645 LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
646 if (LIS)
649 if (LV)
650 Reg = TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
651 MI->eraseFromParent();
652 if (LV)
654 removeMBBifRedundant(MBB);
655 }
656 }
657}
658
659MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
660 MachineBasicBlock &MBB = *MI.getParent();
662 MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
663
664 MachineBasicBlock *SplitBB = &MBB;
665
666 switch (MI.getOpcode()) {
667 case AMDGPU::SI_IF:
668 emitIf(MI);
669 break;
670
671 case AMDGPU::SI_ELSE:
672 emitElse(MI);
673 break;
674
675 case AMDGPU::SI_IF_BREAK:
676 emitIfBreak(MI);
677 break;
678
679 case AMDGPU::SI_LOOP:
680 emitLoop(MI);
681 break;
682
683 case AMDGPU::SI_WATERFALL_LOOP:
684 MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
685 break;
686
687 case AMDGPU::SI_END_CF:
688 SplitBB = emitEndCf(MI);
689 break;
690
691 default:
692 assert(false && "Attempt to process unsupported instruction");
693 break;
694 }
695
697 for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
698 Next = std::next(I);
699 MachineInstr &MaskMI = *I;
700 switch (MaskMI.getOpcode()) {
701 case AMDGPU::S_AND_B64:
702 case AMDGPU::S_OR_B64:
703 case AMDGPU::S_AND_B32:
704 case AMDGPU::S_OR_B32:
705 // Cleanup bit manipulations on exec mask
706 combineMasks(MaskMI);
707 break;
708 default:
709 I = MBB.end();
710 break;
711 }
712 }
713
714 return SplitBB;
715}
716
717bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
718 for (auto &I : MBB.instrs()) {
719 if (!I.isDebugInstr() && !I.isUnconditionalBranch())
720 return false;
721 }
722
723 assert(MBB.succ_size() == 1 && "MBB has more than one successor");
724
725 MachineBasicBlock *Succ = *MBB.succ_begin();
726 MachineBasicBlock *FallThrough = nullptr;
727
728 using DomTreeT = DomTreeBase<MachineBasicBlock>;
730
731 while (!MBB.predecessors().empty()) {
732 MachineBasicBlock *P = *MBB.pred_begin();
733 if (P->getFallThrough(false) == &MBB)
734 FallThrough = P;
736 DTUpdates.push_back({DomTreeT::Insert, P, Succ});
737 DTUpdates.push_back({DomTreeT::Delete, P, &MBB});
738 }
739 MBB.removeSuccessor(Succ);
740 if (LIS) {
741 for (auto &I : MBB.instrs())
743 }
744 if (MDT)
745 MDT->applyUpdates(DTUpdates);
746 if (PDT)
747 PDT->applyUpdates(DTUpdates);
748
749 if (MDT && MDT->getNode(&MBB))
750 MDT->eraseNode(&MBB);
751 if (PDT && PDT->getNode(&MBB))
752 PDT->eraseNode(&MBB);
753
754 MBB.clear();
756 if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
757 // Note: we cannot update block layout and preserve live intervals;
758 // hence we must insert a branch.
759 MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
760 FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
761 .addMBB(Succ);
762 if (LIS)
763 LIS->InsertMachineInstrInMaps(*BranchMI);
764 }
765
766 return true;
767}
768
769bool SILowerControlFlow::run(MachineFunction &MF) {
770 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
771 TII = ST.getInstrInfo();
772 TRI = &TII->getRegisterInfo();
773 EnableOptimizeEndCf = RemoveRedundantEndcf &&
774 MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
775
776 MRI = &MF.getRegInfo();
777 BoolRC = TRI->getBoolRC();
778
779 // Compute set of blocks with kills
780 const bool CanDemote =
781 MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
782 for (auto &MBB : MF) {
783 bool IsKillBlock = false;
784 for (auto &Term : MBB.terminators()) {
785 if (TII->isKillTerminator(Term.getOpcode())) {
786 KillBlocks.insert(&MBB);
787 IsKillBlock = true;
788 break;
789 }
790 }
791 if (CanDemote && !IsKillBlock) {
792 for (auto &MI : MBB) {
793 if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
794 KillBlocks.insert(&MBB);
795 break;
796 }
797 }
798 }
799 }
800
801 bool Changed = false;
803 for (MachineFunction::iterator BI = MF.begin();
804 BI != MF.end(); BI = NextBB) {
805 NextBB = std::next(BI);
806 MachineBasicBlock *MBB = &*BI;
807
809 E = MBB->end();
810 for (I = MBB->begin(); I != E; I = Next) {
811 Next = std::next(I);
812 MachineInstr &MI = *I;
813 MachineBasicBlock *SplitMBB = MBB;
814
815 switch (MI.getOpcode()) {
816 case AMDGPU::SI_IF:
817 case AMDGPU::SI_ELSE:
818 case AMDGPU::SI_IF_BREAK:
819 case AMDGPU::SI_WATERFALL_LOOP:
820 case AMDGPU::SI_LOOP:
821 case AMDGPU::SI_END_CF:
822 SplitMBB = process(MI);
823 Changed = true;
824 break;
825 }
826
827 if (SplitMBB != MBB) {
828 MBB = Next->getParent();
829 E = MBB->end();
830 }
831 }
832 }
833
834 optimizeEndCf();
835
836 if (LIS && Changed) {
837 // These will need to be recomputed for insertions and removals.
838 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
839 LIS->removeAllRegUnitsForPhysReg(AMDGPU::SCC);
840 for (Register Reg : RecomputeRegs) {
841 LIS->removeInterval(Reg);
843 }
844 }
845
846 RecomputeRegs.clear();
847 LoweredEndCf.clear();
848 LoweredIf.clear();
849 KillBlocks.clear();
850
851 return Changed;
852}
853
854bool SILowerControlFlowLegacy::runOnMachineFunction(MachineFunction &MF) {
855 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
856 // This doesn't actually need LiveIntervals, but we can preserve them.
857 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
858 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
859 // This doesn't actually need LiveVariables, but we can preserve them.
860 auto *LVWrapper = getAnalysisIfAvailable<LiveVariablesWrapperPass>();
861 LiveVariables *LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
862 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
863 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
864 auto *PDTWrapper =
865 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
866 MachinePostDominatorTree *PDT =
867 PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
868 return SILowerControlFlow(ST, LIS, LV, MDT, PDT).run(MF);
869}
870
871PreservedAnalyses
874 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
881
882 bool Changed = SILowerControlFlow(ST, LIS, LV, MDT, PDT).run(MF);
883 if (!Changed)
884 return PreservedAnalyses::all();
885
887 PA.preserve<MachineDominatorTreeAnalysis>();
889 PA.preserve<SlotIndexesAnalysis>();
890 PA.preserve<LiveIntervalsAnalysis>();
891 PA.preserve<LiveVariablesAnalysis>();
892 PA.preserve<MachineBlockFrequencyAnalysis>();
893 return PA;
894}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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)
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
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.
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
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:272
const HexagonRegisterInfo & getRegisterInfo() const
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI 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)
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
LLVM_ABI void recomputeForSingleDefVirtReg(Register Reg)
Recompute liveness from scratch for a virtual register Reg that is known to have a single def that do...
LLVM_ABI 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...
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
iterator_range< iterator > terminators()
LLVM_ABI 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()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
BasicBlockListType::iterator iterator
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
static use_instr_nodbg_iterator use_instr_nodbg_end()
void dump() const
Definition Pass.cpp:146
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 isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:262
void clear()
Completely clear the SetVector.
Definition SetVector.h:267
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
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:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
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:187
self_iterator getIterator()
Definition ilist_node.h:123
Changed
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
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
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
char & SILowerControlFlowLegacyID
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
DWARFExpression::Operation Op
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...