LLVM 24.0.0git
MachineSink.cpp
Go to the documentation of this file.
1//===- MachineSink.cpp - Sinking for machine instructions -----------------===//
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// This pass moves instructions into successor blocks when possible, so that
10// they aren't executed on paths where their results aren't needed.
11//
12// This pass is not intended to be a replacement or a complete alternative
13// for an LLVM-IR-level sinking pass. It is only designed to sink simple
14// constructs that are not exposed before lowering and instruction selection.
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
28#include "llvm/Analysis/CFG.h"
52#include "llvm/IR/BasicBlock.h"
54#include "llvm/IR/LLVMContext.h"
56#include "llvm/Pass.h"
59#include "llvm/Support/Debug.h"
61#include <cassert>
62#include <cstdint>
63#include <utility>
64#include <vector>
65
66using namespace llvm;
67
68#define DEBUG_TYPE "machine-sink"
69
70static cl::opt<bool>
71 SplitEdges("machine-sink-split",
72 cl::desc("Split critical edges during machine sinking"),
73 cl::init(true), cl::Hidden);
74
76 "machine-sink-bfi",
77 cl::desc("Use block frequency info to find successors to sink"),
78 cl::init(true), cl::Hidden);
79
81 "machine-sink-split-probability-threshold",
83 "Percentage threshold for splitting single-instruction critical edge. "
84 "If the branch threshold is higher than this threshold, we allow "
85 "speculative execution of up to 1 instruction to avoid branching to "
86 "splitted critical edge"),
87 cl::init(40), cl::Hidden);
88
90 "machine-sink-load-instrs-threshold",
91 cl::desc("Do not try to find alias store for a load if there is a in-path "
92 "block whose instruction number is higher than this threshold."),
93 cl::init(2000), cl::Hidden);
94
96 "machine-sink-load-blocks-threshold",
97 cl::desc("Do not try to find alias store for a load if the block number in "
98 "the straight line is higher than this threshold."),
99 cl::init(20), cl::Hidden);
100
101static cl::opt<bool>
102 SinkInstsIntoCycle("sink-insts-to-avoid-spills",
103 cl::desc("Sink instructions into cycles to avoid "
104 "register spills"),
105 cl::init(false), cl::Hidden);
106
108 "machine-sink-cycle-limit",
109 cl::desc(
110 "The maximum number of instructions considered for cycle sinking."),
111 cl::init(50), cl::Hidden);
112
113STATISTIC(NumSunk, "Number of machine instructions sunk");
114STATISTIC(NumCycleSunk, "Number of machine instructions sunk into a cycle");
115STATISTIC(NumSplit, "Number of critical edges split");
116STATISTIC(NumCoalesces, "Number of copies coalesced");
117STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
118
120
121namespace {
122
123class MachineSinking {
124 const TargetSubtargetInfo *STI = nullptr;
125 const TargetInstrInfo *TII = nullptr;
126 const TargetRegisterInfo *TRI = nullptr;
127 MachineRegisterInfo *MRI = nullptr; // Machine register information
128 MachineDominatorTree *DT = nullptr; // Machine dominator tree
129 MachinePostDominatorTree *PDT = nullptr; // Machine post dominator tree
130 MachineCycleInfo *CI = nullptr;
131 ProfileSummaryInfo *PSI = nullptr;
132 MachineBlockFrequencyInfo *MBFI = nullptr;
133 const MachineBranchProbabilityInfo *MBPI = nullptr;
134 AliasAnalysis *AA = nullptr;
135 RegisterClassInfo *RegClassInfo = nullptr;
136 TargetSchedModel SchedModel;
137 // Required for split critical edge
138 MachineLoopInfo *MLI;
139
140 // Remember which edges have been considered for breaking.
142 CEBCandidates;
143 // Memorize the register that also wanted to sink into the same block along
144 // a different critical edge.
145 // {register to sink, sink-to block} -> the first sink-from block.
146 // We're recording the first sink-from block because that (critical) edge
147 // was deferred until we see another register that's going to sink into the
148 // same block.
150 CEMergeCandidates;
151 // Remember which edges we are about to split.
152 // This is different from CEBCandidates since those edges
153 // will be split.
155
156
157 using AllSuccsCache =
159
160 /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
161 /// post-dominated by another DBG_VALUE of the same variable location.
162 /// This is necessary to detect sequences such as:
163 /// %0 = someinst
164 /// DBG_VALUE %0, !123, !DIExpression()
165 /// %1 = anotherinst
166 /// DBG_VALUE %1, !123, !DIExpression()
167 /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
168 /// would re-order assignments.
169 using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
170
171 using SinkItem = std::pair<MachineInstr *, MachineBasicBlock *>;
172
173 /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
174 /// debug instructions to sink.
176
177 /// Record of debug variables that have had their locations set in the
178 /// current block.
179 DenseSet<DebugVariable> SeenDbgVars;
180
182 HasStoreCache;
183
186 StoreInstrCache;
187
188 /// Cached BB's register pressure.
190 CachedRegisterPressure;
191
192 bool EnableSinkAndFold;
193
194public:
195 MachineSinking(bool EnableSinkAndFold, MachineDominatorTree *DT,
200 RegisterClassInfo *RegClassInfo)
201 : DT(DT), PDT(PDT), CI(CI), PSI(PSI), MBFI(MBFI), MBPI(MBPI), AA(AA),
202 RegClassInfo(RegClassInfo), MLI(MLI),
203 EnableSinkAndFold(EnableSinkAndFold) {}
204
205 bool run(MachineFunction &MF);
206
207 void releaseMemory() {
208 CEBCandidates.clear();
209 CEMergeCandidates.clear();
210 }
211
212private:
214 void ProcessDbgInst(MachineInstr &MI);
215 bool isLegalToBreakCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
216 MachineBasicBlock *To, bool BreakPHIEdge);
217 bool isWorthBreakingCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
219 MachineBasicBlock *&DeferredFromBlock);
220
221 bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
223
224 /// Postpone the splitting of the given critical
225 /// edge (\p From, \p To).
226 ///
227 /// We do not split the edges on the fly. Indeed, this invalidates
228 /// the dominance information and thus triggers a lot of updates
229 /// of that information underneath.
230 /// Instead, we postpone all the splits after each iteration of
231 /// the main loop. That way, the information is at least valid
232 /// for the lifetime of an iteration.
233 ///
234 /// \return True if the edge is marked as toSplit, false otherwise.
235 /// False can be returned if, for instance, this is not profitable.
236 bool PostponeSplitCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
237 MachineBasicBlock *To, bool BreakPHIEdge);
238 bool SinkInstruction(MachineInstr &MI, bool &SawStore,
239 AllSuccsCache &AllSuccessors);
240
241 /// If we sink a COPY inst, some debug users of it's destination may no
242 /// longer be dominated by the COPY, and will eventually be dropped.
243 /// This is easily rectified by forwarding the non-dominated debug uses
244 /// to the copy source.
245 void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
246 MachineBasicBlock *TargetBlock);
247 bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
248 MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
249 bool &LocalUse) const;
251 bool &BreakPHIEdge,
252 AllSuccsCache &AllSuccessors);
253
254 void FindCycleSinkCandidates(CycleRef Cycle, MachineBasicBlock *BB,
256
257 bool
258 aggressivelySinkIntoCycle(CycleRef Cycle, MachineInstr &I,
260
261 bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
263 MachineBasicBlock *SuccToSinkTo,
264 AllSuccsCache &AllSuccessors);
265
266 bool PerformTrivialForwardCoalescing(MachineInstr &MI,
268
269 bool PerformSinkAndFold(MachineInstr &MI, MachineBasicBlock *MBB);
270
272 GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
273 AllSuccsCache &AllSuccessors) const;
274
275 std::vector<unsigned> &getBBRegisterPressure(const MachineBasicBlock &MBB,
276 bool UseCache = true);
277
278 bool registerPressureSetExceedsLimit(unsigned NRegs,
279 const TargetRegisterClass *RC,
280 const MachineBasicBlock &MBB);
281
282 bool registerPressureExceedsLimit(const MachineBasicBlock &MBB);
283};
284
285class MachineSinkingLegacy : public MachineFunctionPass {
286public:
287 static char ID;
288
289 MachineSinkingLegacy() : MachineFunctionPass(ID) {}
290
291 bool runOnMachineFunction(MachineFunction &MF) override;
292
293 void getAnalysisUsage(AnalysisUsage &AU) const override {
305 if (UseBlockFreqInfo) {
308 }
310 }
311};
312
313} // end anonymous namespace
314
315char MachineSinkingLegacy::ID = 0;
316
317char &llvm::MachineSinkingLegacyID = MachineSinkingLegacy::ID;
318
319INITIALIZE_PASS_BEGIN(MachineSinkingLegacy, DEBUG_TYPE, "Machine code sinking",
320 false, false)
327INITIALIZE_PASS_END(MachineSinkingLegacy, DEBUG_TYPE, "Machine code sinking",
329
330/// Return true if a target defined block prologue instruction interferes
331/// with a sink candidate.
338 for (MachineBasicBlock::const_iterator PI = BB->getFirstNonPHI(); PI != End;
339 ++PI) {
340 // Only check target defined prologue instructions
341 if (!TII->isBasicBlockPrologue(*PI))
342 continue;
343 for (auto &MO : MI.operands()) {
344 if (!MO.isReg())
345 continue;
346 Register Reg = MO.getReg();
347 if (!Reg)
348 continue;
349 if (MO.isUse()) {
350 if (Reg.isPhysical() &&
351 (TII->isIgnorableUse(MI, MI.getOperandNo(&MO)) ||
352 (MRI && MRI->isConstantPhysReg(Reg))))
353 continue;
354 if (PI->modifiesRegister(Reg, TRI))
355 return true;
356 } else {
357 if (PI->readsRegister(Reg, TRI))
358 return true;
359 // Check for interference with non-dead defs
360 auto *DefOp = PI->findRegisterDefOperand(Reg, TRI, false, true);
361 if (DefOp && !DefOp->isDead())
362 return true;
363 }
364 }
365 }
366
367 return false;
368}
369
370bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
372 if (!MI.isCopy())
373 return false;
374
375 Register SrcReg = MI.getOperand(1).getReg();
376 Register DstReg = MI.getOperand(0).getReg();
377 if (!SrcReg.isVirtual() || !DstReg.isVirtual() ||
378 !MRI->hasOneNonDBGUse(SrcReg))
379 return false;
380
381 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
382 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
383 if (SRC != DRC)
384 return false;
385
386 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
387 if (!DefMI || DefMI->isCopyLike())
388 return false;
389 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
390 LLVM_DEBUG(dbgs() << "*** to: " << MI);
391 MRI->replaceRegWith(DstReg, SrcReg);
392 MI.eraseFromParent();
393
394 ++NumCoalesces;
395 return true;
396}
397
398bool MachineSinking::PerformSinkAndFold(MachineInstr &MI,
399 MachineBasicBlock *MBB) {
400 if (MI.isCopy() || MI.mayLoadOrStore() ||
401 MI.getOpcode() == TargetOpcode::REG_SEQUENCE)
402 return false;
403
404 // Don't sink instructions that the target prefers not to sink.
405 if (!TII->shouldSink(MI))
406 return false;
407
408 // Check if it's safe to move the instruction.
409 bool SawStore = true;
410 if (!MI.isSafeToMove(SawStore))
411 return false;
412
413 // Convergent operations may not be made control-dependent on additional
414 // values.
415 if (MI.isConvergent())
416 return false;
417
418 // Don't sink defs/uses of hard registers or if the instruction defines more
419 // than one register.
420 // Don't sink more than two register uses - it'll cover most of the cases and
421 // greatly simplifies the register pressure checks.
422 Register DefReg;
423 Register UsedRegA, UsedRegB;
424 for (const MachineOperand &MO : MI.operands()) {
425 if (MO.isImm() || MO.isRegMask() || MO.isRegLiveOut() || MO.isMetadata() ||
426 MO.isMCSymbol() || MO.isDbgInstrRef() || MO.isCFIIndex() ||
427 MO.isIntrinsicID() || MO.isPredicate() || MO.isShuffleMask())
428 continue;
429 if (!MO.isReg())
430 return false;
431
432 Register Reg = MO.getReg();
433 if (Reg == 0)
434 continue;
435
436 if (Reg.isVirtual()) {
437 if (MO.isDef()) {
438 if (DefReg)
439 return false;
440 DefReg = Reg;
441 continue;
442 }
443
444 if (UsedRegA == 0)
445 UsedRegA = Reg;
446 else if (UsedRegB == 0)
447 UsedRegB = Reg;
448 else
449 return false;
450 continue;
451 }
452
453 if (Reg.isPhysical() && MO.isUse() &&
455 TII->isIgnorableUse(MI, MI.getOperandNo(&MO))))
456 continue;
457
458 return false;
459 }
460
461 // Scan uses of the destination register. Every use, except the last, must be
462 // a copy, with a chain of copies terminating with either a copy into a hard
463 // register, or a load/store instruction where the use is part of the
464 // address (*not* the stored value).
465 using SinkInfo = std::pair<MachineInstr *, ExtAddrMode>;
466 SmallVector<SinkInfo> SinkInto;
467 SmallVector<Register> Worklist;
468
469 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
470 const TargetRegisterClass *RCA =
471 UsedRegA == 0 ? nullptr : MRI->getRegClass(UsedRegA);
472 const TargetRegisterClass *RCB =
473 UsedRegB == 0 ? nullptr : MRI->getRegClass(UsedRegB);
474
475 Worklist.push_back(DefReg);
476 while (!Worklist.empty()) {
477 Register Reg = Worklist.pop_back_val();
478
479 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
480 ExtAddrMode MaybeAM;
481 MachineInstr &UseInst = *MO.getParent();
482 if (UseInst.isCopy()) {
483 Register DstReg;
484 if (const MachineOperand &O = UseInst.getOperand(0); O.isReg())
485 DstReg = O.getReg();
486 if (DstReg == 0)
487 return false;
488 if (DstReg.isVirtual()) {
489 Worklist.push_back(DstReg);
490 continue;
491 }
492 // If we are going to replace a copy, the original instruction must be
493 // as cheap as a copy.
494 if (!TII->isAsCheapAsAMove(MI))
495 return false;
496 // The hard register must be in the register class of the original
497 // instruction's destination register.
498 if (!RC->contains(DstReg))
499 return false;
500 } else if (UseInst.mayLoadOrStore()) {
501 // If the destination instruction contains more than one use of the
502 // register, we won't be able to remove the original instruction, so
503 // don't sink.
504 if (llvm::count_if(UseInst.operands(), [Reg](const MachineOperand &MO) {
505 return MO.isReg() && MO.getReg() == Reg;
506 }) > 1)
507 return false;
508 ExtAddrMode AM;
509 if (!TII->canFoldIntoAddrMode(UseInst, Reg, MI, AM))
510 return false;
511 MaybeAM = AM;
512 } else {
513 return false;
514 }
515
516 if (UseInst.getParent() != MI.getParent()) {
517 // If the register class of the register we are replacing is a superset
518 // of any of the register classes of the operands of the materialized
519 // instruction don't consider that live range extended.
520 const TargetRegisterClass *RCS = MRI->getRegClass(Reg);
521 if (RCA && RCA->hasSuperClassEq(RCS))
522 RCA = nullptr;
523 else if (RCB && RCB->hasSuperClassEq(RCS))
524 RCB = nullptr;
525 if (RCA || RCB) {
526 if (RCA == nullptr) {
527 RCA = RCB;
528 RCB = nullptr;
529 }
530
531 unsigned NRegs = !!RCA + !!RCB;
532 if (RCA == RCB)
533 RCB = nullptr;
534
535 // Check we don't exceed register pressure at the destination.
536 const MachineBasicBlock &MBB = *UseInst.getParent();
537 if (RCB == nullptr) {
538 if (registerPressureSetExceedsLimit(NRegs, RCA, MBB))
539 return false;
540 } else if (registerPressureSetExceedsLimit(1, RCA, MBB) ||
541 registerPressureSetExceedsLimit(1, RCB, MBB)) {
542 return false;
543 }
544 }
545 }
546
547 SinkInto.emplace_back(&UseInst, MaybeAM);
548 }
549 }
550
551 if (SinkInto.empty())
552 return false;
553
554 // Now we know we can fold the instruction in all its users.
555 for (auto &[SinkDst, MaybeAM] : SinkInto) {
556 MachineInstr *New = nullptr;
557 LLVM_DEBUG(dbgs() << "Sinking copy of"; MI.dump(); dbgs() << "into";
558 SinkDst->dump());
559 if (SinkDst->isCopy()) {
560 // TODO: After performing the sink-and-fold, the original instruction is
561 // deleted. Its value is still available (in a hard register), so if there
562 // are debug instructions which refer to the (now deleted) virtual
563 // register they could be updated to refer to the hard register, in
564 // principle. However, it's not clear how to do that, moreover in some
565 // cases the debug instructions may need to be replicated proportionally
566 // to the number of the COPY instructions replaced and in some extreme
567 // cases we can end up with quadratic increase in the number of debug
568 // instructions.
569
570 // Sink a copy of the instruction, replacing a COPY instruction.
571 MachineBasicBlock::iterator InsertPt = SinkDst->getIterator();
572 Register DstReg = SinkDst->getOperand(0).getReg();
573 TII->reMaterialize(*SinkDst->getParent(), InsertPt, DstReg, 0, MI);
574 New = &*std::prev(InsertPt);
575 if (!New->getDebugLoc())
576 New->setDebugLoc(SinkDst->getDebugLoc());
577 } else {
578 // Fold instruction into the addressing mode of a memory instruction.
579 New = TII->emitLdStWithAddr(*SinkDst, MaybeAM);
580 }
581 LLVM_DEBUG(dbgs() << "yielding"; New->dump());
582 // Clear the StoreInstrCache, since we may invalidate it by erasing.
583 if (SinkDst->mayStore() && !SinkDst->hasOrderedMemoryRef())
584 StoreInstrCache.clear();
585 SinkDst->eraseFromParent();
586 }
587
588 // Collect operands that need to be cleaned up because the registers no longer
589 // exist (in COPYs and debug instructions). We cannot delete instructions or
590 // clear operands while traversing register uses.
592 Worklist.push_back(DefReg);
593 while (!Worklist.empty()) {
594 Register Reg = Worklist.pop_back_val();
595 for (MachineOperand &MO : MRI->use_operands(Reg)) {
596 MachineInstr *U = MO.getParent();
597 assert((U->isCopy() || U->isDebugInstr()) &&
598 "Only debug uses and copies must remain");
599 if (U->isCopy())
600 Worklist.push_back(U->getOperand(0).getReg());
601 Cleanup.push_back(&MO);
602 }
603 }
604
605 // Delete the dead COPYs and clear operands in debug instructions
606 for (MachineOperand *MO : Cleanup) {
607 MachineInstr *I = MO->getParent();
608 if (I->isCopy()) {
609 I->eraseFromParent();
610 } else {
611 MO->setReg(0);
612 MO->setSubReg(0);
613 }
614 }
615
616 MI.eraseFromParent();
617 return true;
618}
619
620/// AllUsesDominatedByBlock - Return true if all uses of the specified register
621/// occur in blocks dominated by the specified block. If any use is in the
622/// definition block, then return false since it is never legal to move def
623/// after uses.
624bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
625 MachineBasicBlock *MBB,
626 MachineBasicBlock *DefMBB,
627 bool &BreakPHIEdge,
628 bool &LocalUse) const {
629 assert(Reg.isVirtual() && "Only makes sense for vregs");
630
631 // Ignore debug uses because debug info doesn't affect the code.
632 if (MRI->use_nodbg_empty(Reg))
633 return true;
634
635 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
636 // into and they are all PHI nodes. In this case, machine-sink must break
637 // the critical edge first. e.g.
638 //
639 // %bb.1:
640 // Predecessors according to CFG: %bb.0
641 // ...
642 // %def = DEC64_32r %x, implicit-def dead %eflags
643 // ...
644 // JE_4 <%bb.37>, implicit %eflags
645 // Successors according to CFG: %bb.37 %bb.2
646 //
647 // %bb.2:
648 // %p = PHI %y, %bb.0, %def, %bb.1
649 if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
650 MachineInstr *UseInst = MO.getParent();
651 unsigned OpNo = MO.getOperandNo();
652 MachineBasicBlock *UseBlock = UseInst->getParent();
653 return UseBlock == MBB && UseInst->isPHI() &&
654 UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
655 })) {
656 BreakPHIEdge = true;
657 return true;
658 }
659
660 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
661 // Determine the block of the use.
662 MachineInstr *UseInst = MO.getParent();
663 unsigned OpNo = &MO - &UseInst->getOperand(0);
664 MachineBasicBlock *UseBlock = UseInst->getParent();
665 if (UseInst->isPHI()) {
666 // PHI nodes use the operand in the predecessor block, not the block with
667 // the PHI.
668 UseBlock = UseInst->getOperand(OpNo + 1).getMBB();
669 } else if (UseBlock == DefMBB) {
670 LocalUse = true;
671 return false;
672 }
673
674 // Check that it dominates.
675 if (!DT->dominates(MBB, UseBlock))
676 return false;
677 }
678
679 return true;
680}
681
682/// Return true if this machine instruction loads from global offset table or
683/// constant pool.
685 assert(MI.mayLoad() && "Expected MI that loads!");
686
687 // If we lost memory operands, conservatively assume that the instruction
688 // reads from everything..
689 if (MI.memoperands_empty())
690 return true;
691
692 for (MachineMemOperand *MemOp : MI.memoperands())
693 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
694 if (PSV->isGOT() || PSV->isConstantPool())
695 return true;
696
697 return false;
698}
699
700void MachineSinking::FindCycleSinkCandidates(
701 CycleRef Cycle, MachineBasicBlock *BB,
702 SmallVectorImpl<MachineInstr *> &Candidates) {
703 for (auto &MI : *BB) {
704 LLVM_DEBUG(dbgs() << "CycleSink: Analysing candidate: " << MI);
705 if (MI.isMetaInstruction()) {
706 LLVM_DEBUG(dbgs() << "CycleSink: not sinking meta instruction\n");
707 continue;
708 }
709 if (!TII->shouldSink(MI)) {
710 LLVM_DEBUG(dbgs() << "CycleSink: Instruction not a candidate for this "
711 "target\n");
712 continue;
713 }
714 if (!isCycleInvariant(*CI, Cycle, MI)) {
715 LLVM_DEBUG(dbgs() << "CycleSink: Instruction is not cycle invariant\n");
716 continue;
717 }
718 bool DontMoveAcrossStore = true;
719 if (!MI.isSafeToMove(DontMoveAcrossStore)) {
720 LLVM_DEBUG(dbgs() << "CycleSink: Instruction not safe to move.\n");
721 continue;
722 }
723 if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) {
724 LLVM_DEBUG(dbgs() << "CycleSink: Dont sink GOT or constant pool loads\n");
725 continue;
726 }
727 if (MI.isConvergent())
728 continue;
729
730 const MachineOperand &MO = MI.getOperand(0);
731 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
732 continue;
733 if (!MRI->hasOneDef(MO.getReg()))
734 continue;
735
736 LLVM_DEBUG(dbgs() << "CycleSink: Instruction added as candidate.\n");
737 Candidates.push_back(&MI);
738 }
739}
740
741PreservedAnalyses
744 auto *DT = &MFAM.getResult<MachineDominatorTreeAnalysis>(MF);
745 auto *PDT = &MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
746 auto *CI = &MFAM.getResult<MachineCycleAnalysis>(MF);
748 .getCachedResult<ProfileSummaryAnalysis>(
749 *MF.getFunction().getParent());
750 auto *MBFI = UseBlockFreqInfo
752 : nullptr;
753 auto *MBPI = &MFAM.getResult<MachineBranchProbabilityAnalysis>(MF);
755 .getManager()
756 .getResult<AAManager>(MF.getFunction());
757 auto *MLI = MFAM.getCachedResult<MachineLoopAnalysis>(MF);
758 auto *RegClassInfo = &MFAM.getResult<MachineRegisterClassAnalysis>(MF);
759 MachineSinking Impl(EnableSinkAndFold, DT, PDT, MLI, CI, PSI, MBFI, MBPI, AA,
760 RegClassInfo);
761 bool Changed = Impl.run(MF);
762 if (!Changed)
763 return PreservedAnalyses::all();
765 PA.preserve<MachineCycleAnalysis>();
766 PA.preserve<MachineLoopAnalysis>();
768 PA.preserve<MachineBlockFrequencyAnalysis>();
769 return PA;
770}
771
773 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
774 OS << MapClassName2PassName(name()); // ideally machine-sink
775 if (EnableSinkAndFold)
776 OS << "<enable-sink-fold>";
777}
778
779bool MachineSinkingLegacy::runOnMachineFunction(MachineFunction &MF) {
780 if (skipFunction(MF.getFunction()))
781 return false;
782
783 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
784 bool EnableSinkAndFold = PassConfig->getEnableSinkAndFold();
785
786 auto *DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
787 auto *PDT =
788 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
789 auto *CI = &getAnalysis<MachineCycleInfoWrapperPass>().getCycleInfo();
790 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
791 auto *MBFI =
793 ? &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI()
794 : nullptr;
795 auto *MBPI =
796 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
797 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
798 // Get analyses for split critical edge.
799 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
800 auto *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
801 auto *RegClassInfo =
802 &getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
803
804 MachineSinking Impl(EnableSinkAndFold, DT, PDT, MLI, CI, PSI, MBFI, MBPI, AA,
805 RegClassInfo);
806 return Impl.run(MF);
807}
808
809bool MachineSinking::run(MachineFunction &MF) {
810 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
811
812 STI = &MF.getSubtarget();
813 TII = STI->getInstrInfo();
814 TRI = STI->getRegisterInfo();
815 MRI = &MF.getRegInfo();
816
817 bool EverMadeChange = false;
818
819 while (true) {
820 bool MadeChange = false;
821
822 // Process all basic blocks.
823 CEBCandidates.clear();
824 CEMergeCandidates.clear();
825 ToSplit.clear();
826 for (auto &MBB : MF)
827 MadeChange |= ProcessBlock(MBB);
828
829 // If we have anything we marked as toSplit, split it now.
830 MachineDomTreeUpdater MDTU(DT, PDT,
831 MachineDomTreeUpdater::UpdateStrategy::Lazy);
832 for (const auto &Pair : ToSplit) {
833 auto NewSucc = Pair.first->SplitCriticalEdge(
834 Pair.second, {/*LIS=*/nullptr, /*SI=*/nullptr, MLI}, &MDTU);
835 if (NewSucc != nullptr) {
836 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
837 << printMBBReference(*Pair.first) << " -- "
838 << printMBBReference(*NewSucc) << " -- "
839 << printMBBReference(*Pair.second) << '\n');
840 if (MBFI)
841 MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
842
843 MadeChange = true;
844 ++NumSplit;
845 CI->splitCriticalEdge(Pair.first, Pair.second, NewSucc);
846 } else
847 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
848 }
849 // If this iteration over the code changed anything, keep iterating.
850 if (!MadeChange)
851 break;
852 EverMadeChange = true;
853 }
854
855 if (SinkInstsIntoCycle) {
857 SchedModel.init(STI);
858 bool HasHighPressure;
859
860 DenseMap<SinkItem, MachineInstr *> SunkInstrs;
861
862 enum CycleSinkStage { COPY, LOW_LATENCY, AGGRESSIVE, END };
863 for (unsigned Stage = CycleSinkStage::COPY; Stage != CycleSinkStage::END;
864 ++Stage, SunkInstrs.clear()) {
865 HasHighPressure = false;
866
867 for (auto Cycle : Cycles) {
868 MachineBasicBlock *Preheader = CI->getCyclePreheader(Cycle);
869 if (!Preheader) {
870 LLVM_DEBUG(dbgs() << "CycleSink: Can't find preheader\n");
871 continue;
872 }
873 SmallVector<MachineInstr *, 8> Candidates;
874 FindCycleSinkCandidates(Cycle, Preheader, Candidates);
875
876 unsigned i = 0;
877
878 // Walk the candidates in reverse order so that we start with the use
879 // of a def-use chain, if there is any.
880 // TODO: Sort the candidates using a cost-model.
881 for (MachineInstr *I : llvm::reverse(Candidates)) {
882 // CycleSinkStage::COPY: Sink a limited number of copies
883 if (Stage == CycleSinkStage::COPY) {
884 if (i++ == SinkIntoCycleLimit) {
886 << "CycleSink: Limit reached of instructions to "
887 "be analyzed.");
888 break;
889 }
890
891 if (!I->isCopy())
892 continue;
893 }
894
895 // CycleSinkStage::LOW_LATENCY: sink unlimited number of instructions
896 // which the target specifies as low-latency
897 if (Stage == CycleSinkStage::LOW_LATENCY &&
898 !TII->hasLowDefLatency(SchedModel, *I, 0))
899 continue;
900
901 if (!aggressivelySinkIntoCycle(Cycle, *I, SunkInstrs))
902 continue;
903 EverMadeChange = true;
904 ++NumCycleSunk;
905 }
906
907 // Recalculate the pressure after sinking
908 if (!HasHighPressure)
909 HasHighPressure = registerPressureExceedsLimit(*Preheader);
910 }
911 if (!HasHighPressure)
912 break;
913 }
914 }
915
916 HasStoreCache.clear();
917 StoreInstrCache.clear();
918
919 releaseMemory();
920 return EverMadeChange;
921}
922
923bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
924 if ((!EnableSinkAndFold && MBB.succ_size() <= 1) || MBB.empty())
925 return false;
926
927 // Don't bother sinking code out of unreachable blocks. In addition to being
928 // unprofitable, it can also lead to infinite looping, because in an
929 // unreachable cycle there may be nowhere to stop.
930 if (!DT->isReachableFromEntry(&MBB))
931 return false;
932
933 bool MadeChange = false;
934
935 // Cache all successors, sorted by frequency info and cycle depth.
936 AllSuccsCache AllSuccessors;
937
938 // Walk the basic block bottom-up. Remember if we saw a store.
940 --I;
941 bool ProcessedBegin, SawStore = false;
942 do {
943 MachineInstr &MI = *I; // The instruction to sink.
944
945 // Predecrement I (if it's not begin) so that it isn't invalidated by
946 // sinking.
947 ProcessedBegin = I == MBB.begin();
948 if (!ProcessedBegin)
949 --I;
950
951 if (MI.isDebugOrPseudoInstr() || MI.isFakeUse()) {
952 if (MI.isDebugValue())
953 ProcessDbgInst(MI);
954 continue;
955 }
956
957 if (EnableSinkAndFold && PerformSinkAndFold(MI, &MBB)) {
958 MadeChange = true;
959 continue;
960 }
961
962 // Can't sink anything out of a block that has less than two successors.
963 if (MBB.succ_size() <= 1)
964 continue;
965
966 if (PerformTrivialForwardCoalescing(MI, &MBB)) {
967 MadeChange = true;
968 continue;
969 }
970
971 if (SinkInstruction(MI, SawStore, AllSuccessors)) {
972 ++NumSunk;
973 MadeChange = true;
974 }
975
976 // If we just processed the first instruction in the block, we're done.
977 } while (!ProcessedBegin);
978
979 SeenDbgUsers.clear();
980 SeenDbgVars.clear();
981 // recalculate the bb register pressure after sinking one BB.
982 CachedRegisterPressure.clear();
983 return MadeChange;
984}
985
986void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
987 // When we see DBG_VALUEs for registers, record any vreg it reads, so that
988 // we know what to sink if the vreg def sinks.
989 assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
990
991 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
992 MI.getDebugLoc()->getInlinedAt());
993 bool SeenBefore = SeenDbgVars.contains(Var);
994
995 for (MachineOperand &MO : MI.debug_operands()) {
996 if (MO.isReg() && MO.getReg().isVirtual())
997 SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
998 }
999
1000 // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
1001 SeenDbgVars.insert(Var);
1002}
1003
1004bool MachineSinking::isWorthBreakingCriticalEdge(
1005 MachineInstr &MI, MachineBasicBlock *From, MachineBasicBlock *To,
1006 MachineBasicBlock *&DeferredFromBlock) {
1007 // FIXME: Need much better heuristics.
1008
1009 // If the pass has already considered breaking this edge (during this pass
1010 // through the function), then let's go ahead and break it. This means
1011 // sinking multiple "cheap" instructions into the same block.
1012 if (!CEBCandidates.insert(std::make_pair(From, To)).second)
1013 return true;
1014
1015 if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
1016 return true;
1017
1018 // Check and record the register and the destination block we want to sink
1019 // into. Note that we want to do the following before the next check on branch
1020 // probability. Because we want to record the initial candidate even if it's
1021 // on hot edge, so that other candidates that might not on hot edges can be
1022 // sinked as well.
1023 for (const auto &MO : MI.all_defs()) {
1024 Register Reg = MO.getReg();
1025 if (!Reg)
1026 continue;
1027 Register SrcReg = Reg.isVirtual() ? TRI->lookThruCopyLike(Reg, MRI) : Reg;
1028 auto Key = std::make_pair(SrcReg, To);
1029 auto Res = CEMergeCandidates.try_emplace(Key, From);
1030 // We wanted to sink the same register into the same block, consider it to
1031 // be profitable.
1032 if (!Res.second) {
1033 // Return the source block that was previously held off.
1034 DeferredFromBlock = Res.first->second;
1035 return true;
1036 }
1037 }
1038
1039 if (From->isSuccessor(To) &&
1040 MBPI->getEdgeProbability(From, To) <=
1041 BranchProbability(SplitEdgeProbabilityThreshold, 100))
1042 return true;
1043
1044 // MI is cheap, we probably don't want to break the critical edge for it.
1045 // However, if this would allow some definitions of its source operands
1046 // to be sunk then it's probably worth it.
1047 for (const MachineOperand &MO : MI.all_uses()) {
1048 Register Reg = MO.getReg();
1049 if (Reg == 0)
1050 continue;
1051
1052 // We don't move live definitions of physical registers,
1053 // so sinking their uses won't enable any opportunities.
1054 if (Reg.isPhysical())
1055 continue;
1056
1057 // If this instruction is the only user of a virtual register,
1058 // check if breaking the edge will enable sinking
1059 // both this instruction and the defining instruction.
1060 if (MRI->hasOneNonDBGUse(Reg)) {
1061 // If the definition resides in same MBB,
1062 // claim it's likely we can sink these together.
1063 // If definition resides elsewhere, we aren't
1064 // blocking it from being sunk so don't break the edge.
1065 if (MRI->getDefBlock(Reg) == MI.getParent())
1066 return true;
1067 }
1068 }
1069
1070 // Let the target decide if it's worth breaking this
1071 // critical edge for a "cheap" instruction.
1072 return TII->shouldBreakCriticalEdgeToSink(MI);
1073}
1074
1075bool MachineSinking::isLegalToBreakCriticalEdge(MachineInstr &MI,
1076 MachineBasicBlock *FromBB,
1077 MachineBasicBlock *ToBB,
1078 bool BreakPHIEdge) {
1079 // Avoid breaking back edge. From == To means backedge for single BB cycle.
1080 if (!SplitEdges || FromBB == ToBB || !FromBB->isSuccessor(ToBB))
1081 return false;
1082
1083 CycleRef FromCycle = CI->getCycle(FromBB);
1084 CycleRef ToCycle = CI->getCycle(ToBB);
1085
1086 // Check for backedges of more "complex" cycles.
1087 if (FromCycle == ToCycle && FromCycle &&
1088 (!CI->isReducible(FromCycle) || CI->getHeader(FromCycle) == ToBB))
1089 return false;
1090
1091 // It's not always legal to break critical edges and sink the computation
1092 // to the edge.
1093 //
1094 // %bb.1:
1095 // v1024
1096 // Beq %bb.3
1097 // <fallthrough>
1098 // %bb.2:
1099 // ... no uses of v1024
1100 // <fallthrough>
1101 // %bb.3:
1102 // ...
1103 // = v1024
1104 //
1105 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
1106 //
1107 // %bb.1:
1108 // ...
1109 // Bne %bb.2
1110 // %bb.4:
1111 // v1024 =
1112 // B %bb.3
1113 // %bb.2:
1114 // ... no uses of v1024
1115 // <fallthrough>
1116 // %bb.3:
1117 // ...
1118 // = v1024
1119 //
1120 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
1121 // flow. We need to ensure the new basic block where the computation is
1122 // sunk to dominates all the uses.
1123 // It's only legal to break critical edge and sink the computation to the
1124 // new block if all the predecessors of "To", except for "From", are
1125 // not dominated by "From". Given SSA property, this means these
1126 // predecessors are dominated by "To".
1127 //
1128 // There is no need to do this check if all the uses are PHI nodes. PHI
1129 // sources are only defined on the specific predecessor edges.
1130 if (!BreakPHIEdge) {
1131 for (MachineBasicBlock *Pred : ToBB->predecessors())
1132 if (Pred != FromBB && !DT->dominates(ToBB, Pred))
1133 return false;
1134 }
1135
1136 return true;
1137}
1138
1139bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
1140 MachineBasicBlock *FromBB,
1141 MachineBasicBlock *ToBB,
1142 bool BreakPHIEdge) {
1143 bool Status = false;
1144 MachineBasicBlock *DeferredFromBB = nullptr;
1145 if (isWorthBreakingCriticalEdge(MI, FromBB, ToBB, DeferredFromBB)) {
1146 // If there is a DeferredFromBB, we consider FromBB only if _both_
1147 // of them are legal to split.
1148 if ((!DeferredFromBB ||
1149 ToSplit.count(std::make_pair(DeferredFromBB, ToBB)) ||
1150 isLegalToBreakCriticalEdge(MI, DeferredFromBB, ToBB, BreakPHIEdge)) &&
1151 isLegalToBreakCriticalEdge(MI, FromBB, ToBB, BreakPHIEdge)) {
1152 ToSplit.insert(std::make_pair(FromBB, ToBB));
1153 if (DeferredFromBB)
1154 ToSplit.insert(std::make_pair(DeferredFromBB, ToBB));
1155 Status = true;
1156 }
1157 }
1158
1159 return Status;
1160}
1161
1162std::vector<unsigned> &
1163MachineSinking::getBBRegisterPressure(const MachineBasicBlock &MBB,
1164 bool UseCache) {
1165 // Currently to save compiling time, MBB's register pressure will not change
1166 // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
1167 // register pressure is changed after sinking any instructions into it.
1168 // FIXME: need a accurate and cheap register pressure estiminate model here.
1169
1170 auto RP = CachedRegisterPressure.find(&MBB);
1171 if (UseCache && RP != CachedRegisterPressure.end())
1172 return RP->second;
1173
1174 RegionPressure Pressure;
1175 RegPressureTracker RPTracker(Pressure);
1176
1177 // Initialize the register pressure tracker.
1178 RPTracker.init(MBB.getParent(), RegClassInfo, nullptr, &MBB, MBB.end(),
1179 /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
1180
1182 MIE = MBB.instr_begin();
1183 MII != MIE; --MII) {
1184 const MachineInstr &MI = *std::prev(MII);
1185 if (MI.isDebugOrPseudoInstr())
1186 continue;
1187 RegisterOperands RegOpers;
1188 RegOpers.collect(MI, *TRI, *MRI, false, false);
1189 RPTracker.recedeSkipDebugValues();
1190 assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
1191 RPTracker.recede(RegOpers);
1192 }
1193
1194 RPTracker.closeRegion();
1195
1196 if (RP != CachedRegisterPressure.end()) {
1197 CachedRegisterPressure[&MBB] = RPTracker.getPressure().MaxSetPressure;
1198 return CachedRegisterPressure[&MBB];
1199 }
1200
1201 auto It = CachedRegisterPressure.insert(
1202 std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
1203 return It.first->second;
1204}
1205
1206bool MachineSinking::registerPressureSetExceedsLimit(
1207 unsigned NRegs, const TargetRegisterClass *RC,
1208 const MachineBasicBlock &MBB) {
1209 unsigned Weight = NRegs * TRI->getRegClassWeight(RC).RegWeight;
1210 const int *PS = TRI->getRegClassPressureSets(RC);
1211 std::vector<unsigned> BBRegisterPressure = getBBRegisterPressure(MBB);
1212 for (; *PS != -1; PS++)
1213 if (Weight + BBRegisterPressure[*PS] >=
1214 RegClassInfo->getRegPressureSetLimit(*PS))
1215 return true;
1216 return false;
1217}
1218
1219// Recalculate RP and check if any pressure set exceeds the set limit.
1220bool MachineSinking::registerPressureExceedsLimit(
1221 const MachineBasicBlock &MBB) {
1222 std::vector<unsigned> BBRegisterPressure = getBBRegisterPressure(MBB, false);
1223
1224 for (unsigned PS = 0; PS < BBRegisterPressure.size(); ++PS) {
1225 if (BBRegisterPressure[PS] >= RegClassInfo->getRegPressureSetLimit(PS)) {
1226 return true;
1227 }
1228 }
1229
1230 return false;
1231}
1232
1233/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
1234bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
1235 MachineBasicBlock *MBB,
1236 MachineBasicBlock *SuccToSinkTo,
1237 AllSuccsCache &AllSuccessors) {
1238 assert(SuccToSinkTo && "Invalid SinkTo Candidate BB");
1239
1240 if (MBB == SuccToSinkTo)
1241 return false;
1242
1243 // It is profitable if SuccToSinkTo does not post dominate current block.
1244 if (!PDT->dominates(SuccToSinkTo, MBB))
1245 return true;
1246
1247 // It is profitable to sink an instruction from a deeper cycle to a shallower
1248 // cycle, even if the latter post-dominates the former (PR21115).
1249 if (CI->getCycleDepth(MBB) > CI->getCycleDepth(SuccToSinkTo))
1250 return true;
1251
1252 // Check if only use in post dominated block is PHI instruction.
1253 bool NonPHIUse = false;
1254 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
1255 MachineBasicBlock *UseBlock = UseInst.getParent();
1256 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
1257 NonPHIUse = true;
1258 }
1259 if (!NonPHIUse)
1260 return true;
1261
1262 // If SuccToSinkTo post dominates then also it may be profitable if MI
1263 // can further profitably sinked into another block in next round.
1264 bool BreakPHIEdge = false;
1265 // FIXME - If finding successor is compile time expensive then cache results.
1266 if (MachineBasicBlock *MBB2 =
1267 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
1268 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
1269
1270 CycleRef MCycle = CI->getCycle(MBB);
1271
1272 // If the instruction is not inside a cycle, it is not profitable to sink MI
1273 // to a post dominate block SuccToSinkTo.
1274 if (!MCycle)
1275 return false;
1276
1277 // If this instruction is inside a Cycle and sinking this instruction can make
1278 // more registers live range shorten, it is still prifitable.
1279 for (const MachineOperand &MO : MI.operands()) {
1280 // Ignore non-register operands.
1281 if (!MO.isReg())
1282 continue;
1283 Register Reg = MO.getReg();
1284 if (Reg == 0)
1285 continue;
1286
1287 if (Reg.isPhysical()) {
1288 // Don't handle non-constant and non-ignorable physical register uses.
1289 if (MO.isUse() && !MRI->isConstantPhysReg(Reg) &&
1290 !TII->isIgnorableUse(MI, MI.getOperandNo(&MO)))
1291 return false;
1292 continue;
1293 }
1294
1295 // Users for the defs are all dominated by SuccToSinkTo.
1296 if (MO.isDef()) {
1297 // This def register's live range is shortened after sinking.
1298 bool LocalUse = false;
1299 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1300 LocalUse))
1301 return false;
1302 } else {
1303 MachineInstr *DefMI = MRI->getVRegDef(Reg);
1304 if (!DefMI)
1305 continue;
1306 CycleRef Cycle = CI->getCycle(DefMI->getParent());
1307 // DefMI is defined outside of cycle. There should be no live range
1308 // impact for this operand. Defination outside of cycle means:
1309 // 1: defination is outside of cycle.
1310 // 2: defination is in this cycle, but it is a PHI in the cycle header.
1311 if (Cycle != MCycle ||
1312 (DefMI->isPHI() && Cycle && CI->isReducible(Cycle) &&
1313 CI->getHeader(Cycle) == DefMI->getParent()))
1314 continue;
1315 // The DefMI is defined inside the cycle.
1316 // If sinking this operand makes some register pressure set exceed limit,
1317 // it is not profitable.
1318 if (registerPressureSetExceedsLimit(1, MRI->getRegClass(Reg),
1319 *SuccToSinkTo)) {
1320 LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
1321 return false;
1322 }
1323 }
1324 }
1325
1326 // If MI is in cycle and all its operands are alive across the whole cycle or
1327 // if no operand sinking make register pressure set exceed limit, it is
1328 // profitable to sink MI.
1329 return true;
1330}
1331
1332/// Get the sorted sequence of successors for this MachineBasicBlock, possibly
1333/// computing it if it was not already cached.
1334SmallVector<MachineBasicBlock *, 4> &
1335MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
1336 AllSuccsCache &AllSuccessors) const {
1337 // Do we have the sorted successors in cache ?
1338 auto Succs = AllSuccessors.find(MBB);
1339 if (Succs != AllSuccessors.end())
1340 return Succs->second;
1341
1342 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
1343
1344 // Handle cases where sinking can happen but where the sink point isn't a
1345 // successor. For example:
1346 //
1347 // x = computation
1348 // if () {} else {}
1349 // use x
1350 //
1351 for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
1352 // DomTree children of MBB that have MBB as immediate dominator are added.
1353 if (DTChild->getIDom()->getBlock() == MI.getParent() &&
1354 // Skip MBBs already added to the AllSuccs vector above.
1355 !MBB->isSuccessor(DTChild->getBlock()))
1356 AllSuccs.push_back(DTChild->getBlock());
1357 }
1358
1359 // Sort Successors according to their cycle depth or block frequency info.
1361 AllSuccs, [&](const MachineBasicBlock *L, const MachineBasicBlock *R) {
1362 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
1363 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
1364 if (llvm::shouldOptimizeForSize(MBB, PSI, MBFI) ||
1365 (!LHSFreq && !RHSFreq))
1366 return CI->getCycleDepth(L) < CI->getCycleDepth(R);
1367 return LHSFreq < RHSFreq;
1368 });
1369
1370 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
1371
1372 return it.first->second;
1373}
1374
1375/// FindSuccToSinkTo - Find a successor to sink this instruction to.
1376MachineBasicBlock *
1377MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
1378 bool &BreakPHIEdge,
1379 AllSuccsCache &AllSuccessors) {
1380 assert(MBB && "Invalid MachineBasicBlock!");
1381
1382 // loop over all the operands of the specified instruction. If there is
1383 // anything we can't handle, bail out.
1384
1385 // SuccToSinkTo - This is the successor to sink this instruction to, once we
1386 // decide.
1387 MachineBasicBlock *SuccToSinkTo = nullptr;
1388 for (const MachineOperand &MO : MI.operands()) {
1389 if (!MO.isReg())
1390 continue; // Ignore non-register operands.
1391
1392 Register Reg = MO.getReg();
1393 if (Reg == 0)
1394 continue;
1395
1396 if (Reg.isPhysical()) {
1397 if (MO.isUse()) {
1398 // If the physreg has no defs anywhere, it's just an ambient register
1399 // and we can freely move its uses. Alternatively, if it's allocatable,
1400 // it could get allocated to something with a def during allocation.
1401 if (!MRI->isConstantPhysReg(Reg) &&
1402 !TII->isIgnorableUse(MI, MI.getOperandNo(&MO)))
1403 return nullptr;
1404 } else if (!MO.isDead()) {
1405 // A def that isn't dead. We can't move it.
1406 return nullptr;
1407 }
1408 } else {
1409 // Virtual register uses are always safe to sink.
1410 if (MO.isUse())
1411 continue;
1412
1413 // If it's not safe to move defs of the register class, then abort.
1414 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
1415 return nullptr;
1416
1417 // Virtual register defs can only be sunk if all their uses are in blocks
1418 // dominated by one of the successors.
1419 if (SuccToSinkTo) {
1420 // If a previous operand picked a block to sink to, then this operand
1421 // must be sinkable to the same block.
1422 bool LocalUse = false;
1423 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1424 LocalUse))
1425 return nullptr;
1426
1427 continue;
1428 }
1429
1430 // Otherwise, we should look at all the successors and decide which one
1431 // we should sink to. If we have reliable block frequency information
1432 // (frequency != 0) available, give successors with smaller frequencies
1433 // higher priority, otherwise prioritize smaller cycle depths.
1434 for (MachineBasicBlock *SuccBlock :
1435 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
1436 bool LocalUse = false;
1437 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, BreakPHIEdge,
1438 LocalUse)) {
1439 SuccToSinkTo = SuccBlock;
1440 break;
1441 }
1442 if (LocalUse)
1443 // Def is used locally, it's never safe to move this def.
1444 return nullptr;
1445 }
1446
1447 // If we couldn't find a block to sink to, ignore this instruction.
1448 if (!SuccToSinkTo)
1449 return nullptr;
1450 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
1451 return nullptr;
1452 }
1453 }
1454
1455 // It is not possible to sink an instruction into its own block. This can
1456 // happen with cycles.
1457 if (MBB == SuccToSinkTo)
1458 return nullptr;
1459
1460 // It's not safe to sink instructions to EH landing pad. Control flow into
1461 // landing pad is implicitly defined.
1462 if (SuccToSinkTo && SuccToSinkTo->isEHPad())
1463 return nullptr;
1464
1465 // It ought to be okay to sink instructions into an INLINEASM_BR target, but
1466 // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
1467 // the source block (which this code does not yet do). So for now, forbid
1468 // doing so.
1469 if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
1470 return nullptr;
1471
1472 if (SuccToSinkTo && !TII->isSafeToSink(MI, SuccToSinkTo, CI))
1473 return nullptr;
1474
1475 return SuccToSinkTo;
1476}
1477
1478/// Return true if MI is likely to be usable as a memory operation by the
1479/// implicit null check optimization.
1480///
1481/// This is a "best effort" heuristic, and should not be relied upon for
1482/// correctness. This returning true does not guarantee that the implicit null
1483/// check optimization is legal over MI, and this returning false does not
1484/// guarantee MI cannot possibly be used to do a null check.
1486 const TargetInstrInfo *TII) {
1487 using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
1488
1489 auto *MBB = MI.getParent();
1490 if (MBB->pred_size() != 1)
1491 return false;
1492
1493 auto *PredMBB = *MBB->pred_begin();
1494 auto *PredBB = PredMBB->getBasicBlock();
1495
1496 // Frontends that don't use implicit null checks have no reason to emit
1497 // branches with make.implicit metadata, and this function should always
1498 // return false for them.
1499 if (!PredBB ||
1500 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
1501 return false;
1502
1503 const MachineOperand *BaseOp;
1504 int64_t Offset;
1505 bool OffsetIsScalable;
1506 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable))
1507 return false;
1508
1509 if (!BaseOp->isReg())
1510 return false;
1511
1512 if (!(MI.mayLoad() && !MI.isPredicable()))
1513 return false;
1514
1515 MachineBranchPredicate MBP;
1516 if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
1517 return false;
1518
1519 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
1520 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
1521 MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
1522 MBP.LHS.getReg() == BaseOp->getReg();
1523}
1524
1525/// If the sunk instruction is a copy, try to forward the copy instead of
1526/// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
1527/// there's any subregister weirdness involved. Returns true if copy
1528/// propagation occurred.
1529static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
1530 Register Reg) {
1531 const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
1532 const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
1533
1534 // Copy DBG_VALUE operand and set the original to undef. We then check to
1535 // see whether this is something that can be copy-forwarded. If it isn't,
1536 // continue around the loop.
1537
1538 const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
1539 auto CopyOperands = TII.isCopyInstr(SinkInst);
1540 if (!CopyOperands)
1541 return false;
1542 SrcMO = CopyOperands->Source;
1543 DstMO = CopyOperands->Destination;
1544
1545 // Check validity of forwarding this copy.
1546 bool PostRA = MRI.getNumVirtRegs() == 0;
1547
1548 // Trying to forward between physical and virtual registers is too hard.
1549 if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
1550 return false;
1551
1552 // Only try virtual register copy-forwarding before regalloc, and physical
1553 // register copy-forwarding after regalloc.
1554 bool arePhysRegs = !Reg.isVirtual();
1555 if (arePhysRegs != PostRA)
1556 return false;
1557
1558 // Pre-regalloc, only forward if all subregisters agree (or there are no
1559 // subregs at all). More analysis might recover some forwardable copies.
1560 if (!PostRA)
1561 for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
1562 if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
1563 DbgMO.getSubReg() != DstMO->getSubReg())
1564 return false;
1565
1566 // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
1567 // of this copy. Only forward the copy if the DBG_VALUE operand exactly
1568 // matches the copy destination.
1569 if (PostRA && Reg != DstMO->getReg())
1570 return false;
1571
1572 for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
1573 DbgMO.setReg(SrcMO->getReg());
1574 DbgMO.setSubReg(SrcMO->getSubReg());
1575 }
1576 return true;
1577}
1578
1579using MIRegs = std::pair<MachineInstr *, SmallVector<Register, 2>>;
1580/// Sink an instruction and its associated debug instructions.
1581static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
1583 ArrayRef<MIRegs> DbgValuesToSink) {
1584 // If we cannot find a location to use (merge with), then we erase the debug
1585 // location to prevent debug-info driven tools from potentially reporting
1586 // wrong location information.
1587 if (SuccToSinkTo.empty())
1588 MI.setDebugLoc(DebugLoc::getDropped());
1589 else
1590 MI.setDebugLoc(DebugLoc::getMergedLocation(
1591 MI.getDebugLoc(), SuccToSinkTo.findDebugLoc(InsertPos)));
1592
1593 // Move the instruction.
1594 MachineBasicBlock *ParentBlock = MI.getParent();
1595 SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
1597
1598 // Sink a copy of debug users to the insert position. Mark the original
1599 // DBG_VALUE location as 'undef', indicating that any earlier variable
1600 // location should be terminated as we've optimised away the value at this
1601 // point.
1602 for (const auto &DbgValueToSink : DbgValuesToSink) {
1603 MachineInstr *DbgMI = DbgValueToSink.first;
1604 MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
1605 SuccToSinkTo.insert(InsertPos, NewDbgMI);
1606
1607 bool PropagatedAllSunkOps = true;
1608 for (Register Reg : DbgValueToSink.second) {
1609 if (DbgMI->hasDebugOperandForReg(Reg)) {
1610 if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
1611 PropagatedAllSunkOps = false;
1612 break;
1613 }
1614 }
1615 }
1616 if (!PropagatedAllSunkOps)
1617 DbgMI->setDebugValueUndef();
1618 }
1619}
1620
1621/// hasStoreBetween - check if there is store betweeen straight line blocks From
1622/// and To.
1623bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
1624 MachineBasicBlock *To, MachineInstr &MI) {
1625 // Make sure From and To are in straight line which means From dominates To
1626 // and To post dominates From.
1627 if (!DT->dominates(From, To) || !PDT->dominates(To, From))
1628 return true;
1629
1630 auto BlockPair = std::make_pair(From, To);
1631
1632 // Does these two blocks pair be queried before and have a definite cached
1633 // result?
1634 if (auto It = HasStoreCache.find(BlockPair); It != HasStoreCache.end())
1635 return It->second;
1636
1637 if (auto It = StoreInstrCache.find(BlockPair); It != StoreInstrCache.end())
1638 return llvm::any_of(It->second, [&](MachineInstr *I) {
1639 return I->mayAlias(AA, MI, false);
1640 });
1641
1642 bool SawStore = false;
1643 bool HasAliasedStore = false;
1644 DenseSet<MachineBasicBlock *> HandledBlocks;
1645 DenseSet<MachineBasicBlock *> HandledDomBlocks;
1646 // Go through all reachable blocks from From.
1647 for (MachineBasicBlock *BB : depth_first(From)) {
1648 // We insert the instruction at the start of block To, so no need to worry
1649 // about stores inside To.
1650 // Store in block From should be already considered when just enter function
1651 // SinkInstruction.
1652 if (BB == To || BB == From)
1653 continue;
1654
1655 // We already handle this BB in previous iteration.
1656 if (HandledBlocks.count(BB))
1657 continue;
1658
1659 HandledBlocks.insert(BB);
1660 // To post dominates BB, it must be a path from block From.
1661 if (PDT->dominates(To, BB)) {
1662 if (!HandledDomBlocks.count(BB))
1663 HandledDomBlocks.insert(BB);
1664
1665 // If this BB is too big or the block number in straight line between From
1666 // and To is too big, stop searching to save compiling time.
1667 if (BB->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold) ||
1668 HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
1669 for (auto *DomBB : HandledDomBlocks) {
1670 if (DomBB != BB && DT->dominates(DomBB, BB))
1671 HasStoreCache[std::make_pair(DomBB, To)] = true;
1672 else if (DomBB != BB && DT->dominates(BB, DomBB))
1673 HasStoreCache[std::make_pair(From, DomBB)] = true;
1674 }
1675 HasStoreCache[BlockPair] = true;
1676 return true;
1677 }
1678
1679 for (MachineInstr &I : *BB) {
1680 // Treat as alias conservatively for a call or an ordered memory
1681 // operation.
1682 if (I.isCall() || I.hasOrderedMemoryRef()) {
1683 for (auto *DomBB : HandledDomBlocks) {
1684 if (DomBB != BB && DT->dominates(DomBB, BB))
1685 HasStoreCache[std::make_pair(DomBB, To)] = true;
1686 else if (DomBB != BB && DT->dominates(BB, DomBB))
1687 HasStoreCache[std::make_pair(From, DomBB)] = true;
1688 }
1689 HasStoreCache[BlockPair] = true;
1690 return true;
1691 }
1692
1693 if (I.mayStore()) {
1694 SawStore = true;
1695 // We still have chance to sink MI if all stores between are not
1696 // aliased to MI.
1697 // Cache all store instructions, so that we don't need to go through
1698 // all From reachable blocks for next load instruction.
1699 if (I.mayAlias(AA, MI, false))
1700 HasAliasedStore = true;
1701 StoreInstrCache[BlockPair].push_back(&I);
1702 }
1703 }
1704 }
1705 }
1706 // If there is no store at all, cache the result.
1707 if (!SawStore)
1708 HasStoreCache[BlockPair] = false;
1709 return HasAliasedStore;
1710}
1711
1712/// Aggressively sink instructions into cycles. This will aggressively try to
1713/// sink all instructions in the top-most preheaders in an attempt to reduce RP.
1714/// In particular, it will sink into multiple successor blocks without limits
1715/// based on the amount of sinking, or the type of ops being sunk (so long as
1716/// they are safe to sink).
1717bool MachineSinking::aggressivelySinkIntoCycle(
1718 CycleRef Cycle, MachineInstr &I,
1719 DenseMap<SinkItem, MachineInstr *> &SunkInstrs) {
1720 // TODO: support instructions with multiple defs
1721 if (I.getNumDefs() > 1)
1722 return false;
1723
1724 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Finding sink block for: " << I);
1725 assert(CI->getCyclePreheader(Cycle) && "Cycle sink needs a preheader block");
1727
1728 MachineOperand &DefMO = I.getOperand(0);
1729 for (MachineInstr &MI : MRI->use_instructions(DefMO.getReg())) {
1730 Uses.push_back({{DefMO.getReg(), DefMO.getSubReg()}, &MI});
1731 }
1732
1733 for (std::pair<RegSubRegPair, MachineInstr *> Entry : Uses) {
1734 MachineInstr *MI = Entry.second;
1735 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Analysing use: " << MI);
1736 if (MI->isPHI()) {
1737 LLVM_DEBUG(
1738 dbgs() << "AggressiveCycleSink: Not attempting to sink for PHI.\n");
1739 continue;
1740 }
1741 // We cannot sink before the prologue
1742 if (MI->isPosition() || TII->isBasicBlockPrologue(*MI)) {
1743 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Use is BasicBlock prologue, "
1744 "can't sink.\n");
1745 continue;
1746 }
1747 if (!CI->contains(Cycle, MI->getParent())) {
1748 LLVM_DEBUG(
1749 dbgs() << "AggressiveCycleSink: Use not in cycle, can't sink.\n");
1750 continue;
1751 }
1752
1753 MachineBasicBlock *SinkBlock = MI->getParent();
1754 MachineInstr *NewMI = nullptr;
1755 SinkItem MapEntry(&I, SinkBlock);
1756
1757 auto SI = SunkInstrs.find(MapEntry);
1758
1759 // Check for the case in which we have already sunk a copy of this
1760 // instruction into the user block.
1761 if (SI != SunkInstrs.end()) {
1762 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Already sunk to block: "
1763 << printMBBReference(*SinkBlock) << "\n");
1764 NewMI = SI->second;
1765 }
1766
1767 // Create a copy of the instruction in the use block.
1768 if (!NewMI) {
1769 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Sinking instruction to block: "
1770 << printMBBReference(*SinkBlock) << "\n");
1771
1772 NewMI = I.getMF()->CloneMachineInstr(&I);
1773 if (DefMO.getReg().isVirtual()) {
1774 const TargetRegisterClass *TRC = MRI->getRegClass(DefMO.getReg());
1775 Register DestReg = MRI->createVirtualRegister(TRC);
1776 NewMI->substituteRegister(DefMO.getReg(), DestReg, DefMO.getSubReg(),
1777 *TRI);
1778 }
1779 SinkBlock->insert(SinkBlock->SkipPHIsAndLabels(SinkBlock->begin()),
1780 NewMI);
1781 SunkInstrs.insert({MapEntry, NewMI});
1782 }
1783
1784 // The instruction is moved from its basic block, so do not retain the
1785 // debug information.
1786 assert(!NewMI->isDebugInstr() && "Should not sink debug inst");
1787 NewMI->setDebugLoc(DebugLoc());
1788
1789 // Replace the use with the newly created virtual register.
1790 RegSubRegPair &UseReg = Entry.first;
1791 MI->substituteRegister(UseReg.Reg, NewMI->getOperand(0).getReg(),
1792 UseReg.SubReg, *TRI);
1793 }
1794 // If we have replaced all uses, then delete the dead instruction
1795 if (I.isDead(*MRI))
1796 I.eraseFromParent();
1797 return true;
1798}
1799
1800/// SinkInstruction - Determine whether it is safe to sink the specified machine
1801/// instruction out of its current block into a successor.
1802bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
1803 AllSuccsCache &AllSuccessors) {
1804 // Don't sink instructions that the target prefers not to sink.
1805 if (!TII->shouldSink(MI))
1806 return false;
1807
1808 // Check if it's safe to move the instruction.
1809 if (!MI.isSafeToMove(SawStore))
1810 return false;
1811
1812 // Convergent operations may not be made control-dependent on additional
1813 // values.
1814 if (MI.isConvergent())
1815 return false;
1816
1817 // Don't break implicit null checks. This is a performance heuristic, and not
1818 // required for correctness.
1820 return false;
1821
1822 // FIXME: This should include support for sinking instructions within the
1823 // block they are currently in to shorten the live ranges. We often get
1824 // instructions sunk into the top of a large block, but it would be better to
1825 // also sink them down before their first use in the block. This xform has to
1826 // be careful not to *increase* register pressure though, e.g. sinking
1827 // "x = y + z" down if it kills y and z would increase the live ranges of y
1828 // and z and only shrink the live range of x.
1829
1830 bool BreakPHIEdge = false;
1831 MachineBasicBlock *ParentBlock = MI.getParent();
1832 MachineBasicBlock *SuccToSinkTo =
1833 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
1834
1835 // If there are no outputs, it must have side-effects.
1836 if (!SuccToSinkTo)
1837 return false;
1838
1839 // If the instruction to move defines a dead physical register which is live
1840 // when leaving the basic block, don't move it because it could turn into a
1841 // "zombie" define of that preg. E.g., EFLAGS.
1842 for (const MachineOperand &MO : MI.all_defs()) {
1843 Register Reg = MO.getReg();
1844 if (Reg == 0 || !Reg.isPhysical())
1845 continue;
1846 if (SuccToSinkTo->isLiveIn(Reg))
1847 return false;
1848 }
1849
1850 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
1851
1852 // If the block has multiple predecessors, this is a critical edge.
1853 // Decide if we can sink along it or need to break the edge.
1854 if (SuccToSinkTo->pred_size() > 1) {
1855 // We cannot sink a load across a critical edge - there may be stores in
1856 // other code paths.
1857 bool TryBreak = false;
1858 bool Store =
1859 MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
1860 if (!MI.isSafeToMove(Store)) {
1861 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
1862 TryBreak = true;
1863 }
1864
1865 // We don't want to sink across a critical edge if we don't dominate the
1866 // successor. We could be introducing calculations to new code paths.
1867 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
1868 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
1869 TryBreak = true;
1870 }
1871
1872 // Don't sink instructions into a cycle.
1873 if (!TryBreak && CI->getCycle(SuccToSinkTo) &&
1874 (!CI->isReducible(CI->getCycle(SuccToSinkTo)) ||
1875 CI->getHeader(CI->getCycle(SuccToSinkTo)) == SuccToSinkTo)) {
1876 LLVM_DEBUG(dbgs() << " *** NOTE: cycle header found\n");
1877 TryBreak = true;
1878 }
1879
1880 // Otherwise we are OK with sinking along a critical edge.
1881 if (!TryBreak)
1882 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
1883 else {
1884 // Mark this edge as to be split.
1885 // If the edge can actually be split, the next iteration of the main loop
1886 // will sink MI in the newly created block.
1887 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo,
1888 BreakPHIEdge);
1889 if (!Status)
1890 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1891 "break critical edge\n");
1892 // The instruction will not be sunk this time.
1893 return false;
1894 }
1895 }
1896
1897 if (BreakPHIEdge) {
1898 // BreakPHIEdge is true if all the uses are in the successor MBB being
1899 // sunken into and they are all PHI nodes. In this case, machine-sink must
1900 // break the critical edge first.
1901 bool Status =
1902 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
1903 if (!Status)
1904 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1905 "break critical edge\n");
1906 // The instruction will not be sunk this time.
1907 return false;
1908 }
1909
1910 // Determine where to insert into. Skip phi nodes.
1911 MachineBasicBlock::iterator InsertPos =
1912 SuccToSinkTo->SkipPHIsAndLabels(SuccToSinkTo->begin());
1913 if (blockPrologueInterferes(SuccToSinkTo, InsertPos, MI, TRI, TII, MRI)) {
1914 LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
1915 return false;
1916 }
1917
1918 // Collect debug users of any vreg that this inst defines.
1919 SmallVector<MIRegs, 4> DbgUsersToSink;
1920 for (auto &MO : MI.all_defs()) {
1921 if (!MO.getReg().isVirtual())
1922 continue;
1923 auto It = SeenDbgUsers.find(MO.getReg());
1924 if (It == SeenDbgUsers.end())
1925 continue;
1926
1927 // Sink any users that don't pass any other DBG_VALUEs for this variable.
1928 auto &Users = It->second;
1929 for (auto &User : Users) {
1930 MachineInstr *DbgMI = User.getPointer();
1931 if (User.getInt()) {
1932 // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1933 // it, it can't be recovered. Set it undef.
1934 if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
1935 DbgMI->setDebugValueUndef();
1936 } else {
1937 DbgUsersToSink.push_back(
1938 {DbgMI, SmallVector<Register, 2>(1, MO.getReg())});
1939 }
1940 }
1941 }
1942
1943 // After sinking, some debug users may not be dominated any more. If possible,
1944 // copy-propagate their operands. As it's expensive, don't do this if there's
1945 // no debuginfo in the program.
1946 if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1947 SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1948
1949 performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
1950
1951 return true;
1952}
1953
1954void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
1955 MachineInstr &MI, MachineBasicBlock *TargetBlock) {
1956 assert(MI.isCopy());
1957 assert(MI.getOperand(1).isReg());
1958
1959 // Enumerate all users of vreg operands that are def'd. Skip those that will
1960 // be sunk. For the rest, if they are not dominated by the block we will sink
1961 // MI into, propagate the copy source to them.
1962 SmallVector<MachineInstr *, 4> DbgDefUsers;
1963 SmallVector<Register, 4> DbgUseRegs;
1964 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1965 for (auto &MO : MI.all_defs()) {
1966 if (!MO.getReg().isVirtual())
1967 continue;
1968 DbgUseRegs.push_back(MO.getReg());
1969 for (auto &User : MRI.use_instructions(MO.getReg())) {
1970 if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
1971 continue;
1972
1973 // If is in same block, will either sink or be use-before-def.
1974 if (User.getParent() == MI.getParent())
1975 continue;
1976
1977 assert(User.hasDebugOperandForReg(MO.getReg()) &&
1978 "DBG_VALUE user of vreg, but has no operand for it?");
1979 DbgDefUsers.push_back(&User);
1980 }
1981 }
1982
1983 // Point the users of this copy that are no longer dominated, at the source
1984 // of the copy.
1985 for (auto *User : DbgDefUsers) {
1986 for (auto &Reg : DbgUseRegs) {
1987 for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
1988 DbgOp.setReg(MI.getOperand(1).getReg());
1989 DbgOp.setSubReg(MI.getOperand(1).getSubReg());
1990 }
1991 }
1992 }
1993}
1994
1995//===----------------------------------------------------------------------===//
1996// This pass is not intended to be a replacement or a complete alternative
1997// for the pre-ra machine sink pass. It is only designed to sink COPY
1998// instructions which should be handled after RA.
1999//
2000// This pass sinks COPY instructions into a successor block, if the COPY is not
2001// used in the current block and the COPY is live-in to a single successor
2002// (i.e., doesn't require the COPY to be duplicated). This avoids executing the
2003// copy on paths where their results aren't needed. This also exposes
2004// additional opportunites for dead copy elimination and shrink wrapping.
2005//
2006// These copies were either not handled by or are inserted after the MachineSink
2007// pass. As an example of the former case, the MachineSink pass cannot sink
2008// COPY instructions with allocatable source registers; for AArch64 these type
2009// of copy instructions are frequently used to move function parameters (PhyReg)
2010// into virtual registers in the entry block.
2011//
2012// For the machine IR below, this pass will sink %w19 in the entry into its
2013// successor (%bb.1) because %w19 is only live-in in %bb.1.
2014// %bb.0:
2015// %wzr = SUBSWri %w1, 1
2016// %w19 = COPY %w0
2017// Bcc 11, %bb.2
2018// %bb.1:
2019// Live Ins: %w19
2020// BL @fun
2021// %w0 = ADDWrr %w0, %w19
2022// RET %w0
2023// %bb.2:
2024// %w0 = COPY %wzr
2025// RET %w0
2026// As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
2027// able to see %bb.0 as a candidate.
2028//===----------------------------------------------------------------------===//
2029namespace {
2030
2031class PostRAMachineSinkingImpl {
2032 /// Track which register units have been modified and used.
2033 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
2034
2035 /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
2036 /// entry in this map for each unit it touches. The DBG_VALUE's entry
2037 /// consists of a pointer to the instruction itself, and a vector of registers
2038 /// referred to by the instruction that overlap the key register unit.
2039 DenseMap<MCRegUnit, SmallVector<MIRegs, 2>> SeenDbgInstrs;
2040
2041 /// Sink Copy instructions unused in the same block close to their uses in
2042 /// successors.
2043 bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
2044 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
2045
2046public:
2047 bool run(MachineFunction &MF);
2048};
2049
2050class PostRAMachineSinkingLegacy : public MachineFunctionPass {
2051public:
2052 bool runOnMachineFunction(MachineFunction &MF) override;
2053
2054 static char ID;
2055 PostRAMachineSinkingLegacy() : MachineFunctionPass(ID) {}
2056 StringRef getPassName() const override { return "PostRA Machine Sink"; }
2057
2058 void getAnalysisUsage(AnalysisUsage &AU) const override {
2059 AU.setPreservesCFG();
2061 }
2062
2063 MachineFunctionProperties getRequiredProperties() const override {
2064 return MachineFunctionProperties().setNoVRegs();
2065 }
2066};
2067
2068} // namespace
2069
2070char PostRAMachineSinkingLegacy::ID = 0;
2071char &llvm::PostRAMachineSinkingID = PostRAMachineSinkingLegacy::ID;
2072
2073INITIALIZE_PASS(PostRAMachineSinkingLegacy, "postra-machine-sink",
2074 "PostRA Machine Sink", false, false)
2075
2076static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, Register Reg,
2078 LiveRegUnits LiveInRegUnits(*TRI);
2079 LiveInRegUnits.addLiveIns(MBB);
2080 return !LiveInRegUnits.available(Reg);
2081}
2082
2083static MachineBasicBlock *
2085 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
2087 // Try to find a single sinkable successor in which Reg is live-in.
2088 MachineBasicBlock *BB = nullptr;
2089 for (auto *SI : SinkableBBs) {
2090 if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
2091 // If BB is set here, Reg is live-in to at least two sinkable successors,
2092 // so quit.
2093 if (BB)
2094 return nullptr;
2095 BB = SI;
2096 }
2097 }
2098 // Reg is not live-in to any sinkable successors.
2099 if (!BB)
2100 return nullptr;
2101
2102 // Check if any register aliased with Reg is live-in in other successors.
2103 for (auto *SI : CurBB.successors()) {
2104 if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
2105 return nullptr;
2106 }
2107 return BB;
2108}
2109
2110static MachineBasicBlock *
2112 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
2113 ArrayRef<Register> DefedRegsInCopy,
2114 const TargetRegisterInfo *TRI) {
2115 MachineBasicBlock *SingleBB = nullptr;
2116 for (auto DefReg : DefedRegsInCopy) {
2117 MachineBasicBlock *BB =
2118 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
2119 if (!BB || (SingleBB && SingleBB != BB))
2120 return nullptr;
2121 SingleBB = BB;
2122 }
2123 return SingleBB;
2124}
2125
2127 const SmallVectorImpl<unsigned> &UsedOpsInCopy,
2128 const LiveRegUnits &UsedRegUnits,
2129 const TargetRegisterInfo *TRI) {
2130 for (auto U : UsedOpsInCopy) {
2131 MachineOperand &MO = MI->getOperand(U);
2132 Register SrcReg = MO.getReg();
2133 if (!UsedRegUnits.available(SrcReg)) {
2134 MachineBasicBlock::iterator NI = std::next(MI->getIterator());
2135 for (MachineInstr &UI : make_range(NI, CurBB.end())) {
2136 if (UI.killsRegister(SrcReg, TRI)) {
2137 UI.clearRegisterKills(SrcReg, TRI);
2138 MO.setIsKill(true);
2139 break;
2140 }
2141 }
2142 }
2143 }
2144}
2145
2147 const SmallVectorImpl<unsigned> &UsedOpsInCopy,
2148 const SmallVectorImpl<Register> &DefedRegsInCopy) {
2149 for (Register DefReg : DefedRegsInCopy)
2150 SuccBB->removeLiveInOverlappedWith(DefReg);
2151
2152 for (auto U : UsedOpsInCopy)
2153 SuccBB->addLiveIn(MI->getOperand(U).getReg());
2154 SuccBB->sortUniqueLiveIns();
2155}
2156
2158 SmallVectorImpl<unsigned> &UsedOpsInCopy,
2159 SmallVectorImpl<Register> &DefedRegsInCopy,
2160 LiveRegUnits &ModifiedRegUnits,
2161 LiveRegUnits &UsedRegUnits) {
2162 bool HasRegDependency = false;
2163 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2164 MachineOperand &MO = MI->getOperand(i);
2165 if (!MO.isReg())
2166 continue;
2167 Register Reg = MO.getReg();
2168 if (!Reg)
2169 continue;
2170 if (MO.isDef()) {
2171 if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
2172 HasRegDependency = true;
2173 break;
2174 }
2175 DefedRegsInCopy.push_back(Reg);
2176
2177 // FIXME: instead of isUse(), readsReg() would be a better fix here,
2178 // For example, we can ignore modifications in reg with undef. However,
2179 // it's not perfectly clear if skipping the internal read is safe in all
2180 // other targets.
2181 } else if (MO.isUse()) {
2182 if (!ModifiedRegUnits.available(Reg)) {
2183 HasRegDependency = true;
2184 break;
2185 }
2186 UsedOpsInCopy.push_back(i);
2187 }
2188 }
2189 return HasRegDependency;
2190}
2191
2192bool PostRAMachineSinkingImpl::tryToSinkCopy(MachineBasicBlock &CurBB,
2193 MachineFunction &MF,
2194 const TargetRegisterInfo *TRI,
2195 const TargetInstrInfo *TII) {
2196 SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
2197 // FIXME: For now, we sink only to a successor which has a single predecessor
2198 // so that we can directly sink COPY instructions to the successor without
2199 // adding any new block or branch instruction.
2200 for (MachineBasicBlock *SI : CurBB.successors())
2201 if (!SI->livein_empty() && SI->pred_size() == 1 && !SI->isEHPad())
2202 SinkableBBs.insert(SI);
2203
2204 if (SinkableBBs.empty())
2205 return false;
2206
2207 bool Changed = false;
2208
2209 // Track which registers have been modified and used between the end of the
2210 // block and the current instruction.
2211 ModifiedRegUnits.clear();
2212 UsedRegUnits.clear();
2213 SeenDbgInstrs.clear();
2214
2215 for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
2216 // Track the operand index for use in Copy.
2217 SmallVector<unsigned, 2> UsedOpsInCopy;
2218 // Track the register number defed in Copy.
2219 SmallVector<Register, 2> DefedRegsInCopy;
2220
2221 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
2222 // for DBG_VALUEs later, record them when they're encountered.
2223 if (MI.isDebugValue() && !MI.isDebugRef()) {
2224 SmallDenseMap<MCRegUnit, SmallVector<Register, 2>, 4> MIUnits;
2225 bool IsValid = true;
2226 for (MachineOperand &MO : MI.debug_operands()) {
2227 if (MO.isReg() && MO.getReg().isPhysical()) {
2228 // Bail if we can already tell the sink would be rejected, rather
2229 // than needlessly accumulating lots of DBG_VALUEs.
2230 if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2231 ModifiedRegUnits, UsedRegUnits)) {
2232 IsValid = false;
2233 break;
2234 }
2235
2236 // Record debug use of each reg unit.
2237 for (MCRegUnit Unit : TRI->regunits(MO.getReg()))
2238 MIUnits[Unit].push_back(MO.getReg());
2239 }
2240 }
2241 if (IsValid) {
2242 for (auto &RegOps : MIUnits)
2243 SeenDbgInstrs[RegOps.first].emplace_back(&MI,
2244 std::move(RegOps.second));
2245 }
2246 continue;
2247 }
2248
2249 // Don't postRASink instructions that the target prefers not to sink.
2250 if (!TII->shouldPostRASink(MI)) {
2251 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2252 TRI);
2253 continue;
2254 }
2255
2256 if (MI.isDebugOrPseudoInstr())
2257 continue;
2258
2259 // Do not move any instruction across function call.
2260 if (MI.isCall())
2261 return false;
2262
2263 if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
2264 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2265 TRI);
2266 continue;
2267 }
2268
2269 // Don't sink the COPY if it would violate a register dependency.
2270 if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2271 ModifiedRegUnits, UsedRegUnits)) {
2272 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2273 TRI);
2274 continue;
2275 }
2276 assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
2277 "Unexpect SrcReg or DefReg");
2278 MachineBasicBlock *SuccBB =
2279 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
2280 // Don't sink if we cannot find a single sinkable successor in which Reg
2281 // is live-in.
2282 if (!SuccBB) {
2283 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2284 TRI);
2285 continue;
2286 }
2287 assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
2288 "Unexpected predecessor");
2289
2290 // Collect DBG_VALUEs that must sink with this copy. We've previously
2291 // recorded which reg units that DBG_VALUEs read, if this instruction
2292 // writes any of those units then the corresponding DBG_VALUEs must sink.
2293 MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
2294 for (auto &MO : MI.all_defs()) {
2295 for (MCRegUnit Unit : TRI->regunits(MO.getReg())) {
2296 for (const auto &MIRegs : SeenDbgInstrs.lookup(Unit)) {
2297 auto &Regs = DbgValsToSinkMap[MIRegs.first];
2298 llvm::append_range(Regs, MIRegs.second);
2299 }
2300 }
2301 }
2302 auto DbgValsToSink = DbgValsToSinkMap.takeVector();
2303
2304 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccBB);
2305
2306 MachineBasicBlock::iterator InsertPos =
2307 SuccBB->SkipPHIsAndLabels(SuccBB->begin());
2308 if (blockPrologueInterferes(SuccBB, InsertPos, MI, TRI, TII, nullptr)) {
2309 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2310 TRI);
2311 LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
2312 continue;
2313 }
2314
2315 // Clear the kill flag if SrcReg is killed between MI and the end of the
2316 // block.
2317 clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
2318 performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
2319 updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
2320
2321 Changed = true;
2322 ++NumPostRACopySink;
2323 }
2324 return Changed;
2325}
2326
2327bool PostRAMachineSinkingImpl::run(MachineFunction &MF) {
2328 bool Changed = false;
2329 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2330 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2331
2332 ModifiedRegUnits.init(*TRI);
2333 UsedRegUnits.init(*TRI);
2334 for (auto &BB : MF)
2335 Changed |= tryToSinkCopy(BB, MF, TRI, TII);
2336
2337 return Changed;
2338}
2339
2340bool PostRAMachineSinkingLegacy::runOnMachineFunction(MachineFunction &MF) {
2341 if (skipFunction(MF.getFunction()))
2342 return false;
2343
2344 return PostRAMachineSinkingImpl().run(MF);
2345}
2346
2347PreservedAnalyses
2350 MFPropsModifier _(*this, MF);
2351
2352 if (!PostRAMachineSinkingImpl().run(MF))
2353 return PreservedAnalyses::all();
2354
2357 return PA;
2358}
MachineInstrBuilder MachineInstrBuilder & DefMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
MachineBasicBlock & MBB
basic Basic Alias true
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
#define DEBUG_TYPE
ManagedStatic< HTTPClientCleanup > Cleanup
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
iv Induction Variable Users
Definition IVUsers.cpp:48
#define I(x, y, z)
Definition MD5.cpp:57
static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI)
Return true if this machine instruction loads from global offset table or constant pool.
static cl::opt< unsigned > SinkLoadInstsPerBlockThreshold("machine-sink-load-instrs-threshold", cl::desc("Do not try to find alias store for a load if there is a in-path " "block whose instruction number is higher than this threshold."), cl::init(2000), cl::Hidden)
static cl::opt< unsigned > SinkIntoCycleLimit("machine-sink-cycle-limit", cl::desc("The maximum number of instructions considered for cycle sinking."), cl::init(50), cl::Hidden)
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB, const SmallVectorImpl< unsigned > &UsedOpsInCopy, const LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo, MachineBasicBlock::iterator InsertPos, ArrayRef< MIRegs > DbgValuesToSink)
Sink an instruction and its associated debug instructions.
static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI, const TargetInstrInfo *TII)
Return true if MI is likely to be usable as a memory operation by the implicit null check optimizatio...
static cl::opt< bool > SplitEdges("machine-sink-split", cl::desc("Split critical edges during machine sinking"), cl::init(true), cl::Hidden)
static cl::opt< bool > SinkInstsIntoCycle("sink-insts-to-avoid-spills", cl::desc("Sink instructions into cycles to avoid " "register spills"), cl::init(false), cl::Hidden)
static cl::opt< unsigned > SinkLoadBlocksThreshold("machine-sink-load-blocks-threshold", cl::desc("Do not try to find alias store for a load if the block number in " "the straight line is higher than this threshold."), cl::init(20), cl::Hidden)
static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB, const SmallVectorImpl< unsigned > &UsedOpsInCopy, const SmallVectorImpl< Register > &DefedRegsInCopy)
static bool hasRegisterDependency(MachineInstr *MI, SmallVectorImpl< unsigned > &UsedOpsInCopy, SmallVectorImpl< Register > &DefedRegsInCopy, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits)
Register const TargetRegisterInfo * TRI
std::pair< MachineInstr *, SmallVector< Register, 2 > > MIRegs
Machine code static false bool blockPrologueInterferes(const MachineBasicBlock *BB, MachineBasicBlock::const_iterator End, const MachineInstr &MI, const TargetRegisterInfo *TRI, const TargetInstrInfo *TII, const MachineRegisterInfo *MRI)
Return true if a target defined block prologue instruction interferes with a sink candidate.
static cl::opt< unsigned > SplitEdgeProbabilityThreshold("machine-sink-split-probability-threshold", cl::desc("Percentage threshold for splitting single-instruction critical edge. " "If the branch threshold is higher than this threshold, we allow " "speculative execution of up to 1 instruction to avoid branching to " "splitted critical edge"), cl::init(40), cl::Hidden)
static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI, Register Reg)
If the sunk instruction is a copy, try to forward the copy instead of leaving an 'undef' DBG_VALUE in...
static cl::opt< bool > UseBlockFreqInfo("machine-sink-bfi", cl::desc("Use block frequency info to find successors to sink"), cl::init(true), cl::Hidden)
static MachineBasicBlock * getSingleLiveInSuccBB(MachineBasicBlock &CurBB, const SmallPtrSetImpl< MachineBasicBlock * > &SinkableBBs, Register Reg, const TargetRegisterInfo *TRI)
This file implements a map that provides insertion order iteration.
Promote Memory to Register
Definition Mem2Reg.cpp:110
#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
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the PointerIntPair class.
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
static const char * name
This file implements a set that has insertion order iteration characteristics.
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
Definition Sink.cpp:174
static bool SinkInstruction(Instruction *Inst, SmallPtrSetImpl< Instruction * > &Stores, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
SinkInstruction - Determine whether it is safe to sink the specified machine instruction out of its c...
Definition Sink.cpp:104
This file defines the SmallSet class.
This file defines the SmallVector 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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
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.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:186
static DebugLoc getDropped()
Definition DebugLoc.h:155
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
iterator_range< const_toplevel_iterator > toplevel_cycles() const
bool isReducible(CycleRef C) const
BlockT * getCyclePreheader(CycleRef C) const
Return the preheader block for C.
void splitCriticalEdge(BlockT *Pred, BlockT *Succ, BlockT *New)
bool contains(CycleRef Outer, CycleRef Inner) const
Returns true iff Outer contains Inner. O(1). Non-strict.
unsigned getCycleDepth(const BlockT *Block) const
Return the depth of the innermost cycle containing Block, or 0 if it is not contained in any cycle.
BlockT * getHeader(CycleRef C) const
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
Module * getParent()
Get the module that this global value is contained inside of...
bool isAsCheapAsAMove(const MachineInstr &MI) const override
bool shouldSink(const MachineInstr &MI) const override
A set of register units used to track register liveness.
static void accumulateUsedDefed(const MachineInstr &MI, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
For a machine instruction MI, adds all register units used in UsedRegUnits and defined or clobbered i...
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
LLVM_ABI void addLiveIns(const MachineBasicBlock &MBB)
Adds registers living into block MBB.
void clear()
Clears the set.
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.
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
bool isEHPad() const
Returns true if the block is a landing pad.
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI void removeLiveInOverlappedWith(MCRegister Reg)
Remove the specified register from any overlapped live in.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI void onEdgeSplit(const MachineBasicBlock &NewPredecessor, const MachineBasicBlock &NewSuccessor, const MachineBranchProbabilityInfo &MBPI)
incrementally calculate block frequencies when we split edges, to avoid full CFG traversal.
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Legacy analysis pass which computes a MachineCycleInfo.
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
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.
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.
bool hasDebugOperandForReg(Register Reg) const
Returns whether this debug value has at least one debug operand with the register Reg.
void setDebugValueUndef()
Sets all register debug operands in this debug value instruction to be undef.
LLVM_ABI iterator_range< filter_iterator< const MachineOperand *, std::function< bool(const MachineOperand &Op)> > > getDebugOperandsForReg(Register Reg) const
Returns a range of all of the operands that correspond to a debug use of Reg.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool isCopy() const
const MachineBasicBlock * getParent() const
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool isDebugInstr() const
mop_range operands()
LLVM_ABI void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx, const TargetRegisterInfo &RegInfo)
Replace all occurrences of FromReg with ToReg:SubIdx, properly composing subreg indices where necessa...
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const MachineOperand & getOperand(unsigned i) const
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
MachineBasicBlock * getDefBlock(Register Reg) const
Return the machine basic block in which the specified virtual register is defined,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
const MachineFunction & getMF() const
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
iterator_range< use_iterator > use_operands(Register Reg) const
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
VectorType takeVector()
Clear the MapVector and return the underlying vector.
Definition MapVector.h:51
PointerIntPair - This class implements a pair of a pointer and small integer.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Special value supplied for machine level alias analysis.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
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
A vector that has set insertion semantics.
Definition SetVector.h:57
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
Target-Independent Code Generator Pass Configuration Options.
bool getEnableSinkAndFold() const
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 void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
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.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type size() const
Definition DenseSet.h:85
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Abstract Attribute helper functions.
Definition Attributor.h:165
@ Entry
Definition COFF.h:862
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
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.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isCycleInvariant(const MachineCycleInfo &CI, CycleRef Cycle, MachineInstr &I)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI char & PostRAMachineSinkingID
This pass perform post-ra machine sink for COPY instructions.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
LLVM_ABI char & MachineSinkingLegacyID
MachineSinking - This pass performs sinking on machine instructions.
iterator_range< df_iterator< T > > depth_first(const T &G)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Represents a predicate at the MachineFunction level.
A pair composed of a register and a sub-register index.