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