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