1//===- MacroFusion.cpp - Macro Fusion -------------------------------------===//
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 This file contains the implementation of the DAG scheduling mutation
10/// to pair instructions back to back.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/MacroFusion.h"
15#include "llvm/ADT/Statistic.h"
16#include "llvm/CodeGen/MachineInstr.h"
17#include "llvm/CodeGen/ScheduleDAG.h"
18#include "llvm/CodeGen/ScheduleDAGInstrs.h"
19#include "llvm/CodeGen/ScheduleDAGMutation.h"
20#include "llvm/CodeGen/TargetInstrInfo.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/raw_ostream.h"
24
25#define DEBUG_TYPE "machine-scheduler"
26
27STATISTIC(NumFused, "Number of instr pairs fused");
28STATISTIC(NumFusionConflicts,
29 "Number of conflicts between a fusion pair and an already existing "
30 "cluster (either fusion or non-fusion)");
31
32using namespace llvm;
33
34static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
35 cl::desc("Enable scheduling for macro fusion."), cl::init(Val: true));
36
37static bool isHazard(const SDep &Dep) {
38 return Dep.getKind() == SDep::Anti || Dep.getKind() == SDep::Output;
39}
40
41static SUnit *getPredClusterSU(const SUnit &SU) {
42 for (const SDep &SI : SU.Preds)
43 if (SI.isCluster())
44 return SI.getSUnit();
45
46 return nullptr;
47}
48
49bool llvm::hasLessThanNumFused(const SUnit &SU, unsigned FuseLimit) {
50 unsigned Num = 1;
51 const SUnit *CurrentSU = &SU;
52 while ((CurrentSU = getPredClusterSU(SU: *CurrentSU)) && Num < FuseLimit) Num ++;
53 return Num < FuseLimit;
54}
55
56bool llvm::isNonDataDep(const SDep *Dep) {
57 return Dep && Dep->getKind() != SDep::Data;
58}
59
60bool llvm::fuseInstructionPair(ScheduleDAGInstrs &DAG, SUnit &FirstSU,
61 SUnit &SecondSU) {
62 // Check that neither instr is already associated with a cluster (either
63 // fusion or non-fusion)
64 if (FirstSU.isClustered() || SecondSU.isClustered()) {
65 ++NumFusionConflicts;
66 LLVM_DEBUG({
67 dbgs() << "Fusion conflict: cannot fuse " << FirstSU << " and ";
68 DAG.dumpNodeName(SecondSU);
69 dbgs() << "\n";
70 if (FirstSU.isClustered())
71 dbgs() << " " << FirstSU << " already clustered\n";
72 if (SecondSU.isClustered()) {
73 dbgs() << " ";
74 DAG.dumpNodeName(SecondSU);
75 dbgs() << " already clustered\n";
76 }
77 });
78 return false;
79 }
80
81 // Create a single weak edge between the adjacent instrs. The only effect is
82 // to cause bottom-up scheduling to heavily prioritize the clustered instrs.
83 if (!DAG.addEdge(SuccSU: &SecondSU, PredDep: SDep(&FirstSU, SDep::Cluster)))
84 return false;
85
86 auto &Clusters = DAG.getClusters();
87
88 unsigned ClusterIdx = Clusters.size();
89 FirstSU.ParentClusterIdx = ClusterIdx;
90 SecondSU.ParentClusterIdx = ClusterIdx;
91
92 SmallPtrSet<SUnit *, 8> Cluster{{&FirstSU, &SecondSU}};
93 Clusters.push_back(Elt: Cluster);
94
95 // TODO - If we want to chain more than two instructions, we need to create
96 // artifical edges to make dependencies from the FirstSU also dependent
97 // on other chained instructions, and other chained instructions also
98 // dependent on the dependencies of the SecondSU, to prevent them from being
99 // scheduled into these chained instructions.
100 assert(hasLessThanNumFused(FirstSU, 2) &&
101 "Currently we only support chaining together two instructions");
102
103 // Adjust the latency between both instrs.
104 for (SDep &SI : FirstSU.Succs)
105 if (SI.getSUnit() == &SecondSU)
106 SI.setLatency(0);
107
108 for (SDep &SI : SecondSU.Preds)
109 if (SI.getSUnit() == &FirstSU)
110 SI.setLatency(0);
111
112 LLVM_DEBUG(
113 dbgs() << "Macro fuse: "; DAG.dumpNodeName(FirstSU); dbgs() << " - ";
114 DAG.dumpNodeName(SecondSU); dbgs() << " / ";
115 dbgs() << DAG.TII->getName(FirstSU.getInstr()->getOpcode()) << " - "
116 << DAG.TII->getName(SecondSU.getInstr()->getOpcode()) << '\n';);
117
118 // Make data dependencies from the FirstSU also dependent on the SecondSU to
119 // prevent them from being scheduled between the FirstSU and the SecondSU.
120 if (&SecondSU != &DAG.ExitSU)
121 for (const SDep &SI : FirstSU.Succs) {
122 SUnit *SU = SI.getSUnit();
123 if (SI.isWeak() || isHazard(Dep: SI) ||
124 SU == &DAG.ExitSU || SU == &SecondSU || SU->isPred(N: &SecondSU))
125 continue;
126 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(SecondSU);
127 dbgs() << " - "; DAG.dumpNodeName(*SU); dbgs() << '\n';);
128 DAG.addEdge(SuccSU: SU, PredDep: SDep(&SecondSU, SDep::Artificial));
129 }
130
131 // Make the FirstSU also dependent on the dependencies of the SecondSU to
132 // prevent them from being scheduled between the FirstSU and the SecondSU.
133 if (&FirstSU != &DAG.EntrySU) {
134 for (const SDep &SI : SecondSU.Preds) {
135 SUnit *SU = SI.getSUnit();
136 if (SI.isWeak() || isHazard(Dep: SI) || &FirstSU == SU || FirstSU.isSucc(N: SU))
137 continue;
138 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(*SU); dbgs() << " - ";
139 DAG.dumpNodeName(FirstSU); dbgs() << '\n';);
140 DAG.addEdge(SuccSU: &FirstSU, PredDep: SDep(SU, SDep::Artificial));
141 }
142 // ExitSU comes last by design, which acts like an implicit dependency
143 // between ExitSU and any bottom root in the graph. We should transfer
144 // this to FirstSU as well.
145 if (&SecondSU == &DAG.ExitSU) {
146 for (SUnit &SU : DAG.SUnits) {
147 if (SU.Succs.empty())
148 DAG.addEdge(SuccSU: &FirstSU, PredDep: SDep(&SU, SDep::Artificial));
149 }
150 }
151 }
152
153 ++NumFused;
154 return true;
155}
156
157namespace {
158
159/// Post-process the DAG to create cluster edges between instrs that may
160/// be fused by the processor into a single operation.
161class MacroFusion : public ScheduleDAGMutation {
162 std::vector<MacroFusionPredTy> Predicates;
163 bool FuseBlock;
164 bool scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU);
165
166public:
167 MacroFusion(ArrayRef<MacroFusionPredTy> Predicates, bool FuseBlock)
168 : Predicates(Predicates.begin(), Predicates.end()), FuseBlock(FuseBlock) {
169 }
170
171 void apply(ScheduleDAGInstrs *DAGInstrs) override;
172
173 bool shouldScheduleAdjacent(const TargetInstrInfo &TII,
174 const TargetSubtargetInfo &STI,
175 const MachineInstr *FirstMI,
176 const MachineInstr &SecondMI, const SDep *Dep);
177};
178
179} // end anonymous namespace
180
181bool MacroFusion::shouldScheduleAdjacent(const TargetInstrInfo &TII,
182 const TargetSubtargetInfo &STI,
183 const MachineInstr *FirstMI,
184 const MachineInstr &SecondMI,
185 const SDep *Dep) {
186 return llvm::any_of(Range&: Predicates, P: [&](MacroFusionPredTy Predicate) {
187 return Predicate(TII, STI, FirstMI, SecondMI, Dep);
188 });
189}
190
191void MacroFusion::apply(ScheduleDAGInstrs *DAG) {
192 if (FuseBlock)
193 // For each of the SUnits in the scheduling block, try to fuse the instr in
194 // it with one in its predecessors.
195 for (SUnit &ISU : DAG->SUnits)
196 scheduleAdjacentImpl(DAG&: *DAG, AnchorSU&: ISU);
197
198 if (DAG->ExitSU.getInstr())
199 // Try to fuse the instr in the ExitSU with one in its predecessors.
200 scheduleAdjacentImpl(DAG&: *DAG, AnchorSU&: DAG->ExitSU);
201}
202
203/// Implement the fusion of instr pairs in the scheduling DAG,
204/// anchored at the instr in AnchorSU..
205bool MacroFusion::scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU) {
206 const MachineInstr &AnchorMI = *AnchorSU.getInstr();
207 const TargetInstrInfo &TII = *DAG.TII;
208 const TargetSubtargetInfo &ST = DAG.MF.getSubtarget();
209
210 // Check if the anchor instr may be fused.
211 if (!shouldScheduleAdjacent(TII, STI: ST, FirstMI: nullptr, SecondMI: AnchorMI, Dep: nullptr))
212 return false;
213
214 // Explorer for fusion candidates among the dependencies of the anchor instr.
215 for (SDep &Dep : AnchorSU.Preds) {
216 SUnit &DepSU = *Dep.getSUnit();
217 if (DepSU.isBoundaryNode())
218 continue;
219
220 // Only chain two instructions together at most.
221 const MachineInstr *DepMI = DepSU.getInstr();
222 if (!hasLessThanNumFused(SU: DepSU, FuseLimit: 2) ||
223 !shouldScheduleAdjacent(TII, STI: ST, FirstMI: DepMI, SecondMI: AnchorMI, Dep: &Dep))
224 continue;
225
226 if (fuseInstructionPair(DAG, FirstSU&: DepSU, SecondSU&: AnchorSU))
227 return true;
228 }
229
230 return false;
231}
232
233std::unique_ptr<ScheduleDAGMutation>
234llvm::createMacroFusionDAGMutation(ArrayRef<MacroFusionPredTy> Predicates,
235 bool BranchOnly) {
236 if (EnableMacroFusion)
237 return std::make_unique<MacroFusion>(args&: Predicates, args: !BranchOnly);
238 return nullptr;
239}
240