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