blob: 218484715db63ae3f660fa03108ebf2c38f6bb01 [file] [log] [blame]
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001//===---- MachineCombiner.cpp - Instcombining on SSA form machine code ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// The machine combiner pass uses machine trace metrics to ensure the combined
Eric Christopher17ce8a22017-03-15 21:50:46 +000010// instructions do not lengthen the critical path or the resource depth.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000011//===----------------------------------------------------------------------===//
Hans Wennborg083ca9b2015-10-06 23:24:35 +000012
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000013#include "llvm/ADT/DenseMap.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000014#include "llvm/ADT/Statistic.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000015#include "llvm/CodeGen/MachineDominators.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000018#include "llvm/CodeGen/MachineLoopInfo.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/CodeGen/MachineTraceMetrics.h"
21#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000022#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000023#include "llvm/CodeGen/TargetRegisterInfo.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000024#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000025#include "llvm/CodeGen/TargetSubtargetInfo.h"
Florian Hahnceb44942017-09-20 11:54:37 +000026#include "llvm/Support/CommandLine.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/raw_ostream.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000029
30using namespace llvm;
31
Jakub Kuderski1d2dc682017-07-13 19:30:52 +000032#define DEBUG_TYPE "machine-combiner"
33
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000034STATISTIC(NumInstCombined, "Number of machineinst combined");
35
Florian Hahnceb44942017-09-20 11:54:37 +000036static cl::opt<unsigned>
37inc_threshold("machine-combiner-inc-threshold", cl::Hidden,
38 cl::desc("Incremental depth computation will be used for basic "
39 "blocks with more instructions."), cl::init(500));
40
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +000041static cl::opt<bool> dump_intrs("machine-combiner-dump-subst-intrs", cl::Hidden,
42 cl::desc("Dump all substituted intrs"),
43 cl::init(false));
44
Florian Hahnc68428b2018-01-31 13:54:30 +000045#ifdef EXPENSIVE_CHECKS
46static cl::opt<bool> VerifyPatternOrder(
47 "machine-combiner-verify-pattern-order", cl::Hidden,
48 cl::desc(
49 "Verify that the generated patterns are ordered by increasing latency"),
50 cl::init(true));
51#else
52static cl::opt<bool> VerifyPatternOrder(
53 "machine-combiner-verify-pattern-order", cl::Hidden,
54 cl::desc(
55 "Verify that the generated patterns are ordered by increasing latency"),
56 cl::init(false));
57#endif
58
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000059namespace {
60class MachineCombiner : public MachineFunctionPass {
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +000061 const TargetSubtargetInfo *STI;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000062 const TargetInstrInfo *TII;
63 const TargetRegisterInfo *TRI;
Pete Cooper11759452014-09-02 17:43:54 +000064 MCSchedModel SchedModel;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000065 MachineRegisterInfo *MRI;
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +000066 MachineLoopInfo *MLI; // Current MachineLoopInfo
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000067 MachineTraceMetrics *Traces;
68 MachineTraceMetrics::Ensemble *MinInstr;
69
70 TargetSchedModel TSchedModel;
71
Sanjay Patelb1ca4e42015-01-27 22:26:56 +000072 /// True if optimizing for code size.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000073 bool OptSize;
74
75public:
76 static char ID;
77 MachineCombiner() : MachineFunctionPass(ID) {
78 initializeMachineCombinerPass(*PassRegistry::getPassRegistry());
79 }
80 void getAnalysisUsage(AnalysisUsage &AU) const override;
81 bool runOnMachineFunction(MachineFunction &MF) override;
Mehdi Amini117296c2016-10-01 02:56:57 +000082 StringRef getPassName() const override { return "Machine InstCombiner"; }
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000083
84private:
85 bool doSubstitute(unsigned NewSize, unsigned OldSize);
86 bool combineInstructions(MachineBasicBlock *);
87 MachineInstr *getOperandDef(const MachineOperand &MO);
88 unsigned getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
89 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
90 MachineTraceMetrics::Trace BlockTrace);
91 unsigned getLatency(MachineInstr *Root, MachineInstr *NewRoot,
92 MachineTraceMetrics::Trace BlockTrace);
93 bool
Sanjay Patele79b43a2015-06-23 00:39:40 +000094 improvesCriticalPathLen(MachineBasicBlock *MBB, MachineInstr *Root,
Sanjay Patel766589e2015-11-10 16:48:53 +000095 MachineTraceMetrics::Trace BlockTrace,
96 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Pope08d9c72016-12-11 19:39:32 +000097 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patel766589e2015-11-10 16:48:53 +000098 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahnceb44942017-09-20 11:54:37 +000099 MachineCombinerPattern Pattern, bool SlackIsAccurate);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000100 bool preservesResourceLen(MachineBasicBlock *MBB,
101 MachineTraceMetrics::Trace BlockTrace,
102 SmallVectorImpl<MachineInstr *> &InsInstrs,
103 SmallVectorImpl<MachineInstr *> &DelInstrs);
104 void instr2instrSC(SmallVectorImpl<MachineInstr *> &Instrs,
105 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC);
Florian Hahnc68428b2018-01-31 13:54:30 +0000106 std::pair<unsigned, unsigned>
107 getLatenciesForInstrSequences(MachineInstr &MI,
108 SmallVectorImpl<MachineInstr *> &InsInstrs,
109 SmallVectorImpl<MachineInstr *> &DelInstrs,
110 MachineTraceMetrics::Trace BlockTrace);
111
112 void verifyPatternOrder(MachineBasicBlock *MBB, MachineInstr &Root,
113 SmallVector<MachineCombinerPattern, 16> &Patterns);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000114};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000115}
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000116
117char MachineCombiner::ID = 0;
118char &llvm::MachineCombinerID = MachineCombiner::ID;
119
Matthias Braun1527baa2017-05-25 21:26:32 +0000120INITIALIZE_PASS_BEGIN(MachineCombiner, DEBUG_TYPE,
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000121 "Machine InstCombiner", false, false)
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000122INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000123INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Matthias Braun1527baa2017-05-25 21:26:32 +0000124INITIALIZE_PASS_END(MachineCombiner, DEBUG_TYPE, "Machine InstCombiner",
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000125 false, false)
126
127void MachineCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
128 AU.setPreservesCFG();
129 AU.addPreserved<MachineDominatorTree>();
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000130 AU.addRequired<MachineLoopInfo>();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000131 AU.addPreserved<MachineLoopInfo>();
132 AU.addRequired<MachineTraceMetrics>();
133 AU.addPreserved<MachineTraceMetrics>();
134 MachineFunctionPass::getAnalysisUsage(AU);
135}
136
137MachineInstr *MachineCombiner::getOperandDef(const MachineOperand &MO) {
138 MachineInstr *DefInstr = nullptr;
139 // We need a virtual register definition.
140 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
141 DefInstr = MRI->getUniqueVRegDef(MO.getReg());
142 // PHI's have no depth etc.
143 if (DefInstr && DefInstr->isPHI())
144 DefInstr = nullptr;
145 return DefInstr;
146}
147
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000148/// Computes depth of instructions in vector \InsInstr.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000149///
150/// \param InsInstrs is a vector of machine instructions
151/// \param InstrIdxForVirtReg is a dense map of virtual register to index
152/// of defining machine instruction in \p InsInstrs
153/// \param BlockTrace is a trace of machine instructions
154///
155/// \returns Depth of last instruction in \InsInstrs ("NewRoot")
156unsigned
157MachineCombiner::getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
158 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
159 MachineTraceMetrics::Trace BlockTrace) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000160 SmallVector<unsigned, 16> InstrDepth;
Hal Finkele0fa8f22015-07-15 08:22:23 +0000161 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
162 "Missing machine model\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000163
Sanjay Patel6b280772015-01-27 22:16:52 +0000164 // For each instruction in the new sequence compute the depth based on the
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000165 // operands. Use the trace information when possible. For new operands which
166 // are tracked in the InstrIdxForVirtReg map depth is looked up in InstrDepth
167 for (auto *InstrPtr : InsInstrs) { // for each Use
168 unsigned IDepth = 0;
Sanjay Patelf69f4e42015-05-21 17:43:26 +0000169 for (const MachineOperand &MO : InstrPtr->operands()) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000170 // Check for virtual register operand.
171 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
172 continue;
173 if (!MO.isUse())
174 continue;
175 unsigned DepthOp = 0;
176 unsigned LatencyOp = 0;
177 DenseMap<unsigned, unsigned>::iterator II =
178 InstrIdxForVirtReg.find(MO.getReg());
179 if (II != InstrIdxForVirtReg.end()) {
180 // Operand is new virtual register not in trace
Saleem Abdulrasoolbefa2152014-08-03 23:00:38 +0000181 assert(II->second < InstrDepth.size() && "Bad Index");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000182 MachineInstr *DefInstr = InsInstrs[II->second];
183 assert(DefInstr &&
184 "There must be a definition for a new virtual register");
185 DepthOp = InstrDepth[II->second];
Simon Pilgrim194693e2017-10-30 17:24:40 +0000186 int DefIdx = DefInstr->findRegisterDefOperandIdx(MO.getReg());
187 int UseIdx = InstrPtr->findRegisterUseOperandIdx(MO.getReg());
188 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
189 InstrPtr, UseIdx);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000190 } else {
191 MachineInstr *DefInstr = getOperandDef(MO);
192 if (DefInstr) {
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000193 DepthOp = BlockTrace.getInstrCycles(*DefInstr).Depth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000194 LatencyOp = TSchedModel.computeOperandLatency(
195 DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
196 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
197 }
198 }
199 IDepth = std::max(IDepth, DepthOp + LatencyOp);
200 }
201 InstrDepth.push_back(IDepth);
202 }
203 unsigned NewRootIdx = InsInstrs.size() - 1;
204 return InstrDepth[NewRootIdx];
205}
206
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000207/// Computes instruction latency as max of latency of defined operands.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000208///
209/// \param Root is a machine instruction that could be replaced by NewRoot.
210/// It is used to compute a more accurate latency information for NewRoot in
211/// case there is a dependent instruction in the same trace (\p BlockTrace)
212/// \param NewRoot is the instruction for which the latency is computed
213/// \param BlockTrace is a trace of machine instructions
214///
215/// \returns Latency of \p NewRoot
216unsigned MachineCombiner::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
217 MachineTraceMetrics::Trace BlockTrace) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000218 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
219 "Missing machine model\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000220
221 // Check each definition in NewRoot and compute the latency
222 unsigned NewRootLatency = 0;
223
Sanjay Patelf69f4e42015-05-21 17:43:26 +0000224 for (const MachineOperand &MO : NewRoot->operands()) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000225 // Check for virtual register operand.
226 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
227 continue;
228 if (!MO.isDef())
229 continue;
230 // Get the first instruction that uses MO
231 MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(MO.getReg());
232 RI++;
Gerolf Hoflehnercb7d9682019-01-10 21:53:13 +0000233 if (RI == MRI->reg_end())
234 continue;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000235 MachineInstr *UseMO = RI->getParent();
236 unsigned LatencyOp = 0;
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000237 if (UseMO && BlockTrace.isDepInTrace(*Root, *UseMO)) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000238 LatencyOp = TSchedModel.computeOperandLatency(
239 NewRoot, NewRoot->findRegisterDefOperandIdx(MO.getReg()), UseMO,
240 UseMO->findRegisterUseOperandIdx(MO.getReg()));
241 } else {
Hal Finkel17caf322015-08-05 07:45:28 +0000242 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000243 }
244 NewRootLatency = std::max(NewRootLatency, LatencyOp);
245 }
246 return NewRootLatency;
247}
248
Sanjay Patel766589e2015-11-10 16:48:53 +0000249/// The combiner's goal may differ based on which pattern it is attempting
250/// to optimize.
251enum class CombinerObjective {
252 MustReduceDepth, // The data dependency chain must be improved.
253 Default // The critical path must not be lengthened.
254};
255
256static CombinerObjective getCombinerObjective(MachineCombinerPattern P) {
257 // TODO: If C++ ever gets a real enum class, make this part of the
258 // MachineCombinerPattern class.
259 switch (P) {
260 case MachineCombinerPattern::REASSOC_AX_BY:
261 case MachineCombinerPattern::REASSOC_AX_YB:
262 case MachineCombinerPattern::REASSOC_XA_BY:
263 case MachineCombinerPattern::REASSOC_XA_YB:
264 return CombinerObjective::MustReduceDepth;
265 default:
266 return CombinerObjective::Default;
267 }
268}
269
Florian Hahnc68428b2018-01-31 13:54:30 +0000270/// Estimate the latency of the new and original instruction sequence by summing
271/// up the latencies of the inserted and deleted instructions. This assumes
272/// that the inserted and deleted instructions are dependent instruction chains,
273/// which might not hold in all cases.
274std::pair<unsigned, unsigned> MachineCombiner::getLatenciesForInstrSequences(
275 MachineInstr &MI, SmallVectorImpl<MachineInstr *> &InsInstrs,
276 SmallVectorImpl<MachineInstr *> &DelInstrs,
277 MachineTraceMetrics::Trace BlockTrace) {
278 assert(!InsInstrs.empty() && "Only support sequences that insert instrs.");
279 unsigned NewRootLatency = 0;
280 // NewRoot is the last instruction in the \p InsInstrs vector.
281 MachineInstr *NewRoot = InsInstrs.back();
282 for (unsigned i = 0; i < InsInstrs.size() - 1; i++)
283 NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
284 NewRootLatency += getLatency(&MI, NewRoot, BlockTrace);
285
286 unsigned RootLatency = 0;
287 for (auto I : DelInstrs)
288 RootLatency += TSchedModel.computeInstrLatency(I);
289
290 return {NewRootLatency, RootLatency};
291}
292
Sanjay Patele79b43a2015-06-23 00:39:40 +0000293/// The DAGCombine code sequence ends in MI (Machine Instruction) Root.
294/// The new code sequence ends in MI NewRoot. A necessary condition for the new
295/// sequence to replace the old sequence is that it cannot lengthen the critical
Sanjay Patel766589e2015-11-10 16:48:53 +0000296/// path. The definition of "improve" may be restricted by specifying that the
297/// new path improves the data dependency chain (MustReduceDepth).
Sanjay Patele79b43a2015-06-23 00:39:40 +0000298bool MachineCombiner::improvesCriticalPathLen(
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000299 MachineBasicBlock *MBB, MachineInstr *Root,
300 MachineTraceMetrics::Trace BlockTrace,
301 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Pope08d9c72016-12-11 19:39:32 +0000302 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patele79b43a2015-06-23 00:39:40 +0000303 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahnceb44942017-09-20 11:54:37 +0000304 MachineCombinerPattern Pattern,
305 bool SlackIsAccurate) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000306 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
307 "Missing machine model\n");
Sanjay Patel766589e2015-11-10 16:48:53 +0000308 // Get depth and latency of NewRoot and Root.
309 unsigned NewRootDepth = getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace);
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000310 unsigned RootDepth = BlockTrace.getInstrCycles(*Root).Depth;
Sanjay Patel766589e2015-11-10 16:48:53 +0000311
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000312 LLVM_DEBUG(dbgs() << " Dependence data for " << *Root << "\tNewRootDepth: "
313 << NewRootDepth << "\tRootDepth: " << RootDepth);
Sanjay Patel766589e2015-11-10 16:48:53 +0000314
315 // For a transform such as reassociation, the cost equation is
316 // conservatively calculated so that we must improve the depth (data
317 // dependency cycles) in the critical path to proceed with the transform.
318 // Being conservative also protects against inaccuracies in the underlying
319 // machine trace metrics and CPU models.
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000320 if (getCombinerObjective(Pattern) == CombinerObjective::MustReduceDepth) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000321 LLVM_DEBUG(dbgs() << "\tIt MustReduceDepth ");
322 LLVM_DEBUG(NewRootDepth < RootDepth
323 ? dbgs() << "\t and it does it\n"
324 : dbgs() << "\t but it does NOT do it\n");
Sanjay Patel766589e2015-11-10 16:48:53 +0000325 return NewRootDepth < RootDepth;
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000326 }
Sanjay Patel766589e2015-11-10 16:48:53 +0000327
328 // A more flexible cost calculation for the critical path includes the slack
329 // of the original code sequence. This may allow the transform to proceed
330 // even if the instruction depths (data dependency cycles) become worse.
Sebastian Pope08d9c72016-12-11 19:39:32 +0000331
Florian Hahn001c3dd2017-12-06 20:27:33 +0000332 // Account for the latency of the inserted and deleted instructions by
Florian Hahnc68428b2018-01-31 13:54:30 +0000333 unsigned NewRootLatency, RootLatency;
334 std::tie(NewRootLatency, RootLatency) =
335 getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
Sebastian Pope08d9c72016-12-11 19:39:32 +0000336
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000337 unsigned RootSlack = BlockTrace.getInstrSlack(*Root);
Florian Hahnceb44942017-09-20 11:54:37 +0000338 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000339 unsigned OldCycleCount =
340 RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000341 LLVM_DEBUG(dbgs() << "\n\tNewRootLatency: " << NewRootLatency
342 << "\tRootLatency: " << RootLatency << "\n\tRootSlack: "
343 << RootSlack << " SlackIsAccurate=" << SlackIsAccurate
344 << "\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
345 << "\n\tRootDepth + RootLatency + RootSlack = "
346 << OldCycleCount;);
347 LLVM_DEBUG(NewCycleCount <= OldCycleCount
348 ? dbgs() << "\n\t It IMPROVES PathLen because"
349 : dbgs() << "\n\t It DOES NOT improve PathLen because");
350 LLVM_DEBUG(dbgs() << "\n\t\tNewCycleCount = " << NewCycleCount
351 << ", OldCycleCount = " << OldCycleCount << "\n");
Junmo Park272a2bc2016-02-27 01:10:43 +0000352
Sanjay Patel766589e2015-11-10 16:48:53 +0000353 return NewCycleCount <= OldCycleCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000354}
355
356/// helper routine to convert instructions into SC
357void MachineCombiner::instr2instrSC(
358 SmallVectorImpl<MachineInstr *> &Instrs,
359 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
360 for (auto *InstrPtr : Instrs) {
361 unsigned Opc = InstrPtr->getOpcode();
362 unsigned Idx = TII->get(Opc).getSchedClass();
Pete Cooper11759452014-09-02 17:43:54 +0000363 const MCSchedClassDesc *SC = SchedModel.getSchedClassDesc(Idx);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000364 InstrsSC.push_back(SC);
365 }
366}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000367
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000368/// True when the new instructions do not increase resource length
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000369bool MachineCombiner::preservesResourceLen(
370 MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
371 SmallVectorImpl<MachineInstr *> &InsInstrs,
372 SmallVectorImpl<MachineInstr *> &DelInstrs) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000373 if (!TSchedModel.hasInstrSchedModel())
374 return true;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000375
376 // Compute current resource length
377
Gerolf Hoflehner97c383b2014-08-07 21:40:58 +0000378 //ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
379 SmallVector <const MachineBasicBlock *, 1> MBBarr;
380 MBBarr.push_back(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000381 unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
382
383 // Deal with SC rather than Instructions.
384 SmallVector<const MCSchedClassDesc *, 16> InsInstrsSC;
385 SmallVector<const MCSchedClassDesc *, 16> DelInstrsSC;
386
387 instr2instrSC(InsInstrs, InsInstrsSC);
388 instr2instrSC(DelInstrs, DelInstrsSC);
389
390 ArrayRef<const MCSchedClassDesc *> MSCInsArr = makeArrayRef(InsInstrsSC);
391 ArrayRef<const MCSchedClassDesc *> MSCDelArr = makeArrayRef(DelInstrsSC);
392
Sanjay Patelccb8d5c2015-06-10 19:52:58 +0000393 // Compute new resource length.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000394 unsigned ResLenAfterCombine =
395 BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
396
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000397 LLVM_DEBUG(dbgs() << "\t\tResource length before replacement: "
398 << ResLenBeforeCombine
399 << " and after: " << ResLenAfterCombine << "\n";);
400 LLVM_DEBUG(
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000401 ResLenAfterCombine <= ResLenBeforeCombine
402 ? dbgs() << "\t\t As result it IMPROVES/PRESERVES Resource Length\n"
403 : dbgs() << "\t\t As result it DOES NOT improve/preserve Resource "
404 "Length\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000405
406 return ResLenAfterCombine <= ResLenBeforeCombine;
407}
408
409/// \returns true when new instruction sequence should be generated
Sanjay Patel6b280772015-01-27 22:16:52 +0000410/// independent if it lengthens critical path or not
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000411bool MachineCombiner::doSubstitute(unsigned NewSize, unsigned OldSize) {
Reid Kleckner2aeb9302018-03-16 20:11:55 +0000412 if (OptSize && (NewSize < OldSize))
413 return true;
Hal Finkele0fa8f22015-07-15 08:22:23 +0000414 if (!TSchedModel.hasInstrSchedModelOrItineraries())
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000415 return true;
416 return false;
417}
418
Florian Hahnceb44942017-09-20 11:54:37 +0000419/// Inserts InsInstrs and deletes DelInstrs. Incrementally updates instruction
420/// depths if requested.
421///
422/// \param MBB basic block to insert instructions in
423/// \param MI current machine instruction
424/// \param InsInstrs new instructions to insert in \p MBB
425/// \param DelInstrs instruction to delete from \p MBB
426/// \param MinInstr is a pointer to the machine trace information
427/// \param RegUnits set of live registers, needed to compute instruction depths
428/// \param IncrementalUpdate if true, compute instruction depths incrementally,
429/// otherwise invalidate the trace
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000430static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI,
431 SmallVector<MachineInstr *, 16> InsInstrs,
432 SmallVector<MachineInstr *, 16> DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000433 MachineTraceMetrics::Ensemble *MinInstr,
434 SparseSet<LiveRegUnit> &RegUnits,
435 bool IncrementalUpdate) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000436 for (auto *InstrPtr : InsInstrs)
437 MBB->insert((MachineBasicBlock::iterator)&MI, InstrPtr);
Florian Hahnceb44942017-09-20 11:54:37 +0000438
439 for (auto *InstrPtr : DelInstrs) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000440 InstrPtr->eraseFromParentAndMarkDBGValuesForRemoval();
Florian Hahnceb44942017-09-20 11:54:37 +0000441 // Erase all LiveRegs defined by the removed instruction
442 for (auto I = RegUnits.begin(); I != RegUnits.end(); ) {
443 if (I->MI == InstrPtr)
444 I = RegUnits.erase(I);
445 else
446 I++;
447 }
448 }
449
450 if (IncrementalUpdate)
451 for (auto *InstrPtr : InsInstrs)
452 MinInstr->updateDepth(MBB, *InstrPtr, RegUnits);
453 else
454 MinInstr->invalidate(MBB);
455
456 NumInstCombined++;
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000457}
458
Florian Hahnc68428b2018-01-31 13:54:30 +0000459// Check that the difference between original and new latency is decreasing for
460// later patterns. This helps to discover sub-optimal pattern orderings.
461void MachineCombiner::verifyPatternOrder(
462 MachineBasicBlock *MBB, MachineInstr &Root,
463 SmallVector<MachineCombinerPattern, 16> &Patterns) {
464 long PrevLatencyDiff = std::numeric_limits<long>::max();
Alexander Ivchenko68050042018-02-06 09:53:02 +0000465 (void)PrevLatencyDiff; // Variable is used in assert only.
Florian Hahnc68428b2018-01-31 13:54:30 +0000466 for (auto P : Patterns) {
467 SmallVector<MachineInstr *, 16> InsInstrs;
468 SmallVector<MachineInstr *, 16> DelInstrs;
469 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
470 TII->genAlternativeCodeSequence(Root, P, InsInstrs, DelInstrs,
471 InstrIdxForVirtReg);
472 // Found pattern, but did not generate alternative sequence.
473 // This can happen e.g. when an immediate could not be materialized
474 // in a single instruction.
475 if (InsInstrs.empty() || !TSchedModel.hasInstrSchedModelOrItineraries())
476 continue;
477
478 unsigned NewRootLatency, RootLatency;
479 std::tie(NewRootLatency, RootLatency) = getLatenciesForInstrSequences(
480 Root, InsInstrs, DelInstrs, MinInstr->getTrace(MBB));
481 long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
482 assert(CurrentLatencyDiff <= PrevLatencyDiff &&
483 "Current pattern is better than previous pattern.");
484 PrevLatencyDiff = CurrentLatencyDiff;
485 }
486}
487
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000488/// Substitute a slow code sequence with a faster one by
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000489/// evaluating instruction combining pattern.
490/// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
491/// combining based on machine trace metrics. Only combine a sequence of
492/// instructions when this neither lengthens the critical path nor increases
493/// resource pressure. When optimizing for codesize always combine when the new
494/// sequence is shorter.
495bool MachineCombiner::combineInstructions(MachineBasicBlock *MBB) {
496 bool Changed = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000497 LLVM_DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000498
Florian Hahnceb44942017-09-20 11:54:37 +0000499 bool IncrementalUpdate = false;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000500 auto BlockIter = MBB->begin();
Florian Hahne52abba2017-10-11 20:25:58 +0000501 decltype(BlockIter) LastUpdate;
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000502 // Check if the block is in a loop.
503 const MachineLoop *ML = MLI->getLoopFor(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000504 if (!MinInstr)
505 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
506
507 SparseSet<LiveRegUnit> RegUnits;
508 RegUnits.setUniverse(TRI->getNumRegUnits());
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000509
510 while (BlockIter != MBB->end()) {
511 auto &MI = *BlockIter++;
Sanjay Patel387e66e2015-11-05 19:34:57 +0000512 SmallVector<MachineCombinerPattern, 16> Patterns;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000513 // The motivating example is:
514 //
515 // MUL Other MUL_op1 MUL_op2 Other
516 // \ / \ | /
517 // ADD/SUB => MADD/MSUB
518 // (=Root) (=NewRoot)
519
520 // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
521 // usually beneficial for code size it unfortunately can hurt performance
522 // when the ADD is on the critical path, but the MUL is not. With the
523 // substitution the MUL becomes part of the critical path (in form of the
524 // MADD) and can lengthen it on architectures where the MADD latency is
525 // longer than the ADD latency.
526 //
527 // For each instruction we check if it can be the root of a combiner
528 // pattern. Then for each pattern the new code sequence in form of MI is
529 // generated and evaluated. When the efficiency criteria (don't lengthen
530 // critical path, don't use more resources) is met the new sequence gets
531 // hooked up into the basic block before the old sequence is removed.
532 //
533 // The algorithm does not try to evaluate all patterns and pick the best.
534 // This is only an artificial restriction though. In practice there is
Sanjay Patelcfe03932015-06-19 23:21:42 +0000535 // mostly one pattern, and getMachineCombinerPatterns() can order patterns
Florian Hahnc68428b2018-01-31 13:54:30 +0000536 // based on an internal cost heuristic. If
537 // machine-combiner-verify-pattern-order is enabled, all patterns are
538 // checked to ensure later patterns do not provide better latency savings.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000539
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000540 if (!TII->getMachineCombinerPatterns(MI, Patterns))
541 continue;
542
Florian Hahnc68428b2018-01-31 13:54:30 +0000543 if (VerifyPatternOrder)
544 verifyPatternOrder(MBB, MI, Patterns);
545
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000546 for (auto P : Patterns) {
547 SmallVector<MachineInstr *, 16> InsInstrs;
548 SmallVector<MachineInstr *, 16> DelInstrs;
549 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000550 TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
551 InstrIdxForVirtReg);
552 unsigned NewInstCount = InsInstrs.size();
553 unsigned OldInstCount = DelInstrs.size();
554 // Found pattern, but did not generate alternative sequence.
555 // This can happen e.g. when an immediate could not be materialized
556 // in a single instruction.
557 if (!NewInstCount)
558 continue;
559
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000560 LLVM_DEBUG(if (dump_intrs) {
Andrea Di Biagioedbf06a2019-02-04 12:51:26 +0000561 dbgs() << "\tFor the Pattern (" << (int)P
562 << ") these instructions could be removed\n";
563 for (auto const *InstrPtr : DelInstrs)
Andrew V. Tischenko08389192018-02-26 09:43:21 +0000564 InstrPtr->print(dbgs(), false, false, false, TII);
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000565 dbgs() << "\tThese instructions could replace the removed ones\n";
Andrea Di Biagioedbf06a2019-02-04 12:51:26 +0000566 for (auto const *InstrPtr : InsInstrs)
Andrew V. Tischenko08389192018-02-26 09:43:21 +0000567 InstrPtr->print(dbgs(), false, false, false, TII);
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000568 });
569
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000570 bool SubstituteAlways = false;
571 if (ML && TII->isThroughputPattern(P))
572 SubstituteAlways = true;
573
Florian Hahnceb44942017-09-20 11:54:37 +0000574 if (IncrementalUpdate) {
575 // Update depths since the last incremental update.
576 MinInstr->updateDepths(LastUpdate, BlockIter, RegUnits);
577 LastUpdate = BlockIter;
578 }
579
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000580 // Substitute when we optimize for codesize and the new sequence has
581 // fewer instructions OR
582 // the new sequence neither lengthens the critical path nor increases
583 // resource pressure.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000584 if (SubstituteAlways || doSubstitute(NewInstCount, OldInstCount)) {
Florian Hahnceb44942017-09-20 11:54:37 +0000585 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
586 RegUnits, IncrementalUpdate);
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000587 // Eagerly stop after the first pattern fires.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000588 Changed = true;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000589 break;
Reid Kleckner2aeb9302018-03-16 20:11:55 +0000590 } else {
Florian Hahnceb44942017-09-20 11:54:37 +0000591 // For big basic blocks, we only compute the full trace the first time
592 // we hit this. We do not invalidate the trace, but instead update the
593 // instruction depths incrementally.
594 // NOTE: Only the instruction depths up to MI are accurate. All other
595 // trace information is not updated.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000596 MachineTraceMetrics::Trace BlockTrace = MinInstr->getTrace(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000597 Traces->verifyAnalysis();
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000598 if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000599 InstrIdxForVirtReg, P,
600 !IncrementalUpdate) &&
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000601 preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
Florian Hahne52abba2017-10-11 20:25:58 +0000602 if (MBB->size() > inc_threshold) {
Florian Hahnceb44942017-09-20 11:54:37 +0000603 // Use incremental depth updates for basic blocks above treshold
604 IncrementalUpdate = true;
Florian Hahne52abba2017-10-11 20:25:58 +0000605 LastUpdate = BlockIter;
606 }
Florian Hahnceb44942017-09-20 11:54:37 +0000607
608 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
609 RegUnits, IncrementalUpdate);
610
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000611 // Eagerly stop after the first pattern fires.
612 Changed = true;
613 break;
614 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000615 // Cleanup instructions of the alternative code sequence. There is no
616 // use for them.
617 MachineFunction *MF = MBB->getParent();
618 for (auto *InstrPtr : InsInstrs)
619 MF->DeleteMachineInstr(InstrPtr);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000620 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000621 InstrIdxForVirtReg.clear();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000622 }
623 }
624
Florian Hahnceb44942017-09-20 11:54:37 +0000625 if (Changed && IncrementalUpdate)
626 Traces->invalidate(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000627 return Changed;
628}
629
630bool MachineCombiner::runOnMachineFunction(MachineFunction &MF) {
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000631 STI = &MF.getSubtarget();
632 TII = STI->getInstrInfo();
633 TRI = STI->getRegisterInfo();
634 SchedModel = STI->getSchedModel();
Sanjay Patel0d7df362018-04-08 19:56:04 +0000635 TSchedModel.init(STI);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000636 MRI = &MF.getRegInfo();
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000637 MLI = &getAnalysis<MachineLoopInfo>();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000638 Traces = &getAnalysis<MachineTraceMetrics>();
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000639 MinInstr = nullptr;
Evandro Menezes85bd3972019-04-04 22:40:06 +0000640 OptSize = MF.getFunction().hasOptSize();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000641
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000642 LLVM_DEBUG(dbgs() << getPassName() << ": " << MF.getName() << '\n');
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000643 if (!TII->useMachineCombiner()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000644 LLVM_DEBUG(
645 dbgs()
646 << " Skipping pass: Target does not support machine combiner\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000647 return false;
648 }
649
650 bool Changed = false;
651
652 // Try to combine instructions.
653 for (auto &MBB : MF)
654 Changed |= combineInstructions(&MBB);
655
656 return Changed;
657}