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