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
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;
938 SmallVector<MachineOperand, 4> Cond;
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 = MRI->hasOneNonDBGUse(Reg);
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 =
1715 Pred->SplitCriticalEdge(CurLoop->getHeader(), LegacyPass, MFAM, 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!")
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:629
#define GET_RESULT(RESULT, GETTER, INFIX)
static cl::opt< bool > HoistConstStores("hoist-const-stores", cl::desc("Hoist invariant stores"), cl::init(true), cl::Hidden)
static cl::opt< UseBFI > DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks", cl::desc("Disable hoisting instructions to" " hotter blocks"), cl::init(UseBFI::PGO), cl::Hidden, cl::values(clEnumValN(UseBFI::None, "none", "disable the feature"), clEnumValN(UseBFI::PGO, "pgo", "enable the feature when using profile data"), clEnumValN(UseBFI::All, "all", "enable the feature with/wo profile data")))
static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI)
Return true if this machine instruction loads from global offset table or constant pool.
static cl::opt< bool > HoistConstLoads("hoist-const-loads", cl::desc("Hoist invariant loads"), cl::init(true), cl::Hidden)
UseBFI
Machine Loop Invariant Code false
static cl::opt< bool > AvoidSpeculation("avoid-speculation", cl::desc("MachineLICM should avoid speculation"), cl::init(true), cl::Hidden)
static bool InstructionStoresToFI(const MachineInstr *MI, int FI)
Return true if instruction stores to the specified frame.
static bool isCopyFeedingInvariantStore(const MachineInstr &MI, const MachineRegisterInfo *MRI, const TargetRegisterInfo *TRI)
static void applyBitsNotInRegMaskToRegUnitsMask(const TargetRegisterInfo &TRI, BitVector &RUs, const uint32_t *Mask)
static cl::opt< bool > HoistCheapInsts("hoist-cheap-insts", cl::desc("MachineLICM should hoist even cheap instructions"), cl::init(false), cl::Hidden)
static bool isInvariantStore(const MachineInstr &MI, const TargetRegisterInfo *TRI, const MachineRegisterInfo *MRI)
static cl::opt< unsigned > BlockFrequencyRatioThreshold("block-freq-ratio-threshold", cl::desc("Do not hoist instructions if target" "block is N times hotter than the source."), cl::init(100), cl::Hidden)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
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:794
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:719
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Special value supplied for machine level alias analysis.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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