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