LLVM 24.0.0git
MachineCombiner.cpp
Go to the documentation of this file.
1//===---- MachineCombiner.cpp - Instcombining on SSA form machine code ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The machine combiner pass uses machine trace metrics to ensure the combined
10// instructions do not lengthen the critical path or the resource depth.
11//===----------------------------------------------------------------------===//
12
14#include "CodeGenOptions.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/Statistic.h"
36#include "llvm/Support/Debug.h"
38
39using namespace llvm;
40
41#define DEBUG_TYPE "machine-combiner"
42
43STATISTIC(NumInstCombined, "Number of machineinst combined");
44
45namespace {
46class MachineCombinerImpl {
47 const CodeGenOptions &Opts;
48 const TargetSubtargetInfo *STI = nullptr;
49 const TargetInstrInfo *TII = nullptr;
50 const TargetRegisterInfo *TRI = nullptr;
51 MCSchedModel SchedModel;
52 MachineRegisterInfo *MRI = nullptr;
53 MachineLoopInfo *MLI = nullptr; // Current MachineLoopInfo
54 MachineTraceMetrics *Traces = nullptr;
55 MachineTraceMetrics::Ensemble *TraceEnsemble = nullptr;
56 MachineBlockFrequencyInfo *MBFI = nullptr;
57 ProfileSummaryInfo *PSI = nullptr;
58 RegisterClassInfo *RegClassInfo = nullptr;
59
60 TargetSchedModel TSchedModel;
61
62public:
63 explicit MachineCombinerImpl(const CodeGenOptions &Opts) : Opts(Opts) {}
64 bool run(MachineFunction &MF, MachineLoopInfo *MLI,
65 MachineTraceMetrics *Traces, ProfileSummaryInfo *PSI,
66 MachineBlockFrequencyInfo *MBFI, RegisterClassInfo *RegClassInfo);
67
68private:
69 bool combineInstructions(MachineBasicBlock *);
70 MachineInstr *getOperandDef(const MachineOperand &MO);
71 bool isTransientMI(const MachineInstr *MI);
72 unsigned getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
73 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
75 const MachineBasicBlock &MBB);
76 unsigned getLatency(MachineInstr *Root, MachineInstr *NewRoot,
78 bool improvesCriticalPathLen(MachineBasicBlock *MBB, MachineInstr *Root,
80 SmallVectorImpl<MachineInstr *> &InsInstrs,
81 SmallVectorImpl<MachineInstr *> &DelInstrs,
82 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
83 unsigned Pattern, bool SlackIsAccurate);
84 bool reduceRegisterPressure(MachineInstr &Root, MachineBasicBlock *MBB,
85 SmallVectorImpl<MachineInstr *> &InsInstrs,
86 SmallVectorImpl<MachineInstr *> &DelInstrs,
87 unsigned Pattern);
88 bool preservesResourceLen(MachineBasicBlock *MBB,
90 SmallVectorImpl<MachineInstr *> &InsInstrs,
91 SmallVectorImpl<MachineInstr *> &DelInstrs);
92 void instr2instrSC(SmallVectorImpl<MachineInstr *> &Instrs,
93 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC);
94 std::pair<unsigned, unsigned>
95 getLatenciesForInstrSequences(MachineInstr &MI,
96 SmallVectorImpl<MachineInstr *> &InsInstrs,
97 SmallVectorImpl<MachineInstr *> &DelInstrs,
99
100 CombinerObjective getCombinerObjective(unsigned Pattern);
101};
102
103class MachineCombinerLegacy : public MachineFunctionPass {
104public:
105 static char ID;
106 MachineCombinerLegacy() : MachineFunctionPass(ID) {}
107 void getAnalysisUsage(AnalysisUsage &AU) const override;
108 bool runOnMachineFunction(MachineFunction &MF) override;
109 StringRef getPassName() const override { return "Machine InstCombiner"; }
110};
111} // namespace
112
113char MachineCombinerLegacy::ID = 0;
114char &llvm::MachineCombinerID = MachineCombinerLegacy::ID;
115
116INITIALIZE_PASS_BEGIN(MachineCombinerLegacy, DEBUG_TYPE, "Machine InstCombiner",
117 false, false)
121INITIALIZE_PASS_END(MachineCombinerLegacy, DEBUG_TYPE, "Machine InstCombiner",
123
124void MachineCombinerLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
125 AU.setPreservesCFG();
126 AU.addRequired<MachineLoopInfoWrapperPass>();
127 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
128 AU.addRequired<MachineTraceMetricsWrapperPass>();
129 AU.addPreserved<MachineTraceMetricsWrapperPass>();
130 AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
131 AU.addRequired<ProfileSummaryInfoWrapperPass>();
133}
134
135MachineInstr *MachineCombinerImpl::getOperandDef(const MachineOperand &MO) {
136 MachineInstr *DefInstr = nullptr;
137 // We need a virtual register definition.
138 if (MO.isReg() && MO.getReg().isVirtual())
139 DefInstr = MRI->getUniqueVRegDef(MO.getReg());
140 return DefInstr;
141}
142
143/// Return true if MI is unlikely to generate an actual target instruction.
144bool MachineCombinerImpl::isTransientMI(const MachineInstr *MI) {
145 if (!MI->isCopy())
146 return MI->isTransient();
147
148 // If MI is a COPY, check if its src and dst registers can be coalesced.
149 Register Dst = MI->getOperand(0).getReg();
150 Register Src = MI->getOperand(1).getReg();
151
152 if (!MI->isFullCopy()) {
153 // If src RC contains super registers of dst RC, it can also be coalesced.
154 if (MI->getOperand(0).getSubReg() || Src.isPhysical() || Dst.isPhysical())
155 return false;
156
157 auto SrcSub = MI->getOperand(1).getSubReg();
158 auto SrcRC = MRI->getRegClass(Src);
159 auto DstRC = MRI->getRegClass(Dst);
160 return TRI->getMatchingSuperRegClass(SrcRC, DstRC, SrcSub) != nullptr;
161 }
162
163 if (Src.isPhysical() && Dst.isPhysical())
164 return Src == Dst;
165
166 if (Src.isVirtual() && Dst.isVirtual()) {
167 auto SrcRC = MRI->getRegClass(Src);
168 auto DstRC = MRI->getRegClass(Dst);
169 return SrcRC->hasSuperClassEq(DstRC) || SrcRC->hasSubClassEq(DstRC);
170 }
171
172 if (Src.isVirtual())
173 std::swap(Src, Dst);
174
175 // Now Src is physical register, Dst is virtual register.
176 auto DstRC = MRI->getRegClass(Dst);
177 return DstRC->contains(Src);
178}
179
180/// Computes depth of instructions in vector \InsInstr.
181///
182/// \param InsInstrs is a vector of machine instructions
183/// \param InstrIdxForVirtReg is a dense map of virtual register to index
184/// of defining machine instruction in \p InsInstrs
185/// \param BlockTrace is a trace of machine instructions
186///
187/// \returns Depth of last instruction in \InsInstrs ("NewRoot")
188unsigned
189MachineCombinerImpl::getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
190 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
192 const MachineBasicBlock &MBB) {
193 SmallVector<unsigned, 16> InstrDepth;
194 // For each instruction in the new sequence compute the depth based on the
195 // operands. Use the trace information when possible. For new operands which
196 // are tracked in the InstrIdxForVirtReg map depth is looked up in InstrDepth
197 for (auto *InstrPtr : InsInstrs) { // for each Use
198 unsigned IDepth = 0;
199 for (const MachineOperand &MO : InstrPtr->all_uses()) {
200 // Check for virtual register operand.
201 if (!MO.getReg().isVirtual())
202 continue;
203 unsigned DepthOp = 0;
204 unsigned LatencyOp = 0;
205 auto II = InstrIdxForVirtReg.find(MO.getReg());
206 if (II != InstrIdxForVirtReg.end()) {
207 // Operand is new virtual register not in trace
208 assert(II->second < InstrDepth.size() && "Bad Index");
209 MachineInstr *DefInstr = InsInstrs[II->second];
210 assert(DefInstr &&
211 "There must be a definition for a new virtual register");
212 DepthOp = InstrDepth[II->second];
213 int DefIdx =
214 DefInstr->findRegisterDefOperandIdx(MO.getReg(), /*TRI=*/nullptr);
215 int UseIdx =
216 InstrPtr->findRegisterUseOperandIdx(MO.getReg(), /*TRI=*/nullptr);
217 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
218 InstrPtr, UseIdx);
219 } else {
220 MachineInstr *DefInstr = getOperandDef(MO);
221 if (DefInstr && (TII->getMachineCombinerTraceStrategy() !=
222 MachineTraceStrategy::TS_Local ||
223 DefInstr->getParent() == &MBB)) {
224 DepthOp = BlockTrace.getInstrCycles(*DefInstr).Depth;
225 if (!isTransientMI(DefInstr))
226 LatencyOp = TSchedModel.computeOperandLatency(
227 DefInstr,
228 DefInstr->findRegisterDefOperandIdx(MO.getReg(),
229 /*TRI=*/nullptr),
230 InstrPtr,
231 InstrPtr->findRegisterUseOperandIdx(MO.getReg(),
232 /*TRI=*/nullptr));
233 }
234 }
235 IDepth = std::max(IDepth, DepthOp + LatencyOp);
236 }
237 InstrDepth.push_back(IDepth);
238 }
239 unsigned NewRootIdx = InsInstrs.size() - 1;
240 return InstrDepth[NewRootIdx];
241}
242
243/// Computes instruction latency as max of latency of defined operands.
244///
245/// \param Root is a machine instruction that could be replaced by NewRoot.
246/// It is used to compute a more accurate latency information for NewRoot in
247/// case there is a dependent instruction in the same trace (\p BlockTrace)
248/// \param NewRoot is the instruction for which the latency is computed
249/// \param BlockTrace is a trace of machine instructions
250///
251/// \returns Latency of \p NewRoot
252unsigned
253MachineCombinerImpl::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
254 MachineTraceMetrics::Trace BlockTrace) {
255 // Check each definition in NewRoot and compute the latency
256 unsigned NewRootLatency = 0;
257
258 for (const MachineOperand &MO : NewRoot->all_defs()) {
259 // Check for virtual register operand.
260 if (!MO.getReg().isVirtual())
261 continue;
262 // Get the first instruction that uses MO
264 RI++;
265 if (RI == MRI->reg_end())
266 continue;
267 MachineInstr *UseMO = RI->getParent();
268 unsigned LatencyOp = 0;
269 if (UseMO && BlockTrace.isDepInTrace(*Root, *UseMO)) {
270 LatencyOp = TSchedModel.computeOperandLatency(
271 NewRoot,
272 NewRoot->findRegisterDefOperandIdx(MO.getReg(), /*TRI=*/nullptr),
273 UseMO,
274 UseMO->findRegisterUseOperandIdx(MO.getReg(), /*TRI=*/nullptr));
275 } else {
276 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
277 }
278 NewRootLatency = std::max(NewRootLatency, LatencyOp);
279 }
280 return NewRootLatency;
281}
282
283CombinerObjective MachineCombinerImpl::getCombinerObjective(unsigned Pattern) {
284 // TODO: If C++ ever gets a real enum class, make this part of the
285 // MachineCombinerPattern class.
286 switch (Pattern) {
287 case MachineCombinerPattern::REASSOC_AX_BY:
288 case MachineCombinerPattern::REASSOC_AX_YB:
289 case MachineCombinerPattern::REASSOC_XA_BY:
290 case MachineCombinerPattern::REASSOC_XA_YB:
291 return CombinerObjective::MustReduceDepth;
292 default:
293 return TII->getCombinerObjective(Pattern);
294 }
295}
296
297/// Estimate the latency of the new and original instruction sequence by summing
298/// up the latencies of the inserted and deleted instructions. This assumes
299/// that the inserted and deleted instructions are dependent instruction chains,
300/// which might not hold in all cases.
301std::pair<unsigned, unsigned>
302MachineCombinerImpl::getLatenciesForInstrSequences(
303 MachineInstr &MI, SmallVectorImpl<MachineInstr *> &InsInstrs,
304 SmallVectorImpl<MachineInstr *> &DelInstrs,
305 MachineTraceMetrics::Trace BlockTrace) {
306 assert(!InsInstrs.empty() && "Only support sequences that insert instrs.");
307 unsigned NewRootLatency = 0;
308 // NewRoot is the last instruction in the \p InsInstrs vector.
309 MachineInstr *NewRoot = InsInstrs.back();
310 for (unsigned i = 0; i < InsInstrs.size() - 1; i++)
311 NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
312 NewRootLatency += getLatency(&MI, NewRoot, BlockTrace);
313
314 unsigned RootLatency = 0;
315 for (auto *I : DelInstrs)
316 RootLatency += TSchedModel.computeInstrLatency(I);
317
318 return {NewRootLatency, RootLatency};
319}
320
321bool MachineCombinerImpl::reduceRegisterPressure(
322 MachineInstr &Root, MachineBasicBlock *MBB,
323 SmallVectorImpl<MachineInstr *> &InsInstrs,
324 SmallVectorImpl<MachineInstr *> &DelInstrs, unsigned Pattern) {
325 // FIXME: for now, we don't do any check for the register pressure patterns.
326 // We treat them as always profitable. But we can do better if we make
327 // RegPressureTracker class be aware of TIE attribute. Then we can get an
328 // accurate compare of register pressure with DelInstrs or InsInstrs.
329 return true;
330}
331
332/// The DAGCombine code sequence ends in MI (Machine Instruction) Root.
333/// The new code sequence ends in MI NewRoot. A necessary condition for the new
334/// sequence to replace the old sequence is that it cannot lengthen the critical
335/// path. The definition of "improve" may be restricted by specifying that the
336/// new path improves the data dependency chain (MustReduceDepth).
337bool MachineCombinerImpl::improvesCriticalPathLen(
338 MachineBasicBlock *MBB, MachineInstr *Root,
340 SmallVectorImpl<MachineInstr *> &InsInstrs,
341 SmallVectorImpl<MachineInstr *> &DelInstrs,
342 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned Pattern,
343 bool SlackIsAccurate) {
344 // Get depth and latency of NewRoot and Root.
345 unsigned NewRootDepth =
346 getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace, *MBB);
347 unsigned RootDepth = BlockTrace.getInstrCycles(*Root).Depth;
348
349 LLVM_DEBUG(dbgs() << " Dependence data for " << *Root << "\tNewRootDepth: "
350 << NewRootDepth << "\tRootDepth: " << RootDepth);
351
352 // For a transform such as reassociation, the cost equation is
353 // conservatively calculated so that we must improve the depth (data
354 // dependency cycles) in the critical path to proceed with the transform.
355 // Being conservative also protects against inaccuracies in the underlying
356 // machine trace metrics and CPU models.
357 if (getCombinerObjective(Pattern) == CombinerObjective::MustReduceDepth) {
358 LLVM_DEBUG(dbgs() << "\tIt MustReduceDepth ");
359 LLVM_DEBUG(NewRootDepth < RootDepth
360 ? dbgs() << "\t and it does it\n"
361 : dbgs() << "\t but it does NOT do it\n");
362 return NewRootDepth < RootDepth;
363 }
364
365 // A more flexible cost calculation for the critical path includes the slack
366 // of the original code sequence. This may allow the transform to proceed
367 // even if the instruction depths (data dependency cycles) become worse.
368
369 // Account for the latency of the inserted and deleted instructions by
370 unsigned NewRootLatency, RootLatency;
371 if (TII->accumulateInstrSeqToRootLatency(*Root)) {
372 std::tie(NewRootLatency, RootLatency) =
373 getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
374 } else {
375 NewRootLatency = TSchedModel.computeInstrLatency(InsInstrs.back());
376 RootLatency = TSchedModel.computeInstrLatency(Root);
377 }
378
379 unsigned RootSlack = BlockTrace.getInstrSlack(*Root);
380 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
381 unsigned OldCycleCount =
382 RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
383 LLVM_DEBUG(dbgs() << "\n\tNewRootLatency: " << NewRootLatency
384 << "\tRootLatency: " << RootLatency << "\n\tRootSlack: "
385 << RootSlack << " SlackIsAccurate=" << SlackIsAccurate
386 << "\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
387 << "\n\tRootDepth + RootLatency + RootSlack = "
388 << OldCycleCount);
389 LLVM_DEBUG(NewCycleCount <= OldCycleCount
390 ? dbgs() << "\n\t It IMPROVES PathLen because"
391 : dbgs() << "\n\t It DOES NOT improve PathLen because");
392 LLVM_DEBUG(dbgs() << "\n\t\tNewCycleCount = " << NewCycleCount
393 << ", OldCycleCount = " << OldCycleCount << "\n");
394
395 return NewCycleCount <= OldCycleCount;
396}
397
398/// helper routine to convert instructions into SC
399void MachineCombinerImpl::instr2instrSC(
400 SmallVectorImpl<MachineInstr *> &Instrs,
401 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
402 for (auto *InstrPtr : Instrs) {
403 unsigned Opc = InstrPtr->getOpcode();
404 unsigned Idx = TII->get(Opc).getSchedClass();
405 const MCSchedClassDesc *SC = SchedModel.getSchedClassDesc(Idx);
406 InstrsSC.push_back(SC);
407 }
408}
409
410/// True when the new instructions do not increase resource length
411bool MachineCombinerImpl::preservesResourceLen(
412 MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
413 SmallVectorImpl<MachineInstr *> &InsInstrs,
414 SmallVectorImpl<MachineInstr *> &DelInstrs) {
415 if (!TSchedModel.hasInstrSchedModel())
416 return true;
417
418 // Compute current resource length
419
420 // ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
422 MBBarr.push_back(MBB);
423 unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
424
425 // Deal with SC rather than Instructions.
428
429 instr2instrSC(InsInstrs, InsInstrsSC);
430 instr2instrSC(DelInstrs, DelInstrsSC);
431
432 ArrayRef<const MCSchedClassDesc *> MSCInsArr{InsInstrsSC};
433 ArrayRef<const MCSchedClassDesc *> MSCDelArr{DelInstrsSC};
434
435 // Compute new resource length.
436 unsigned ResLenAfterCombine =
437 BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
438
439 LLVM_DEBUG(dbgs() << "\t\tResource length before replacement: "
440 << ResLenBeforeCombine
441 << " and after: " << ResLenAfterCombine << "\n");
443 ResLenAfterCombine <=
444 ResLenBeforeCombine + TII->getExtendResourceLenLimit()
445 ? dbgs() << "\t\t As result it IMPROVES/PRESERVES Resource Length\n"
446 : dbgs() << "\t\t As result it DOES NOT improve/preserve Resource "
447 "Length\n");
448
449 return ResLenAfterCombine <=
450 ResLenBeforeCombine + TII->getExtendResourceLenLimit();
451}
452
453/// Inserts InsInstrs and deletes DelInstrs. Incrementally updates instruction
454/// depths if requested.
455///
456/// \param MBB basic block to insert instructions in
457/// \param MI current machine instruction
458/// \param InsInstrs new instructions to insert in \p MBB
459/// \param DelInstrs instruction to delete from \p MBB
460/// \param TraceEnsemble is a pointer to the machine trace information
461/// \param RegUnits set of live registers, needed to compute instruction depths
462/// \param TII is target instruction info, used to call target hook
463/// \param Pattern is used to call target hook finalizeInsInstrs
464/// \param IncrementalUpdate if true, compute instruction depths incrementally,
465/// otherwise invalidate the trace
466static void
470 MachineTraceMetrics::Ensemble *TraceEnsemble,
471 LiveRegUnitSet &RegUnits, const TargetInstrInfo *TII,
472 unsigned Pattern, bool IncrementalUpdate) {
473 // If we want to fix up some placeholder for some target, do it now.
474 // We need this because in genAlternativeCodeSequence, we have not decided the
475 // better pattern InsInstrs or DelInstrs, so we don't want generate some
476 // sideeffect to the function. For example we need to delay the constant pool
477 // entry creation here after InsInstrs is selected as better pattern.
478 // Otherwise the constant pool entry created for InsInstrs will not be deleted
479 // even if InsInstrs is not the better pattern.
480 TII->finalizeInsInstrs(MI, Pattern, InsInstrs);
481
483 // Moved links are emitted at MI, so physical registers they read stay live
484 // past the instructions they move over.
485 assert(!DelInstrs.empty() && DelInstrs.back() == &MI &&
486 "expected moved chain ending at root");
487 const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
488 SmallSet<Register, 2> PhysUses;
489 auto NextDel = DelInstrs.begin();
490 for (MachineInstr &I :
491 llvm::make_range((*NextDel)->getIterator(), MI.getIterator())) {
492 if (&I == *NextDel) {
493 ++NextDel;
494 for (const MachineOperand &MO : I.all_uses())
495 if (MO.getReg().isPhysical() && !MO.isUndef())
496 PhysUses.insert(MO.getReg());
497 continue;
498 }
499 if (I.isDebugInstr())
500 continue;
501 for (Register Reg : PhysUses)
502 I.clearRegisterKills(Reg, TRI);
503 }
504 assert(NextDel == std::prev(DelInstrs.end()) &&
505 "expected deleted chain in block order");
506 }
507
508 for (auto *InstrPtr : InsInstrs)
509 MBB->insert((MachineBasicBlock::iterator)&MI, InstrPtr);
510
511 for (auto *InstrPtr : DelInstrs) {
512 InstrPtr->eraseFromParent();
513 // Erase all LiveRegs defined by the removed instruction
514 for (auto *I = RegUnits.begin(); I != RegUnits.end();) {
515 if (I->MI == InstrPtr)
516 I = RegUnits.erase(I);
517 else
518 I++;
519 }
520 }
521
522 if (IncrementalUpdate)
523 for (auto *InstrPtr : InsInstrs)
524 TraceEnsemble->updateDepth(MBB, *InstrPtr, RegUnits);
525 else
526 TraceEnsemble->invalidate(MBB);
527
528 NumInstCombined++;
529}
530
531/// Substitute a slow code sequence with a faster one by
532/// evaluating instruction combining pattern.
533/// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
534/// combining based on machine trace metrics. Only combine a sequence of
535/// instructions when this neither lengthens the critical path nor increases
536/// resource pressure. When optimizing for codesize always combine when the new
537/// sequence is shorter.
538bool MachineCombinerImpl::combineInstructions(MachineBasicBlock *MBB) {
539 bool Changed = false;
540 LLVM_DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
541
542 bool IncrementalUpdate = false;
543 auto BlockIter = MBB->begin();
544 decltype(BlockIter) LastUpdate;
545 // Check if the block is in a loop.
546 const MachineLoop *ML = MLI->getLoopFor(MBB);
547 if (!TraceEnsemble)
548 TraceEnsemble = Traces->getEnsemble(TII->getMachineCombinerTraceStrategy());
549
550 LiveRegUnitSet RegUnits;
551 RegUnits.setUniverse(TRI->getNumRegUnits());
552
553 bool OptForSize = llvm::shouldOptimizeForSize(MBB, PSI, MBFI);
554
555 bool DoRegPressureReduce =
556 TII->shouldReduceRegisterPressure(MBB, RegClassInfo);
557
558 // A fused multiply-add may end an FP accumulation chain, so revisit it. The
559 // block resources are cached apart from the trace and are recomputed unless
560 // the trace is updated incrementally, which keeps large blocks linear.
561 auto RevisitFusedFMA = [&](MachineInstr &NewRoot) {
562 if (!NewRoot.getFlag(MachineInstr::MIFlag::FmReassoc) ||
563 !NewRoot.getFlag(MachineInstr::MIFlag::FmNsz))
564 return;
565 std::optional<TargetInstrInfo::FMAChainLinkInfo> Info =
566 TII->getFMAChainLinkInfo(NewRoot);
567 if (!Info || !Info->isFused())
568 return;
569 BlockIter = NewRoot.getIterator();
570 if (!IncrementalUpdate)
571 Traces->invalidate(MBB);
572 };
573
574 while (BlockIter != MBB->end()) {
575 auto &MI = *BlockIter++;
576 SmallVector<unsigned, 16> Patterns;
577 // The motivating example is:
578 //
579 // MUL Other MUL_op1 MUL_op2 Other
580 // \ / \ | /
581 // ADD/SUB => MADD/MSUB
582 // (=Root) (=NewRoot)
583
584 // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
585 // usually beneficial for code size it unfortunately can hurt performance
586 // when the ADD is on the critical path, but the MUL is not. With the
587 // substitution the MUL becomes part of the critical path (in form of the
588 // MADD) and can lengthen it on architectures where the MADD latency is
589 // longer than the ADD latency.
590 //
591 // For each instruction we check if it can be the root of a combiner
592 // pattern. Then for each pattern the new code sequence in form of MI is
593 // generated and evaluated. When the efficiency criteria (don't lengthen
594 // critical path, don't use more resources) is met the new sequence gets
595 // hooked up into the basic block before the old sequence is removed.
596 //
597 // The algorithm does not try to evaluate all patterns and pick the best.
598 // This is only an artificial restriction though. In practice there is
599 // mostly one pattern, and getMachineCombinerPatterns() can order patterns
600 // based on an internal cost heuristic. If
601 // machine-combiner-verify-pattern-order is enabled, all patterns are
602 // checked to ensure later patterns do not provide better latency savings.
603
604 if (!TII->getMachineCombinerPatterns(MI, Patterns, DoRegPressureReduce))
605 continue;
606
607 // Only used with -machine-combiner-verify-pattern-order.
608 [[maybe_unused]] long PrevLatencyDiff = std::numeric_limits<long>::max();
609
610 for (const auto P : Patterns) {
613 DenseMap<Register, unsigned> InstrIdxForVirtReg;
614 TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
615 InstrIdxForVirtReg);
616 // Found pattern, but did not generate alternative sequence.
617 // This can happen e.g. when an immediate could not be materialized
618 // in a single instruction.
619 if (InsInstrs.empty())
620 continue;
621
622 LLVM_DEBUG(if (Opts.machine_combiner_dump_subst_intrs) {
623 dbgs() << "\tFor the Pattern (" << (int)P
624 << ") these instructions could be removed\n";
625 for (auto const *InstrPtr : DelInstrs)
626 InstrPtr->print(dbgs(), /*IsStandalone*/false, /*SkipOpers*/false,
627 /*SkipDebugLoc*/false, /*AddNewLine*/true, TII);
628 dbgs() << "\tThese instructions could replace the removed ones\n";
629 for (auto const *InstrPtr : InsInstrs)
630 InstrPtr->print(dbgs(), /*IsStandalone*/false, /*SkipOpers*/false,
631 /*SkipDebugLoc*/false, /*AddNewLine*/true, TII);
632 });
633
634 // Check that the difference between original and new latency is
635 // decreasing for later patterns. This helps to discover sub-optimal
636 // pattern orderings.
637 if (Opts.machine_combiner_verify_pattern_order &&
638 TSchedModel.hasInstrSchedModelOrItineraries()) {
639 auto [NewRootLatency, RootLatency] = getLatenciesForInstrSequences(
640 MI, InsInstrs, DelInstrs, TraceEnsemble->getTrace(MBB));
641 long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
642 assert(CurrentLatencyDiff <= PrevLatencyDiff &&
643 "Current pattern is expected to be better than the previous "
644 "pattern.");
645 PrevLatencyDiff = CurrentLatencyDiff;
646 }
647
648 if (IncrementalUpdate && LastUpdate != BlockIter) {
649 // Update depths since the last incremental update.
650 TraceEnsemble->updateDepths(LastUpdate, BlockIter, RegUnits);
651 LastUpdate = BlockIter;
652 }
653
654 if (DoRegPressureReduce &&
655 getCombinerObjective(P) ==
656 CombinerObjective::MustReduceRegisterPressure) {
658 Opts.machine_combiner_inc_threshold)) {
659 // Use incremental depth updates for basic blocks above threshold
660 IncrementalUpdate = true;
661 LastUpdate = BlockIter;
662 }
663 if (reduceRegisterPressure(MI, MBB, InsInstrs, DelInstrs, P)) {
664 // Replace DelInstrs with InsInstrs.
665 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
666 RegUnits, TII, P, IncrementalUpdate);
667 Changed |= true;
668
669 // Go back to previous instruction as it may have ILP reassociation
670 // opportunity.
671 BlockIter--;
672 break;
673 }
674 }
675
676 if (ML && TII->isThroughputPattern(P)) {
677 LLVM_DEBUG(dbgs() << "\t Replacing due to throughput pattern in loop\n");
678 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
679 RegUnits, TII, P, IncrementalUpdate);
680 RevisitFusedFMA(*InsInstrs.back());
681 // Eagerly stop after the first pattern fires.
682 Changed = true;
683 break;
684 } else if (OptForSize && InsInstrs.size() < DelInstrs.size()) {
685 LLVM_DEBUG(dbgs() << "\t Replacing due to OptForSize ("
686 << InsInstrs.size() << " < "
687 << DelInstrs.size() << ")\n");
688 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
689 RegUnits, TII, P, IncrementalUpdate);
690 // Eagerly stop after the first pattern fires.
691 Changed = true;
692 break;
693 } else {
694 // For big basic blocks, we only compute the full trace the first time
695 // we hit this. We do not invalidate the trace, but instead update the
696 // instruction depths incrementally.
697 // NOTE: Only the instruction depths up to MI are accurate. All other
698 // trace information is not updated.
699 MachineTraceMetrics::Trace BlockTrace = TraceEnsemble->getTrace(MBB);
700 Traces->verifyAnalysis();
701 if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
702 InstrIdxForVirtReg, P,
703 !IncrementalUpdate) &&
704 preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
706 Opts.machine_combiner_inc_threshold)) {
707 // Use incremental depth updates for basic blocks above treshold
708 IncrementalUpdate = true;
709 LastUpdate = BlockIter;
710 }
711
712 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
713 RegUnits, TII, P, IncrementalUpdate);
714 RevisitFusedFMA(*InsInstrs.back());
715
716 // Eagerly stop after the first pattern fires.
717 Changed = true;
718 break;
719 }
720 // Cleanup instructions of the alternative code sequence. There is no
721 // use for them.
723 for (auto *InstrPtr : InsInstrs)
724 MF->deleteMachineInstr(InstrPtr);
725 }
726 InstrIdxForVirtReg.clear();
727 }
728 }
729
730 if (Changed && IncrementalUpdate)
731 Traces->invalidate(MBB);
732 return Changed;
733}
734
735bool MachineCombinerImpl::run(MachineFunction &MF, MachineLoopInfo *MLI,
736 MachineTraceMetrics *Traces,
737 ProfileSummaryInfo *PSI,
738 MachineBlockFrequencyInfo *MBFI,
739 RegisterClassInfo *RegClassInfo) {
740 STI = &MF.getSubtarget();
741 TII = STI->getInstrInfo();
742 TRI = STI->getRegisterInfo();
743 SchedModel = STI->getSchedModel();
744 TSchedModel.init(STI);
745 MRI = &MF.getRegInfo();
746 this->MLI = MLI;
747 this->Traces = Traces;
748 this->PSI = PSI;
749 this->MBFI = MBFI;
750 this->RegClassInfo = RegClassInfo;
751 TraceEnsemble = nullptr;
752
753 LLVM_DEBUG(dbgs() << "Machine InstCombiner: " << MF.getName() << '\n');
754 if (!TII->useMachineCombiner()) {
756 dbgs()
757 << " Skipping pass: Target does not support machine combiner\n");
758 return false;
759 }
760
761 bool Changed = false;
762
763 // Try to combine instructions.
764 for (auto &MBB : MF)
765 Changed |= combineInstructions(&MBB);
766
767 return Changed;
768}
769
770bool MachineCombinerLegacy::runOnMachineFunction(MachineFunction &MF) {
771 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
772 auto *Traces = &getAnalysis<MachineTraceMetricsWrapperPass>().getMTM();
773 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
774 auto *MBFI = (PSI && PSI->hasProfileSummary())
775 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
776 : nullptr;
777 auto &RegClassInfo =
778 getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
779 return MachineCombinerImpl(getCodeGenOptions(MF))
780 .run(MF, MLI, Traces, PSI, MBFI, &RegClassInfo);
781}
782
783PreservedAnalyses
786 MFPropsModifier _(*this, MF);
787 auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
788 auto &Traces = MFAM.getResult<MachineTraceMetricsAnalysis>(MF);
790 .getCachedResult<ProfileSummaryAnalysis>(
791 *MF.getFunction().getParent());
792 auto *MBFI = (PSI && PSI->hasProfileSummary())
794 : nullptr;
795 auto &RegClassInfo = MFAM.getResult<MachineRegisterClassAnalysis>(MF);
796 if (!MachineCombinerImpl(getCodeGenOptions(MF))
797 .run(MF, &MLI, &Traces, PSI, MBFI, &RegClassInfo))
798 return PreservedAnalyses::all();
799
801 PA.preserveSet<CFGAnalyses>();
802 PA.preserve<MachineTraceMetricsAnalysis>();
803 return PA;
804}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, MachineTraceMetrics::Ensemble *TraceEnsemble, LiveRegUnitSet &RegUnits, const TargetInstrInfo *TII, unsigned Pattern, bool IncrementalUpdate)
Inserts InsInstrs and deletes DelInstrs.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Module * getParent()
Get the module that this global value is contained inside of...
bool useMachineCombiner() const override
This is an alternative analysis pass to MachineBlockFrequencyInfo.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
An RAII based helper class to modify MachineFunctionProperties when running pass.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI bool sizeWithoutDebugLargerThan(unsigned Limit) const
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
LLVM_ABI int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
bool isTransient() const
Return true if this is a transient instruction that is either very likely to be eliminated during reg...
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static reg_iterator reg_end()
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
reg_iterator reg_begin(Register RegNo) const
defusechain_iterator< true, true, false, true, false > reg_iterator
reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified register.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
A trace ensemble is a collection of traces selected using the same strategy, for example 'minimum res...
void invalidate(const MachineBasicBlock *MBB)
Invalidate traces through BadMBB.
void updateDepth(TraceBlockInfo &TBI, const MachineInstr &, LiveRegUnitSet &RegUnits)
Updates the depth of an machine instruction, given RegUnits.
void updateDepths(MachineBasicBlock::iterator Start, MachineBasicBlock::iterator End, LiveRegUnitSet &RegUnits)
Updates the depth of the instructions from Start to End.
Trace getTrace(const MachineBasicBlock *MBB)
Get the trace that passes through MBB.
LLVM_ABI unsigned getResourceLength(ArrayRef< const MachineBasicBlock * > Extrablocks={}, ArrayRef< const MCSchedClassDesc * > ExtraInstrs={}, ArrayRef< const MCSchedClassDesc * > RemoveInstrs={}) const
Return the resource length of the trace.
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
LLVM_ABI unsigned getInstrSlack(const MachineInstr &MI) const
Return the slack of MI.
LLVM_ABI bool isDepInTrace(const MachineInstr &DefMI, const MachineInstr &UseMI) const
A dependence is useful if the basic block of the defining instruction is part of the trace of the use...
LLVM_ABI Ensemble * getEnsemble(MachineTraceStrategy)
Get the trace ensemble representing the given trace selection strategy.
LLVM_ABI void verifyAnalysis() const
LLVM_ABI void invalidate(const MachineBasicBlock *MBB)
Invalidate cached information about MBB.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
Definition SparseSet.h:288
const_iterator begin() const
Definition SparseSet.h:171
const_iterator end() const
Definition SparseSet.h:172
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
Definition SparseSet.h:153
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
LLVM_ABI unsigned computeOperandLatency(const MachineInstr *DefMI, unsigned DefOperIdx, const MachineInstr *UseMI, unsigned UseOperIdx) const
Compute operand latency based on the available machine model.
bool hasInstrSchedModelOrItineraries() const
Return true if this machine model includes an instruction-level scheduling model or cycle-to-cycle it...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & MachineCombinerID
This pass performs instruction combining using trace metrics to estimate critical-path and resource d...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
SparseSet< LiveRegUnit, MCRegUnit, MCRegUnitToIndex > LiveRegUnitSet
ArrayRef(const T &OneElt) -> ArrayRef< T >
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:268
const MCSchedClassDesc * getSchedClassDesc(unsigned SchedClassIdx) const
Definition MCSchedule.h:376
unsigned Depth
Earliest issue cycle as determined by data dependencies and instruction latencies from the beginning ...