blob: f51b482e20e33f5302a9c924ca6f44e76f83a280 [file] [log] [blame]
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001//===---- MachineCombiner.cpp - Instcombining on SSA form machine code ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The machine combiner pass uses machine trace metrics to ensure the combined
Eric Christopher22582072017-03-15 21:50:46 +000011// instructions do not lengthen the critical path or the resource depth.
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000012//===----------------------------------------------------------------------===//
Hans Wennborg4d651e42015-10-06 23:24:35 +000013
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000014#include "llvm/ADT/DenseMap.h"
Mehdi Aminif6071e12016-04-18 09:17:29 +000015#include "llvm/ADT/Statistic.h"
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000016#include "llvm/CodeGen/MachineDominators.h"
17#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000019#include "llvm/CodeGen/MachineLoopInfo.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/CodeGen/MachineTraceMetrics.h"
22#include "llvm/CodeGen/Passes.h"
David Blaikie48319232017-11-08 01:01:31 +000023#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000024#include "llvm/CodeGen/TargetRegisterInfo.h"
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000025#include "llvm/CodeGen/TargetSchedule.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000026#include "llvm/CodeGen/TargetSubtargetInfo.h"
Florian Hahn6aed4212017-09-20 11:54:37 +000027#include "llvm/Support/CommandLine.h"
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000030
31using namespace llvm;
32
Jakub Kuderski14382182017-07-13 19:30:52 +000033#define DEBUG_TYPE "machine-combiner"
34
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000035STATISTIC(NumInstCombined, "Number of machineinst combined");
36
Florian Hahn6aed4212017-09-20 11:54:37 +000037static cl::opt<unsigned>
38inc_threshold("machine-combiner-inc-threshold", cl::Hidden,
39 cl::desc("Incremental depth computation will be used for basic "
40 "blocks with more instructions."), cl::init(500));
41
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +000042static cl::opt<bool> dump_intrs("machine-combiner-dump-subst-intrs", cl::Hidden,
43 cl::desc("Dump all substituted intrs"),
44 cl::init(false));
45
Florian Hahnc4f543d2018-01-31 13:54:30 +000046#ifdef EXPENSIVE_CHECKS
47static cl::opt<bool> VerifyPatternOrder(
48 "machine-combiner-verify-pattern-order", cl::Hidden,
49 cl::desc(
50 "Verify that the generated patterns are ordered by increasing latency"),
51 cl::init(true));
52#else
53static cl::opt<bool> VerifyPatternOrder(
54 "machine-combiner-verify-pattern-order", cl::Hidden,
55 cl::desc(
56 "Verify that the generated patterns are ordered by increasing latency"),
57 cl::init(false));
58#endif
59
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000060namespace {
61class MachineCombiner : public MachineFunctionPass {
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +000062 const TargetSubtargetInfo *STI;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000063 const TargetInstrInfo *TII;
64 const TargetRegisterInfo *TRI;
Pete Cooper6de6c6a2014-09-02 17:43:54 +000065 MCSchedModel SchedModel;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000066 MachineRegisterInfo *MRI;
Gerolf Hoflehner3f71db12016-04-24 05:14:01 +000067 MachineLoopInfo *MLI; // Current MachineLoopInfo
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000068 MachineTraceMetrics *Traces;
69 MachineTraceMetrics::Ensemble *MinInstr;
70
71 TargetSchedModel TSchedModel;
72
Sanjay Patelc232e7f2015-01-27 22:26:56 +000073 /// True if optimizing for code size.
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000074 bool OptSize;
75
76public:
77 static char ID;
78 MachineCombiner() : MachineFunctionPass(ID) {
79 initializeMachineCombinerPass(*PassRegistry::getPassRegistry());
80 }
81 void getAnalysisUsage(AnalysisUsage &AU) const override;
82 bool runOnMachineFunction(MachineFunction &MF) override;
Mehdi Amini67f335d2016-10-01 02:56:57 +000083 StringRef getPassName() const override { return "Machine InstCombiner"; }
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +000084
85private:
86 bool doSubstitute(unsigned NewSize, unsigned OldSize);
87 bool combineInstructions(MachineBasicBlock *);
88 MachineInstr *getOperandDef(const MachineOperand &MO);
89 unsigned getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
90 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
91 MachineTraceMetrics::Trace BlockTrace);
92 unsigned getLatency(MachineInstr *Root, MachineInstr *NewRoot,
93 MachineTraceMetrics::Trace BlockTrace);
94 bool
Sanjay Patel8bd59f52015-06-23 00:39:40 +000095 improvesCriticalPathLen(MachineBasicBlock *MBB, MachineInstr *Root,
Sanjay Patel76d9fb32015-11-10 16:48:53 +000096 MachineTraceMetrics::Trace BlockTrace,
97 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Popcfc6ce92016-12-11 19:39:32 +000098 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patel76d9fb32015-11-10 16:48:53 +000099 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahn6aed4212017-09-20 11:54:37 +0000100 MachineCombinerPattern Pattern, bool SlackIsAccurate);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000101 bool preservesResourceLen(MachineBasicBlock *MBB,
102 MachineTraceMetrics::Trace BlockTrace,
103 SmallVectorImpl<MachineInstr *> &InsInstrs,
104 SmallVectorImpl<MachineInstr *> &DelInstrs);
105 void instr2instrSC(SmallVectorImpl<MachineInstr *> &Instrs,
106 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC);
Florian Hahnc4f543d2018-01-31 13:54:30 +0000107 std::pair<unsigned, unsigned>
108 getLatenciesForInstrSequences(MachineInstr &MI,
109 SmallVectorImpl<MachineInstr *> &InsInstrs,
110 SmallVectorImpl<MachineInstr *> &DelInstrs,
111 MachineTraceMetrics::Trace BlockTrace);
112
113 void verifyPatternOrder(MachineBasicBlock *MBB, MachineInstr &Root,
114 SmallVector<MachineCombinerPattern, 16> &Patterns);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000115};
Alexander Kornienkocd52a7a2015-06-23 09:49:53 +0000116}
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000117
118char MachineCombiner::ID = 0;
119char &llvm::MachineCombinerID = MachineCombiner::ID;
120
Matthias Braun94c49042017-05-25 21:26:32 +0000121INITIALIZE_PASS_BEGIN(MachineCombiner, DEBUG_TYPE,
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000122 "Machine InstCombiner", false, false)
Gerolf Hoflehner3f71db12016-04-24 05:14:01 +0000123INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000124INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Matthias Braun94c49042017-05-25 21:26:32 +0000125INITIALIZE_PASS_END(MachineCombiner, DEBUG_TYPE, "Machine InstCombiner",
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000126 false, false)
127
128void MachineCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
129 AU.setPreservesCFG();
130 AU.addPreserved<MachineDominatorTree>();
Gerolf Hoflehner3f71db12016-04-24 05:14:01 +0000131 AU.addRequired<MachineLoopInfo>();
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000132 AU.addPreserved<MachineLoopInfo>();
133 AU.addRequired<MachineTraceMetrics>();
134 AU.addPreserved<MachineTraceMetrics>();
135 MachineFunctionPass::getAnalysisUsage(AU);
136}
137
138MachineInstr *MachineCombiner::getOperandDef(const MachineOperand &MO) {
139 MachineInstr *DefInstr = nullptr;
140 // We need a virtual register definition.
141 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
142 DefInstr = MRI->getUniqueVRegDef(MO.getReg());
143 // PHI's have no depth etc.
144 if (DefInstr && DefInstr->isPHI())
145 DefInstr = nullptr;
146 return DefInstr;
147}
148
Sanjay Patelc232e7f2015-01-27 22:26:56 +0000149/// Computes depth of instructions in vector \InsInstr.
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000150///
151/// \param InsInstrs is a vector of machine instructions
152/// \param InstrIdxForVirtReg is a dense map of virtual register to index
153/// of defining machine instruction in \p InsInstrs
154/// \param BlockTrace is a trace of machine instructions
155///
156/// \returns Depth of last instruction in \InsInstrs ("NewRoot")
157unsigned
158MachineCombiner::getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
159 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
160 MachineTraceMetrics::Trace BlockTrace) {
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000161 SmallVector<unsigned, 16> InstrDepth;
Hal Finkelb2a353c2015-07-15 08:22:23 +0000162 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
163 "Missing machine model\n");
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000164
Sanjay Patel5d683062015-01-27 22:16:52 +0000165 // For each instruction in the new sequence compute the depth based on the
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000166 // operands. Use the trace information when possible. For new operands which
167 // are tracked in the InstrIdxForVirtReg map depth is looked up in InstrDepth
168 for (auto *InstrPtr : InsInstrs) { // for each Use
169 unsigned IDepth = 0;
Sanjay Patel430cdab2015-05-21 17:43:26 +0000170 for (const MachineOperand &MO : InstrPtr->operands()) {
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000171 // Check for virtual register operand.
172 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
173 continue;
174 if (!MO.isUse())
175 continue;
176 unsigned DepthOp = 0;
177 unsigned LatencyOp = 0;
178 DenseMap<unsigned, unsigned>::iterator II =
179 InstrIdxForVirtReg.find(MO.getReg());
180 if (II != InstrIdxForVirtReg.end()) {
181 // Operand is new virtual register not in trace
Saleem Abdulrasool335c0ca2014-08-03 23:00:38 +0000182 assert(II->second < InstrDepth.size() && "Bad Index");
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000183 MachineInstr *DefInstr = InsInstrs[II->second];
184 assert(DefInstr &&
185 "There must be a definition for a new virtual register");
186 DepthOp = InstrDepth[II->second];
Simon Pilgrimde321cd2017-10-30 17:24:40 +0000187 int DefIdx = DefInstr->findRegisterDefOperandIdx(MO.getReg());
188 int UseIdx = InstrPtr->findRegisterUseOperandIdx(MO.getReg());
189 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
190 InstrPtr, UseIdx);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000191 } else {
192 MachineInstr *DefInstr = getOperandDef(MO);
193 if (DefInstr) {
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +0000194 DepthOp = BlockTrace.getInstrCycles(*DefInstr).Depth;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000195 LatencyOp = TSchedModel.computeOperandLatency(
196 DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
197 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
198 }
199 }
200 IDepth = std::max(IDepth, DepthOp + LatencyOp);
201 }
202 InstrDepth.push_back(IDepth);
203 }
204 unsigned NewRootIdx = InsInstrs.size() - 1;
205 return InstrDepth[NewRootIdx];
206}
207
Sanjay Patelc232e7f2015-01-27 22:26:56 +0000208/// Computes instruction latency as max of latency of defined operands.
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000209///
210/// \param Root is a machine instruction that could be replaced by NewRoot.
211/// It is used to compute a more accurate latency information for NewRoot in
212/// case there is a dependent instruction in the same trace (\p BlockTrace)
213/// \param NewRoot is the instruction for which the latency is computed
214/// \param BlockTrace is a trace of machine instructions
215///
216/// \returns Latency of \p NewRoot
217unsigned MachineCombiner::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
218 MachineTraceMetrics::Trace BlockTrace) {
Hal Finkelb2a353c2015-07-15 08:22:23 +0000219 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
220 "Missing machine model\n");
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000221
222 // Check each definition in NewRoot and compute the latency
223 unsigned NewRootLatency = 0;
224
Sanjay Patel430cdab2015-05-21 17:43:26 +0000225 for (const MachineOperand &MO : NewRoot->operands()) {
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000226 // Check for virtual register operand.
227 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
228 continue;
229 if (!MO.isDef())
230 continue;
231 // Get the first instruction that uses MO
232 MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(MO.getReg());
233 RI++;
Gerolf Hoflehner7ed96832019-01-10 21:53:13 +0000234 if (RI == MRI->reg_end())
235 continue;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000236 MachineInstr *UseMO = RI->getParent();
237 unsigned LatencyOp = 0;
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +0000238 if (UseMO && BlockTrace.isDepInTrace(*Root, *UseMO)) {
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000239 LatencyOp = TSchedModel.computeOperandLatency(
240 NewRoot, NewRoot->findRegisterDefOperandIdx(MO.getReg()), UseMO,
241 UseMO->findRegisterUseOperandIdx(MO.getReg()));
242 } else {
Hal Finkel7b3dad02015-08-05 07:45:28 +0000243 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000244 }
245 NewRootLatency = std::max(NewRootLatency, LatencyOp);
246 }
247 return NewRootLatency;
248}
249
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000250/// The combiner's goal may differ based on which pattern it is attempting
251/// to optimize.
252enum class CombinerObjective {
253 MustReduceDepth, // The data dependency chain must be improved.
254 Default // The critical path must not be lengthened.
255};
256
257static CombinerObjective getCombinerObjective(MachineCombinerPattern P) {
258 // TODO: If C++ ever gets a real enum class, make this part of the
259 // MachineCombinerPattern class.
260 switch (P) {
261 case MachineCombinerPattern::REASSOC_AX_BY:
262 case MachineCombinerPattern::REASSOC_AX_YB:
263 case MachineCombinerPattern::REASSOC_XA_BY:
264 case MachineCombinerPattern::REASSOC_XA_YB:
265 return CombinerObjective::MustReduceDepth;
266 default:
267 return CombinerObjective::Default;
268 }
269}
270
Florian Hahnc4f543d2018-01-31 13:54:30 +0000271/// Estimate the latency of the new and original instruction sequence by summing
272/// up the latencies of the inserted and deleted instructions. This assumes
273/// that the inserted and deleted instructions are dependent instruction chains,
274/// which might not hold in all cases.
275std::pair<unsigned, unsigned> MachineCombiner::getLatenciesForInstrSequences(
276 MachineInstr &MI, SmallVectorImpl<MachineInstr *> &InsInstrs,
277 SmallVectorImpl<MachineInstr *> &DelInstrs,
278 MachineTraceMetrics::Trace BlockTrace) {
279 assert(!InsInstrs.empty() && "Only support sequences that insert instrs.");
280 unsigned NewRootLatency = 0;
281 // NewRoot is the last instruction in the \p InsInstrs vector.
282 MachineInstr *NewRoot = InsInstrs.back();
283 for (unsigned i = 0; i < InsInstrs.size() - 1; i++)
284 NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
285 NewRootLatency += getLatency(&MI, NewRoot, BlockTrace);
286
287 unsigned RootLatency = 0;
288 for (auto I : DelInstrs)
289 RootLatency += TSchedModel.computeInstrLatency(I);
290
291 return {NewRootLatency, RootLatency};
292}
293
Sanjay Patel8bd59f52015-06-23 00:39:40 +0000294/// The DAGCombine code sequence ends in MI (Machine Instruction) Root.
295/// The new code sequence ends in MI NewRoot. A necessary condition for the new
296/// sequence to replace the old sequence is that it cannot lengthen the critical
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000297/// path. The definition of "improve" may be restricted by specifying that the
298/// new path improves the data dependency chain (MustReduceDepth).
Sanjay Patel8bd59f52015-06-23 00:39:40 +0000299bool MachineCombiner::improvesCriticalPathLen(
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000300 MachineBasicBlock *MBB, MachineInstr *Root,
301 MachineTraceMetrics::Trace BlockTrace,
302 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Popcfc6ce92016-12-11 19:39:32 +0000303 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patel8bd59f52015-06-23 00:39:40 +0000304 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahn6aed4212017-09-20 11:54:37 +0000305 MachineCombinerPattern Pattern,
306 bool SlackIsAccurate) {
Hal Finkelb2a353c2015-07-15 08:22:23 +0000307 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
308 "Missing machine model\n");
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000309 // Get depth and latency of NewRoot and Root.
310 unsigned NewRootDepth = getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace);
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +0000311 unsigned RootDepth = BlockTrace.getInstrCycles(*Root).Depth;
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000312
Nicola Zaghen0818e782018-05-14 12:53:11 +0000313 LLVM_DEBUG(dbgs() << " Dependence data for " << *Root << "\tNewRootDepth: "
314 << NewRootDepth << "\tRootDepth: " << RootDepth);
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000315
316 // For a transform such as reassociation, the cost equation is
317 // conservatively calculated so that we must improve the depth (data
318 // dependency cycles) in the critical path to proceed with the transform.
319 // Being conservative also protects against inaccuracies in the underlying
320 // machine trace metrics and CPU models.
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000321 if (getCombinerObjective(Pattern) == CombinerObjective::MustReduceDepth) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000322 LLVM_DEBUG(dbgs() << "\tIt MustReduceDepth ");
323 LLVM_DEBUG(NewRootDepth < RootDepth
324 ? dbgs() << "\t and it does it\n"
325 : dbgs() << "\t but it does NOT do it\n");
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000326 return NewRootDepth < RootDepth;
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000327 }
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000328
329 // A more flexible cost calculation for the critical path includes the slack
330 // of the original code sequence. This may allow the transform to proceed
331 // even if the instruction depths (data dependency cycles) become worse.
Sebastian Popcfc6ce92016-12-11 19:39:32 +0000332
Florian Hahn1c6190d2017-12-06 20:27:33 +0000333 // Account for the latency of the inserted and deleted instructions by
Florian Hahnc4f543d2018-01-31 13:54:30 +0000334 unsigned NewRootLatency, RootLatency;
335 std::tie(NewRootLatency, RootLatency) =
336 getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
Sebastian Popcfc6ce92016-12-11 19:39:32 +0000337
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +0000338 unsigned RootSlack = BlockTrace.getInstrSlack(*Root);
Florian Hahn6aed4212017-09-20 11:54:37 +0000339 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000340 unsigned OldCycleCount =
341 RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000342 LLVM_DEBUG(dbgs() << "\n\tNewRootLatency: " << NewRootLatency
343 << "\tRootLatency: " << RootLatency << "\n\tRootSlack: "
344 << RootSlack << " SlackIsAccurate=" << SlackIsAccurate
345 << "\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
346 << "\n\tRootDepth + RootLatency + RootSlack = "
347 << OldCycleCount;);
348 LLVM_DEBUG(NewCycleCount <= OldCycleCount
349 ? dbgs() << "\n\t It IMPROVES PathLen because"
350 : dbgs() << "\n\t It DOES NOT improve PathLen because");
351 LLVM_DEBUG(dbgs() << "\n\t\tNewCycleCount = " << NewCycleCount
352 << ", OldCycleCount = " << OldCycleCount << "\n");
Junmo Parkfbd6d6e2016-02-27 01:10:43 +0000353
Sanjay Patel76d9fb32015-11-10 16:48:53 +0000354 return NewCycleCount <= OldCycleCount;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000355}
356
357/// helper routine to convert instructions into SC
358void MachineCombiner::instr2instrSC(
359 SmallVectorImpl<MachineInstr *> &Instrs,
360 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
361 for (auto *InstrPtr : Instrs) {
362 unsigned Opc = InstrPtr->getOpcode();
363 unsigned Idx = TII->get(Opc).getSchedClass();
Pete Cooper6de6c6a2014-09-02 17:43:54 +0000364 const MCSchedClassDesc *SC = SchedModel.getSchedClassDesc(Idx);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000365 InstrsSC.push_back(SC);
366 }
367}
Hans Wennborg4d651e42015-10-06 23:24:35 +0000368
Sanjay Patelc232e7f2015-01-27 22:26:56 +0000369/// True when the new instructions do not increase resource length
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000370bool MachineCombiner::preservesResourceLen(
371 MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
372 SmallVectorImpl<MachineInstr *> &InsInstrs,
373 SmallVectorImpl<MachineInstr *> &DelInstrs) {
Hal Finkelb2a353c2015-07-15 08:22:23 +0000374 if (!TSchedModel.hasInstrSchedModel())
375 return true;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000376
377 // Compute current resource length
378
Gerolf Hoflehnere4fa3412014-08-07 21:40:58 +0000379 //ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
380 SmallVector <const MachineBasicBlock *, 1> MBBarr;
381 MBBarr.push_back(MBB);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000382 unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
383
384 // Deal with SC rather than Instructions.
385 SmallVector<const MCSchedClassDesc *, 16> InsInstrsSC;
386 SmallVector<const MCSchedClassDesc *, 16> DelInstrsSC;
387
388 instr2instrSC(InsInstrs, InsInstrsSC);
389 instr2instrSC(DelInstrs, DelInstrsSC);
390
391 ArrayRef<const MCSchedClassDesc *> MSCInsArr = makeArrayRef(InsInstrsSC);
392 ArrayRef<const MCSchedClassDesc *> MSCDelArr = makeArrayRef(DelInstrsSC);
393
Sanjay Patelbb794232015-06-10 19:52:58 +0000394 // Compute new resource length.
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000395 unsigned ResLenAfterCombine =
396 BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
397
Nicola Zaghen0818e782018-05-14 12:53:11 +0000398 LLVM_DEBUG(dbgs() << "\t\tResource length before replacement: "
399 << ResLenBeforeCombine
400 << " and after: " << ResLenAfterCombine << "\n";);
401 LLVM_DEBUG(
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000402 ResLenAfterCombine <= ResLenBeforeCombine
403 ? dbgs() << "\t\t As result it IMPROVES/PRESERVES Resource Length\n"
404 : dbgs() << "\t\t As result it DOES NOT improve/preserve Resource "
405 "Length\n");
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000406
407 return ResLenAfterCombine <= ResLenBeforeCombine;
408}
409
410/// \returns true when new instruction sequence should be generated
Sanjay Patel5d683062015-01-27 22:16:52 +0000411/// independent if it lengthens critical path or not
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000412bool MachineCombiner::doSubstitute(unsigned NewSize, unsigned OldSize) {
Reid Klecknerf6f2e192018-03-16 20:11:55 +0000413 if (OptSize && (NewSize < OldSize))
414 return true;
Hal Finkelb2a353c2015-07-15 08:22:23 +0000415 if (!TSchedModel.hasInstrSchedModelOrItineraries())
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000416 return true;
417 return false;
418}
419
Florian Hahn6aed4212017-09-20 11:54:37 +0000420/// Inserts InsInstrs and deletes DelInstrs. Incrementally updates instruction
421/// depths if requested.
422///
423/// \param MBB basic block to insert instructions in
424/// \param MI current machine instruction
425/// \param InsInstrs new instructions to insert in \p MBB
426/// \param DelInstrs instruction to delete from \p MBB
427/// \param MinInstr is a pointer to the machine trace information
428/// \param RegUnits set of live registers, needed to compute instruction depths
429/// \param IncrementalUpdate if true, compute instruction depths incrementally,
430/// otherwise invalidate the trace
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000431static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI,
432 SmallVector<MachineInstr *, 16> InsInstrs,
433 SmallVector<MachineInstr *, 16> DelInstrs,
Florian Hahn6aed4212017-09-20 11:54:37 +0000434 MachineTraceMetrics::Ensemble *MinInstr,
435 SparseSet<LiveRegUnit> &RegUnits,
436 bool IncrementalUpdate) {
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000437 for (auto *InstrPtr : InsInstrs)
438 MBB->insert((MachineBasicBlock::iterator)&MI, InstrPtr);
Florian Hahn6aed4212017-09-20 11:54:37 +0000439
440 for (auto *InstrPtr : DelInstrs) {
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000441 InstrPtr->eraseFromParentAndMarkDBGValuesForRemoval();
Florian Hahn6aed4212017-09-20 11:54:37 +0000442 // Erase all LiveRegs defined by the removed instruction
443 for (auto I = RegUnits.begin(); I != RegUnits.end(); ) {
444 if (I->MI == InstrPtr)
445 I = RegUnits.erase(I);
446 else
447 I++;
448 }
449 }
450
451 if (IncrementalUpdate)
452 for (auto *InstrPtr : InsInstrs)
453 MinInstr->updateDepth(MBB, *InstrPtr, RegUnits);
454 else
455 MinInstr->invalidate(MBB);
456
457 NumInstCombined++;
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000458}
459
Florian Hahnc4f543d2018-01-31 13:54:30 +0000460// Check that the difference between original and new latency is decreasing for
461// later patterns. This helps to discover sub-optimal pattern orderings.
462void MachineCombiner::verifyPatternOrder(
463 MachineBasicBlock *MBB, MachineInstr &Root,
464 SmallVector<MachineCombinerPattern, 16> &Patterns) {
465 long PrevLatencyDiff = std::numeric_limits<long>::max();
Alexander Ivchenkoe6162002018-02-06 09:53:02 +0000466 (void)PrevLatencyDiff; // Variable is used in assert only.
Florian Hahnc4f543d2018-01-31 13:54:30 +0000467 for (auto P : Patterns) {
468 SmallVector<MachineInstr *, 16> InsInstrs;
469 SmallVector<MachineInstr *, 16> DelInstrs;
470 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
471 TII->genAlternativeCodeSequence(Root, P, InsInstrs, DelInstrs,
472 InstrIdxForVirtReg);
473 // Found pattern, but did not generate alternative sequence.
474 // This can happen e.g. when an immediate could not be materialized
475 // in a single instruction.
476 if (InsInstrs.empty() || !TSchedModel.hasInstrSchedModelOrItineraries())
477 continue;
478
479 unsigned NewRootLatency, RootLatency;
480 std::tie(NewRootLatency, RootLatency) = getLatenciesForInstrSequences(
481 Root, InsInstrs, DelInstrs, MinInstr->getTrace(MBB));
482 long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
483 assert(CurrentLatencyDiff <= PrevLatencyDiff &&
484 "Current pattern is better than previous pattern.");
485 PrevLatencyDiff = CurrentLatencyDiff;
486 }
487}
488
Sanjay Patelc232e7f2015-01-27 22:26:56 +0000489/// Substitute a slow code sequence with a faster one by
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000490/// evaluating instruction combining pattern.
491/// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
492/// combining based on machine trace metrics. Only combine a sequence of
493/// instructions when this neither lengthens the critical path nor increases
494/// resource pressure. When optimizing for codesize always combine when the new
495/// sequence is shorter.
496bool MachineCombiner::combineInstructions(MachineBasicBlock *MBB) {
497 bool Changed = false;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000498 LLVM_DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000499
Florian Hahn6aed4212017-09-20 11:54:37 +0000500 bool IncrementalUpdate = false;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000501 auto BlockIter = MBB->begin();
Florian Hahn07826182017-10-11 20:25:58 +0000502 decltype(BlockIter) LastUpdate;
Gerolf Hoflehner3f71db12016-04-24 05:14:01 +0000503 // Check if the block is in a loop.
504 const MachineLoop *ML = MLI->getLoopFor(MBB);
Florian Hahn6aed4212017-09-20 11:54:37 +0000505 if (!MinInstr)
506 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
507
508 SparseSet<LiveRegUnit> RegUnits;
509 RegUnits.setUniverse(TRI->getNumRegUnits());
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000510
511 while (BlockIter != MBB->end()) {
512 auto &MI = *BlockIter++;
Sanjay Patel834952e2015-11-05 19:34:57 +0000513 SmallVector<MachineCombinerPattern, 16> Patterns;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000514 // The motivating example is:
515 //
516 // MUL Other MUL_op1 MUL_op2 Other
517 // \ / \ | /
518 // ADD/SUB => MADD/MSUB
519 // (=Root) (=NewRoot)
520
521 // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
522 // usually beneficial for code size it unfortunately can hurt performance
523 // when the ADD is on the critical path, but the MUL is not. With the
524 // substitution the MUL becomes part of the critical path (in form of the
525 // MADD) and can lengthen it on architectures where the MADD latency is
526 // longer than the ADD latency.
527 //
528 // For each instruction we check if it can be the root of a combiner
529 // pattern. Then for each pattern the new code sequence in form of MI is
530 // generated and evaluated. When the efficiency criteria (don't lengthen
531 // critical path, don't use more resources) is met the new sequence gets
532 // hooked up into the basic block before the old sequence is removed.
533 //
534 // The algorithm does not try to evaluate all patterns and pick the best.
535 // This is only an artificial restriction though. In practice there is
Sanjay Patel30c3b2a2015-06-19 23:21:42 +0000536 // mostly one pattern, and getMachineCombinerPatterns() can order patterns
Florian Hahnc4f543d2018-01-31 13:54:30 +0000537 // based on an internal cost heuristic. If
538 // machine-combiner-verify-pattern-order is enabled, all patterns are
539 // checked to ensure later patterns do not provide better latency savings.
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000540
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000541 if (!TII->getMachineCombinerPatterns(MI, Patterns))
542 continue;
543
Florian Hahnc4f543d2018-01-31 13:54:30 +0000544 if (VerifyPatternOrder)
545 verifyPatternOrder(MBB, MI, Patterns);
546
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000547 for (auto P : Patterns) {
548 SmallVector<MachineInstr *, 16> InsInstrs;
549 SmallVector<MachineInstr *, 16> DelInstrs;
550 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000551 TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
552 InstrIdxForVirtReg);
553 unsigned NewInstCount = InsInstrs.size();
554 unsigned OldInstCount = DelInstrs.size();
555 // Found pattern, but did not generate alternative sequence.
556 // This can happen e.g. when an immediate could not be materialized
557 // in a single instruction.
558 if (!NewInstCount)
559 continue;
560
Nicola Zaghen0818e782018-05-14 12:53:11 +0000561 LLVM_DEBUG(if (dump_intrs) {
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000562 dbgs() << "\tFor the Pattern (" << (int)P << ") these instructions could be removed\n";
563 for (auto const *InstrPtr : DelInstrs) {
564 dbgs() << "\t\t" << STI->getSchedInfoStr(*InstrPtr) << ": ";
Andrew V. Tischenko07ea57a2018-02-26 09:43:21 +0000565 InstrPtr->print(dbgs(), false, false, false, TII);
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000566 }
567 dbgs() << "\tThese instructions could replace the removed ones\n";
568 for (auto const *InstrPtr : InsInstrs) {
569 dbgs() << "\t\t" << STI->getSchedInfoStr(*InstrPtr) << ": ";
Andrew V. Tischenko07ea57a2018-02-26 09:43:21 +0000570 InstrPtr->print(dbgs(), false, false, false, TII);
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000571 }
572 });
573
Gerolf Hoflehner3f71db12016-04-24 05:14:01 +0000574 bool SubstituteAlways = false;
575 if (ML && TII->isThroughputPattern(P))
576 SubstituteAlways = true;
577
Florian Hahn6aed4212017-09-20 11:54:37 +0000578 if (IncrementalUpdate) {
579 // Update depths since the last incremental update.
580 MinInstr->updateDepths(LastUpdate, BlockIter, RegUnits);
581 LastUpdate = BlockIter;
582 }
583
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000584 // Substitute when we optimize for codesize and the new sequence has
585 // fewer instructions OR
586 // the new sequence neither lengthens the critical path nor increases
587 // resource pressure.
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000588 if (SubstituteAlways || doSubstitute(NewInstCount, OldInstCount)) {
Florian Hahn6aed4212017-09-20 11:54:37 +0000589 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
590 RegUnits, IncrementalUpdate);
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000591 // Eagerly stop after the first pattern fires.
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000592 Changed = true;
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000593 break;
Reid Klecknerf6f2e192018-03-16 20:11:55 +0000594 } else {
Florian Hahn6aed4212017-09-20 11:54:37 +0000595 // For big basic blocks, we only compute the full trace the first time
596 // we hit this. We do not invalidate the trace, but instead update the
597 // instruction depths incrementally.
598 // NOTE: Only the instruction depths up to MI are accurate. All other
599 // trace information is not updated.
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000600 MachineTraceMetrics::Trace BlockTrace = MinInstr->getTrace(MBB);
Florian Hahn6aed4212017-09-20 11:54:37 +0000601 Traces->verifyAnalysis();
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000602 if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
Florian Hahn6aed4212017-09-20 11:54:37 +0000603 InstrIdxForVirtReg, P,
604 !IncrementalUpdate) &&
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000605 preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
Florian Hahn07826182017-10-11 20:25:58 +0000606 if (MBB->size() > inc_threshold) {
Florian Hahn6aed4212017-09-20 11:54:37 +0000607 // Use incremental depth updates for basic blocks above treshold
608 IncrementalUpdate = true;
Florian Hahn07826182017-10-11 20:25:58 +0000609 LastUpdate = BlockIter;
610 }
Florian Hahn6aed4212017-09-20 11:54:37 +0000611
612 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
613 RegUnits, IncrementalUpdate);
614
Andrew V. Tischenkoed1646e2017-02-13 09:43:37 +0000615 // Eagerly stop after the first pattern fires.
616 Changed = true;
617 break;
618 }
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000619 // Cleanup instructions of the alternative code sequence. There is no
620 // use for them.
621 MachineFunction *MF = MBB->getParent();
622 for (auto *InstrPtr : InsInstrs)
623 MF->DeleteMachineInstr(InstrPtr);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000624 }
Sanjay Patelfffd73b2015-11-10 20:09:02 +0000625 InstrIdxForVirtReg.clear();
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000626 }
627 }
628
Florian Hahn6aed4212017-09-20 11:54:37 +0000629 if (Changed && IncrementalUpdate)
630 Traces->invalidate(MBB);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000631 return Changed;
632}
633
634bool MachineCombiner::runOnMachineFunction(MachineFunction &MF) {
Andrew V. Tischenko89b2bec2018-02-15 07:55:02 +0000635 STI = &MF.getSubtarget();
636 TII = STI->getInstrInfo();
637 TRI = STI->getRegisterInfo();
638 SchedModel = STI->getSchedModel();
Sanjay Patele599cea2018-04-08 19:56:04 +0000639 TSchedModel.init(STI);
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000640 MRI = &MF.getRegInfo();
Gerolf Hoflehner3f71db12016-04-24 05:14:01 +0000641 MLI = &getAnalysis<MachineLoopInfo>();
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000642 Traces = &getAnalysis<MachineTraceMetrics>();
Hans Wennborg4d651e42015-10-06 23:24:35 +0000643 MinInstr = nullptr;
Matthias Braund3181392017-12-15 22:22:58 +0000644 OptSize = MF.getFunction().optForSize();
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000645
Nicola Zaghen0818e782018-05-14 12:53:11 +0000646 LLVM_DEBUG(dbgs() << getPassName() << ": " << MF.getName() << '\n');
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000647 if (!TII->useMachineCombiner()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000648 LLVM_DEBUG(
649 dbgs()
650 << " Skipping pass: Target does not support machine combiner\n");
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +0000651 return false;
652 }
653
654 bool Changed = false;
655
656 // Try to combine instructions.
657 for (auto &MBB : MF)
658 Changed |= combineInstructions(&MBB);
659
660 return Changed;
661}