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"
62
63using namespace llvm;
64
65#define DEBUG_TYPE "si-lower-control-flow"
66
67static cl::opt<bool>
68RemoveRedundantEndcf("amdgpu-remove-redundant-endcf",
70
71namespace {
72
73class SILowerControlFlow {
74private:
75 const SIRegisterInfo *TRI = nullptr;
76 const SIInstrInfo *TII = nullptr;
77 LiveIntervals *LIS = nullptr;
78 MachineDominatorTree *MDT = nullptr;
79 MachinePostDominatorTree *PDT = nullptr;
80 MachineRegisterInfo *MRI = nullptr;
81 SetVector<MachineInstr*> LoweredEndCf;
82 DenseSet<Register> LoweredIf;
84 SmallSet<Register, 8> RecomputeRegs;
85
86 const TargetRegisterClass *BoolRC = nullptr;
88
89 bool EnableOptimizeEndCf = false;
90
91 bool hasKill(const MachineBasicBlock *Begin, const MachineBasicBlock *End);
92
93 void emitIf(MachineInstr &MI);
94 void emitElse(MachineInstr &MI);
95 void emitIfBreak(MachineInstr &MI);
96 void emitLoop(MachineInstr &MI);
97
99
100 void findMaskOperands(MachineInstr &MI, unsigned OpNo,
102
103 void combineMasks(MachineInstr &MI);
104
105 bool removeMBBifRedundant(MachineBasicBlock &MBB);
106
108
109 // Skip to the next instruction, ignoring debug instructions, and trivial
110 // block boundaries (blocks that have one (typically fallthrough) successor,
111 // and the successor has one predecessor.
113 skipIgnoreExecInstsTrivialSucc(MachineBasicBlock &MBB,
115
116 /// Find the insertion point for a new conditional branch.
118 skipToUncondBrOrEnd(MachineBasicBlock &MBB,
120 assert(I->isTerminator());
121
122 // FIXME: What if we had multiple pre-existing conditional branches?
124 while (I != End && !I->isUnconditionalBranch())
125 ++I;
126 return I;
127 }
128
129 // Remove redundant SI_END_CF instructions.
130 void optimizeEndCf();
131
132public:
133 SILowerControlFlow(const GCNSubtarget *ST, LiveIntervals *LIS,
134 MachineDominatorTree *MDT, MachinePostDominatorTree *PDT)
135 : LIS(LIS), MDT(MDT), PDT(PDT), LMC(AMDGPU::LaneMaskConstants::get(*ST)) {
136 }
137 bool run(MachineFunction &MF);
138};
139
140class SILowerControlFlowLegacy : public MachineFunctionPass {
141public:
142 static char ID;
143
144 SILowerControlFlowLegacy() : MachineFunctionPass(ID) {}
145
146 bool runOnMachineFunction(MachineFunction &MF) override;
147
148 StringRef getPassName() const override {
149 return "SI Lower control flow pseudo instructions";
150 }
151
152 void getAnalysisUsage(AnalysisUsage &AU) const override {
153 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
154 // Should preserve the same set that TwoAddressInstructions does.
155 AU.addPreserved<MachineDominatorTreeWrapperPass>();
156 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
157 AU.addPreserved<SlotIndexesWrapperPass>();
158 AU.addPreserved<LiveIntervalsWrapperPass>();
159 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
160 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
162 }
163};
164
165} // end anonymous namespace
166
167char SILowerControlFlowLegacy::ID = 0;
168
169INITIALIZE_PASS(SILowerControlFlowLegacy, DEBUG_TYPE, "SI lower control flow",
170 false, false)
171
172static void setImpSCCDefDead(MachineInstr &MI, bool IsDead = true) {
173 MachineOperand &ImpDefSCC = MI.getOperand(3);
174 assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef());
175
176 ImpDefSCC.setIsDead(IsDead);
177}
178
179static void copySCCDefDead(MachineInstr &MI, const MachineOperand &OrigSCCDef) {
180 assert(OrigSCCDef.getReg() == AMDGPU::SCC && OrigSCCDef.isDef());
181 setImpSCCDefDead(MI, OrigSCCDef.isDead());
182}
183
184char &llvm::SILowerControlFlowLegacyID = SILowerControlFlowLegacy::ID;
185
186bool SILowerControlFlow::hasKill(const MachineBasicBlock *Begin,
187 const MachineBasicBlock *End) {
188 DenseSet<const MachineBasicBlock*> Visited;
189 SmallVector<MachineBasicBlock *, 4> Worklist(Begin->successors());
190
191 while (!Worklist.empty()) {
192 MachineBasicBlock *MBB = Worklist.pop_back_val();
193
194 if (MBB == End || !Visited.insert(MBB).second)
195 continue;
196 if (KillBlocks.contains(MBB))
197 return true;
198
199 Worklist.append(MBB->succ_begin(), MBB->succ_end());
200 }
201
202 return false;
203}
204
205static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI) {
206 Register SaveExecReg = MI.getOperand(0).getReg();
207 auto U = MRI->use_instr_nodbg_begin(SaveExecReg);
208
209 if (U == MRI->use_instr_nodbg_end() ||
210 std::next(U) != MRI->use_instr_nodbg_end() ||
211 U->getOpcode() != AMDGPU::SI_END_CF)
212 return false;
213
214 return true;
215}
216
217void SILowerControlFlow::emitIf(MachineInstr &MI) {
218 MachineBasicBlock &MBB = *MI.getParent();
219 const DebugLoc &DL = MI.getDebugLoc();
221 Register SaveExecReg = MI.getOperand(0).getReg();
222 MachineOperand& Cond = MI.getOperand(1);
223 assert(Cond.getSubReg() == AMDGPU::NoSubRegister);
224
225 // If there is only one use of save exec register and that use is SI_END_CF,
226 // we can optimize SI_IF by returning the full saved exec mask instead of
227 // just cleared bits.
228 bool SimpleIf = isSimpleIf(MI, MRI);
229
230 if (SimpleIf) {
231 // Check for SI_KILL_*_TERMINATOR on path from if to endif.
232 // if there is any such terminator simplifications are not safe.
233 auto UseMI = MRI->use_instr_nodbg_begin(SaveExecReg);
234 SimpleIf = !hasKill(MI.getParent(), UseMI->getParent());
235 }
236
237 // Add an implicit def of exec to discourage scheduling VALU after this which
238 // will interfere with trying to form s_and_saveexec_b64 later.
239 Register CopyReg = SimpleIf ? SaveExecReg
240 : MRI->createVirtualRegister(BoolRC);
241 MachineInstr *CopyExec = BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg)
242 .addReg(LMC.ExecReg)
243 .addReg(LMC.ExecReg, RegState::ImplicitDefine);
244 LoweredIf.insert(CopyReg);
245
246 Register Tmp = MRI->createVirtualRegister(BoolRC);
247
248 MachineInstr *And =
249 BuildMI(MBB, I, DL, TII->get(LMC.AndOpc), Tmp).addReg(CopyReg).add(Cond);
250 setImpSCCDefDead(*And);
251
252 MachineInstr *Xor = nullptr;
253 if (!SimpleIf) {
254 Xor = BuildMI(MBB, I, DL, TII->get(LMC.XorOpc), SaveExecReg)
255 .addReg(Tmp)
256 .addReg(CopyReg);
257 copySCCDefDead(*Xor, MI.getOperand(4));
258 }
259
260 // Use a copy that is a terminator to get correct spill code placement it with
261 // fast regalloc.
262 MachineInstr *SetExec =
263 BuildMI(MBB, I, DL, TII->get(LMC.MovTermOpc), LMC.ExecReg)
264 .addReg(Tmp, RegState::Kill);
265
266 // Skip ahead to the unconditional branch in case there are other terminators
267 // present.
268 I = skipToUncondBrOrEnd(MBB, I);
269
270 // Insert the S_CBRANCH_EXECZ instruction which will be optimized later
271 // during SIPreEmitPeephole.
272 MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
273 .add(MI.getOperand(2));
274
275 if (!LIS) {
276 MI.eraseFromParent();
277 return;
278 }
279
280 LIS->InsertMachineInstrInMaps(*CopyExec);
281
282 // Replace with and so we don't need to fix the live interval for condition
283 // register.
285
286 if (!SimpleIf)
288 LIS->InsertMachineInstrInMaps(*SetExec);
289 LIS->InsertMachineInstrInMaps(*NewBr);
290
291 MI.eraseFromParent();
292
293 // FIXME: Is there a better way of adjusting the liveness? It shouldn't be
294 // hard to add another def here but I'm not sure how to correctly update the
295 // valno.
296 RecomputeRegs.insert(SaveExecReg);
298 if (!SimpleIf)
300}
301
302void SILowerControlFlow::emitElse(MachineInstr &MI) {
303 MachineBasicBlock &MBB = *MI.getParent();
304 const DebugLoc &DL = MI.getDebugLoc();
305
306 Register DstReg = MI.getOperand(0).getReg();
307 Register SrcReg = MI.getOperand(1).getReg();
308
310
311 // This must be inserted before phis and any spill code inserted before the
312 // else.
313 Register SaveReg = MRI->createVirtualRegister(BoolRC);
314 MachineInstr *OrSaveExec =
315 BuildMI(MBB, Start, DL, TII->get(LMC.OrSaveExecOpc), SaveReg)
316 .add(MI.getOperand(1)); // Saved EXEC
317 setImpSCCDefDead(*OrSaveExec, /*IsDead=*/true);
318
319 MachineBasicBlock *DestBB = MI.getOperand(2).getMBB();
320
322
323 // This accounts for any modification of the EXEC mask within the block and
324 // can be optimized out pre-RA when not required.
325 MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(LMC.AndOpc), DstReg)
326 .addReg(LMC.ExecReg)
327 .addReg(SaveReg);
328 setImpSCCDefDead(*And, /*IsDead=*/true);
329
330 MachineInstr *Xor =
331 BuildMI(MBB, ElsePt, DL, TII->get(LMC.XorTermOpc), LMC.ExecReg)
332 .addReg(LMC.ExecReg)
333 .addReg(DstReg);
334 copySCCDefDead(*Xor, MI.getOperand(4));
335
336 // Skip ahead to the unconditional branch in case there are other terminators
337 // present.
338 ElsePt = skipToUncondBrOrEnd(MBB, ElsePt);
339
340 MachineInstr *Branch =
341 BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ))
342 .addMBB(DestBB);
343
344 if (!LIS) {
345 MI.eraseFromParent();
346 return;
347 }
348
350 MI.eraseFromParent();
351
352 LIS->InsertMachineInstrInMaps(*OrSaveExec);
354
356 LIS->InsertMachineInstrInMaps(*Branch);
357
358 RecomputeRegs.insert(SrcReg);
359 RecomputeRegs.insert(DstReg);
361}
362
363void SILowerControlFlow::emitIfBreak(MachineInstr &MI) {
364 MachineBasicBlock &MBB = *MI.getParent();
365 const DebugLoc &DL = MI.getDebugLoc();
366 auto Dst = MI.getOperand(0).getReg();
367
368 // Skip ANDing with exec if the break condition is already masked by exec
369 // because it is a V_CMP in the same basic block. (We know the break
370 // condition operand was an i1 in IR, so if it is a VALU instruction it must
371 // be one with a carry-out.)
372 bool SkipAnding = false;
373 if (MI.getOperand(1).isReg()) {
374 if (MachineInstr *Def = MRI->getUniqueVRegDef(MI.getOperand(1).getReg())) {
375 SkipAnding = Def->getParent() == MI.getParent() &&
376 SIInstrInfo::isVALU(*Def, /*AllowLDSDMA=*/false);
377 }
378 }
379
380 // AND the break condition operand with exec, then OR that into the "loop
381 // exit" mask.
382 MachineInstr *And = nullptr, *Or = nullptr;
383 Register AndReg;
384 if (!SkipAnding) {
385 AndReg = MRI->createVirtualRegister(BoolRC);
386 And = BuildMI(MBB, &MI, DL, TII->get(LMC.AndOpc), AndReg)
387 .addReg(LMC.ExecReg)
388 .add(MI.getOperand(1));
389 setImpSCCDefDead(*And, /*IsDead=*/true);
390 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
391 .addReg(AndReg)
392 .add(MI.getOperand(2));
393 } else {
394 Or = BuildMI(MBB, &MI, DL, TII->get(LMC.OrOpc), Dst)
395 .add(MI.getOperand(1))
396 .add(MI.getOperand(2));
397 }
398
399 copySCCDefDead(*Or, MI.getOperand(3));
400
401 if (LIS) {
403 if (And) {
404 // Read of original operand 1 is on And now not Or.
405 RecomputeRegs.insert(And->getOperand(2).getReg());
408 }
409 }
410
411 MI.eraseFromParent();
412}
413
414void SILowerControlFlow::emitLoop(MachineInstr &MI) {
415 MachineBasicBlock &MBB = *MI.getParent();
416 const DebugLoc &DL = MI.getDebugLoc();
417
418 MachineInstr *AndN2 =
419 BuildMI(MBB, &MI, DL, TII->get(LMC.AndN2TermOpc), LMC.ExecReg)
420 .addReg(LMC.ExecReg)
421 .add(MI.getOperand(0));
422 copySCCDefDead(*AndN2, MI.getOperand(3));
423
424 auto BranchPt = skipToUncondBrOrEnd(MBB, MI.getIterator());
425 MachineInstr *Branch =
426 BuildMI(MBB, BranchPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
427 .add(MI.getOperand(1));
428
429 if (LIS) {
430 RecomputeRegs.insert(MI.getOperand(0).getReg());
431 LIS->ReplaceMachineInstrInMaps(MI, *AndN2);
432 LIS->InsertMachineInstrInMaps(*Branch);
433 }
434
435 MI.eraseFromParent();
436}
437
439SILowerControlFlow::skipIgnoreExecInstsTrivialSucc(
440 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
441
442 SmallPtrSet<const MachineBasicBlock *, 4> Visited;
443 MachineBasicBlock *B = &MBB;
444 do {
445 if (!Visited.insert(B).second)
446 return MBB.end();
447
448 auto E = B->end();
449 for ( ; It != E; ++It) {
450 if (TII->mayReadEXEC(*MRI, *It))
451 break;
452 }
453
454 if (It != E)
455 return It;
456
457 if (B->succ_size() != 1)
458 return MBB.end();
459
460 // If there is one trivial successor, advance to the next block.
461 MachineBasicBlock *Succ = *B->succ_begin();
462
463 It = Succ->begin();
464 B = Succ;
465 } while (true);
466}
467
468MachineBasicBlock *SILowerControlFlow::emitEndCf(MachineInstr &MI) {
469 MachineBasicBlock &MBB = *MI.getParent();
470 const DebugLoc &DL = MI.getDebugLoc();
471
473
474 // If we have instructions that aren't prolog instructions, split the block
475 // and emit a terminator instruction. This ensures correct spill placement.
476 // FIXME: We should unconditionally split the block here.
477 bool NeedBlockSplit = false;
478 Register DataReg = MI.getOperand(0).getReg();
479 for (MachineBasicBlock::iterator I = InsPt, E = MI.getIterator();
480 I != E; ++I) {
481 if (I->modifiesRegister(DataReg, TRI)) {
482 NeedBlockSplit = true;
483 break;
484 }
485 }
486
487 unsigned Opcode = LMC.OrOpc;
488 MachineBasicBlock *SplitBB = &MBB;
489 if (NeedBlockSplit) {
490 SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/true, LIS);
491 if (SplitBB != &MBB && (MDT || PDT)) {
492 using DomTreeT = DomTreeBase<MachineBasicBlock>;
494 for (MachineBasicBlock *Succ : SplitBB->successors()) {
495 DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
496 DTUpdates.push_back({DomTreeT::Delete, &MBB, Succ});
497 }
498 DTUpdates.push_back({DomTreeT::Insert, &MBB, SplitBB});
499 if (MDT)
500 MDT->applyUpdates(DTUpdates);
501 if (PDT)
502 PDT->applyUpdates(DTUpdates);
503 }
504 Opcode = LMC.OrTermOpc;
505 InsPt = MI;
506 }
507
508 MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(Opcode), LMC.ExecReg)
509 .addReg(LMC.ExecReg)
510 .add(MI.getOperand(0));
511 copySCCDefDead(*NewMI, MI.getOperand(2));
512
513 LoweredEndCf.insert(NewMI);
514
515 if (LIS)
516 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
517
518 MI.eraseFromParent();
519
520 if (LIS)
521 LIS->handleMove(*NewMI);
522 return SplitBB;
523}
524
525// Returns replace operands for a logical operation, either single result
526// for exec or two operands if source was another equivalent operation.
527void SILowerControlFlow::findMaskOperands(
528 MachineInstr &MI, unsigned OpNo,
529 SmallVectorImpl<MachineOperand *> &Src) const {
530 MachineOperand &Op = MI.getOperand(OpNo);
531 if (!Op.isReg() || !Op.getReg().isVirtual()) {
532 Src.push_back(&Op);
533 return;
534 }
535
536 MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg());
537 if (!Def || Def->getParent() != MI.getParent() ||
538 !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode())))
539 return;
540
541 // Make sure we do not modify exec between def and use.
542 // A copy with implicitly defined exec inserted earlier is an exclusion, it
543 // does not really modify exec.
544 for (auto I = Def->getIterator(); I != MI.getIterator(); ++I)
545 if (I->modifiesRegister(AMDGPU::EXEC, TRI) &&
546 !(I->isCopy() && I->getOperand(0).getReg() != LMC.ExecReg))
547 return;
548
549 for (MachineOperand &SrcOp : Def->explicit_operands())
550 if (SrcOp.isReg() && SrcOp.isUse() &&
551 (SrcOp.getReg().isVirtual() || SrcOp.getReg() == LMC.ExecReg))
552 Src.push_back(&SrcOp);
553}
554
555// Search and combine pairs of equivalent instructions, like
556// S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y
557// S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y
558// One of the operands is exec mask.
559void SILowerControlFlow::combineMasks(MachineInstr &MI) {
560 assert(MI.getNumExplicitOperands() == 3);
562 findMaskOperands(MI, 1, Src1);
563 findMaskOperands(MI, 2, Src2);
564
565 // Exactly one of the two operands must resolve to the nested LHS and RHS.
566 // Another one must resolve to a single value, exec or its copy.
567 unsigned OpToReplace;
568 MachineOperand *Leaf, *NestedLHS, *NestedRHS;
569 if (Src1.size() == 2 && Src2.size() == 1) {
570 OpToReplace = 1;
571 NestedLHS = Src1[0];
572 NestedRHS = Src1[1];
573 Leaf = Src2[0];
574 } else if (Src1.size() == 1 && Src2.size() == 2) {
575 OpToReplace = 2;
576 Leaf = Src1[0];
577 NestedLHS = Src2[0];
578 NestedRHS = Src2[1];
579 } else {
580 return;
581 }
582
583 // Always keep a nested operand, never the leaf operand.
584 MachineOperand *KeepOp;
585 if (Leaf->isIdenticalTo(*NestedLHS))
586 KeepOp = NestedRHS;
587 else if (Leaf->isIdenticalTo(*NestedRHS) ||
588 NestedLHS->isIdenticalTo(*NestedRHS))
589 KeepOp = NestedLHS;
590 else
591 return;
592
593 Register Reg = MI.getOperand(OpToReplace).getReg();
594 MI.removeOperand(OpToReplace);
595 MI.addOperand(*KeepOp);
596 if (MRI->use_empty(Reg))
598}
599
600void SILowerControlFlow::optimizeEndCf() {
601 // If the only instruction immediately following this END_CF is another
602 // END_CF in the only successor we can avoid emitting exec mask restore here.
603 if (!EnableOptimizeEndCf)
604 return;
605
606 for (MachineInstr *MI : reverse(LoweredEndCf)) {
607 MachineBasicBlock &MBB = *MI->getParent();
608 auto Next =
609 skipIgnoreExecInstsTrivialSucc(MBB, std::next(MI->getIterator()));
610 if (Next == MBB.end() || !LoweredEndCf.count(&*Next))
611 continue;
612 // Only skip inner END_CF if outer ENDCF belongs to SI_IF.
613 // If that belongs to SI_ELSE then saved mask has an inverted value.
614 Register SavedExec
615 = TII->getNamedOperand(*Next, AMDGPU::OpName::src1)->getReg();
616 assert(SavedExec.isVirtual() && "Expected saved exec to be src1!");
617
618 const MachineInstr *Def = MRI->getUniqueVRegDef(SavedExec);
619 if (Def && LoweredIf.count(SavedExec)) {
620 LLVM_DEBUG(dbgs() << "Skip redundant "; MI->dump());
621 if (LIS)
623 MI->eraseFromParent();
624 removeMBBifRedundant(MBB);
625 }
626 }
627}
628
629MachineBasicBlock *SILowerControlFlow::process(MachineInstr &MI) {
630 MachineBasicBlock &MBB = *MI.getParent();
632 MachineInstr *Prev = (I != MBB.begin()) ? &*(std::prev(I)) : nullptr;
633
634 MachineBasicBlock *SplitBB = &MBB;
635
636 switch (MI.getOpcode()) {
637 case AMDGPU::SI_IF:
638 emitIf(MI);
639 break;
640
641 case AMDGPU::SI_ELSE:
642 emitElse(MI);
643 break;
644
645 case AMDGPU::SI_IF_BREAK:
646 emitIfBreak(MI);
647 break;
648
649 case AMDGPU::SI_LOOP:
650 emitLoop(MI);
651 break;
652
653 case AMDGPU::SI_WATERFALL_LOOP:
654 MI.setDesc(TII->get(AMDGPU::S_CBRANCH_EXECNZ));
655 break;
656
657 case AMDGPU::SI_END_CF:
658 SplitBB = emitEndCf(MI);
659 break;
660
661 default:
662 assert(false && "Attempt to process unsupported instruction");
663 break;
664 }
665
667 for (I = Prev ? Prev->getIterator() : MBB.begin(); I != MBB.end(); I = Next) {
668 Next = std::next(I);
669 MachineInstr &MaskMI = *I;
670 switch (MaskMI.getOpcode()) {
671 case AMDGPU::S_AND_B64:
672 case AMDGPU::S_OR_B64:
673 case AMDGPU::S_AND_B32:
674 case AMDGPU::S_OR_B32:
675 // Cleanup bit manipulations on exec mask
676 combineMasks(MaskMI);
677 break;
678 default:
679 I = MBB.end();
680 break;
681 }
682 }
683
684 return SplitBB;
685}
686
687bool SILowerControlFlow::removeMBBifRedundant(MachineBasicBlock &MBB) {
688 for (auto &I : MBB.instrs()) {
689 if (!I.isDebugInstr() && !I.isUnconditionalBranch())
690 return false;
691 }
692
693 assert(MBB.succ_size() == 1 && "MBB has more than one successor");
694
695 MachineBasicBlock *Succ = *MBB.succ_begin();
696 MachineBasicBlock *FallThrough = nullptr;
697
698 using DomTreeT = DomTreeBase<MachineBasicBlock>;
700
701 while (!MBB.predecessors().empty()) {
702 MachineBasicBlock *P = *MBB.pred_begin();
703 if (P->getFallThrough(false) == &MBB)
704 FallThrough = P;
706 DTUpdates.push_back({DomTreeT::Insert, P, Succ});
707 DTUpdates.push_back({DomTreeT::Delete, P, &MBB});
708 }
709 MBB.removeSuccessor(Succ);
710 if (LIS) {
711 // Registers live across MBB have intervals spanning it, which must be
712 // recomputed once it is erased. removeMBBifRedundant only runs from
713 // optimizeEndCf, so defer to the pass-wide RecomputeRegs handling.
714 SlotIndex StartIdx = LIS->getMBBStartIdx(&MBB);
715 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
716 Register Reg = Register::index2VirtReg(I);
717 if (!LIS->hasInterval(Reg))
718 continue;
719 const LiveInterval &LI = LIS->getInterval(Reg);
720 if (LI.liveAt(StartIdx) || LI.liveAt(StartIdx.getPrevSlot()))
721 RecomputeRegs.insert(Reg);
722 }
723
724 for (auto &I : MBB.instrs())
726
727 // Drop MBB from the slot index maps before it is erased.
729 }
730 if (MDT)
731 MDT->applyUpdates(DTUpdates);
732 if (PDT)
733 PDT->applyUpdates(DTUpdates);
734
735 if (MDT && MDT->getNode(&MBB))
736 MDT->eraseNode(&MBB);
737 if (PDT && PDT->getNode(&MBB))
738 PDT->eraseNode(&MBB);
739
740 MBB.clear();
742 if (FallThrough && !FallThrough->isLayoutSuccessor(Succ)) {
743 // Note: we cannot update block layout and preserve live intervals;
744 // hence we must insert a branch.
745 MachineInstr *BranchMI = BuildMI(*FallThrough, FallThrough->end(),
746 FallThrough->findBranchDebugLoc(), TII->get(AMDGPU::S_BRANCH))
747 .addMBB(Succ);
748 if (LIS)
749 LIS->InsertMachineInstrInMaps(*BranchMI);
750 }
751
752 return true;
753}
754
755bool SILowerControlFlow::run(MachineFunction &MF) {
756 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
757 TII = ST.getInstrInfo();
758 TRI = &TII->getRegisterInfo();
759 EnableOptimizeEndCf = RemoveRedundantEndcf &&
760 MF.getTarget().getOptLevel() > CodeGenOptLevel::None;
761
762 MRI = &MF.getRegInfo();
763 BoolRC = TRI->getBoolRC();
764
765 // Compute set of blocks with kills
766 const bool CanDemote =
767 MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
768 for (auto &MBB : MF) {
769 bool IsKillBlock = false;
770 for (auto &Term : MBB.terminators()) {
771 if (TII->isKillTerminator(Term.getOpcode())) {
772 KillBlocks.insert(&MBB);
773 IsKillBlock = true;
774 break;
775 }
776 }
777 if (CanDemote && !IsKillBlock) {
778 for (auto &MI : MBB) {
779 if (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1) {
780 KillBlocks.insert(&MBB);
781 break;
782 }
783 }
784 }
785 }
786
787 bool Changed = false;
789 for (MachineFunction::iterator BI = MF.begin();
790 BI != MF.end(); BI = NextBB) {
791 NextBB = std::next(BI);
792 MachineBasicBlock *MBB = &*BI;
793
795 E = MBB->end();
796 for (I = MBB->begin(); I != E; I = Next) {
797 Next = std::next(I);
798 MachineInstr &MI = *I;
799 MachineBasicBlock *SplitMBB = MBB;
800
801 switch (MI.getOpcode()) {
802 case AMDGPU::SI_IF:
803 case AMDGPU::SI_ELSE:
804 case AMDGPU::SI_IF_BREAK:
805 case AMDGPU::SI_WATERFALL_LOOP:
806 case AMDGPU::SI_LOOP:
807 case AMDGPU::SI_END_CF:
808 SplitMBB = process(MI);
809 Changed = true;
810 break;
811 }
812
813 if (SplitMBB != MBB) {
814 MBB = Next->getParent();
815 E = MBB->end();
816 }
817 }
818 }
819
820 optimizeEndCf();
821
822 if (LIS && Changed) {
823 // These will need to be recomputed for insertions and removals.
824 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
825 LIS->removeAllRegUnitsForPhysReg(AMDGPU::SCC);
826 for (Register Reg : RecomputeRegs) {
827 LIS->removeInterval(Reg);
829 }
830 }
831
832 RecomputeRegs.clear();
833 LoweredEndCf.clear();
834 LoweredIf.clear();
835 KillBlocks.clear();
836
837 return Changed;
838}
839
840bool SILowerControlFlowLegacy::runOnMachineFunction(MachineFunction &MF) {
841 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
842 // This doesn't actually need LiveIntervals, but we can preserve them.
843 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
844 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
845 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
846 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
847 auto *PDTWrapper =
848 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
849 MachinePostDominatorTree *PDT =
850 PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
851 return SILowerControlFlow(ST, LIS, MDT, PDT).run(MF);
852}
853
854PreservedAnalyses
857 const GCNSubtarget *ST = &MF.getSubtarget<GCNSubtarget>();
863
864 bool Changed = SILowerControlFlow(ST, LIS, MDT, PDT).run(MF);
865 if (!Changed)
866 return PreservedAnalyses::all();
867
869 PA.preserve<MachineDominatorTreeAnalysis>();
871 PA.preserve<SlotIndexesAnalysis>();
872 PA.preserve<LiveIntervalsAnalysis>();
873 PA.preserve<MachineBlockFrequencyAnalysis>();
874 return PA;
875}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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
#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)
bool IsDead
static bool isSimpleIf(const MachineInstr &MI, const MachineRegisterInfo *MRI)
#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:273
const HexagonRegisterInfo & getRegisterInfo() const
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
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.
SlotIndexes * getSlotIndexes() const
void RemoveMachineInstrFromMaps(MachineInstr &MI)
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
bool liveAt(SlotIndex index) const
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.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
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 LLVM_READONLY 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()
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:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
LLVM_ABI void removeMBBFromMaps(MachineBasicBlock &MBB)
Inverse of insertMBBInMaps: merge MBB's slot range into its layout predecessor and drop it from the m...
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 push_back(const T &Elt)
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
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)
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.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
char & SILowerControlFlowLegacyID
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:408
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...
@ 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