blob: 9fc990f5c24035c3fea3eac22c942b661f015471 [file] [log] [blame]
Gerolf Hoflehner5e1207e2014-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 Christopher17ce8a22017-03-15 21:50:46 +000011// instructions do not lengthen the critical path or the resource depth.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000012//===----------------------------------------------------------------------===//
Hans Wennborg083ca9b2015-10-06 23:24:35 +000013
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000014#include "llvm/ADT/DenseMap.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000015#include "llvm/ADT/Statistic.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000016#include "llvm/CodeGen/MachineDominators.h"
17#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineLoopInfo.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/MachineTraceMetrics.h"
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/CodeGen/TargetSchedule.h"
Florian Hahnceb44942017-09-20 11:54:37 +000025#include "llvm/Support/CommandLine.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetRegisterInfo.h"
30#include "llvm/Target/TargetSubtargetInfo.h"
31
32using namespace llvm;
33
Jakub Kuderski1d2dc682017-07-13 19:30:52 +000034#define DEBUG_TYPE "machine-combiner"
35
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000036STATISTIC(NumInstCombined, "Number of machineinst combined");
37
Florian Hahnceb44942017-09-20 11:54:37 +000038static cl::opt<unsigned>
39inc_threshold("machine-combiner-inc-threshold", cl::Hidden,
40 cl::desc("Incremental depth computation will be used for basic "
41 "blocks with more instructions."), cl::init(500));
42
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000043namespace {
44class MachineCombiner : public MachineFunctionPass {
45 const TargetInstrInfo *TII;
46 const TargetRegisterInfo *TRI;
Pete Cooper11759452014-09-02 17:43:54 +000047 MCSchedModel SchedModel;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000048 MachineRegisterInfo *MRI;
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +000049 MachineLoopInfo *MLI; // Current MachineLoopInfo
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000050 MachineTraceMetrics *Traces;
51 MachineTraceMetrics::Ensemble *MinInstr;
52
53 TargetSchedModel TSchedModel;
54
Sanjay Patelb1ca4e42015-01-27 22:26:56 +000055 /// True if optimizing for code size.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000056 bool OptSize;
57
58public:
59 static char ID;
60 MachineCombiner() : MachineFunctionPass(ID) {
61 initializeMachineCombinerPass(*PassRegistry::getPassRegistry());
62 }
63 void getAnalysisUsage(AnalysisUsage &AU) const override;
64 bool runOnMachineFunction(MachineFunction &MF) override;
Mehdi Amini117296c2016-10-01 02:56:57 +000065 StringRef getPassName() const override { return "Machine InstCombiner"; }
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000066
67private:
68 bool doSubstitute(unsigned NewSize, unsigned OldSize);
69 bool combineInstructions(MachineBasicBlock *);
70 MachineInstr *getOperandDef(const MachineOperand &MO);
71 unsigned getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
72 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
73 MachineTraceMetrics::Trace BlockTrace);
74 unsigned getLatency(MachineInstr *Root, MachineInstr *NewRoot,
75 MachineTraceMetrics::Trace BlockTrace);
76 bool
Sanjay Patele79b43a2015-06-23 00:39:40 +000077 improvesCriticalPathLen(MachineBasicBlock *MBB, MachineInstr *Root,
Sanjay Patel766589e2015-11-10 16:48:53 +000078 MachineTraceMetrics::Trace BlockTrace,
79 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Pope08d9c72016-12-11 19:39:32 +000080 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patel766589e2015-11-10 16:48:53 +000081 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahnceb44942017-09-20 11:54:37 +000082 MachineCombinerPattern Pattern, bool SlackIsAccurate);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000083 bool preservesResourceLen(MachineBasicBlock *MBB,
84 MachineTraceMetrics::Trace BlockTrace,
85 SmallVectorImpl<MachineInstr *> &InsInstrs,
86 SmallVectorImpl<MachineInstr *> &DelInstrs);
87 void instr2instrSC(SmallVectorImpl<MachineInstr *> &Instrs,
88 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC);
89};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000090}
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000091
92char MachineCombiner::ID = 0;
93char &llvm::MachineCombinerID = MachineCombiner::ID;
94
Matthias Braun1527baa2017-05-25 21:26:32 +000095INITIALIZE_PASS_BEGIN(MachineCombiner, DEBUG_TYPE,
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000096 "Machine InstCombiner", false, false)
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +000097INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000098INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Matthias Braun1527baa2017-05-25 21:26:32 +000099INITIALIZE_PASS_END(MachineCombiner, DEBUG_TYPE, "Machine InstCombiner",
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000100 false, false)
101
102void MachineCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
103 AU.setPreservesCFG();
104 AU.addPreserved<MachineDominatorTree>();
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000105 AU.addRequired<MachineLoopInfo>();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000106 AU.addPreserved<MachineLoopInfo>();
107 AU.addRequired<MachineTraceMetrics>();
108 AU.addPreserved<MachineTraceMetrics>();
109 MachineFunctionPass::getAnalysisUsage(AU);
110}
111
112MachineInstr *MachineCombiner::getOperandDef(const MachineOperand &MO) {
113 MachineInstr *DefInstr = nullptr;
114 // We need a virtual register definition.
115 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
116 DefInstr = MRI->getUniqueVRegDef(MO.getReg());
117 // PHI's have no depth etc.
118 if (DefInstr && DefInstr->isPHI())
119 DefInstr = nullptr;
120 return DefInstr;
121}
122
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000123/// Computes depth of instructions in vector \InsInstr.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000124///
125/// \param InsInstrs is a vector of machine instructions
126/// \param InstrIdxForVirtReg is a dense map of virtual register to index
127/// of defining machine instruction in \p InsInstrs
128/// \param BlockTrace is a trace of machine instructions
129///
130/// \returns Depth of last instruction in \InsInstrs ("NewRoot")
131unsigned
132MachineCombiner::getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
133 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
134 MachineTraceMetrics::Trace BlockTrace) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000135 SmallVector<unsigned, 16> InstrDepth;
Hal Finkele0fa8f22015-07-15 08:22:23 +0000136 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
137 "Missing machine model\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000138
Sanjay Patel6b280772015-01-27 22:16:52 +0000139 // For each instruction in the new sequence compute the depth based on the
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000140 // operands. Use the trace information when possible. For new operands which
141 // are tracked in the InstrIdxForVirtReg map depth is looked up in InstrDepth
142 for (auto *InstrPtr : InsInstrs) { // for each Use
143 unsigned IDepth = 0;
Matthias Brauna4976c62017-01-29 18:20:42 +0000144 DEBUG(dbgs() << "NEW INSTR ";
145 InstrPtr->print(dbgs(), TII);
146 dbgs() << "\n";);
Sanjay Patelf69f4e42015-05-21 17:43:26 +0000147 for (const MachineOperand &MO : InstrPtr->operands()) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000148 // Check for virtual register operand.
149 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
150 continue;
151 if (!MO.isUse())
152 continue;
153 unsigned DepthOp = 0;
154 unsigned LatencyOp = 0;
155 DenseMap<unsigned, unsigned>::iterator II =
156 InstrIdxForVirtReg.find(MO.getReg());
157 if (II != InstrIdxForVirtReg.end()) {
158 // Operand is new virtual register not in trace
Saleem Abdulrasoolbefa2152014-08-03 23:00:38 +0000159 assert(II->second < InstrDepth.size() && "Bad Index");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000160 MachineInstr *DefInstr = InsInstrs[II->second];
161 assert(DefInstr &&
162 "There must be a definition for a new virtual register");
163 DepthOp = InstrDepth[II->second];
Simon Pilgrim194693e2017-10-30 17:24:40 +0000164 int DefIdx = DefInstr->findRegisterDefOperandIdx(MO.getReg());
165 int UseIdx = InstrPtr->findRegisterUseOperandIdx(MO.getReg());
166 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
167 InstrPtr, UseIdx);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000168 } else {
169 MachineInstr *DefInstr = getOperandDef(MO);
170 if (DefInstr) {
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000171 DepthOp = BlockTrace.getInstrCycles(*DefInstr).Depth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000172 LatencyOp = TSchedModel.computeOperandLatency(
173 DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
174 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
175 }
176 }
177 IDepth = std::max(IDepth, DepthOp + LatencyOp);
178 }
179 InstrDepth.push_back(IDepth);
180 }
181 unsigned NewRootIdx = InsInstrs.size() - 1;
182 return InstrDepth[NewRootIdx];
183}
184
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000185/// Computes instruction latency as max of latency of defined operands.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000186///
187/// \param Root is a machine instruction that could be replaced by NewRoot.
188/// It is used to compute a more accurate latency information for NewRoot in
189/// case there is a dependent instruction in the same trace (\p BlockTrace)
190/// \param NewRoot is the instruction for which the latency is computed
191/// \param BlockTrace is a trace of machine instructions
192///
193/// \returns Latency of \p NewRoot
194unsigned MachineCombiner::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
195 MachineTraceMetrics::Trace BlockTrace) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000196 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
197 "Missing machine model\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000198
199 // Check each definition in NewRoot and compute the latency
200 unsigned NewRootLatency = 0;
201
Sanjay Patelf69f4e42015-05-21 17:43:26 +0000202 for (const MachineOperand &MO : NewRoot->operands()) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000203 // Check for virtual register operand.
204 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
205 continue;
206 if (!MO.isDef())
207 continue;
208 // Get the first instruction that uses MO
209 MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(MO.getReg());
210 RI++;
211 MachineInstr *UseMO = RI->getParent();
212 unsigned LatencyOp = 0;
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000213 if (UseMO && BlockTrace.isDepInTrace(*Root, *UseMO)) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000214 LatencyOp = TSchedModel.computeOperandLatency(
215 NewRoot, NewRoot->findRegisterDefOperandIdx(MO.getReg()), UseMO,
216 UseMO->findRegisterUseOperandIdx(MO.getReg()));
217 } else {
Hal Finkel17caf322015-08-05 07:45:28 +0000218 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000219 }
220 NewRootLatency = std::max(NewRootLatency, LatencyOp);
221 }
222 return NewRootLatency;
223}
224
Sanjay Patel766589e2015-11-10 16:48:53 +0000225/// The combiner's goal may differ based on which pattern it is attempting
226/// to optimize.
227enum class CombinerObjective {
228 MustReduceDepth, // The data dependency chain must be improved.
229 Default // The critical path must not be lengthened.
230};
231
232static CombinerObjective getCombinerObjective(MachineCombinerPattern P) {
233 // TODO: If C++ ever gets a real enum class, make this part of the
234 // MachineCombinerPattern class.
235 switch (P) {
236 case MachineCombinerPattern::REASSOC_AX_BY:
237 case MachineCombinerPattern::REASSOC_AX_YB:
238 case MachineCombinerPattern::REASSOC_XA_BY:
239 case MachineCombinerPattern::REASSOC_XA_YB:
240 return CombinerObjective::MustReduceDepth;
241 default:
242 return CombinerObjective::Default;
243 }
244}
245
Sanjay Patele79b43a2015-06-23 00:39:40 +0000246/// The DAGCombine code sequence ends in MI (Machine Instruction) Root.
247/// The new code sequence ends in MI NewRoot. A necessary condition for the new
248/// sequence to replace the old sequence is that it cannot lengthen the critical
Sanjay Patel766589e2015-11-10 16:48:53 +0000249/// path. The definition of "improve" may be restricted by specifying that the
250/// new path improves the data dependency chain (MustReduceDepth).
Sanjay Patele79b43a2015-06-23 00:39:40 +0000251bool MachineCombiner::improvesCriticalPathLen(
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000252 MachineBasicBlock *MBB, MachineInstr *Root,
253 MachineTraceMetrics::Trace BlockTrace,
254 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Pope08d9c72016-12-11 19:39:32 +0000255 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patele79b43a2015-06-23 00:39:40 +0000256 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahnceb44942017-09-20 11:54:37 +0000257 MachineCombinerPattern Pattern,
258 bool SlackIsAccurate) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000259 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
260 "Missing machine model\n");
Sanjay Patelccb8d5c2015-06-10 19:52:58 +0000261 // NewRoot is the last instruction in the \p InsInstrs vector.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000262 unsigned NewRootIdx = InsInstrs.size() - 1;
263 MachineInstr *NewRoot = InsInstrs[NewRootIdx];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000264
Sanjay Patel766589e2015-11-10 16:48:53 +0000265 // Get depth and latency of NewRoot and Root.
266 unsigned NewRootDepth = getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace);
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000267 unsigned RootDepth = BlockTrace.getInstrCycles(*Root).Depth;
Sanjay Patel766589e2015-11-10 16:48:53 +0000268
Florian Hahnceb44942017-09-20 11:54:37 +0000269 DEBUG(dbgs() << "DEPENDENCE DATA FOR " << *Root << "\n";
Sanjay Patel766589e2015-11-10 16:48:53 +0000270 dbgs() << " NewRootDepth: " << NewRootDepth << "\n";
271 dbgs() << " RootDepth: " << RootDepth << "\n");
272
273 // For a transform such as reassociation, the cost equation is
274 // conservatively calculated so that we must improve the depth (data
275 // dependency cycles) in the critical path to proceed with the transform.
276 // Being conservative also protects against inaccuracies in the underlying
277 // machine trace metrics and CPU models.
278 if (getCombinerObjective(Pattern) == CombinerObjective::MustReduceDepth)
279 return NewRootDepth < RootDepth;
280
281 // A more flexible cost calculation for the critical path includes the slack
282 // of the original code sequence. This may allow the transform to proceed
283 // even if the instruction depths (data dependency cycles) become worse.
Sebastian Pope08d9c72016-12-11 19:39:32 +0000284
Sanjay Patel766589e2015-11-10 16:48:53 +0000285 unsigned NewRootLatency = getLatency(Root, NewRoot, BlockTrace);
Sebastian Pope08d9c72016-12-11 19:39:32 +0000286 unsigned RootLatency = 0;
287
288 for (auto I : DelInstrs)
289 RootLatency += TSchedModel.computeInstrLatency(I);
290
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000291 unsigned RootSlack = BlockTrace.getInstrSlack(*Root);
Florian Hahnceb44942017-09-20 11:54:37 +0000292 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
293 unsigned OldCycleCount = RootDepth + RootLatency +
294 (SlackIsAccurate ? RootSlack : 0);
Sanjay Patel766589e2015-11-10 16:48:53 +0000295 DEBUG(dbgs() << " NewRootLatency: " << NewRootLatency << "\n";
296 dbgs() << " RootLatency: " << RootLatency << "\n";
Florian Hahnceb44942017-09-20 11:54:37 +0000297 dbgs() << " RootSlack: " << RootSlack << " SlackIsAccurate="
298 << SlackIsAccurate << "\n";
Sanjay Patelacd4bae2015-10-03 20:45:01 +0000299 dbgs() << " NewRootDepth + NewRootLatency = "
Florian Hahnceb44942017-09-20 11:54:37 +0000300 << NewCycleCount << "\n";
Sanjay Patelacd4bae2015-10-03 20:45:01 +0000301 dbgs() << " RootDepth + RootLatency + RootSlack = "
Florian Hahnceb44942017-09-20 11:54:37 +0000302 << OldCycleCount << "\n";
303 );
Junmo Park272a2bc2016-02-27 01:10:43 +0000304
Sanjay Patel766589e2015-11-10 16:48:53 +0000305 return NewCycleCount <= OldCycleCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000306}
307
308/// helper routine to convert instructions into SC
309void MachineCombiner::instr2instrSC(
310 SmallVectorImpl<MachineInstr *> &Instrs,
311 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
312 for (auto *InstrPtr : Instrs) {
313 unsigned Opc = InstrPtr->getOpcode();
314 unsigned Idx = TII->get(Opc).getSchedClass();
Pete Cooper11759452014-09-02 17:43:54 +0000315 const MCSchedClassDesc *SC = SchedModel.getSchedClassDesc(Idx);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000316 InstrsSC.push_back(SC);
317 }
318}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000319
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000320/// True when the new instructions do not increase resource length
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000321bool MachineCombiner::preservesResourceLen(
322 MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
323 SmallVectorImpl<MachineInstr *> &InsInstrs,
324 SmallVectorImpl<MachineInstr *> &DelInstrs) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000325 if (!TSchedModel.hasInstrSchedModel())
326 return true;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000327
328 // Compute current resource length
329
Gerolf Hoflehner97c383b2014-08-07 21:40:58 +0000330 //ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
331 SmallVector <const MachineBasicBlock *, 1> MBBarr;
332 MBBarr.push_back(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000333 unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
334
335 // Deal with SC rather than Instructions.
336 SmallVector<const MCSchedClassDesc *, 16> InsInstrsSC;
337 SmallVector<const MCSchedClassDesc *, 16> DelInstrsSC;
338
339 instr2instrSC(InsInstrs, InsInstrsSC);
340 instr2instrSC(DelInstrs, DelInstrsSC);
341
342 ArrayRef<const MCSchedClassDesc *> MSCInsArr = makeArrayRef(InsInstrsSC);
343 ArrayRef<const MCSchedClassDesc *> MSCDelArr = makeArrayRef(DelInstrsSC);
344
Sanjay Patelccb8d5c2015-06-10 19:52:58 +0000345 // Compute new resource length.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000346 unsigned ResLenAfterCombine =
347 BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
348
349 DEBUG(dbgs() << "RESOURCE DATA: \n";
350 dbgs() << " resource len before: " << ResLenBeforeCombine
351 << " after: " << ResLenAfterCombine << "\n";);
352
353 return ResLenAfterCombine <= ResLenBeforeCombine;
354}
355
356/// \returns true when new instruction sequence should be generated
Sanjay Patel6b280772015-01-27 22:16:52 +0000357/// independent if it lengthens critical path or not
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000358bool MachineCombiner::doSubstitute(unsigned NewSize, unsigned OldSize) {
359 if (OptSize && (NewSize < OldSize))
360 return true;
Hal Finkele0fa8f22015-07-15 08:22:23 +0000361 if (!TSchedModel.hasInstrSchedModelOrItineraries())
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000362 return true;
363 return false;
364}
365
Florian Hahnceb44942017-09-20 11:54:37 +0000366/// Inserts InsInstrs and deletes DelInstrs. Incrementally updates instruction
367/// depths if requested.
368///
369/// \param MBB basic block to insert instructions in
370/// \param MI current machine instruction
371/// \param InsInstrs new instructions to insert in \p MBB
372/// \param DelInstrs instruction to delete from \p MBB
373/// \param MinInstr is a pointer to the machine trace information
374/// \param RegUnits set of live registers, needed to compute instruction depths
375/// \param IncrementalUpdate if true, compute instruction depths incrementally,
376/// otherwise invalidate the trace
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000377static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI,
378 SmallVector<MachineInstr *, 16> InsInstrs,
379 SmallVector<MachineInstr *, 16> DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000380 MachineTraceMetrics::Ensemble *MinInstr,
381 SparseSet<LiveRegUnit> &RegUnits,
382 bool IncrementalUpdate) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000383 for (auto *InstrPtr : InsInstrs)
384 MBB->insert((MachineBasicBlock::iterator)&MI, InstrPtr);
Florian Hahnceb44942017-09-20 11:54:37 +0000385
386 for (auto *InstrPtr : DelInstrs) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000387 InstrPtr->eraseFromParentAndMarkDBGValuesForRemoval();
Florian Hahnceb44942017-09-20 11:54:37 +0000388 // Erase all LiveRegs defined by the removed instruction
389 for (auto I = RegUnits.begin(); I != RegUnits.end(); ) {
390 if (I->MI == InstrPtr)
391 I = RegUnits.erase(I);
392 else
393 I++;
394 }
395 }
396
397 if (IncrementalUpdate)
398 for (auto *InstrPtr : InsInstrs)
399 MinInstr->updateDepth(MBB, *InstrPtr, RegUnits);
400 else
401 MinInstr->invalidate(MBB);
402
403 NumInstCombined++;
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000404}
405
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000406/// Substitute a slow code sequence with a faster one by
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000407/// evaluating instruction combining pattern.
408/// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
409/// combining based on machine trace metrics. Only combine a sequence of
410/// instructions when this neither lengthens the critical path nor increases
411/// resource pressure. When optimizing for codesize always combine when the new
412/// sequence is shorter.
413bool MachineCombiner::combineInstructions(MachineBasicBlock *MBB) {
414 bool Changed = false;
415 DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
416
Florian Hahnceb44942017-09-20 11:54:37 +0000417 bool IncrementalUpdate = false;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000418 auto BlockIter = MBB->begin();
Florian Hahne52abba2017-10-11 20:25:58 +0000419 decltype(BlockIter) LastUpdate;
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000420 // Check if the block is in a loop.
421 const MachineLoop *ML = MLI->getLoopFor(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000422 if (!MinInstr)
423 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
424
425 SparseSet<LiveRegUnit> RegUnits;
426 RegUnits.setUniverse(TRI->getNumRegUnits());
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000427
428 while (BlockIter != MBB->end()) {
429 auto &MI = *BlockIter++;
430
431 DEBUG(dbgs() << "INSTR "; MI.dump(); dbgs() << "\n";);
Sanjay Patel387e66e2015-11-05 19:34:57 +0000432 SmallVector<MachineCombinerPattern, 16> Patterns;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000433 // The motivating example is:
434 //
435 // MUL Other MUL_op1 MUL_op2 Other
436 // \ / \ | /
437 // ADD/SUB => MADD/MSUB
438 // (=Root) (=NewRoot)
439
440 // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
441 // usually beneficial for code size it unfortunately can hurt performance
442 // when the ADD is on the critical path, but the MUL is not. With the
443 // substitution the MUL becomes part of the critical path (in form of the
444 // MADD) and can lengthen it on architectures where the MADD latency is
445 // longer than the ADD latency.
446 //
447 // For each instruction we check if it can be the root of a combiner
448 // pattern. Then for each pattern the new code sequence in form of MI is
449 // generated and evaluated. When the efficiency criteria (don't lengthen
450 // critical path, don't use more resources) is met the new sequence gets
451 // hooked up into the basic block before the old sequence is removed.
452 //
453 // The algorithm does not try to evaluate all patterns and pick the best.
454 // This is only an artificial restriction though. In practice there is
Sanjay Patelcfe03932015-06-19 23:21:42 +0000455 // mostly one pattern, and getMachineCombinerPatterns() can order patterns
456 // based on an internal cost heuristic.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000457
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000458 if (!TII->getMachineCombinerPatterns(MI, Patterns))
459 continue;
460
461 for (auto P : Patterns) {
462 SmallVector<MachineInstr *, 16> InsInstrs;
463 SmallVector<MachineInstr *, 16> DelInstrs;
464 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000465 TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
466 InstrIdxForVirtReg);
467 unsigned NewInstCount = InsInstrs.size();
468 unsigned OldInstCount = DelInstrs.size();
469 // Found pattern, but did not generate alternative sequence.
470 // This can happen e.g. when an immediate could not be materialized
471 // in a single instruction.
472 if (!NewInstCount)
473 continue;
474
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000475 bool SubstituteAlways = false;
476 if (ML && TII->isThroughputPattern(P))
477 SubstituteAlways = true;
478
Florian Hahnceb44942017-09-20 11:54:37 +0000479 if (IncrementalUpdate) {
480 // Update depths since the last incremental update.
481 MinInstr->updateDepths(LastUpdate, BlockIter, RegUnits);
482 LastUpdate = BlockIter;
483 }
484
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000485 // Substitute when we optimize for codesize and the new sequence has
486 // fewer instructions OR
487 // the new sequence neither lengthens the critical path nor increases
488 // resource pressure.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000489 if (SubstituteAlways || doSubstitute(NewInstCount, OldInstCount)) {
Florian Hahnceb44942017-09-20 11:54:37 +0000490 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
491 RegUnits, IncrementalUpdate);
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000492 // Eagerly stop after the first pattern fires.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000493 Changed = true;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000494 break;
495 } else {
Florian Hahnceb44942017-09-20 11:54:37 +0000496 // For big basic blocks, we only compute the full trace the first time
497 // we hit this. We do not invalidate the trace, but instead update the
498 // instruction depths incrementally.
499 // NOTE: Only the instruction depths up to MI are accurate. All other
500 // trace information is not updated.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000501 MachineTraceMetrics::Trace BlockTrace = MinInstr->getTrace(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000502 Traces->verifyAnalysis();
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000503 if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000504 InstrIdxForVirtReg, P,
505 !IncrementalUpdate) &&
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000506 preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
Florian Hahne52abba2017-10-11 20:25:58 +0000507 if (MBB->size() > inc_threshold) {
Florian Hahnceb44942017-09-20 11:54:37 +0000508 // Use incremental depth updates for basic blocks above treshold
509 IncrementalUpdate = true;
Florian Hahne52abba2017-10-11 20:25:58 +0000510 LastUpdate = BlockIter;
511 }
Florian Hahnceb44942017-09-20 11:54:37 +0000512
513 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
514 RegUnits, IncrementalUpdate);
515
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000516 // Eagerly stop after the first pattern fires.
517 Changed = true;
518 break;
519 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000520 // Cleanup instructions of the alternative code sequence. There is no
521 // use for them.
522 MachineFunction *MF = MBB->getParent();
523 for (auto *InstrPtr : InsInstrs)
524 MF->DeleteMachineInstr(InstrPtr);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000525 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000526 InstrIdxForVirtReg.clear();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000527 }
528 }
529
Florian Hahnceb44942017-09-20 11:54:37 +0000530 if (Changed && IncrementalUpdate)
531 Traces->invalidate(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000532 return Changed;
533}
534
535bool MachineCombiner::runOnMachineFunction(MachineFunction &MF) {
Eric Christopher3d4276f2015-01-27 07:31:29 +0000536 const TargetSubtargetInfo &STI = MF.getSubtarget();
Eric Christopherd9134482014-08-04 21:25:23 +0000537 TII = STI.getInstrInfo();
538 TRI = STI.getRegisterInfo();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000539 SchedModel = STI.getSchedModel();
Pete Cooper11759452014-09-02 17:43:54 +0000540 TSchedModel.init(SchedModel, &STI, TII);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000541 MRI = &MF.getRegInfo();
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000542 MLI = &getAnalysis<MachineLoopInfo>();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000543 Traces = &getAnalysis<MachineTraceMetrics>();
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000544 MinInstr = nullptr;
Sanjay Patel74ca3122015-08-11 14:31:14 +0000545 OptSize = MF.getFunction()->optForSize();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000546
547 DEBUG(dbgs() << getPassName() << ": " << MF.getName() << '\n');
548 if (!TII->useMachineCombiner()) {
549 DEBUG(dbgs() << " Skipping pass: Target does not support machine combiner\n");
550 return false;
551 }
552
553 bool Changed = false;
554
555 // Try to combine instructions.
556 for (auto &MBB : MF)
557 Changed |= combineInstructions(&MBB);
558
559 return Changed;
560}