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