blob: d563370dd4fe281d2ee943abc406b85f8678cd46 [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];
164 LatencyOp = TSchedModel.computeOperandLatency(
165 DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
166 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
167 } else {
168 MachineInstr *DefInstr = getOperandDef(MO);
169 if (DefInstr) {
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000170 DepthOp = BlockTrace.getInstrCycles(*DefInstr).Depth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000171 LatencyOp = TSchedModel.computeOperandLatency(
172 DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
173 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
174 }
175 }
176 IDepth = std::max(IDepth, DepthOp + LatencyOp);
177 }
178 InstrDepth.push_back(IDepth);
179 }
180 unsigned NewRootIdx = InsInstrs.size() - 1;
181 return InstrDepth[NewRootIdx];
182}
183
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000184/// Computes instruction latency as max of latency of defined operands.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000185///
186/// \param Root is a machine instruction that could be replaced by NewRoot.
187/// It is used to compute a more accurate latency information for NewRoot in
188/// case there is a dependent instruction in the same trace (\p BlockTrace)
189/// \param NewRoot is the instruction for which the latency is computed
190/// \param BlockTrace is a trace of machine instructions
191///
192/// \returns Latency of \p NewRoot
193unsigned MachineCombiner::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
194 MachineTraceMetrics::Trace BlockTrace) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000195 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
196 "Missing machine model\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000197
198 // Check each definition in NewRoot and compute the latency
199 unsigned NewRootLatency = 0;
200
Sanjay Patelf69f4e42015-05-21 17:43:26 +0000201 for (const MachineOperand &MO : NewRoot->operands()) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000202 // Check for virtual register operand.
203 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
204 continue;
205 if (!MO.isDef())
206 continue;
207 // Get the first instruction that uses MO
208 MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(MO.getReg());
209 RI++;
210 MachineInstr *UseMO = RI->getParent();
211 unsigned LatencyOp = 0;
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000212 if (UseMO && BlockTrace.isDepInTrace(*Root, *UseMO)) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000213 LatencyOp = TSchedModel.computeOperandLatency(
214 NewRoot, NewRoot->findRegisterDefOperandIdx(MO.getReg()), UseMO,
215 UseMO->findRegisterUseOperandIdx(MO.getReg()));
216 } else {
Hal Finkel17caf322015-08-05 07:45:28 +0000217 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000218 }
219 NewRootLatency = std::max(NewRootLatency, LatencyOp);
220 }
221 return NewRootLatency;
222}
223
Sanjay Patel766589e2015-11-10 16:48:53 +0000224/// The combiner's goal may differ based on which pattern it is attempting
225/// to optimize.
226enum class CombinerObjective {
227 MustReduceDepth, // The data dependency chain must be improved.
228 Default // The critical path must not be lengthened.
229};
230
231static CombinerObjective getCombinerObjective(MachineCombinerPattern P) {
232 // TODO: If C++ ever gets a real enum class, make this part of the
233 // MachineCombinerPattern class.
234 switch (P) {
235 case MachineCombinerPattern::REASSOC_AX_BY:
236 case MachineCombinerPattern::REASSOC_AX_YB:
237 case MachineCombinerPattern::REASSOC_XA_BY:
238 case MachineCombinerPattern::REASSOC_XA_YB:
239 return CombinerObjective::MustReduceDepth;
240 default:
241 return CombinerObjective::Default;
242 }
243}
244
Sanjay Patele79b43a2015-06-23 00:39:40 +0000245/// The DAGCombine code sequence ends in MI (Machine Instruction) Root.
246/// The new code sequence ends in MI NewRoot. A necessary condition for the new
247/// sequence to replace the old sequence is that it cannot lengthen the critical
Sanjay Patel766589e2015-11-10 16:48:53 +0000248/// path. The definition of "improve" may be restricted by specifying that the
249/// new path improves the data dependency chain (MustReduceDepth).
Sanjay Patele79b43a2015-06-23 00:39:40 +0000250bool MachineCombiner::improvesCriticalPathLen(
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000251 MachineBasicBlock *MBB, MachineInstr *Root,
252 MachineTraceMetrics::Trace BlockTrace,
253 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Pope08d9c72016-12-11 19:39:32 +0000254 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patele79b43a2015-06-23 00:39:40 +0000255 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahnceb44942017-09-20 11:54:37 +0000256 MachineCombinerPattern Pattern,
257 bool SlackIsAccurate) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000258 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
259 "Missing machine model\n");
Sanjay Patelccb8d5c2015-06-10 19:52:58 +0000260 // NewRoot is the last instruction in the \p InsInstrs vector.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000261 unsigned NewRootIdx = InsInstrs.size() - 1;
262 MachineInstr *NewRoot = InsInstrs[NewRootIdx];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000263
Sanjay Patel766589e2015-11-10 16:48:53 +0000264 // Get depth and latency of NewRoot and Root.
265 unsigned NewRootDepth = getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace);
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000266 unsigned RootDepth = BlockTrace.getInstrCycles(*Root).Depth;
Sanjay Patel766589e2015-11-10 16:48:53 +0000267
Florian Hahnceb44942017-09-20 11:54:37 +0000268 DEBUG(dbgs() << "DEPENDENCE DATA FOR " << *Root << "\n";
Sanjay Patel766589e2015-11-10 16:48:53 +0000269 dbgs() << " NewRootDepth: " << NewRootDepth << "\n";
270 dbgs() << " RootDepth: " << RootDepth << "\n");
271
272 // For a transform such as reassociation, the cost equation is
273 // conservatively calculated so that we must improve the depth (data
274 // dependency cycles) in the critical path to proceed with the transform.
275 // Being conservative also protects against inaccuracies in the underlying
276 // machine trace metrics and CPU models.
277 if (getCombinerObjective(Pattern) == CombinerObjective::MustReduceDepth)
278 return NewRootDepth < RootDepth;
279
280 // A more flexible cost calculation for the critical path includes the slack
281 // of the original code sequence. This may allow the transform to proceed
282 // even if the instruction depths (data dependency cycles) become worse.
Sebastian Pope08d9c72016-12-11 19:39:32 +0000283
Sanjay Patel766589e2015-11-10 16:48:53 +0000284 unsigned NewRootLatency = getLatency(Root, NewRoot, BlockTrace);
Sebastian Pope08d9c72016-12-11 19:39:32 +0000285 unsigned RootLatency = 0;
286
287 for (auto I : DelInstrs)
288 RootLatency += TSchedModel.computeInstrLatency(I);
289
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000290 unsigned RootSlack = BlockTrace.getInstrSlack(*Root);
Florian Hahnceb44942017-09-20 11:54:37 +0000291 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
292 unsigned OldCycleCount = RootDepth + RootLatency +
293 (SlackIsAccurate ? RootSlack : 0);
Sanjay Patel766589e2015-11-10 16:48:53 +0000294 DEBUG(dbgs() << " NewRootLatency: " << NewRootLatency << "\n";
295 dbgs() << " RootLatency: " << RootLatency << "\n";
Florian Hahnceb44942017-09-20 11:54:37 +0000296 dbgs() << " RootSlack: " << RootSlack << " SlackIsAccurate="
297 << SlackIsAccurate << "\n";
Sanjay Patelacd4bae2015-10-03 20:45:01 +0000298 dbgs() << " NewRootDepth + NewRootLatency = "
Florian Hahnceb44942017-09-20 11:54:37 +0000299 << NewCycleCount << "\n";
Sanjay Patelacd4bae2015-10-03 20:45:01 +0000300 dbgs() << " RootDepth + RootLatency + RootSlack = "
Florian Hahnceb44942017-09-20 11:54:37 +0000301 << OldCycleCount << "\n";
302 );
Junmo Park272a2bc2016-02-27 01:10:43 +0000303
Sanjay Patel766589e2015-11-10 16:48:53 +0000304 return NewCycleCount <= OldCycleCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000305}
306
307/// helper routine to convert instructions into SC
308void MachineCombiner::instr2instrSC(
309 SmallVectorImpl<MachineInstr *> &Instrs,
310 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
311 for (auto *InstrPtr : Instrs) {
312 unsigned Opc = InstrPtr->getOpcode();
313 unsigned Idx = TII->get(Opc).getSchedClass();
Pete Cooper11759452014-09-02 17:43:54 +0000314 const MCSchedClassDesc *SC = SchedModel.getSchedClassDesc(Idx);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000315 InstrsSC.push_back(SC);
316 }
317}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000318
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000319/// True when the new instructions do not increase resource length
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000320bool MachineCombiner::preservesResourceLen(
321 MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
322 SmallVectorImpl<MachineInstr *> &InsInstrs,
323 SmallVectorImpl<MachineInstr *> &DelInstrs) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000324 if (!TSchedModel.hasInstrSchedModel())
325 return true;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000326
327 // Compute current resource length
328
Gerolf Hoflehner97c383b2014-08-07 21:40:58 +0000329 //ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
330 SmallVector <const MachineBasicBlock *, 1> MBBarr;
331 MBBarr.push_back(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000332 unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
333
334 // Deal with SC rather than Instructions.
335 SmallVector<const MCSchedClassDesc *, 16> InsInstrsSC;
336 SmallVector<const MCSchedClassDesc *, 16> DelInstrsSC;
337
338 instr2instrSC(InsInstrs, InsInstrsSC);
339 instr2instrSC(DelInstrs, DelInstrsSC);
340
341 ArrayRef<const MCSchedClassDesc *> MSCInsArr = makeArrayRef(InsInstrsSC);
342 ArrayRef<const MCSchedClassDesc *> MSCDelArr = makeArrayRef(DelInstrsSC);
343
Sanjay Patelccb8d5c2015-06-10 19:52:58 +0000344 // Compute new resource length.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000345 unsigned ResLenAfterCombine =
346 BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
347
348 DEBUG(dbgs() << "RESOURCE DATA: \n";
349 dbgs() << " resource len before: " << ResLenBeforeCombine
350 << " after: " << ResLenAfterCombine << "\n";);
351
352 return ResLenAfterCombine <= ResLenBeforeCombine;
353}
354
355/// \returns true when new instruction sequence should be generated
Sanjay Patel6b280772015-01-27 22:16:52 +0000356/// independent if it lengthens critical path or not
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000357bool MachineCombiner::doSubstitute(unsigned NewSize, unsigned OldSize) {
358 if (OptSize && (NewSize < OldSize))
359 return true;
Hal Finkele0fa8f22015-07-15 08:22:23 +0000360 if (!TSchedModel.hasInstrSchedModelOrItineraries())
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000361 return true;
362 return false;
363}
364
Florian Hahnceb44942017-09-20 11:54:37 +0000365/// Inserts InsInstrs and deletes DelInstrs. Incrementally updates instruction
366/// depths if requested.
367///
368/// \param MBB basic block to insert instructions in
369/// \param MI current machine instruction
370/// \param InsInstrs new instructions to insert in \p MBB
371/// \param DelInstrs instruction to delete from \p MBB
372/// \param MinInstr is a pointer to the machine trace information
373/// \param RegUnits set of live registers, needed to compute instruction depths
374/// \param IncrementalUpdate if true, compute instruction depths incrementally,
375/// otherwise invalidate the trace
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000376static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI,
377 SmallVector<MachineInstr *, 16> InsInstrs,
378 SmallVector<MachineInstr *, 16> DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000379 MachineTraceMetrics::Ensemble *MinInstr,
380 SparseSet<LiveRegUnit> &RegUnits,
381 bool IncrementalUpdate) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000382 for (auto *InstrPtr : InsInstrs)
383 MBB->insert((MachineBasicBlock::iterator)&MI, InstrPtr);
Florian Hahnceb44942017-09-20 11:54:37 +0000384
385 for (auto *InstrPtr : DelInstrs) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000386 InstrPtr->eraseFromParentAndMarkDBGValuesForRemoval();
Florian Hahnceb44942017-09-20 11:54:37 +0000387 // Erase all LiveRegs defined by the removed instruction
388 for (auto I = RegUnits.begin(); I != RegUnits.end(); ) {
389 if (I->MI == InstrPtr)
390 I = RegUnits.erase(I);
391 else
392 I++;
393 }
394 }
395
396 if (IncrementalUpdate)
397 for (auto *InstrPtr : InsInstrs)
398 MinInstr->updateDepth(MBB, *InstrPtr, RegUnits);
399 else
400 MinInstr->invalidate(MBB);
401
402 NumInstCombined++;
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000403}
404
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000405/// Substitute a slow code sequence with a faster one by
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000406/// evaluating instruction combining pattern.
407/// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
408/// combining based on machine trace metrics. Only combine a sequence of
409/// instructions when this neither lengthens the critical path nor increases
410/// resource pressure. When optimizing for codesize always combine when the new
411/// sequence is shorter.
412bool MachineCombiner::combineInstructions(MachineBasicBlock *MBB) {
413 bool Changed = false;
414 DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
415
Florian Hahnceb44942017-09-20 11:54:37 +0000416 bool IncrementalUpdate = false;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000417 auto BlockIter = MBB->begin();
Florian Hahnceb44942017-09-20 11:54:37 +0000418 auto LastUpdate = BlockIter;
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000419 // Check if the block is in a loop.
420 const MachineLoop *ML = MLI->getLoopFor(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000421 if (!MinInstr)
422 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
423
424 SparseSet<LiveRegUnit> RegUnits;
425 RegUnits.setUniverse(TRI->getNumRegUnits());
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000426
427 while (BlockIter != MBB->end()) {
428 auto &MI = *BlockIter++;
429
430 DEBUG(dbgs() << "INSTR "; MI.dump(); dbgs() << "\n";);
Sanjay Patel387e66e2015-11-05 19:34:57 +0000431 SmallVector<MachineCombinerPattern, 16> Patterns;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000432 // The motivating example is:
433 //
434 // MUL Other MUL_op1 MUL_op2 Other
435 // \ / \ | /
436 // ADD/SUB => MADD/MSUB
437 // (=Root) (=NewRoot)
438
439 // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
440 // usually beneficial for code size it unfortunately can hurt performance
441 // when the ADD is on the critical path, but the MUL is not. With the
442 // substitution the MUL becomes part of the critical path (in form of the
443 // MADD) and can lengthen it on architectures where the MADD latency is
444 // longer than the ADD latency.
445 //
446 // For each instruction we check if it can be the root of a combiner
447 // pattern. Then for each pattern the new code sequence in form of MI is
448 // generated and evaluated. When the efficiency criteria (don't lengthen
449 // critical path, don't use more resources) is met the new sequence gets
450 // hooked up into the basic block before the old sequence is removed.
451 //
452 // The algorithm does not try to evaluate all patterns and pick the best.
453 // This is only an artificial restriction though. In practice there is
Sanjay Patelcfe03932015-06-19 23:21:42 +0000454 // mostly one pattern, and getMachineCombinerPatterns() can order patterns
455 // based on an internal cost heuristic.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000456
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000457 if (!TII->getMachineCombinerPatterns(MI, Patterns))
458 continue;
459
460 for (auto P : Patterns) {
461 SmallVector<MachineInstr *, 16> InsInstrs;
462 SmallVector<MachineInstr *, 16> DelInstrs;
463 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000464 TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
465 InstrIdxForVirtReg);
466 unsigned NewInstCount = InsInstrs.size();
467 unsigned OldInstCount = DelInstrs.size();
468 // Found pattern, but did not generate alternative sequence.
469 // This can happen e.g. when an immediate could not be materialized
470 // in a single instruction.
471 if (!NewInstCount)
472 continue;
473
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000474 bool SubstituteAlways = false;
475 if (ML && TII->isThroughputPattern(P))
476 SubstituteAlways = true;
477
Florian Hahnceb44942017-09-20 11:54:37 +0000478 if (IncrementalUpdate) {
479 // Update depths since the last incremental update.
480 MinInstr->updateDepths(LastUpdate, BlockIter, RegUnits);
481 LastUpdate = BlockIter;
482 }
483
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000484 // Substitute when we optimize for codesize and the new sequence has
485 // fewer instructions OR
486 // the new sequence neither lengthens the critical path nor increases
487 // resource pressure.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000488 if (SubstituteAlways || doSubstitute(NewInstCount, OldInstCount)) {
Florian Hahnceb44942017-09-20 11:54:37 +0000489 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
490 RegUnits, IncrementalUpdate);
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000491 // Eagerly stop after the first pattern fires.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000492 Changed = true;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000493 break;
494 } else {
Florian Hahnceb44942017-09-20 11:54:37 +0000495 // For big basic blocks, we only compute the full trace the first time
496 // we hit this. We do not invalidate the trace, but instead update the
497 // instruction depths incrementally.
498 // NOTE: Only the instruction depths up to MI are accurate. All other
499 // trace information is not updated.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000500 MachineTraceMetrics::Trace BlockTrace = MinInstr->getTrace(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000501 Traces->verifyAnalysis();
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000502 if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000503 InstrIdxForVirtReg, P,
504 !IncrementalUpdate) &&
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000505 preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
Florian Hahnceb44942017-09-20 11:54:37 +0000506 if (MBB->size() > inc_threshold)
507 // Use incremental depth updates for basic blocks above treshold
508 IncrementalUpdate = true;
509
510 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
511 RegUnits, IncrementalUpdate);
512
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000513 // Eagerly stop after the first pattern fires.
514 Changed = true;
515 break;
516 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000517 // Cleanup instructions of the alternative code sequence. There is no
518 // use for them.
519 MachineFunction *MF = MBB->getParent();
520 for (auto *InstrPtr : InsInstrs)
521 MF->DeleteMachineInstr(InstrPtr);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000522 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000523 InstrIdxForVirtReg.clear();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000524 }
525 }
526
Florian Hahnceb44942017-09-20 11:54:37 +0000527 if (Changed && IncrementalUpdate)
528 Traces->invalidate(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000529 return Changed;
530}
531
532bool MachineCombiner::runOnMachineFunction(MachineFunction &MF) {
Eric Christopher3d4276f2015-01-27 07:31:29 +0000533 const TargetSubtargetInfo &STI = MF.getSubtarget();
Eric Christopherd9134482014-08-04 21:25:23 +0000534 TII = STI.getInstrInfo();
535 TRI = STI.getRegisterInfo();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000536 SchedModel = STI.getSchedModel();
Pete Cooper11759452014-09-02 17:43:54 +0000537 TSchedModel.init(SchedModel, &STI, TII);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000538 MRI = &MF.getRegInfo();
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000539 MLI = &getAnalysis<MachineLoopInfo>();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000540 Traces = &getAnalysis<MachineTraceMetrics>();
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000541 MinInstr = nullptr;
Sanjay Patel74ca3122015-08-11 14:31:14 +0000542 OptSize = MF.getFunction()->optForSize();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000543
544 DEBUG(dbgs() << getPassName() << ": " << MF.getName() << '\n');
545 if (!TII->useMachineCombiner()) {
546 DEBUG(dbgs() << " Skipping pass: Target does not support machine combiner\n");
547 return false;
548 }
549
550 bool Changed = false;
551
552 // Try to combine instructions.
553 for (auto &MBB : MF)
554 Changed |= combineInstructions(&MBB);
555
556 return Changed;
557}