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