LLVM 24.0.0git
MacroFusion.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/Statistic.h"
22#include "llvm/Support/Debug.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
35 cl::desc("Enable scheduling for macro fusion."), cl::init(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(*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
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;
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(&SecondSU, 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(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
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(SI) ||
120 SU == &DAG.ExitSU || SU == &SecondSU || SU->isPred(&SecondSU))
121 continue;
122 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(SecondSU);
123 dbgs() << " - "; DAG.dumpNodeName(*SU); dbgs() << '\n';);
124 DAG.addEdge(SU, 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(SI) || &FirstSU == SU || FirstSU.isSucc(SU))
133 continue;
134 LLVM_DEBUG(dbgs() << " Bind "; DAG.dumpNodeName(*SU); dbgs() << " - ";
135 DAG.dumpNodeName(FirstSU); dbgs() << '\n';);
136 DAG.addEdge(&FirstSU, 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(&FirstSU, 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(Predicates, [&](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, 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->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, ST, nullptr, AnchorMI, 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(DepSU, 2) ||
219 !shouldScheduleAdjacent(TII, ST, DepMI, AnchorMI, &Dep))
220 continue;
221
222 if (fuseInstructionPair(DAG, DepSU, AnchorSU))
223 return true;
224 }
225
226 return false;
227}
228
229std::unique_ptr<ScheduleDAGMutation>
231 bool BranchOnly) {
233 return std::make_unique<MacroFusion>(Predicates, !BranchOnly);
234 return nullptr;
235}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI, const SDep *Dep)
Check if the instr pair, FirstMI and SecondMI, should be fused together.
const HexagonInstrInfo * TII
static cl::opt< bool > EnableMacroFusion("misched-fusion", cl::Hidden, cl::desc("Enable scheduling for macro fusion."), cl::init(true))
static SUnit * getPredClusterSU(const SUnit &SU)
static bool isHazard(const SDep &Dep)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition MCInstrInfo.h:96
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Scheduling dependency.
Definition ScheduleDAG.h:52
SUnit * getSUnit() const
Kind getKind() const
Returns an enum value representing the kind of the dependence.
@ Output
A register output-dependence (aka WAW).
Definition ScheduleDAG.h:58
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:57
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:56
@ Cluster
Weak DAG edge linking a chain of clustered instrs.
Definition ScheduleDAG.h:77
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition ScheduleDAG.h:75
Scheduling unit. This is a node in the scheduling DAG.
unsigned NodeNum
Entry # of node in the node vector.
bool isSucc(const SUnit *N) const
Tests if node N is a successor of this node.
bool isPred(const SUnit *N) const
Tests if node N is a predecessor of this node.
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
unsigned ParentClusterIdx
The parent cluster id.
bool isClustered() const
SmallVector< SDep, 4 > Succs
All sunit successors.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
A ScheduleDAG for scheduling lists of MachineInstr.
SmallVector< ClusterInfo > & getClusters()
Returns the array of the clusters.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
Mutate the DAG as a postpass after normal DAG building.
const TargetInstrInfo * TII
Target instruction information.
std::vector< SUnit > SUnits
The scheduling units.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
void dumpNodeName(const SUnit &SU) const
SUnit ExitSU
Special node for the region exit.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
TargetInstrInfo - Interface to description of machine instruction set.
TargetSubtargetInfo - Generic base class for all target subtargets.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createMacroFusionDAGMutation(ArrayRef< MacroFusionPredTy > Predicates, bool BranchOnly=false)
Create a DAG scheduling mutation to pair instructions back to back for instructions that benefit acco...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool fuseInstructionPair(ScheduleDAGInstrs &DAG, SUnit &FirstSU, SUnit &SecondSU)
Create an artificial edge between FirstSU and SecondSU.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI, const SDep *Dep)
Check if the instr pair, FirstMI and SecondMI, should be fused together.
LLVM_ABI bool isNonDataDep(const SDep *Dep)
Returns true if Dep is a non-null non-data dependency.
bool(*)(const TargetInstrInfo &TII, const TargetSubtargetInfo &STI, const MachineInstr *FirstMI, const MachineInstr &SecondMI, const SDep *Dep) MacroFusionPredTy
Check if the instr pair, FirstMI and SecondMI, should be fused together, based on the dependency betw...
Definition MacroFusion.h:35
LLVM_ABI bool hasLessThanNumFused(const SUnit &SU, unsigned FuseLimit)
Checks if the number of cluster edges between SU and its predecessors is less than FuseLimit.