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 SU(" << FirstSU.NodeNum
68 << ") and SU(" << SecondSU.NodeNum << ")\n";
69 if (FirstSU.isClustered())
70 dbgs() << " SU(" << FirstSU.NodeNum << ") already clustered\n";
71 if (SecondSU.isClustered())
72 dbgs() << " SU(" << SecondSU.NodeNum << ") already clustered\n";
73 });
74 return false;
75 }
76
77 // Create a single weak edge between the adjacent instrs. The only effect is
78 // to cause bottom-up scheduling to heavily prioritize the clustered instrs.
79 if (!DAG.addEdge(SuccSU: &SecondSU, PredDep: SDep(&FirstSU, SDep::Cluster)))
80 return false;
81
82 auto &Clusters = DAG.getClusters();
83
84 unsigned ClusterIdx = Clusters.size();
85 FirstSU.ParentClusterIdx = ClusterIdx;
86 SecondSU.ParentClusterIdx = ClusterIdx;
87
88 SmallPtrSet<SUnit *, 8> Cluster{{&FirstSU, &SecondSU}};
89 Clusters.push_back(Elt: Cluster);
90
91 // TODO - If we want to chain more than two instructions, we need to create
92 // artifical edges to make dependencies from the FirstSU also dependent
93 // on other chained instructions, and other chained instructions also
94 // dependent on the dependencies of the SecondSU, to prevent them from being
95 // scheduled into these chained instructions.
96 assert(hasLessThanNumFused(FirstSU, 2) &&
97 "Currently we only support chaining together two instructions");
98
99 // Adjust the latency between both instrs.
100 for (SDep &SI : FirstSU.Succs)
101 if (SI.getSUnit() == &SecondSU)
102 SI.setLatency(0);
103
104 for (SDep &SI : SecondSU.Preds)
105 if (SI.getSUnit() == &FirstSU)
106 SI.setLatency(0);
107
108 LLVM_DEBUG(
109 dbgs() << "Macro fuse: "; DAG.dumpNodeName(FirstSU); dbgs() << " - ";
110 DAG.dumpNodeName(SecondSU); dbgs() << " / ";
111 dbgs() << DAG.TII->getName(FirstSU.getInstr()->getOpcode()) << " - "
112 << DAG.TII->getName(SecondSU.getInstr()->getOpcode()) << '\n';);
113
114 // Make data dependencies from the FirstSU also dependent on the SecondSU to
115 // prevent them from being scheduled between the FirstSU and the SecondSU.
116 if (&SecondSU != &DAG.ExitSU)
117 for (const SDep &SI : FirstSU.Succs) {
118 SUnit *SU = SI.getSUnit();
119 if (SI.isWeak() || isHazard(Dep: SI) ||
120 SU == &DAG.ExitSU || SU == &SecondSU || SU->isPred(N: &SecondSU))
121 continue;
122 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(SecondSU);
123 dbgs() << " - "; DAG.dumpNodeName(*SU); dbgs() << '\n';);
124 DAG.addEdge(SuccSU: SU, PredDep: SDep(&SecondSU, SDep::Artificial));
125 }
126
127 // Make the FirstSU also dependent on the dependencies of the SecondSU to
128 // prevent them from being scheduled between the FirstSU and the SecondSU.
129 if (&FirstSU != &DAG.EntrySU) {
130 for (const SDep &SI : SecondSU.Preds) {
131 SUnit *SU = SI.getSUnit();
132 if (SI.isWeak() || isHazard(Dep: SI) || &FirstSU == SU || FirstSU.isSucc(N: SU))
133 continue;
134 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(*SU); dbgs() << " - ";
135 DAG.dumpNodeName(FirstSU); dbgs() << '\n';);
136 DAG.addEdge(SuccSU: &FirstSU, PredDep: SDep(SU, SDep::Artificial));
137 }
138 // ExitSU comes last by design, which acts like an implicit dependency
139 // between ExitSU and any bottom root in the graph. We should transfer
140 // this to FirstSU as well.
141 if (&SecondSU == &DAG.ExitSU) {
142 for (SUnit &SU : DAG.SUnits) {
143 if (SU.Succs.empty())
144 DAG.addEdge(SuccSU: &FirstSU, PredDep: SDep(&SU, SDep::Artificial));
145 }
146 }
147 }
148
149 ++NumFused;
150 return true;
151}
152
153namespace {
154
155/// Post-process the DAG to create cluster edges between instrs that may
156/// be fused by the processor into a single operation.
157class MacroFusion : public ScheduleDAGMutation {
158 std::vector<MacroFusionPredTy> Predicates;
159 bool FuseBlock;
160 bool scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU);
161
162public:
163 MacroFusion(ArrayRef<MacroFusionPredTy> Predicates, bool FuseBlock)
164 : Predicates(Predicates.begin(), Predicates.end()), FuseBlock(FuseBlock) {
165 }
166
167 void apply(ScheduleDAGInstrs *DAGInstrs) override;
168
169 bool shouldScheduleAdjacent(const TargetInstrInfo &TII,
170 const TargetSubtargetInfo &STI,
171 const MachineInstr *FirstMI,
172 const MachineInstr &SecondMI, const SDep *Dep);
173};
174
175} // end anonymous namespace
176
177bool MacroFusion::shouldScheduleAdjacent(const TargetInstrInfo &TII,
178 const TargetSubtargetInfo &STI,
179 const MachineInstr *FirstMI,
180 const MachineInstr &SecondMI,
181 const SDep *Dep) {
182 return llvm::any_of(Range&: Predicates, P: [&](MacroFusionPredTy Predicate) {
183 return Predicate(TII, STI, FirstMI, SecondMI, Dep);
184 });
185}
186
187void MacroFusion::apply(ScheduleDAGInstrs *DAG) {
188 if (FuseBlock)
189 // For each of the SUnits in the scheduling block, try to fuse the instr in
190 // it with one in its predecessors.
191 for (SUnit &ISU : DAG->SUnits)
192 scheduleAdjacentImpl(DAG&: *DAG, AnchorSU&: ISU);
193
194 if (DAG->ExitSU.getInstr())
195 // Try to fuse the instr in the ExitSU with one in its predecessors.
196 scheduleAdjacentImpl(DAG&: *DAG, AnchorSU&: DAG->ExitSU);
197}
198
199/// Implement the fusion of instr pairs in the scheduling DAG,
200/// anchored at the instr in AnchorSU..
201bool MacroFusion::scheduleAdjacentImpl(ScheduleDAGInstrs &DAG, SUnit &AnchorSU) {
202 const MachineInstr &AnchorMI = *AnchorSU.getInstr();
203 const TargetInstrInfo &TII = *DAG.TII;
204 const TargetSubtargetInfo &ST = DAG.MF.getSubtarget();
205
206 // Check if the anchor instr may be fused.
207 if (!shouldScheduleAdjacent(TII, STI: ST, FirstMI: nullptr, SecondMI: AnchorMI, Dep: nullptr))
208 return false;
209
210 // Explorer for fusion candidates among the dependencies of the anchor instr.
211 for (SDep &Dep : AnchorSU.Preds) {
212 SUnit &DepSU = *Dep.getSUnit();
213 if (DepSU.isBoundaryNode())
214 continue;
215
216 // Only chain two instructions together at most.
217 const MachineInstr *DepMI = DepSU.getInstr();
218 if (!hasLessThanNumFused(SU: DepSU, FuseLimit: 2) ||
219 !shouldScheduleAdjacent(TII, STI: ST, FirstMI: DepMI, SecondMI: AnchorMI, Dep: &Dep))
220 continue;
221
222 if (fuseInstructionPair(DAG, FirstSU&: DepSU, SecondSU&: AnchorSU))
223 return true;
224 }
225
226 return false;
227}
228
229std::unique_ptr<ScheduleDAGMutation>
230llvm::createMacroFusionDAGMutation(ArrayRef<MacroFusionPredTy> Predicates,
231 bool BranchOnly) {
232 if (EnableMacroFusion)
233 return std::make_unique<MacroFusion>(args&: Predicates, args: !BranchOnly);
234 return nullptr;
235}
236