LLVM 24.0.0git
MachineLICM.cpp
Go to the documentation of this file.
1//===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
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 performs loop invariant code motion on machine instructions. We
10// attempt to remove as much code from the body of a loop as possible.
11//
12// This pass is not intended to be a replacement or a complete alternative
13// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
14// constructs that are not exposed before lowering and instruction selection.
15//
16//===----------------------------------------------------------------------===//
17
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Statistic.h"
45#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/Module.h"
48#include "llvm/MC/MCInstrDesc.h"
49#include "llvm/MC/MCRegister.h"
50#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
56#include <cassert>
57#include <limits>
58#include <vector>
59
60using namespace llvm;
61
62#define DEBUG_TYPE "machinelicm"
63
64static cl::opt<bool>
65AvoidSpeculation("avoid-speculation",
66 cl::desc("MachineLICM should avoid speculation"),
67 cl::init(true), cl::Hidden);
68
69static cl::opt<bool>
70HoistCheapInsts("hoist-cheap-insts",
71 cl::desc("MachineLICM should hoist even cheap instructions"),
72 cl::init(false), cl::Hidden);
73
74static cl::opt<bool>
75HoistConstStores("hoist-const-stores",
76 cl::desc("Hoist invariant stores"),
77 cl::init(true), cl::Hidden);
78
79static cl::opt<bool> HoistConstLoads("hoist-const-loads",
80 cl::desc("Hoist invariant loads"),
81 cl::init(true), cl::Hidden);
82
83// The default threshold of 100 (i.e. if target block is 100 times hotter)
84// is based on empirical data on a single target and is subject to tuning.
86BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
87 cl::desc("Do not hoist instructions if target"
88 "block is N times hotter than the source."),
89 cl::init(100), cl::Hidden);
90
91enum class UseBFI { None, PGO, All };
92
93static cl::opt<UseBFI>
94DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
95 cl::desc("Disable hoisting instructions to"
96 " hotter blocks"),
99 "disable the feature"),
100 clEnumValN(UseBFI::PGO, "pgo",
101 "enable the feature when using profile data"),
102 clEnumValN(UseBFI::All, "all",
103 "enable the feature with/wo profile data")));
104
105STATISTIC(NumHoisted,
106 "Number of machine instructions hoisted out of loops");
107STATISTIC(NumLowRP,
108 "Number of instructions hoisted in low reg pressure situation");
109STATISTIC(NumHighLatency,
110 "Number of high latency instructions hoisted");
111STATISTIC(NumCSEed,
112 "Number of hoisted machine instructions CSEed");
113STATISTIC(NumPostRAHoisted,
114 "Number of machine instructions hoisted out of loops post regalloc");
115STATISTIC(NumStoreConst,
116 "Number of stores of const phys reg hoisted out of loops");
117STATISTIC(NumNotHoistedDueToHotness,
118 "Number of instructions not hoisted due to block frequency");
119
120namespace {
121 enum HoistResult { NotHoisted = 1, Hoisted = 2, ErasedMI = 4 };
122
123 class MachineLICMImpl {
124 const TargetInstrInfo *TII = nullptr;
125 const TargetLoweringBase *TLI = nullptr;
126 const TargetRegisterInfo *TRI = nullptr;
127 const MachineFrameInfo *MFI = nullptr;
128 MachineRegisterInfo *MRI = nullptr;
129 const RegisterClassInfo *RegClassInfo = nullptr;
130 TargetSchedModel SchedModel;
131 bool PreRegAlloc = false;
132 bool HasProfileData = false;
133 Pass *LegacyPass;
135
136 // Various analyses that we use...
137 AliasAnalysis *AA = nullptr; // Alias analysis info.
138 MachineBlockFrequencyInfo *MBFI = nullptr; // Machine block frequncy info
139 MachineLoopInfo *MLI = nullptr; // Current MachineLoopInfo
140 MachineDomTreeUpdater *MDTU = nullptr; // Wraps current dominator tree
141
142 // State that is updated as we process loops
143 bool Changed = false; // True if a loop is changed.
144 bool FirstInLoop = false; // True if it's the first LICM in the loop.
145
146 // Holds information about whether it is allowed to move load instructions
147 // out of the loop
148 SmallDenseMap<MachineLoop *, bool> AllowedToHoistLoads;
149
150 // Exit blocks of each Loop.
151 DenseMap<MachineLoop *, SmallVector<MachineBasicBlock *, 8>> ExitBlockMap;
152
153 bool isExitBlock(MachineLoop *CurLoop, const MachineBasicBlock *MBB) {
154 auto [It, Inserted] = ExitBlockMap.try_emplace(CurLoop);
155 if (Inserted) {
157 CurLoop->getExitBlocks(ExitBlocks);
158 It->second = std::move(ExitBlocks);
159 }
160 return is_contained(It->second, MBB);
161 }
162
163 // Track 'estimated' register pressure.
164 SmallDenseSet<Register> RegSeen;
165 SmallVector<unsigned, 8> RegPressure;
166
167 // Register pressure "limit" per register pressure set. If the pressure
168 // is higher than the limit, then it's considered high.
169 SmallVector<unsigned, 8> RegLimit;
170
171 // Register pressure on path leading from loop preheader to current BB.
173
174 // For each opcode per preheader, keep a list of potential CSE instructions.
175 DenseMap<MachineBasicBlock *,
176 DenseMap<unsigned, std::vector<MachineInstr *>>>
177 CSEMap;
178
179 // If a MBB does not dominate loop exiting blocks then it may not safe
180 // to hoist loads from this block. Cached per loop for the current block,
181 // which is checked against both the outermost loop and its subloops.
182 SmallDenseMap<MachineLoop *, bool> GuaranteedToExecute;
183
184 public:
185 MachineLICMImpl(bool PreRegAlloc, Pass *LegacyPass,
187 : PreRegAlloc(PreRegAlloc), LegacyPass(LegacyPass), MFAM(MFAM) {
188 assert((LegacyPass || MFAM) && "LegacyPass or MFAM must be provided");
189 assert(!(LegacyPass && MFAM) &&
190 "LegacyPass and MFAM cannot be provided at the same time");
191 }
192
193 bool run(MachineFunction &MF);
194
195 void releaseMemory() {
196 RegSeen.clear();
197 RegPressure.clear();
198 RegLimit.clear();
199 BackTrace.clear();
200 CSEMap.clear();
201 ExitBlockMap.clear();
202 }
203
204 private:
205 /// Keep track of information about hoisting candidates.
206 struct CandidateInfo {
207 MachineInstr *MI;
208 Register Def;
209 int FI;
210
211 CandidateInfo(MachineInstr *mi, Register def, int fi)
212 : MI(mi), Def(def), FI(fi) {}
213 };
214
215 void HoistRegionPostRA(MachineLoop *CurLoop);
216
217 void HoistPostRA(MachineInstr *MI, Register Def, MachineLoop *CurLoop);
218
219 void ProcessMI(MachineInstr *MI, BitVector &RUDefs, BitVector &RUClobbers,
220 SmallDenseSet<int> &StoredFIs,
221 SmallVectorImpl<CandidateInfo> &Candidates,
222 MachineLoop *CurLoop);
223
224 void AddToLiveIns(MCRegister Reg, MachineLoop *CurLoop);
225
226 bool IsLICMCandidate(MachineInstr &I, MachineLoop *CurLoop);
227
228 bool IsLoopInvariantInst(MachineInstr &I, MachineLoop *CurLoop);
229
230 bool HasLoopPHIUse(const MachineInstr *MI, MachineLoop *CurLoop);
231
232 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, Register Reg,
233 MachineLoop *CurLoop) const;
234
235 bool IsCheapInstruction(MachineInstr &MI) const;
236
237 bool CanCauseHighRegPressure(const SmallDenseMap<unsigned, int> &Cost,
238 bool Cheap);
239
240 void UpdateBackTraceRegPressure(const MachineInstr *MI);
241
242 bool IsProfitableToHoist(MachineInstr &MI, MachineLoop *CurLoop);
243
244 bool IsGuaranteedToExecute(MachineBasicBlock *BB, MachineLoop *CurLoop);
245
246 void EnterScope(MachineBasicBlock *MBB);
247
248 void ExitScope(MachineBasicBlock *MBB);
249
250 void ExitScopeIfDone(
251 MachineDomTreeNode *Node,
252 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
253 const DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
254
255 void HoistOutOfLoop(MachineDomTreeNode *HeaderN, MachineLoop *CurLoop);
256
257 void InitRegPressure(MachineBasicBlock *BB);
258
259 SmallDenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
260 bool ConsiderSeen,
261 bool ConsiderUnseenAsDef);
262
263 void UpdateRegPressure(const MachineInstr *MI,
264 bool ConsiderUnseenAsDef = false);
265
266 MachineInstr *ExtractHoistableLoad(MachineInstr *MI, MachineLoop *CurLoop);
267
268 MachineInstr *LookForDuplicate(const MachineInstr *MI,
269 std::vector<MachineInstr *> &PrevMIs);
270
271 bool
272 EliminateCSE(MachineInstr *MI,
273 DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI);
274
275 bool MayCSE(MachineInstr *MI);
276
277 unsigned Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
278 MachineLoop *CurLoop);
279
280 void InitCSEMap(MachineBasicBlock *BB);
281
282 void InitializeLoadsHoistableLoops();
283
284 bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
285 MachineBasicBlock *TgtBlock);
286 MachineBasicBlock *getOrCreatePreheader(MachineLoop *CurLoop);
287 };
288
289 class MachineLICMBase : public MachineFunctionPass {
290 bool PreRegAlloc;
291
292 public:
293 MachineLICMBase(char &ID, bool PreRegAlloc)
294 : MachineFunctionPass(ID), PreRegAlloc(PreRegAlloc) {}
295
296 bool runOnMachineFunction(MachineFunction &MF) override;
297
298 void getAnalysisUsage(AnalysisUsage &AU) const override {
299 AU.addRequired<MachineLoopInfoWrapperPass>();
301 AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
302 AU.addRequired<MachineDominatorTreeWrapperPass>();
303 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
304 AU.addRequired<AAResultsWrapperPass>();
305 AU.addPreserved<MachineLoopInfoWrapperPass>();
306 AU.addPreserved<MachineDominatorTreeWrapperPass>();
307 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
309 }
310 };
311
312 class MachineLICM : public MachineLICMBase {
313 public:
314 static char ID;
315 MachineLICM() : MachineLICMBase(ID, false) {}
316 };
317
318 class EarlyMachineLICM : public MachineLICMBase {
319 public:
320 static char ID;
321 EarlyMachineLICM() : MachineLICMBase(ID, true) {}
322 };
323
324} // end anonymous namespace
325
326char MachineLICM::ID;
327char EarlyMachineLICM::ID;
328
329char &llvm::MachineLICMID = MachineLICM::ID;
330char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
331
333 "Machine Loop Invariant Code Motion", false, false)
340 "Machine Loop Invariant Code Motion", false, false)
341
342INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
343 "Early Machine Loop Invariant Code Motion", false, false)
349INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
350 "Early Machine Loop Invariant Code Motion", false, false)
351
352bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
353 if (skipFunction(MF.getFunction()))
354 return false;
355
356 MachineLICMImpl Impl(PreRegAlloc, this, nullptr);
357 return Impl.run(MF);
358}
359
360#define GET_RESULT(RESULT, GETTER, INFIX) \
361 ((LegacyPass) \
362 ? &LegacyPass->getAnalysis<RESULT##INFIX##WrapperPass>().GETTER() \
363 : &MFAM->getResult<RESULT##Analysis>(MF))
364
365bool MachineLICMImpl::run(MachineFunction &MF) {
366 AA = MFAM != nullptr
368 .getManager()
369 .getResult<AAManager>(MF.getFunction())
370 : &LegacyPass->getAnalysis<AAResultsWrapperPass>().getAAResults();
371
372 RegClassInfo =
373 MFAM != nullptr
376 .getRCI();
377
379 MachineDomTreeUpdater::UpdateStrategy::Lazy);
380 MDTU = &DTU;
381 MLI = GET_RESULT(MachineLoop, getLI, Info);
382
383 Changed = FirstInLoop = false;
384 const TargetSubtargetInfo &ST = MF.getSubtarget();
385 TII = ST.getInstrInfo();
386 TLI = ST.getTargetLowering();
387 TRI = ST.getRegisterInfo();
388 MFI = &MF.getFrameInfo();
389 MRI = &MF.getRegInfo();
390 SchedModel.init(&ST);
391
392 HasProfileData = MF.getFunction().hasProfileData();
393
395 (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData))
396 MBFI = LegacyPass
398 .getBFI()
400
401 if (PreRegAlloc)
402 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
403 else
404 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
405 LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
406
407 if (PreRegAlloc) {
408 // Estimate register pressure during pre-regalloc pass.
409 unsigned NumRPS = TRI->getNumRegPressureSets();
410 RegPressure.resize(NumRPS);
411 llvm::fill(RegPressure, 0);
412 RegLimit.resize(NumRPS);
413 for (unsigned i = 0, e = NumRPS; i != e; ++i)
414 RegLimit[i] = RegClassInfo->getRegPressureSetLimit(i);
415 }
416
417 if (HoistConstLoads)
418 InitializeLoadsHoistableLoops();
419
420 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
421 while (!Worklist.empty()) {
422 MachineLoop *CurLoop = Worklist.pop_back_val();
423
424 if (!PreRegAlloc) {
425 HoistRegionPostRA(CurLoop);
426 } else {
427 // CSEMap is initialized for loop header when the first instruction is
428 // being hoisted.
429 MachineDomTreeNode *N = MDTU->getDomTree().getNode(CurLoop->getHeader());
430 FirstInLoop = true;
431 HoistOutOfLoop(N, CurLoop);
432 CSEMap.clear();
433 }
434 }
435 releaseMemory();
436 return Changed;
437}
438
439/// Return true if instruction stores to the specified frame.
440static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
441 // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
442 // true since they have no memory operands.
443 if (!MI->mayStore())
444 return false;
445 // If we lost memory operands, conservatively assume that the instruction
446 // writes to all slots.
447 if (MI->memoperands_empty())
448 return true;
449 for (const MachineMemOperand *MemOp : MI->memoperands()) {
450 if (!MemOp->isStore() || !MemOp->getPseudoValue())
451 continue;
453 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
454 if (Value->getFrameIndex() == FI)
455 return true;
456 }
457 }
458 return false;
459}
460
462 BitVector &RUs,
463 const uint32_t *Mask) {
464 // FIXME: This intentionally works in reverse due to some issues with the
465 // Register Units infrastructure.
466 //
467 // This is used to apply callee-saved-register masks to the clobbered regunits
468 // mask.
469 //
470 // The right way to approach this is to start with a BitVector full of ones,
471 // then reset all the bits of the regunits of each register that is set in the
472 // mask (registers preserved), then OR the resulting bits with the Clobbers
473 // mask. This correctly prioritizes the saved registers, so if a RU is shared
474 // between a register that is preserved, and one that is NOT preserved, that
475 // RU will not be set in the output vector (the clobbers).
476 //
477 // What we have to do for now is the opposite: we have to assume that the
478 // regunits of all registers that are NOT preserved are clobbered, even if
479 // those regunits are preserved by another register. So if a RU is shared
480 // like described previously, that RU will be set.
481 //
482 // This is to work around an issue which appears in AArch64, but isn't
483 // exclusive to that target: AArch64's Qn registers (128 bits) have Dn
484 // register (lower 64 bits). A few Dn registers are preserved by some calling
485 // conventions, but Qn and Dn share exactly the same reg units.
486 //
487 // If we do this the right way, Qn will be marked as NOT clobbered even though
488 // its upper 64 bits are NOT preserved. The conservative approach handles this
489 // correctly at the cost of some missed optimizations on other targets.
490 //
491 // This is caused by how RegUnits are handled within TableGen. Ideally, Qn
492 // should have an extra RegUnit to model the "unknown" bits not covered by the
493 // subregs.
494 BitVector RUsFromRegsNotInMask(TRI.getNumRegUnits());
495 const unsigned NumRegs = TRI.getNumRegs();
496 const unsigned MaskWords = (NumRegs + 31) / 32;
497 for (unsigned K = 0; K < MaskWords; ++K) {
498 const uint32_t Word = Mask[K];
499 for (unsigned Bit = 0; Bit < 32; ++Bit) {
500 const unsigned PhysReg = (K * 32) + Bit;
501 if (PhysReg == NumRegs)
502 break;
503
504 if (PhysReg && !((Word >> Bit) & 1)) {
505 for (MCRegUnit Unit : TRI.regunits(PhysReg))
506 RUsFromRegsNotInMask.set(static_cast<unsigned>(Unit));
507 }
508 }
509 }
510
511 RUs |= RUsFromRegsNotInMask;
512}
513
514/// Examine the instruction for potential LICM candidate. Also
515/// gather register def and frame object update information.
516void MachineLICMImpl::ProcessMI(MachineInstr *MI, BitVector &RUDefs,
517 BitVector &RUClobbers,
518 SmallDenseSet<int> &StoredFIs,
519 SmallVectorImpl<CandidateInfo> &Candidates,
520 MachineLoop *CurLoop) {
521 bool RuledOut = false;
522 bool HasNonInvariantUse = false;
524 for (const MachineOperand &MO : MI->operands()) {
525 if (MO.isFI()) {
526 // Remember if the instruction stores to the frame index.
527 int FI = MO.getIndex();
528 if (!StoredFIs.count(FI) &&
529 MFI->isSpillSlotObjectIndex(FI) &&
531 StoredFIs.insert(FI);
532 HasNonInvariantUse = true;
533 continue;
534 }
535
536 // We can't hoist an instruction defining a physreg that is clobbered in
537 // the loop.
538 if (MO.isRegMask()) {
539 applyBitsNotInRegMaskToRegUnitsMask(*TRI, RUClobbers, MO.getRegMask());
540 continue;
541 }
542
543 if (!MO.isReg())
544 continue;
545 Register Reg = MO.getReg();
546 if (!Reg)
547 continue;
548 assert(Reg.isPhysical() && "Not expecting virtual register!");
549
550 if (!MO.isDef()) {
551 if (!HasNonInvariantUse) {
552 for (MCRegUnit Unit : TRI->regunits(Reg)) {
553 // If it's using a non-loop-invariant register, then it's obviously
554 // not safe to hoist.
555 if (RUDefs.test(static_cast<unsigned>(Unit)) ||
556 RUClobbers.test(static_cast<unsigned>(Unit))) {
557 HasNonInvariantUse = true;
558 break;
559 }
560 }
561 }
562 continue;
563 }
564
565 // FIXME: For now, avoid instructions with multiple defs, unless it's dead.
566 if (!MO.isDead()) {
567 if (Def)
568 RuledOut = true;
569 else
570 Def = Reg;
571 }
572
573 // If we have already seen another instruction that defines the same
574 // register, then this is not safe. Two defs is indicated by setting a
575 // PhysRegClobbers bit.
576 for (MCRegUnit Unit : TRI->regunits(Reg)) {
577 if (RUDefs.test(static_cast<unsigned>(Unit))) {
578 RUClobbers.set(static_cast<unsigned>(Unit));
579 RuledOut = true;
580 } else if (RUClobbers.test(static_cast<unsigned>(Unit))) {
581 // MI defined register is seen defined by another instruction in
582 // the loop, it cannot be a LICM candidate.
583 RuledOut = true;
584 }
585
586 RUDefs.set(static_cast<unsigned>(Unit));
587 }
588 }
589
590 // Only consider reloads for now and remats which do not have register
591 // operands. FIXME: Consider unfold load folding instructions.
592 if (Def && !RuledOut) {
593 int FI = std::numeric_limits<int>::min();
594 if ((!HasNonInvariantUse && IsLICMCandidate(*MI, CurLoop)) ||
596 Candidates.push_back(CandidateInfo(MI, Def, FI));
597 }
598}
599
600/// Walk the specified region of the CFG and hoist loop invariants out to the
601/// preheader.
602void MachineLICMImpl::HoistRegionPostRA(MachineLoop *CurLoop) {
603 MachineBasicBlock *Preheader = getOrCreatePreheader(CurLoop);
604 if (!Preheader)
605 return;
606
607 unsigned NumRegUnits = TRI->getNumRegUnits();
608 BitVector RUDefs(NumRegUnits); // RUs defined once in the loop.
609 BitVector RUClobbers(NumRegUnits); // RUs defined more than once.
610
612 SmallDenseSet<int> StoredFIs;
613
614 // Walk the entire region, count number of defs for each register, and
615 // collect potential LICM candidates.
616 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
617 // If the header of the loop containing this basic block is a landing pad,
618 // then don't try to hoist instructions out of this loop.
619 const MachineLoop *ML = MLI->getLoopFor(BB);
620 if (ML && ML->getHeader()->isEHPad()) continue;
621
622 // Conservatively treat live-in's as an external def.
623 // FIXME: That means a reload that're reused in successor block(s) will not
624 // be LICM'ed.
625 for (const auto &LI : BB->liveins()) {
626 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg))
627 RUDefs.set(static_cast<unsigned>(Unit));
628 }
629
630 // Funclet entry blocks will clobber all registers
631 if (const uint32_t *Mask = BB->getBeginClobberMask(TRI))
632 applyBitsNotInRegMaskToRegUnitsMask(*TRI, RUClobbers, Mask);
633
634 // EH landing pads clobber exception pointer/selector registers.
635 if (BB->isEHPad()) {
636 const MachineFunction &MF = *BB->getParent();
637 const Constant *PersonalityFn = MF.getFunction().getPersonalityFn();
638 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
640 if (MCRegister Reg = TLI.getExceptionPointerRegister(EH, PersonalityFn))
641 for (MCRegUnit Unit : TRI->regunits(Reg))
642 RUClobbers.set(static_cast<unsigned>(Unit));
643 if (MCRegister Reg = TLI.getExceptionSelectorRegister(EH, PersonalityFn))
644 for (MCRegUnit Unit : TRI->regunits(Reg))
645 RUClobbers.set(static_cast<unsigned>(Unit));
646 }
647
648 GuaranteedToExecute.clear();
649 for (MachineInstr &MI : *BB)
650 ProcessMI(&MI, RUDefs, RUClobbers, StoredFIs, Candidates, CurLoop);
651 }
652
653 // Gather the registers read / clobbered by the terminator.
654 BitVector TermRUs(NumRegUnits);
656 if (TI != Preheader->end()) {
657 for (const MachineOperand &MO : TI->operands()) {
658 if (!MO.isReg())
659 continue;
660 Register Reg = MO.getReg();
661 if (!Reg)
662 continue;
663 for (MCRegUnit Unit : TRI->regunits(Reg))
664 TermRUs.set(static_cast<unsigned>(Unit));
665 }
666 }
667
668 // Now evaluate whether the potential candidates qualify.
669 // 1. Check if the candidate defined register is defined by another
670 // instruction in the loop.
671 // 2. If the candidate is a load from stack slot (always true for now),
672 // check if the slot is stored anywhere in the loop.
673 // 3. Make sure candidate def should not clobber
674 // registers read by the terminator. Similarly its def should not be
675 // clobbered by the terminator.
676 for (CandidateInfo &Candidate : Candidates) {
677 if (Candidate.FI != std::numeric_limits<int>::min() &&
678 StoredFIs.count(Candidate.FI))
679 continue;
680
681 Register Def = Candidate.Def;
682 bool Safe = true;
683 for (MCRegUnit Unit : TRI->regunits(Def)) {
684 if (RUClobbers.test(static_cast<unsigned>(Unit)) ||
685 TermRUs.test(static_cast<unsigned>(Unit))) {
686 Safe = false;
687 break;
688 }
689 }
690
691 if (!Safe)
692 continue;
693
694 MachineInstr *MI = Candidate.MI;
695 for (const MachineOperand &MO : MI->all_uses()) {
696 if (!MO.getReg())
697 continue;
698 for (MCRegUnit Unit : TRI->regunits(MO.getReg())) {
699 if (RUDefs.test(static_cast<unsigned>(Unit)) ||
700 RUClobbers.test(static_cast<unsigned>(Unit))) {
701 // If it's using a non-loop-invariant register, then it's obviously
702 // not safe to hoist.
703 Safe = false;
704 break;
705 }
706 }
707
708 if (!Safe)
709 break;
710 }
711
712 if (Safe)
713 HoistPostRA(MI, Candidate.Def, CurLoop);
714 }
715}
716
717/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
718/// sure it is not killed by any instructions in the loop.
719void MachineLICMImpl::AddToLiveIns(MCRegister Reg, MachineLoop *CurLoop) {
720 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
721 if (!BB->isLiveIn(Reg))
722 BB->addLiveIn(Reg);
723 for (MachineInstr &MI : *BB) {
724 for (MachineOperand &MO : MI.all_uses()) {
725 if (!MO.getReg())
726 continue;
727 if (TRI->regsOverlap(Reg, MO.getReg()))
728 MO.setIsKill(false);
729 }
730 }
731 }
732}
733
734/// When an instruction is found to only use loop invariant operands that is
735/// safe to hoist, this instruction is called to do the dirty work.
736void MachineLICMImpl::HoistPostRA(MachineInstr *MI, Register Def,
737 MachineLoop *CurLoop) {
738 MachineBasicBlock *Preheader = CurLoop->getLoopPreheader();
739
740 // Now move the instructions to the predecessor, inserting it before any
741 // terminator instructions.
742 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
743 << " from " << printMBBReference(*MI->getParent()) << ": "
744 << *MI);
745
746 // Splice the instruction to the preheader.
747 MachineBasicBlock *MBB = MI->getParent();
748 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
749
750 // Since we are moving the instruction out of its basic block, we do not
751 // retain its debug location. Doing so would degrade the debugging
752 // experience and adversely affect the accuracy of profiling information.
753 assert(!MI->isDebugInstr() && "Should not hoist debug inst");
754 MI->setDebugLoc(DebugLoc());
755
756 // Add register to livein list to all the BBs in the current loop since a
757 // loop invariant must be kept live throughout the whole loop. This is
758 // important to ensure later passes do not scavenge the def register.
759 AddToLiveIns(Def, CurLoop);
760
761 ++NumPostRAHoisted;
762 Changed = true;
763}
764
765/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
766/// may not be safe to hoist.
767bool MachineLICMImpl::IsGuaranteedToExecute(MachineBasicBlock *BB,
768 MachineLoop *CurLoop) {
769 auto [It, Inserted] = GuaranteedToExecute.try_emplace(CurLoop, true);
770 if (!Inserted)
771 return It->second;
772
773 if (BB != CurLoop->getHeader()) {
774 // Check loop exiting blocks.
775 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
776 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
777 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
778 if (!MDTU->getDomTree().dominates(BB, CurrentLoopExitingBlock)) {
779 It->second = false;
780 return false;
781 }
782 }
783
784 return true;
785}
786
787void MachineLICMImpl::EnterScope(MachineBasicBlock *MBB) {
788 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
789
790 // Remember livein register pressure.
791 BackTrace.push_back(RegPressure);
792}
793
794void MachineLICMImpl::ExitScope(MachineBasicBlock *MBB) {
795 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
796 BackTrace.pop_back();
797}
798
799/// Destroy scope for the MBB that corresponds to the given dominator tree node
800/// if its a leaf or all of its children are done. Walk up the dominator tree to
801/// destroy ancestors which are now done.
802void MachineLICMImpl::ExitScopeIfDone(
803 MachineDomTreeNode *Node,
804 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
805 const DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap) {
806 if (OpenChildren[Node])
807 return;
808
809 for(;;) {
810 ExitScope(Node->getBlock());
811 // Now traverse upwards to pop ancestors whose offsprings are all done.
812 MachineDomTreeNode *Parent = ParentMap.lookup(Node);
813 if (!Parent || --OpenChildren[Parent] != 0)
814 break;
815 Node = Parent;
816 }
817}
818
819/// Walk the specified loop in the CFG (defined by all blocks dominated by the
820/// specified header block, and that are in the current loop) in depth first
821/// order w.r.t the DominatorTree. This allows us to visit definitions before
822/// uses, allowing us to hoist a loop body in one pass without iteration.
823void MachineLICMImpl::HoistOutOfLoop(MachineDomTreeNode *HeaderN,
824 MachineLoop *CurLoop) {
825 MachineBasicBlock *Preheader = getOrCreatePreheader(CurLoop);
826 if (!Preheader)
827 return;
828
831 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
832 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
833
834 // Perform a DFS walk to determine the order of visit.
835 WorkList.push_back(HeaderN);
836 while (!WorkList.empty()) {
838 assert(Node && "Null dominator tree node?");
839 MachineBasicBlock *BB = Node->getBlock();
840
841 // If the header of the loop containing this basic block is a landing pad,
842 // then don't try to hoist instructions out of this loop.
843 const MachineLoop *ML = MLI->getLoopFor(BB);
844 if (ML && ML->getHeader()->isEHPad())
845 continue;
846
847 // If this subregion is not in the top level loop at all, exit.
848 if (!CurLoop->contains(BB))
849 continue;
850
851 Scopes.push_back(Node);
852
853 // Don't hoist things out of a large switch statement. This often causes
854 // code to be hoisted that wasn't going to be executed, and increases
855 // register pressure in a situation where it's likely to matter.
856 if (BB->succ_size() >= 25) {
857 OpenChildren[Node] = 0;
858 continue;
859 }
860
861 // Add children in reverse order as then the next popped worklist node is
862 // the first child of this node. This means we ultimately traverse the
863 // DOM tree in exactly the same order as if we'd recursed.
864 size_t WorkListStart = WorkList.size();
865 for (MachineDomTreeNode *Child : Node->children()) {
866 ParentMap[Child] = Node;
867 WorkList.push_back(Child);
868 }
869 std::reverse(WorkList.begin() + WorkListStart, WorkList.end());
870 OpenChildren[Node] = WorkList.size() - WorkListStart;
871 }
872
873 if (Scopes.size() == 0)
874 return;
875
876 // Compute registers which are livein into the loop headers.
877 RegSeen.clear();
878 BackTrace.clear();
879 InitRegPressure(Preheader);
880
881 // Now perform LICM.
882 for (MachineDomTreeNode *Node : Scopes) {
883 MachineBasicBlock *MBB = Node->getBlock();
884
885 EnterScope(MBB);
886
887 // Process the block
888 GuaranteedToExecute.clear();
889 for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
890 unsigned HoistRes = HoistResult::NotHoisted;
891 HoistRes = Hoist(&MI, Preheader, CurLoop);
892 if (HoistRes & HoistResult::NotHoisted) {
893 // We have failed to hoist MI to outermost loop's preheader. If MI is in
894 // a subloop, try to hoist it to subloop's preheader.
895 SmallVector<MachineLoop *> InnerLoopWorkList;
896 for (MachineLoop *L = MLI->getLoopFor(MI.getParent()); L != CurLoop;
897 L = L->getParentLoop())
898 InnerLoopWorkList.push_back(L);
899
900 while (!InnerLoopWorkList.empty()) {
901 MachineLoop *InnerLoop = InnerLoopWorkList.pop_back_val();
902 MachineBasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
903 if (InnerLoopPreheader) {
904 HoistRes = Hoist(&MI, InnerLoopPreheader, InnerLoop);
905 if (HoistRes & HoistResult::Hoisted)
906 break;
907 }
908 }
909 }
910
911 if (HoistRes & HoistResult::ErasedMI)
912 continue;
913
914 UpdateRegPressure(&MI);
915 }
916
917 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
918 ExitScopeIfDone(Node, OpenChildren, ParentMap);
919 }
920}
921
922/// Find all virtual register references that are liveout of the preheader to
923/// initialize the starting "register pressure". Note this does not count live
924/// through (livein but not used) registers.
925void MachineLICMImpl::InitRegPressure(MachineBasicBlock *BB) {
926 llvm::fill(RegPressure, 0);
927
928 // If the preheader has only a single predecessor and it ends with a
929 // fallthrough or an unconditional branch, then scan its predecessor for live
930 // defs as well. This happens whenever the preheader is created by splitting
931 // the critical edge from the loop predecessor to the loop header.
932 if (BB->pred_size() == 1) {
933 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
934 SmallVector<MachineOperand, 4> Cond;
935 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
936 InitRegPressure(*BB->pred_begin());
937 }
938
939 for (const MachineInstr &MI : *BB)
940 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
941}
942
943/// Update estimate of register pressure after the specified instruction.
944void MachineLICMImpl::UpdateRegPressure(const MachineInstr *MI,
945 bool ConsiderUnseenAsDef) {
946 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
947 for (const auto &[Class, Weight] : Cost) {
948 if (static_cast<int>(RegPressure[Class]) < -Weight)
949 RegPressure[Class] = 0;
950 else
951 RegPressure[Class] += Weight;
952 }
953}
954
955/// Calculate the additional register pressure that the registers used in MI
956/// cause.
957///
958/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
959/// figure out which usages are live-ins.
960/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
961SmallDenseMap<unsigned, int>
962MachineLICMImpl::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
963 bool ConsiderUnseenAsDef) {
964 SmallDenseMap<unsigned, int> Cost;
965 if (MI->isImplicitDef())
966 return Cost;
967 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
968 const MachineOperand &MO = MI->getOperand(i);
969 if (!MO.isReg() || MO.isImplicit())
970 continue;
971 Register Reg = MO.getReg();
972 if (!Reg.isVirtual())
973 continue;
974
975 // FIXME: It seems bad to use RegSeen only for some of these calculations.
976 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
978
979 RegClassWeight W = TRI->getRegClassWeight(RC);
980 int RCCost = 0;
981 if (MO.isDef())
982 RCCost = W.RegWeight;
983 else {
984 bool isKill = MRI->hasOneNonDBGUse(Reg);
985 if (isNew && !isKill && ConsiderUnseenAsDef)
986 // Haven't seen this, it must be a livein.
987 RCCost = W.RegWeight;
988 else if (!isNew && isKill)
989 RCCost = -W.RegWeight;
990 }
991 if (RCCost == 0)
992 continue;
993 const int *PS = TRI->getRegClassPressureSets(RC);
994 for (; *PS != -1; ++PS)
995 Cost[*PS] += RCCost;
996 }
997 return Cost;
998}
999
1000/// Return true if this machine instruction loads from global offset table or
1001/// constant pool.
1003 assert(MI.mayLoad() && "Expected MI that loads!");
1004
1005 // If we lost memory operands, conservatively assume that the instruction
1006 // reads from everything..
1007 if (MI.memoperands_empty())
1008 return true;
1009
1010 for (MachineMemOperand *MemOp : MI.memoperands())
1011 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
1012 if (PSV->isGOT() || PSV->isConstantPool())
1013 return true;
1014
1015 return false;
1016}
1017
1018// This function iterates through all the operands of the input store MI and
1019// checks that each register operand statisfies isCallerPreservedPhysReg.
1020// This means, the value being stored and the address where it is being stored
1021// is constant throughout the body of the function (not including prologue and
1022// epilogue). When called with an MI that isn't a store, it returns false.
1023// A future improvement can be to check if the store registers are constant
1024// throughout the loop rather than throughout the funtion.
1026 const TargetRegisterInfo *TRI,
1027 const MachineRegisterInfo *MRI) {
1028
1029 bool FoundCallerPresReg = false;
1030 if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
1031 (MI.getNumOperands() == 0))
1032 return false;
1033
1034 // Check that all register operands are caller-preserved physical registers.
1035 for (const MachineOperand &MO : MI.operands()) {
1036 if (MO.isReg()) {
1037 Register Reg = MO.getReg();
1038 // If operand is a virtual register, check if it comes from a copy of a
1039 // physical register.
1040 if (Reg.isVirtual())
1041 Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
1042 if (Reg.isVirtual())
1043 return false;
1044 if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF()))
1045 return false;
1046 else
1047 FoundCallerPresReg = true;
1048 } else if (!MO.isImm()) {
1049 return false;
1050 }
1051 }
1052 return FoundCallerPresReg;
1053}
1054
1055// Return true if the input MI is a copy instruction that feeds an invariant
1056// store instruction. This means that the src of the copy has to satisfy
1057// isCallerPreservedPhysReg and atleast one of it's users should satisfy
1058// isInvariantStore.
1060 const MachineRegisterInfo *MRI,
1061 const TargetRegisterInfo *TRI) {
1062
1063 // FIXME: If targets would like to look through instructions that aren't
1064 // pure copies, this can be updated to a query.
1065 if (!MI.isCopy())
1066 return false;
1067
1068 const MachineFunction *MF = MI.getMF();
1069 // Check that we are copying a constant physical register.
1070 Register CopySrcReg = MI.getOperand(1).getReg();
1071 if (CopySrcReg.isVirtual())
1072 return false;
1073
1074 if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF))
1075 return false;
1076
1077 Register CopyDstReg = MI.getOperand(0).getReg();
1078 // Check if any of the uses of the copy are invariant stores.
1079 assert(CopyDstReg.isVirtual() && "copy dst is not a virtual reg");
1080
1081 for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
1082 if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
1083 return true;
1084 }
1085 return false;
1086}
1087
1088/// Returns true if the instruction may be a suitable candidate for LICM.
1089/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
1090bool MachineLICMImpl::IsLICMCandidate(MachineInstr &I, MachineLoop *CurLoop) {
1091 // Check if it's safe to move the instruction.
1092 bool DontMoveAcrossStore = !HoistConstLoads || !AllowedToHoistLoads[CurLoop];
1093 if ((!I.isSafeToMove(DontMoveAcrossStore)) &&
1095 LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
1096 return false;
1097 }
1098
1099 // If it is a load then check if it is guaranteed to execute by making sure
1100 // that it dominates all exiting blocks. If it doesn't, then there is a path
1101 // out of the loop which does not execute this load, so we can't hoist it.
1102 // Loads from constant memory are safe to speculate, for example indexed load
1103 // from a jump table.
1104 // Stores and side effects are already checked by isSafeToMove.
1105 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
1106 !IsGuaranteedToExecute(I.getParent(), CurLoop)) {
1107 LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
1108 return false;
1109 }
1110
1111 // Convergent attribute has been used on operations that involve inter-thread
1112 // communication which results are implicitly affected by the enclosing
1113 // control flows. It is not safe to hoist or sink such operations across
1114 // control flow.
1115 if (I.isConvergent())
1116 return false;
1117
1118 if (!TII->shouldHoist(I, CurLoop))
1119 return false;
1120
1121 return true;
1122}
1123
1124/// Returns true if the instruction is loop invariant.
1125bool MachineLICMImpl::IsLoopInvariantInst(MachineInstr &I,
1126 MachineLoop *CurLoop) {
1127 if (!IsLICMCandidate(I, CurLoop)) {
1128 LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
1129 return false;
1130 }
1131 return CurLoop->isLoopInvariant(I);
1132}
1133
1134/// Return true if the specified instruction is used by a phi node and hoisting
1135/// it could cause a copy to be inserted.
1136bool MachineLICMImpl::HasLoopPHIUse(const MachineInstr *MI,
1137 MachineLoop *CurLoop) {
1139 do {
1140 MI = Work.pop_back_val();
1141 for (const MachineOperand &MO : MI->all_defs()) {
1142 Register Reg = MO.getReg();
1143 if (!Reg.isVirtual())
1144 continue;
1145 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1146 // A PHI may cause a copy to be inserted.
1147 if (UseMI.isPHI()) {
1148 // A PHI inside the loop causes a copy because the live range of Reg is
1149 // extended across the PHI.
1150 if (CurLoop->contains(&UseMI))
1151 return true;
1152 // A PHI in an exit block can cause a copy to be inserted if the PHI
1153 // has multiple predecessors in the loop with different values.
1154 // For now, approximate by rejecting all exit blocks.
1155 if (isExitBlock(CurLoop, UseMI.getParent()))
1156 return true;
1157 continue;
1158 }
1159 // Look past copies as well.
1160 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1161 Work.push_back(&UseMI);
1162 }
1163 }
1164 } while (!Work.empty());
1165 return false;
1166}
1167
1168/// Compute operand latency between a def of 'Reg' and an use in the current
1169/// loop, return true if the target considered it high.
1170bool MachineLICMImpl::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
1171 Register Reg,
1172 MachineLoop *CurLoop) const {
1173 if (MRI->use_nodbg_empty(Reg))
1174 return false;
1175
1176 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1177 if (UseMI.isCopyLike())
1178 continue;
1179 if (!CurLoop->contains(UseMI.getParent()))
1180 continue;
1181 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1182 const MachineOperand &MO = UseMI.getOperand(i);
1183 if (!MO.isReg() || !MO.isUse())
1184 continue;
1185 Register MOReg = MO.getReg();
1186 if (MOReg != Reg)
1187 continue;
1188
1189 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
1190 return true;
1191 }
1192
1193 // Only look at the first in loop use.
1194 break;
1195 }
1196
1197 return false;
1198}
1199
1200/// Return true if the instruction is marked "cheap" or the operand latency
1201/// between its def and a use is one or less.
1202bool MachineLICMImpl::IsCheapInstruction(MachineInstr &MI) const {
1203 if (TII->isAsCheapAsAMove(MI) || MI.isSubregToReg())
1204 return true;
1205
1206 bool isCheap = false;
1207 unsigned NumDefs = MI.getDesc().getNumDefs();
1208 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1209 MachineOperand &DefMO = MI.getOperand(i);
1210 if (!DefMO.isReg() || !DefMO.isDef())
1211 continue;
1212 --NumDefs;
1213 Register Reg = DefMO.getReg();
1214 if (Reg.isPhysical())
1215 continue;
1216
1217 if (!TII->hasLowDefLatency(SchedModel, MI, i))
1218 return false;
1219 isCheap = true;
1220 }
1221
1222 return isCheap;
1223}
1224
1225/// Visit BBs from header to current BB, check if hoisting an instruction of the
1226/// given cost matrix can cause high register pressure.
1227bool MachineLICMImpl::CanCauseHighRegPressure(
1228 const SmallDenseMap<unsigned, int> &Cost, bool CheapInstr) {
1229 for (const auto &[Class, Weight] : Cost) {
1230 if (Weight <= 0)
1231 continue;
1232
1233 int Limit = RegLimit[Class];
1234
1235 // Don't hoist cheap instructions if they would increase register pressure,
1236 // even if we're under the limit.
1237 if (CheapInstr && !HoistCheapInsts)
1238 return true;
1239
1240 for (const auto &RP : BackTrace)
1241 if (static_cast<int>(RP[Class]) + Weight >= Limit)
1242 return true;
1243 }
1244
1245 return false;
1246}
1247
1248/// Traverse the back trace from header to the current block and update their
1249/// register pressures to reflect the effect of hoisting MI from the current
1250/// block to the preheader.
1251void MachineLICMImpl::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1252 // First compute the 'cost' of the instruction, i.e. its contribution
1253 // to register pressure.
1254 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1255 /*ConsiderUnseenAsDef=*/false);
1256
1257 // Update register pressure of blocks from loop header to current block.
1258 for (auto &RP : BackTrace)
1259 for (const auto &[Class, Weight] : Cost)
1260 RP[Class] += Weight;
1261}
1262
1263/// Return true if it is potentially profitable to hoist the given loop
1264/// invariant.
1265bool MachineLICMImpl::IsProfitableToHoist(MachineInstr &MI,
1266 MachineLoop *CurLoop) {
1267 if (MI.isImplicitDef())
1268 return true;
1269
1270 // Besides removing computation from the loop, hoisting an instruction has
1271 // these effects:
1272 //
1273 // - The value defined by the instruction becomes live across the entire
1274 // loop. This increases register pressure in the loop.
1275 //
1276 // - If the value is used by a PHI in the loop, a copy will be required for
1277 // lowering the PHI after extending the live range.
1278 //
1279 // - When hoisting the last use of a value in the loop, that value no longer
1280 // needs to be live in the loop. This lowers register pressure in the loop.
1281
1283 return true;
1284
1285 bool CheapInstr = IsCheapInstruction(MI);
1286 bool CreatesCopy = HasLoopPHIUse(&MI, CurLoop);
1287
1288 // Don't hoist a cheap instruction if it would create a copy in the loop.
1289 if (CheapInstr && CreatesCopy) {
1290 LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1291 return false;
1292 }
1293
1294 // Trivially rematerializable instructions should always be hoisted
1295 // providing the register allocator can just pull them down again when needed.
1296 if (TII->isTriviallyReMaterializable(MI))
1297 return true;
1298
1299 // FIXME: If there are long latency loop-invariant instructions inside the
1300 // loop at this point, why didn't the optimizer's LICM hoist them?
1301 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1302 const MachineOperand &MO = MI.getOperand(i);
1303 if (!MO.isReg() || MO.isImplicit())
1304 continue;
1305 Register Reg = MO.getReg();
1306 if (!Reg.isVirtual())
1307 continue;
1308 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg, CurLoop)) {
1309 LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
1310 ++NumHighLatency;
1311 return true;
1312 }
1313 }
1314
1315 // Estimate register pressure to determine whether to LICM the instruction.
1316 // In low register pressure situation, we can be more aggressive about
1317 // hoisting. Also, favors hoisting long latency instructions even in
1318 // moderately high pressure situation.
1319 // Cheap instructions will only be hoisted if they don't increase register
1320 // pressure at all.
1321 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1322 /*ConsiderUnseenAsDef=*/false);
1323
1324 // Visit BBs from header to current BB, if hoisting this doesn't cause
1325 // high register pressure, then it's safe to proceed.
1326 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1327 LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1328 ++NumLowRP;
1329 return true;
1330 }
1331
1332 // Don't risk increasing register pressure if it would create copies.
1333 if (CreatesCopy) {
1334 LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1335 return false;
1336 }
1337
1338 // Do not "speculate" in high register pressure situation. If an
1339 // instruction is not guaranteed to be executed in the loop, it's best to be
1340 // conservative.
1341 if (AvoidSpeculation &&
1342 (!IsGuaranteedToExecute(MI.getParent(), CurLoop) && !MayCSE(&MI))) {
1343 LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
1344 return false;
1345 }
1346
1347 // If we have a COPY with other uses in the loop, hoist to allow the users to
1348 // also be hoisted.
1349 // TODO: Handle all isCopyLike?
1350 if (MI.isCopy() || MI.isRegSequence()) {
1351 Register DefReg = MI.getOperand(0).getReg();
1352 if (DefReg.isVirtual() &&
1353 all_of(MI.uses(),
1354 [this](const MachineOperand &UseOp) {
1355 return !UseOp.isReg() || UseOp.getReg().isVirtual() ||
1356 MRI->isConstantPhysReg(UseOp.getReg());
1357 }) &&
1358 IsLoopInvariantInst(MI, CurLoop) &&
1360 [&CurLoop, this, DefReg,
1361 Cost = std::move(Cost)](MachineInstr &UseMI) {
1362 if (!CurLoop->contains(&UseMI))
1363 return false;
1364
1365 // COPY is a cheap instruction, but if moving it won't cause
1366 // high RP we're fine to hoist it even if the user can't be
1367 // hoisted later Otherwise we want to check the user if it's
1368 // hoistable
1369 if (CanCauseHighRegPressure(Cost, false) &&
1370 !CurLoop->isLoopInvariant(UseMI, DefReg))
1371 return false;
1372
1373 return true;
1374 }))
1375 return true;
1376 }
1377
1378 // High register pressure situation, only hoist if the instruction is going
1379 // to be remat'ed.
1380 if (!TII->isTriviallyReMaterializable(MI) &&
1381 !MI.isDereferenceableInvariantLoad()) {
1382 LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1383 return false;
1384 }
1385
1386 return true;
1387}
1388
1389/// Unfold a load from the given machineinstr if the load itself could be
1390/// hoisted. Return the unfolded and hoistable load, or null if the load
1391/// couldn't be unfolded or if it wouldn't be hoistable.
1392MachineInstr *MachineLICMImpl::ExtractHoistableLoad(MachineInstr *MI,
1393 MachineLoop *CurLoop) {
1394 // Don't unfold simple loads.
1395 if (MI->canFoldAsLoad())
1396 return nullptr;
1397
1398 // If not, we may be able to unfold a load and hoist that.
1399 // First test whether the instruction is loading from an amenable
1400 // memory location.
1401 if (!MI->isDereferenceableInvariantLoad())
1402 return nullptr;
1403
1404 // Next determine the register class for a temporary register.
1405 unsigned LoadRegIndex;
1406 unsigned NewOpc =
1407 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1408 /*UnfoldLoad=*/true,
1409 /*UnfoldStore=*/false,
1410 &LoadRegIndex);
1411 if (NewOpc == 0) return nullptr;
1412 const MCInstrDesc &MID = TII->get(NewOpc);
1413 MachineFunction &MF = *MI->getMF();
1414 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex);
1415 // Ok, we're unfolding. Create a temporary register and do the unfold.
1417
1418 SmallVector<MachineInstr *, 2> NewMIs;
1419 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1420 /*UnfoldLoad=*/true,
1421 /*UnfoldStore=*/false, NewMIs);
1422 (void)Success;
1423 assert(Success &&
1424 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1425 "succeeded!");
1426 assert(NewMIs.size() == 2 &&
1427 "Unfolded a load into multiple instructions!");
1428 MachineBasicBlock *MBB = MI->getParent();
1430 MBB->insert(Pos, NewMIs[0]);
1431 MBB->insert(Pos, NewMIs[1]);
1432 // If unfolding produced a load that wasn't loop-invariant or profitable to
1433 // hoist, discard the new instructions and bail.
1434 if (!IsLoopInvariantInst(*NewMIs[0], CurLoop) ||
1435 !IsProfitableToHoist(*NewMIs[0], CurLoop)) {
1436 NewMIs[0]->eraseFromParent();
1437 NewMIs[1]->eraseFromParent();
1438 return nullptr;
1439 }
1440
1441 // Update register pressure for the unfolded instruction.
1442 UpdateRegPressure(NewMIs[1]);
1443
1444 // Otherwise we successfully unfolded a load that we can hoist.
1445
1446 // Update the call info.
1447 if (MI->shouldUpdateAdditionalCallInfo())
1449
1450 MI->eraseFromParent();
1451 return NewMIs[0];
1452}
1453
1454/// Initialize the CSE map with instructions that are in the current loop
1455/// preheader that may become duplicates of instructions that are hoisted
1456/// out of the loop.
1457void MachineLICMImpl::InitCSEMap(MachineBasicBlock *BB) {
1458 for (MachineInstr &MI : *BB)
1459 CSEMap[BB][MI.getOpcode()].push_back(&MI);
1460}
1461
1462/// Initialize AllowedToHoistLoads with information about whether invariant
1463/// loads can be moved outside a given loop
1464void MachineLICMImpl::InitializeLoadsHoistableLoops() {
1465 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
1466 SmallVector<MachineLoop *, 8> LoopsInPreOrder;
1467
1468 // Mark all loops as hoistable initially and prepare a list of loops in
1469 // pre-order DFS.
1470 while (!Worklist.empty()) {
1471 auto *L = Worklist.pop_back_val();
1472 AllowedToHoistLoads[L] = true;
1473 LoopsInPreOrder.push_back(L);
1474 llvm::append_range(Worklist, L->getSubLoops());
1475 }
1476
1477 // Going from the innermost to outermost loops, check if a loop has
1478 // instructions preventing invariant load hoisting. If such instruction is
1479 // found, mark this loop and its parent as non-hoistable and continue
1480 // investigating the next loop.
1481 // Visiting in a reversed pre-ordered DFS manner
1482 // allows us to not process all the instructions of the outer loop if the
1483 // inner loop is proved to be non-load-hoistable.
1484 for (auto *Loop : reverse(LoopsInPreOrder)) {
1485 for (auto *MBB : Loop->blocks()) {
1486 // If this loop has already been marked as non-hoistable, skip it.
1487 if (!AllowedToHoistLoads[Loop])
1488 continue;
1489 for (auto &MI : *MBB) {
1490 if (!MI.isLoadFoldBarrier() && !MI.mayStore() && !MI.isCall() &&
1491 !(MI.mayLoad() && MI.hasOrderedMemoryRef()))
1492 continue;
1493 for (MachineLoop *L = Loop; L != nullptr; L = L->getParentLoop())
1494 AllowedToHoistLoads[L] = false;
1495 break;
1496 }
1497 }
1498 }
1499}
1500
1501/// Find an instruction amount PrevMIs that is a duplicate of MI.
1502/// Return this instruction if it's found.
1503MachineInstr *
1504MachineLICMImpl::LookForDuplicate(const MachineInstr *MI,
1505 std::vector<MachineInstr *> &PrevMIs) {
1506 for (MachineInstr *PrevMI : PrevMIs)
1507 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1508 return PrevMI;
1509
1510 return nullptr;
1511}
1512
1513/// Given a LICM'ed instruction, look for an instruction on the preheader that
1514/// computes the same value. If it's found, do a RAU on with the definition of
1515/// the existing instruction rather than hoisting the instruction to the
1516/// preheader.
1517bool MachineLICMImpl::EliminateCSE(
1518 MachineInstr *MI,
1519 DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI) {
1520 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1521 // the undef property onto uses.
1522 if (MI->isImplicitDef())
1523 return false;
1524
1525 // Do not CSE normal loads because between them could be store instructions
1526 // that change the loaded value
1527 if (MI->mayLoad() && !MI->isDereferenceableInvariantLoad())
1528 return false;
1529
1530 if (MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1531 LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1532
1533 // Replace virtual registers defined by MI by their counterparts defined
1534 // by Dup.
1535 SmallVector<unsigned, 2> Defs;
1536 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1537 const MachineOperand &MO = MI->getOperand(i);
1538
1539 // Physical registers may not differ here.
1540 assert((!MO.isReg() || MO.getReg() == 0 || !MO.getReg().isPhysical() ||
1541 MO.getReg() == Dup->getOperand(i).getReg()) &&
1542 "Instructions with different phys regs are not identical!");
1543
1544 if (MO.isReg() && MO.isDef() && !MO.getReg().isPhysical())
1545 Defs.push_back(i);
1546 }
1547
1549 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1550 unsigned Idx = Defs[i];
1551 Register Reg = MI->getOperand(Idx).getReg();
1552 Register DupReg = Dup->getOperand(Idx).getReg();
1553 OrigRCs.push_back(MRI->getRegClass(DupReg));
1554
1555 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1556 // Restore old RCs if more than one defs.
1557 for (unsigned j = 0; j != i; ++j)
1558 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1559 return false;
1560 }
1561 }
1562
1563 for (unsigned Idx : Defs) {
1564 Register Reg = MI->getOperand(Idx).getReg();
1565 Register DupReg = Dup->getOperand(Idx).getReg();
1566 MRI->replaceRegWith(Reg, DupReg);
1567 // Clear Dup dead flag if any, we reuse it for Reg.
1568 if (!MRI->use_nodbg_empty(DupReg))
1569 Dup->getOperand(Idx).setIsDead(false);
1570 }
1571
1572 MI->eraseFromParent();
1573 ++NumCSEed;
1574 return true;
1575 }
1576 return false;
1577}
1578
1579/// Return true if the given instruction will be CSE'd if it's hoisted out of
1580/// the loop.
1581bool MachineLICMImpl::MayCSE(MachineInstr *MI) {
1582 if (MI->mayLoad() && !MI->isDereferenceableInvariantLoad())
1583 return false;
1584
1585 unsigned Opcode = MI->getOpcode();
1586 for (auto &Map : CSEMap) {
1587 // Check this CSEMap's preheader dominates MI's basic block.
1588 if (MDTU->getDomTree().dominates(Map.first, MI->getParent())) {
1589 DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1590 Map.second.find(Opcode);
1591 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1592 // the undef property onto uses.
1593 if (CI == Map.second.end() || MI->isImplicitDef())
1594 continue;
1595 if (LookForDuplicate(MI, CI->second) != nullptr)
1596 return true;
1597 }
1598 }
1599
1600 return false;
1601}
1602
1603/// When an instruction is found to use only loop invariant operands
1604/// that are safe to hoist, this instruction is called to do the dirty work.
1605/// It returns true if the instruction is hoisted.
1606unsigned MachineLICMImpl::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
1607 MachineLoop *CurLoop) {
1608 MachineBasicBlock *SrcBlock = MI->getParent();
1609
1610 // Disable the instruction hoisting due to block hotness
1612 (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
1613 isTgtHotterThanSrc(SrcBlock, Preheader)) {
1614 ++NumNotHoistedDueToHotness;
1615 return HoistResult::NotHoisted;
1616 }
1617 // First check whether we should hoist this instruction.
1618 bool HasExtractHoistableLoad = false;
1619 if (!IsLoopInvariantInst(*MI, CurLoop) ||
1620 !IsProfitableToHoist(*MI, CurLoop)) {
1621 // If not, try unfolding a hoistable load.
1622 MI = ExtractHoistableLoad(MI, CurLoop);
1623 if (!MI)
1624 return HoistResult::NotHoisted;
1625 HasExtractHoistableLoad = true;
1626 }
1627
1628 // If we have hoisted an instruction that may store, it can only be a constant
1629 // store.
1630 if (MI->mayStore())
1631 NumStoreConst++;
1632
1633 // Now move the instructions to the predecessor, inserting it before any
1634 // terminator instructions.
1635 LLVM_DEBUG({
1636 dbgs() << "Hoisting " << *MI;
1637 if (MI->getParent()->getBasicBlock())
1638 dbgs() << " from " << printMBBReference(*MI->getParent());
1639 if (Preheader->getBasicBlock())
1640 dbgs() << " to " << printMBBReference(*Preheader);
1641 dbgs() << "\n";
1642 });
1643
1644 // If this is the first instruction being hoisted to the preheader,
1645 // initialize the CSE map with potential common expressions.
1646 if (FirstInLoop) {
1647 InitCSEMap(Preheader);
1648 FirstInLoop = false;
1649 }
1650
1651 // Look for opportunity to CSE the hoisted instruction.
1652 unsigned Opcode = MI->getOpcode();
1653 bool HasCSEDone = false;
1654 for (auto &Map : CSEMap) {
1655 // Check this CSEMap's preheader dominates MI's basic block.
1656 if (MDTU->getDomTree().dominates(Map.first, MI->getParent())) {
1657 DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1658 Map.second.find(Opcode);
1659 if (CI != Map.second.end()) {
1660 if (EliminateCSE(MI, CI)) {
1661 HasCSEDone = true;
1662 break;
1663 }
1664 }
1665 }
1666 }
1667
1668 if (!HasCSEDone) {
1669 // Otherwise, splice the instruction to the preheader.
1670 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1671
1672 // Since we are moving the instruction out of its basic block, we do not
1673 // retain its debug location. Doing so would degrade the debugging
1674 // experience and adversely affect the accuracy of profiling information.
1675 assert(!MI->isDebugInstr() && "Should not hoist debug inst");
1676 MI->setDebugLoc(DebugLoc());
1677
1678 // Update register pressure for BBs from header to this block.
1679 UpdateBackTraceRegPressure(MI);
1680
1681 CSEMap[Preheader][Opcode].push_back(MI);
1682 }
1683
1684 ++NumHoisted;
1685 Changed = true;
1686
1687 if (HasCSEDone || HasExtractHoistableLoad)
1688 return HoistResult::Hoisted | HoistResult::ErasedMI;
1689 return HoistResult::Hoisted;
1690}
1691
1692/// Get the preheader for the current loop, splitting a critical edge if needed.
1693MachineBasicBlock *MachineLICMImpl::getOrCreatePreheader(MachineLoop *CurLoop) {
1694 // Determine the block to which to hoist instructions. If we can't find a
1695 // suitable loop predecessor, we can't do any hoisting.
1696 if (MachineBasicBlock *Preheader = CurLoop->getLoopPreheader())
1697 return Preheader;
1698
1699 // Try forming a preheader by splitting the critical edge between the single
1700 // predecessor and the loop header.
1701 if (MachineBasicBlock *Pred = CurLoop->getLoopPredecessor()) {
1702 MachineBasicBlock *NewPreheader = Pred->SplitCriticalEdge(
1703 CurLoop->getHeader(), {nullptr, nullptr, MLI}, MDTU);
1704 if (NewPreheader)
1705 Changed = true;
1706 return NewPreheader;
1707 }
1708
1709 return nullptr;
1710}
1711
1712/// Is the target basic block at least "BlockFrequencyRatioThreshold"
1713/// times hotter than the source basic block.
1714bool MachineLICMImpl::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
1715 MachineBasicBlock *TgtBlock) {
1716 // Parse source and target basic block frequency from MBFI
1717 uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
1718 uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
1719
1720 // Disable the hoisting if source block frequency is zero
1721 if (!SrcBF)
1722 return true;
1723
1724 double Ratio = (double)DstBF / SrcBF;
1725
1726 // Compare the block frequency ratio with the threshold
1727 return Ratio > BlockFrequencyRatioThreshold;
1728}
1729
1730template <typename DerivedT, bool PreRegAlloc>
1733 bool Changed = MachineLICMImpl(PreRegAlloc, nullptr, &MFAM).run(MF);
1734 if (!Changed)
1735 return PreservedAnalyses::all();
1737 PA.preserve<MachineLoopAnalysis>();
1738 PA.preserve<MachineDominatorTreeAnalysis>();
1739 return PA;
1740}
1741
#define Success
MachineInstrBuilder & UseMI
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
basic Basic Alias true
This file implements the BitVector class.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static bool isExitBlock(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &ExitBlocks)
Return true if the specified block is in the list.
Definition LCSSA.cpp:68
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:629
#define GET_RESULT(RESULT, GETTER, INFIX)
static cl::opt< bool > HoistConstStores("hoist-const-stores", cl::desc("Hoist invariant stores"), cl::init(true), cl::Hidden)
static cl::opt< UseBFI > DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks", cl::desc("Disable hoisting instructions to" " hotter blocks"), cl::init(UseBFI::PGO), cl::Hidden, cl::values(clEnumValN(UseBFI::None, "none", "disable the feature"), clEnumValN(UseBFI::PGO, "pgo", "enable the feature when using profile data"), clEnumValN(UseBFI::All, "all", "enable the feature with/wo profile data")))
static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI)
Return true if this machine instruction loads from global offset table or constant pool.
static cl::opt< bool > HoistConstLoads("hoist-const-loads", cl::desc("Hoist invariant loads"), cl::init(true), cl::Hidden)
UseBFI
Machine Loop Invariant Code false
static cl::opt< bool > AvoidSpeculation("avoid-speculation", cl::desc("MachineLICM should avoid speculation"), cl::init(true), cl::Hidden)
static bool InstructionStoresToFI(const MachineInstr *MI, int FI)
Return true if instruction stores to the specified frame.
static bool isCopyFeedingInvariantStore(const MachineInstr &MI, const MachineRegisterInfo *MRI, const TargetRegisterInfo *TRI)
static void applyBitsNotInRegMaskToRegUnitsMask(const TargetRegisterInfo &TRI, BitVector &RUs, const uint32_t *Mask)
static cl::opt< bool > HoistCheapInsts("hoist-cheap-insts", cl::desc("MachineLICM should hoist even cheap instructions"), cl::init(false), cl::Hidden)
static bool isInvariantStore(const MachineInstr &MI, const TargetRegisterInfo *TRI, const MachineRegisterInfo *MRI)
static cl::opt< unsigned > BlockFrequencyRatioThreshold("block-freq-ratio-threshold", cl::desc("Do not hoist instructions if target" "block is N times hotter than the source."), cl::init(100), cl::Hidden)
Register Reg
Register const TargetRegisterInfo * TRI
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
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
static DominatorTree getDomTree(Function &F)
This file contains some templates that are useful if you are working with the STL at all.
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
This file describes how to lower LLVM code to machine code.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
A specialized PseudoSourceValue for holding FixedStack values, which must include a frame index.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
bool hasProfileData() const
Return true if the function is annotated with profile data.
Definition Function.h:313
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
Module * getParent()
Get the module that this global value is contained inside of...
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
TargetInstrInfo overrides.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool isAsCheapAsAMove(const MachineInstr &MI) const override
This is an alternative analysis pass to MachineBlockFrequencyInfo.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getHeader() const
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
iterator end() const
iterator begin() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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 BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
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
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
void eraseAdditionalCallInfo(const MachineInstr *MI)
Following functions update call site info.
Representation of each machine instruction.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Analysis pass that exposes the MachineLoopInfo for a machine function.
LLVM_ABI bool isLoopInvariant(MachineInstr &I, const Register ExcludeReg=0) const
Returns true if the instruction is loop invariant.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
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.
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
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
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
ExceptionHandling getExceptionModel() const
Returns the exception model recorded by the "exception-model" module flag, or the target's default ex...
Definition Module.cpp:719
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
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
Special value supplied for machine level alias analysis.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
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
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
virtual Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
virtual Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
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 TargetLowering * getTargetLowering() const
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
Abstract Attribute helper functions.
Definition Attributor.h:165
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
ExceptionHandling
Definition CodeGen.h:54
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI char & MachineLICMID
This pass performs loop invariant code motion on machine instructions.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N