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
18#include "llvm/CodeGen/MachineLICM.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/MachineBasicBlock.h"
26#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27#include "llvm/CodeGen/MachineDomTreeUpdater.h"
28#include "llvm/CodeGen/MachineDominators.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/CodeGen/MachineLoopInfo.h"
34#include "llvm/CodeGen/MachineMemOperand.h"
35#include "llvm/CodeGen/MachineOperand.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/PseudoSourceValue.h"
38#include "llvm/CodeGen/RegisterClassInfo.h"
39#include "llvm/CodeGen/TargetInstrInfo.h"
40#include "llvm/CodeGen/TargetLowering.h"
41#include "llvm/CodeGen/TargetRegisterInfo.h"
42#include "llvm/CodeGen/TargetSchedule.h"
43#include "llvm/CodeGen/TargetSubtargetInfo.h"
44#include "llvm/IR/DebugLoc.h"
45#include "llvm/InitializePasses.h"
46#include "llvm/MC/MCInstrDesc.h"
47#include "llvm/MC/MCRegister.h"
48#include "llvm/Pass.h"
49#include "llvm/Support/Casting.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/raw_ostream.h"
53#include "llvm/Target/TargetMachine.h"
54#include <cassert>
55#include <limits>
56#include <vector>
57
58using namespace llvm;
59
60#define DEBUG_TYPE "machinelicm"
61
62static cl::opt<bool>
63AvoidSpeculation("avoid-speculation",
64 cl::desc("MachineLICM should avoid speculation"),
65 cl::init(Val: true), cl::Hidden);
66
67static cl::opt<bool>
68HoistCheapInsts("hoist-cheap-insts",
69 cl::desc("MachineLICM should hoist even cheap instructions"),
70 cl::init(Val: false), cl::Hidden);
71
72static cl::opt<bool>
73HoistConstStores("hoist-const-stores",
74 cl::desc("Hoist invariant stores"),
75 cl::init(Val: true), cl::Hidden);
76
77static cl::opt<bool> HoistConstLoads("hoist-const-loads",
78 cl::desc("Hoist invariant loads"),
79 cl::init(Val: true), cl::Hidden);
80
81// The default threshold of 100 (i.e. if target block is 100 times hotter)
82// is based on empirical data on a single target and is subject to tuning.
83static cl::opt<unsigned>
84BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
85 cl::desc("Do not hoist instructions if target"
86 "block is N times hotter than the source."),
87 cl::init(Val: 100), cl::Hidden);
88
89enum class UseBFI { None, PGO, All };
90
91static cl::opt<UseBFI>
92DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
93 cl::desc("Disable hoisting instructions to"
94 " hotter blocks"),
95 cl::init(Val: UseBFI::PGO), cl::Hidden,
96 cl::values(clEnumValN(UseBFI::None, "none",
97 "disable the feature"),
98 clEnumValN(UseBFI::PGO, "pgo",
99 "enable the feature when using profile data"),
100 clEnumValN(UseBFI::All, "all",
101 "enable the feature with/wo profile data")));
102
103STATISTIC(NumHoisted,
104 "Number of machine instructions hoisted out of loops");
105STATISTIC(NumLowRP,
106 "Number of instructions hoisted in low reg pressure situation");
107STATISTIC(NumHighLatency,
108 "Number of high latency instructions hoisted");
109STATISTIC(NumCSEed,
110 "Number of hoisted machine instructions CSEed");
111STATISTIC(NumPostRAHoisted,
112 "Number of machine instructions hoisted out of loops post regalloc");
113STATISTIC(NumStoreConst,
114 "Number of stores of const phys reg hoisted out of loops");
115STATISTIC(NumNotHoistedDueToHotness,
116 "Number of instructions not hoisted due to block frequency");
117
118namespace {
119 enum HoistResult { NotHoisted = 1, Hoisted = 2, ErasedMI = 4 };
120
121 class MachineLICMImpl {
122 const TargetInstrInfo *TII = nullptr;
123 const TargetLoweringBase *TLI = nullptr;
124 const TargetRegisterInfo *TRI = nullptr;
125 const MachineFrameInfo *MFI = nullptr;
126 MachineRegisterInfo *MRI = nullptr;
127 const RegisterClassInfo *RegClassInfo = nullptr;
128 TargetSchedModel SchedModel;
129 bool PreRegAlloc = false;
130 bool HasProfileData = false;
131 Pass *LegacyPass;
132 MachineFunctionAnalysisManager *MFAM;
133
134 // Various analyses that we use...
135 AliasAnalysis *AA = nullptr; // Alias analysis info.
136 MachineBlockFrequencyInfo *MBFI = nullptr; // Machine block frequncy info
137 MachineLoopInfo *MLI = nullptr; // Current MachineLoopInfo
138 MachineDomTreeUpdater *MDTU = nullptr; // Wraps current dominator tree
139
140 // State that is updated as we process loops
141 bool Changed = false; // True if a loop is changed.
142 bool FirstInLoop = false; // True if it's the first LICM in the loop.
143
144 // Holds information about whether it is allowed to move load instructions
145 // out of the loop
146 SmallDenseMap<MachineLoop *, bool> AllowedToHoistLoads;
147
148 // Exit blocks of each Loop.
149 DenseMap<MachineLoop *, SmallVector<MachineBasicBlock *, 8>> ExitBlockMap;
150
151 bool isExitBlock(MachineLoop *CurLoop, const MachineBasicBlock *MBB) {
152 auto [It, Inserted] = ExitBlockMap.try_emplace(Key: CurLoop);
153 if (Inserted) {
154 SmallVector<MachineBasicBlock *, 8> ExitBlocks;
155 CurLoop->getExitBlocks(ExitBlocks);
156 It->second = std::move(ExitBlocks);
157 }
158 return is_contained(Range&: It->second, Element: MBB);
159 }
160
161 // Track 'estimated' register pressure.
162 SmallDenseSet<Register> RegSeen;
163 SmallVector<unsigned, 8> RegPressure;
164
165 // Register pressure "limit" per register pressure set. If the pressure
166 // is higher than the limit, then it's considered high.
167 SmallVector<unsigned, 8> RegLimit;
168
169 // Register pressure on path leading from loop preheader to current BB.
170 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
171
172 // For each opcode per preheader, keep a list of potential CSE instructions.
173 DenseMap<MachineBasicBlock *,
174 DenseMap<unsigned, std::vector<MachineInstr *>>>
175 CSEMap;
176
177 enum {
178 SpeculateFalse = 0,
179 SpeculateTrue = 1,
180 SpeculateUnknown = 2
181 };
182
183 // If a MBB does not dominate loop exiting blocks then it may not safe
184 // to hoist loads from this block.
185 // Tri-state: 0 - false, 1 - true, 2 - unknown
186 unsigned SpeculationState = SpeculateUnknown;
187
188 public:
189 MachineLICMImpl(bool PreRegAlloc, Pass *LegacyPass,
190 MachineFunctionAnalysisManager *MFAM)
191 : PreRegAlloc(PreRegAlloc), LegacyPass(LegacyPass), MFAM(MFAM) {
192 assert((LegacyPass || MFAM) && "LegacyPass or MFAM must be provided");
193 assert(!(LegacyPass && MFAM) &&
194 "LegacyPass and MFAM cannot be provided at the same time");
195 }
196
197 bool run(MachineFunction &MF);
198
199 void releaseMemory() {
200 RegSeen.clear();
201 RegPressure.clear();
202 RegLimit.clear();
203 BackTrace.clear();
204 CSEMap.clear();
205 ExitBlockMap.clear();
206 }
207
208 private:
209 /// Keep track of information about hoisting candidates.
210 struct CandidateInfo {
211 MachineInstr *MI;
212 Register Def;
213 int FI;
214
215 CandidateInfo(MachineInstr *mi, Register def, int fi)
216 : MI(mi), Def(def), FI(fi) {}
217 };
218
219 void HoistRegionPostRA(MachineLoop *CurLoop);
220
221 void HoistPostRA(MachineInstr *MI, Register Def, MachineLoop *CurLoop);
222
223 void ProcessMI(MachineInstr *MI, BitVector &RUDefs, BitVector &RUClobbers,
224 SmallDenseSet<int> &StoredFIs,
225 SmallVectorImpl<CandidateInfo> &Candidates,
226 MachineLoop *CurLoop);
227
228 void AddToLiveIns(MCRegister Reg, MachineLoop *CurLoop);
229
230 bool IsLICMCandidate(MachineInstr &I, MachineLoop *CurLoop);
231
232 bool IsLoopInvariantInst(MachineInstr &I, MachineLoop *CurLoop);
233
234 bool HasLoopPHIUse(const MachineInstr *MI, MachineLoop *CurLoop);
235
236 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, Register Reg,
237 MachineLoop *CurLoop) const;
238
239 bool IsCheapInstruction(MachineInstr &MI) const;
240
241 bool CanCauseHighRegPressure(const SmallDenseMap<unsigned, int> &Cost,
242 bool Cheap);
243
244 void UpdateBackTraceRegPressure(const MachineInstr *MI);
245
246 bool IsProfitableToHoist(MachineInstr &MI, MachineLoop *CurLoop);
247
248 bool IsGuaranteedToExecute(MachineBasicBlock *BB, MachineLoop *CurLoop);
249
250 void EnterScope(MachineBasicBlock *MBB);
251
252 void ExitScope(MachineBasicBlock *MBB);
253
254 void ExitScopeIfDone(
255 MachineDomTreeNode *Node,
256 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
257 const DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
258
259 void HoistOutOfLoop(MachineDomTreeNode *HeaderN, MachineLoop *CurLoop);
260
261 void InitRegPressure(MachineBasicBlock *BB);
262
263 SmallDenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
264 bool ConsiderSeen,
265 bool ConsiderUnseenAsDef);
266
267 void UpdateRegPressure(const MachineInstr *MI,
268 bool ConsiderUnseenAsDef = false);
269
270 MachineInstr *ExtractHoistableLoad(MachineInstr *MI, MachineLoop *CurLoop);
271
272 MachineInstr *LookForDuplicate(const MachineInstr *MI,
273 std::vector<MachineInstr *> &PrevMIs);
274
275 bool
276 EliminateCSE(MachineInstr *MI,
277 DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI);
278
279 bool MayCSE(MachineInstr *MI);
280
281 unsigned Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
282 MachineLoop *CurLoop);
283
284 void InitCSEMap(MachineBasicBlock *BB);
285
286 void InitializeLoadsHoistableLoops();
287
288 bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
289 MachineBasicBlock *TgtBlock);
290 MachineBasicBlock *getOrCreatePreheader(MachineLoop *CurLoop);
291 };
292
293 class MachineLICMBase : public MachineFunctionPass {
294 bool PreRegAlloc;
295
296 public:
297 MachineLICMBase(char &ID, bool PreRegAlloc)
298 : MachineFunctionPass(ID), PreRegAlloc(PreRegAlloc) {}
299
300 bool runOnMachineFunction(MachineFunction &MF) override;
301
302 void getAnalysisUsage(AnalysisUsage &AU) const override {
303 AU.addRequired<MachineLoopInfoWrapperPass>();
304 if (DisableHoistingToHotterBlocks != UseBFI::None)
305 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
306 AU.addRequired<MachineDominatorTreeWrapperPass>();
307 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
308 AU.addRequired<AAResultsWrapperPass>();
309 AU.addPreserved<MachineLoopInfoWrapperPass>();
310 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
311 MachineFunctionPass::getAnalysisUsage(AU);
312 }
313 };
314
315 class MachineLICM : public MachineLICMBase {
316 public:
317 static char ID;
318 MachineLICM() : MachineLICMBase(ID, false) {}
319 };
320
321 class EarlyMachineLICM : public MachineLICMBase {
322 public:
323 static char ID;
324 EarlyMachineLICM() : MachineLICMBase(ID, true) {}
325 };
326
327} // end anonymous namespace
328
329char MachineLICM::ID;
330char EarlyMachineLICM::ID;
331
332char &llvm::MachineLICMID = MachineLICM::ID;
333char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
334
335INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
336 "Machine Loop Invariant Code Motion", false, false)
337INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
338INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
339INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
340INITIALIZE_PASS_DEPENDENCY(MachineRegisterClassInfoWrapperPass)
341INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
342INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
343 "Machine Loop Invariant Code Motion", false, false)
344
345INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
346 "Early Machine Loop Invariant Code Motion", false, false)
347INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
348INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
349INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
350INITIALIZE_PASS_DEPENDENCY(MachineRegisterClassInfoWrapperPass)
351INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
352INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
353 "Early Machine Loop Invariant Code Motion", false, false)
354
355bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
356 if (skipFunction(F: MF.getFunction()))
357 return false;
358
359 MachineLICMImpl Impl(PreRegAlloc, this, nullptr);
360 return Impl.run(MF);
361}
362
363#define GET_RESULT(RESULT, GETTER, INFIX) \
364 ((LegacyPass) \
365 ? &LegacyPass->getAnalysis<RESULT##INFIX##WrapperPass>().GETTER() \
366 : &MFAM->getResult<RESULT##Analysis>(MF))
367
368bool MachineLICMImpl::run(MachineFunction &MF) {
369 AA = MFAM != nullptr
370 ? &MFAM->getResult<FunctionAnalysisManagerMachineFunctionProxy>(IR&: MF)
371 .getManager()
372 .getResult<AAManager>(IR&: MF.getFunction())
373 : &LegacyPass->getAnalysis<AAResultsWrapperPass>().getAAResults();
374
375 RegClassInfo =
376 MFAM != nullptr
377 ? &MFAM->getResult<MachineRegisterClassAnalysis>(IR&: MF)
378 : &LegacyPass->getAnalysis<MachineRegisterClassInfoWrapperPass>()
379 .getRCI();
380
381 MachineDomTreeUpdater DTU(GET_RESULT(MachineDominatorTree, getDomTree, ),
382 MachineDomTreeUpdater::UpdateStrategy::Lazy);
383 MDTU = &DTU;
384 MLI = GET_RESULT(MachineLoop, getLI, Info);
385 MBFI = DisableHoistingToHotterBlocks != UseBFI::None
386 ? GET_RESULT(MachineBlockFrequency, getMBFI, Info)
387 : nullptr;
388
389 Changed = FirstInLoop = false;
390 const TargetSubtargetInfo &ST = MF.getSubtarget();
391 TII = ST.getInstrInfo();
392 TLI = ST.getTargetLowering();
393 TRI = ST.getRegisterInfo();
394 MFI = &MF.getFrameInfo();
395 MRI = &MF.getRegInfo();
396 SchedModel.init(TSInfo: &ST);
397
398 HasProfileData = MF.getFunction().hasProfileData();
399
400 if (PreRegAlloc)
401 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
402 else
403 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
404 LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
405
406 if (PreRegAlloc) {
407 // Estimate register pressure during pre-regalloc pass.
408 unsigned NumRPS = TRI->getNumRegPressureSets();
409 RegPressure.resize(N: NumRPS);
410 llvm::fill(Range&: RegPressure, Value: 0);
411 RegLimit.resize(N: NumRPS);
412 for (unsigned i = 0, e = NumRPS; i != e; ++i)
413 RegLimit[i] = RegClassInfo->getRegPressureSetLimit(Idx: i);
414 }
415
416 if (HoistConstLoads)
417 InitializeLoadsHoistableLoops();
418
419 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
420 while (!Worklist.empty()) {
421 MachineLoop *CurLoop = Worklist.pop_back_val();
422
423 if (!PreRegAlloc) {
424 HoistRegionPostRA(CurLoop);
425 } else {
426 // CSEMap is initialized for loop header when the first instruction is
427 // being hoisted.
428 MachineDomTreeNode *N = MDTU->getDomTree().getNode(BB: CurLoop->getHeader());
429 FirstInLoop = true;
430 HoistOutOfLoop(HeaderN: N, CurLoop);
431 CSEMap.clear();
432 }
433 }
434 releaseMemory();
435 return Changed;
436}
437
438/// Return true if instruction stores to the specified frame.
439static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
440 // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
441 // true since they have no memory operands.
442 if (!MI->mayStore())
443 return false;
444 // If we lost memory operands, conservatively assume that the instruction
445 // writes to all slots.
446 if (MI->memoperands_empty())
447 return true;
448 for (const MachineMemOperand *MemOp : MI->memoperands()) {
449 if (!MemOp->isStore() || !MemOp->getPseudoValue())
450 continue;
451 if (const FixedStackPseudoSourceValue *Value =
452 dyn_cast<FixedStackPseudoSourceValue>(Val: MemOp->getPseudoValue())) {
453 if (Value->getFrameIndex() == FI)
454 return true;
455 }
456 }
457 return false;
458}
459
460static void applyBitsNotInRegMaskToRegUnitsMask(const TargetRegisterInfo &TRI,
461 BitVector &RUs,
462 const uint32_t *Mask) {
463 // FIXME: This intentionally works in reverse due to some issues with the
464 // Register Units infrastructure.
465 //
466 // This is used to apply callee-saved-register masks to the clobbered regunits
467 // mask.
468 //
469 // The right way to approach this is to start with a BitVector full of ones,
470 // then reset all the bits of the regunits of each register that is set in the
471 // mask (registers preserved), then OR the resulting bits with the Clobbers
472 // mask. This correctly prioritizes the saved registers, so if a RU is shared
473 // between a register that is preserved, and one that is NOT preserved, that
474 // RU will not be set in the output vector (the clobbers).
475 //
476 // What we have to do for now is the opposite: we have to assume that the
477 // regunits of all registers that are NOT preserved are clobbered, even if
478 // those regunits are preserved by another register. So if a RU is shared
479 // like described previously, that RU will be set.
480 //
481 // This is to work around an issue which appears in AArch64, but isn't
482 // exclusive to that target: AArch64's Qn registers (128 bits) have Dn
483 // register (lower 64 bits). A few Dn registers are preserved by some calling
484 // conventions, but Qn and Dn share exactly the same reg units.
485 //
486 // If we do this the right way, Qn will be marked as NOT clobbered even though
487 // its upper 64 bits are NOT preserved. The conservative approach handles this
488 // correctly at the cost of some missed optimizations on other targets.
489 //
490 // This is caused by how RegUnits are handled within TableGen. Ideally, Qn
491 // should have an extra RegUnit to model the "unknown" bits not covered by the
492 // subregs.
493 BitVector RUsFromRegsNotInMask(TRI.getNumRegUnits());
494 const unsigned NumRegs = TRI.getNumRegs();
495 const unsigned MaskWords = (NumRegs + 31) / 32;
496 for (unsigned K = 0; K < MaskWords; ++K) {
497 const uint32_t Word = Mask[K];
498 for (unsigned Bit = 0; Bit < 32; ++Bit) {
499 const unsigned PhysReg = (K * 32) + Bit;
500 if (PhysReg == NumRegs)
501 break;
502
503 if (PhysReg && !((Word >> Bit) & 1)) {
504 for (MCRegUnit Unit : TRI.regunits(Reg: PhysReg))
505 RUsFromRegsNotInMask.set(static_cast<unsigned>(Unit));
506 }
507 }
508 }
509
510 RUs |= RUsFromRegsNotInMask;
511}
512
513/// Examine the instruction for potential LICM candidate. Also
514/// gather register def and frame object update information.
515void MachineLICMImpl::ProcessMI(MachineInstr *MI, BitVector &RUDefs,
516 BitVector &RUClobbers,
517 SmallDenseSet<int> &StoredFIs,
518 SmallVectorImpl<CandidateInfo> &Candidates,
519 MachineLoop *CurLoop) {
520 bool RuledOut = false;
521 bool HasNonInvariantUse = false;
522 Register Def;
523 for (const MachineOperand &MO : MI->operands()) {
524 if (MO.isFI()) {
525 // Remember if the instruction stores to the frame index.
526 int FI = MO.getIndex();
527 if (!StoredFIs.count(V: FI) &&
528 MFI->isSpillSlotObjectIndex(ObjectIdx: FI) &&
529 InstructionStoresToFI(MI, FI))
530 StoredFIs.insert(V: FI);
531 HasNonInvariantUse = true;
532 continue;
533 }
534
535 // We can't hoist an instruction defining a physreg that is clobbered in
536 // the loop.
537 if (MO.isRegMask()) {
538 applyBitsNotInRegMaskToRegUnitsMask(TRI: *TRI, RUs&: RUClobbers, Mask: MO.getRegMask());
539 continue;
540 }
541
542 if (!MO.isReg())
543 continue;
544 Register Reg = MO.getReg();
545 if (!Reg)
546 continue;
547 assert(Reg.isPhysical() && "Not expecting virtual register!");
548
549 if (!MO.isDef()) {
550 if (!HasNonInvariantUse) {
551 for (MCRegUnit Unit : TRI->regunits(Reg)) {
552 // If it's using a non-loop-invariant register, then it's obviously
553 // not safe to hoist.
554 if (RUDefs.test(Idx: static_cast<unsigned>(Unit)) ||
555 RUClobbers.test(Idx: static_cast<unsigned>(Unit))) {
556 HasNonInvariantUse = true;
557 break;
558 }
559 }
560 }
561 continue;
562 }
563
564 // FIXME: For now, avoid instructions with multiple defs, unless it's dead.
565 if (!MO.isDead()) {
566 if (Def)
567 RuledOut = true;
568 else
569 Def = Reg;
570 }
571
572 // If we have already seen another instruction that defines the same
573 // register, then this is not safe. Two defs is indicated by setting a
574 // PhysRegClobbers bit.
575 for (MCRegUnit Unit : TRI->regunits(Reg)) {
576 if (RUDefs.test(Idx: static_cast<unsigned>(Unit))) {
577 RUClobbers.set(static_cast<unsigned>(Unit));
578 RuledOut = true;
579 } else if (RUClobbers.test(Idx: static_cast<unsigned>(Unit))) {
580 // MI defined register is seen defined by another instruction in
581 // the loop, it cannot be a LICM candidate.
582 RuledOut = true;
583 }
584
585 RUDefs.set(static_cast<unsigned>(Unit));
586 }
587 }
588
589 // Only consider reloads for now and remats which do not have register
590 // operands. FIXME: Consider unfold load folding instructions.
591 if (Def && !RuledOut) {
592 int FI = std::numeric_limits<int>::min();
593 if ((!HasNonInvariantUse && IsLICMCandidate(I&: *MI, CurLoop)) ||
594 (TII->isLoadFromStackSlot(MI: *MI, FrameIndex&: FI) && MFI->isSpillSlotObjectIndex(ObjectIdx: FI)))
595 Candidates.push_back(Elt: CandidateInfo(MI, Def, FI));
596 }
597}
598
599/// Walk the specified region of the CFG and hoist loop invariants out to the
600/// preheader.
601void MachineLICMImpl::HoistRegionPostRA(MachineLoop *CurLoop) {
602 MachineBasicBlock *Preheader = getOrCreatePreheader(CurLoop);
603 if (!Preheader)
604 return;
605
606 unsigned NumRegUnits = TRI->getNumRegUnits();
607 BitVector RUDefs(NumRegUnits); // RUs defined once in the loop.
608 BitVector RUClobbers(NumRegUnits); // RUs defined more than once.
609
610 SmallVector<CandidateInfo, 32> Candidates;
611 SmallDenseSet<int> StoredFIs;
612
613 // Walk the entire region, count number of defs for each register, and
614 // collect potential LICM candidates.
615 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
616 // If the header of the loop containing this basic block is a landing pad,
617 // then don't try to hoist instructions out of this loop.
618 const MachineLoop *ML = MLI->getLoopFor(BB);
619 if (ML && ML->getHeader()->isEHPad()) continue;
620
621 // Conservatively treat live-in's as an external def.
622 // FIXME: That means a reload that're reused in successor block(s) will not
623 // be LICM'ed.
624 for (const auto &LI : BB->liveins()) {
625 for (MCRegUnit Unit : TRI->regunits(Reg: LI.PhysReg))
626 RUDefs.set(static_cast<unsigned>(Unit));
627 }
628
629 // Funclet entry blocks will clobber all registers
630 if (const uint32_t *Mask = BB->getBeginClobberMask(TRI))
631 applyBitsNotInRegMaskToRegUnitsMask(TRI: *TRI, RUs&: RUClobbers, Mask);
632
633 // EH landing pads clobber exception pointer/selector registers.
634 if (BB->isEHPad()) {
635 const MachineFunction &MF = *BB->getParent();
636 const Constant *PersonalityFn = MF.getFunction().getPersonalityFn();
637 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
638 if (MCRegister Reg = TLI.getExceptionPointerRegister(
639 EH: TLI.getTargetMachine().getExceptionModel(), PersonalityFn))
640 for (MCRegUnit Unit : TRI->regunits(Reg))
641 RUClobbers.set(static_cast<unsigned>(Unit));
642 if (MCRegister Reg = TLI.getExceptionSelectorRegister(
643 EH: TLI.getTargetMachine().getExceptionModel(), PersonalityFn))
644 for (MCRegUnit Unit : TRI->regunits(Reg))
645 RUClobbers.set(static_cast<unsigned>(Unit));
646 }
647
648 SpeculationState = SpeculateUnknown;
649 for (MachineInstr &MI : *BB)
650 ProcessMI(MI: &MI, RUDefs, RUClobbers, StoredFIs, Candidates, CurLoop);
651 }
652
653 // Gather the registers read / clobbered by the terminator.
654 BitVector TermRUs(NumRegUnits);
655 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
656 if (TI != Preheader->end()) {
657 for (const MachineOperand &MO : TI->operands()) {
658 if (!MO.isReg())
659 continue;
660 Register Reg = MO.getReg();
661 if (!Reg)
662 continue;
663 for (MCRegUnit Unit : TRI->regunits(Reg))
664 TermRUs.set(static_cast<unsigned>(Unit));
665 }
666 }
667
668 // Now evaluate whether the potential candidates qualify.
669 // 1. Check if the candidate defined register is defined by another
670 // instruction in the loop.
671 // 2. If the candidate is a load from stack slot (always true for now),
672 // check if the slot is stored anywhere in the loop.
673 // 3. Make sure candidate def should not clobber
674 // registers read by the terminator. Similarly its def should not be
675 // clobbered by the terminator.
676 for (CandidateInfo &Candidate : Candidates) {
677 if (Candidate.FI != std::numeric_limits<int>::min() &&
678 StoredFIs.count(V: Candidate.FI))
679 continue;
680
681 Register Def = Candidate.Def;
682 bool Safe = true;
683 for (MCRegUnit Unit : TRI->regunits(Reg: Def)) {
684 if (RUClobbers.test(Idx: static_cast<unsigned>(Unit)) ||
685 TermRUs.test(Idx: static_cast<unsigned>(Unit))) {
686 Safe = false;
687 break;
688 }
689 }
690
691 if (!Safe)
692 continue;
693
694 MachineInstr *MI = Candidate.MI;
695 for (const MachineOperand &MO : MI->all_uses()) {
696 if (!MO.getReg())
697 continue;
698 for (MCRegUnit Unit : TRI->regunits(Reg: MO.getReg())) {
699 if (RUDefs.test(Idx: static_cast<unsigned>(Unit)) ||
700 RUClobbers.test(Idx: static_cast<unsigned>(Unit))) {
701 // If it's using a non-loop-invariant register, then it's obviously
702 // not safe to hoist.
703 Safe = false;
704 break;
705 }
706 }
707
708 if (!Safe)
709 break;
710 }
711
712 if (Safe)
713 HoistPostRA(MI, Def: Candidate.Def, CurLoop);
714 }
715}
716
717/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
718/// sure it is not killed by any instructions in the loop.
719void MachineLICMImpl::AddToLiveIns(MCRegister Reg, MachineLoop *CurLoop) {
720 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
721 if (!BB->isLiveIn(Reg))
722 BB->addLiveIn(PhysReg: Reg);
723 for (MachineInstr &MI : *BB) {
724 for (MachineOperand &MO : MI.all_uses()) {
725 if (!MO.getReg())
726 continue;
727 if (TRI->regsOverlap(RegA: Reg, RegB: MO.getReg()))
728 MO.setIsKill(false);
729 }
730 }
731 }
732}
733
734/// When an instruction is found to only use loop invariant operands that is
735/// safe to hoist, this instruction is called to do the dirty work.
736void MachineLICMImpl::HoistPostRA(MachineInstr *MI, Register Def,
737 MachineLoop *CurLoop) {
738 MachineBasicBlock *Preheader = CurLoop->getLoopPreheader();
739
740 // Now move the instructions to the predecessor, inserting it before any
741 // terminator instructions.
742 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
743 << " from " << printMBBReference(*MI->getParent()) << ": "
744 << *MI);
745
746 // Splice the instruction to the preheader.
747 MachineBasicBlock *MBB = MI->getParent();
748 Preheader->splice(Where: Preheader->getFirstTerminator(), Other: MBB, From: MI);
749
750 // Since we are moving the instruction out of its basic block, we do not
751 // retain its debug location. Doing so would degrade the debugging
752 // experience and adversely affect the accuracy of profiling information.
753 assert(!MI->isDebugInstr() && "Should not hoist debug inst");
754 MI->setDebugLoc(DebugLoc());
755
756 // Add register to livein list to all the BBs in the current loop since a
757 // loop invariant must be kept live throughout the whole loop. This is
758 // important to ensure later passes do not scavenge the def register.
759 AddToLiveIns(Reg: Def, CurLoop);
760
761 ++NumPostRAHoisted;
762 Changed = true;
763}
764
765/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
766/// may not be safe to hoist.
767bool MachineLICMImpl::IsGuaranteedToExecute(MachineBasicBlock *BB,
768 MachineLoop *CurLoop) {
769 if (SpeculationState != SpeculateUnknown)
770 return SpeculationState == SpeculateFalse;
771
772 if (BB != CurLoop->getHeader()) {
773 // Check loop exiting blocks.
774 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
775 CurLoop->getExitingBlocks(ExitingBlocks&: CurrentLoopExitingBlocks);
776 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
777 if (!MDTU->getDomTree().dominates(A: BB, B: CurrentLoopExitingBlock)) {
778 SpeculationState = SpeculateTrue;
779 return false;
780 }
781 }
782
783 SpeculationState = SpeculateFalse;
784 return true;
785}
786
787void MachineLICMImpl::EnterScope(MachineBasicBlock *MBB) {
788 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
789
790 // Remember livein register pressure.
791 BackTrace.push_back(Elt: RegPressure);
792}
793
794void MachineLICMImpl::ExitScope(MachineBasicBlock *MBB) {
795 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
796 BackTrace.pop_back();
797}
798
799/// Destroy scope for the MBB that corresponds to the given dominator tree node
800/// if its a leaf or all of its children are done. Walk up the dominator tree to
801/// destroy ancestors which are now done.
802void MachineLICMImpl::ExitScopeIfDone(
803 MachineDomTreeNode *Node,
804 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
805 const DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap) {
806 if (OpenChildren[Node])
807 return;
808
809 for(;;) {
810 ExitScope(MBB: Node->getBlock());
811 // Now traverse upwards to pop ancestors whose offsprings are all done.
812 MachineDomTreeNode *Parent = ParentMap.lookup(Val: Node);
813 if (!Parent || --OpenChildren[Parent] != 0)
814 break;
815 Node = Parent;
816 }
817}
818
819/// Walk the specified loop in the CFG (defined by all blocks dominated by the
820/// specified header block, and that are in the current loop) in depth first
821/// order w.r.t the DominatorTree. This allows us to visit definitions before
822/// uses, allowing us to hoist a loop body in one pass without iteration.
823void MachineLICMImpl::HoistOutOfLoop(MachineDomTreeNode *HeaderN,
824 MachineLoop *CurLoop) {
825 MachineBasicBlock *Preheader = getOrCreatePreheader(CurLoop);
826 if (!Preheader)
827 return;
828
829 SmallVector<MachineDomTreeNode*, 32> Scopes;
830 SmallVector<MachineDomTreeNode*, 8> WorkList;
831 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
832 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
833
834 // Perform a DFS walk to determine the order of visit.
835 WorkList.push_back(Elt: HeaderN);
836 while (!WorkList.empty()) {
837 MachineDomTreeNode *Node = WorkList.pop_back_val();
838 assert(Node && "Null dominator tree node?");
839 MachineBasicBlock *BB = Node->getBlock();
840
841 // If the header of the loop containing this basic block is a landing pad,
842 // then don't try to hoist instructions out of this loop.
843 const MachineLoop *ML = MLI->getLoopFor(BB);
844 if (ML && ML->getHeader()->isEHPad())
845 continue;
846
847 // If this subregion is not in the top level loop at all, exit.
848 if (!CurLoop->contains(BB))
849 continue;
850
851 Scopes.push_back(Elt: Node);
852
853 // Don't hoist things out of a large switch statement. This often causes
854 // code to be hoisted that wasn't going to be executed, and increases
855 // register pressure in a situation where it's likely to matter.
856 if (BB->succ_size() >= 25) {
857 OpenChildren[Node] = 0;
858 continue;
859 }
860
861 // Add children in reverse order as then the next popped worklist node is
862 // the first child of this node. This means we ultimately traverse the
863 // DOM tree in exactly the same order as if we'd recursed.
864 size_t WorkListStart = WorkList.size();
865 for (MachineDomTreeNode *Child : Node->children()) {
866 ParentMap[Child] = Node;
867 WorkList.push_back(Elt: Child);
868 }
869 std::reverse(first: WorkList.begin() + WorkListStart, last: WorkList.end());
870 OpenChildren[Node] = WorkList.size() - WorkListStart;
871 }
872
873 if (Scopes.size() == 0)
874 return;
875
876 // Compute registers which are livein into the loop headers.
877 RegSeen.clear();
878 BackTrace.clear();
879 InitRegPressure(BB: Preheader);
880
881 // Now perform LICM.
882 for (MachineDomTreeNode *Node : Scopes) {
883 MachineBasicBlock *MBB = Node->getBlock();
884
885 EnterScope(MBB);
886
887 // Process the block
888 SpeculationState = SpeculateUnknown;
889 for (MachineInstr &MI : llvm::make_early_inc_range(Range&: *MBB)) {
890 unsigned HoistRes = HoistResult::NotHoisted;
891 HoistRes = Hoist(MI: &MI, Preheader, CurLoop);
892 if (HoistRes & HoistResult::NotHoisted) {
893 // We have failed to hoist MI to outermost loop's preheader. If MI is in
894 // a subloop, try to hoist it to subloop's preheader.
895 SmallVector<MachineLoop *> InnerLoopWorkList;
896 for (MachineLoop *L = MLI->getLoopFor(BB: MI.getParent()); L != CurLoop;
897 L = L->getParentLoop())
898 InnerLoopWorkList.push_back(Elt: L);
899
900 while (!InnerLoopWorkList.empty()) {
901 MachineLoop *InnerLoop = InnerLoopWorkList.pop_back_val();
902 MachineBasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
903 if (InnerLoopPreheader) {
904 HoistRes = Hoist(MI: &MI, Preheader: InnerLoopPreheader, CurLoop: InnerLoop);
905 if (HoistRes & HoistResult::Hoisted)
906 break;
907 }
908 }
909 }
910
911 if (HoistRes & HoistResult::ErasedMI)
912 continue;
913
914 UpdateRegPressure(MI: &MI);
915 }
916
917 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
918 ExitScopeIfDone(Node, OpenChildren, ParentMap);
919 }
920}
921
922static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
923 return MO.isKill() || MRI->hasOneNonDBGUse(RegNo: MO.getReg());
924}
925
926/// Find all virtual register references that are liveout of the preheader to
927/// initialize the starting "register pressure". Note this does not count live
928/// through (livein but not used) registers.
929void MachineLICMImpl::InitRegPressure(MachineBasicBlock *BB) {
930 llvm::fill(Range&: RegPressure, Value: 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(MBB&: *BB, TBB, FBB, Cond, AllowModify: false) && Cond.empty())
940 InitRegPressure(BB: *BB->pred_begin());
941 }
942
943 for (const MachineInstr &MI : *BB)
944 UpdateRegPressure(MI: &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(V: Reg).second : false;
981 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
982
983 RegClassWeight W = TRI->getRegClassWeight(RC);
984 int RCCost = 0;
985 if (MO.isDef())
986 RCCost = W.RegWeight;
987 else {
988 bool isKill = isOperandKill(MO, MRI);
989 if (isNew && !isKill && ConsiderUnseenAsDef)
990 // Haven't seen this, it must be a livein.
991 RCCost = W.RegWeight;
992 else if (!isNew && isKill)
993 RCCost = -W.RegWeight;
994 }
995 if (RCCost == 0)
996 continue;
997 const int *PS = TRI->getRegClassPressureSets(RC);
998 for (; *PS != -1; ++PS)
999 Cost[*PS] += RCCost;
1000 }
1001 return Cost;
1002}
1003
1004/// Return true if this machine instruction loads from global offset table or
1005/// constant pool.
1006static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
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.
1029static bool isInvariantStore(const MachineInstr &MI,
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(SrcReg: MO.getReg(), MRI);
1046 if (Reg.isVirtual())
1047 return false;
1048 if (!TRI->isCallerPreservedPhysReg(PhysReg: Reg.asMCReg(), MF: *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.
1063static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
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(i: 1).getReg();
1075 if (CopySrcReg.isVirtual())
1076 return false;
1077
1078 if (!TRI->isCallerPreservedPhysReg(PhysReg: CopySrcReg.asMCReg(), MF: *MF))
1079 return false;
1080
1081 Register CopyDstReg = MI.getOperand(i: 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(Reg: CopyDstReg)) {
1086 if (UseMI.mayStore() && isInvariantStore(MI: 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(SawStore&: DontMoveAcrossStore)) &&
1098 !(HoistConstStores && isInvariantStore(MI: 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(MI&: I) &&
1110 !IsGuaranteedToExecute(BB: 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(MI: I, FromLoop: 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) {
1142 SmallVector<const MachineInstr *, 8> Work(1, MI);
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(Inst: &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, MBB: UseMI.getParent()))
1160 return true;
1161 continue;
1162 }
1163 // Look past copies as well.
1164 if (UseMI.isCopy() && CurLoop->contains(Inst: &UseMI))
1165 Work.push_back(Elt: &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(RegNo: Reg))
1178 return false;
1179
1180 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1181 if (UseMI.isCopyLike())
1182 continue;
1183 if (!CurLoop->contains(BB: 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, DefMI: MI, DefIdx, UseMI, UseIdx: 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, DefMI: MI, DefIdx: 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
1286 if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
1287 return true;
1288
1289 bool CheapInstr = IsCheapInstruction(MI);
1290 bool CreatesCopy = HasLoopPHIUse(MI: &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, DefIdx: 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: &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(BB: MI.getParent(), CurLoop) && !MayCSE(MI: &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(i: 0).getReg();
1356 if (DefReg.isVirtual() &&
1357 all_of(Range: MI.uses(),
1358 P: [this](const MachineOperand &UseOp) {
1359 return !UseOp.isReg() || UseOp.getReg().isVirtual() ||
1360 MRI->isConstantPhysReg(PhysReg: UseOp.getReg());
1361 }) &&
1362 IsLoopInvariantInst(I&: MI, CurLoop) &&
1363 any_of(Range: MRI->use_nodbg_instructions(Reg: DefReg),
1364 P: [&CurLoop, this, DefReg,
1365 Cost = std::move(Cost)](MachineInstr &UseMI) {
1366 if (!CurLoop->contains(Inst: &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, CheapInstr: false) &&
1374 !CurLoop->isLoopInvariant(I&: UseMI, ExcludeReg: 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(Opc: MI->getOpcode(),
1412 /*UnfoldLoad=*/true,
1413 /*UnfoldStore=*/false,
1414 LoadRegIndex: &LoadRegIndex);
1415 if (NewOpc == 0) return nullptr;
1416 const MCInstrDesc &MID = TII->get(Opcode: NewOpc);
1417 MachineFunction &MF = *MI->getMF();
1418 const TargetRegisterClass *RC = TII->getRegClass(MCID: MID, OpNum: LoadRegIndex);
1419 // Ok, we're unfolding. Create a temporary register and do the unfold.
1420 Register Reg = MRI->createVirtualRegister(RegClass: RC);
1421
1422 SmallVector<MachineInstr *, 2> NewMIs;
1423 bool Success = TII->unfoldMemoryOperand(MF, MI&: *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();
1433 MachineBasicBlock::iterator Pos = MI;
1434 MBB->insert(I: Pos, MI: NewMIs[0]);
1435 MBB->insert(I: Pos, MI: 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(I&: *NewMIs[0], CurLoop) ||
1439 !IsProfitableToHoist(MI&: *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(MI: NewMIs[1]);
1447
1448 // Otherwise we successfully unfolded a load that we can hoist.
1449
1450 // Update the call info.
1451 if (MI->shouldUpdateAdditionalCallInfo())
1452 MF.eraseAdditionalCallInfo(MI);
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(x: &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(Elt: L);
1478 llvm::append_range(C&: Worklist, R: 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(C&: 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(MI0: *MI, MI1: *PrevMI, MRI: (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, PrevMIs&: 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(Elt: i);
1550 }
1551
1552 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1553 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1554 unsigned Idx = Defs[i];
1555 Register Reg = MI->getOperand(i: Idx).getReg();
1556 Register DupReg = Dup->getOperand(i: Idx).getReg();
1557 OrigRCs.push_back(Elt: MRI->getRegClass(Reg: DupReg));
1558
1559 if (!MRI->constrainRegClass(Reg: DupReg, RC: MRI->getRegClass(Reg))) {
1560 // Restore old RCs if more than one defs.
1561 for (unsigned j = 0; j != i; ++j)
1562 MRI->setRegClass(Reg: Dup->getOperand(i: Defs[j]).getReg(), RC: OrigRCs[j]);
1563 return false;
1564 }
1565 }
1566
1567 for (unsigned Idx : Defs) {
1568 Register Reg = MI->getOperand(i: Idx).getReg();
1569 Register DupReg = Dup->getOperand(i: Idx).getReg();
1570 MRI->replaceRegWith(FromReg: Reg, ToReg: DupReg);
1571 MRI->clearKillFlags(Reg: DupReg);
1572 // Clear Dup dead flag if any, we reuse it for Reg.
1573 if (!MRI->use_nodbg_empty(RegNo: DupReg))
1574 Dup->getOperand(i: 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(A: Map.first, B: MI->getParent())) {
1594 DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1595 Map.second.find(Val: 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, PrevMIs&: 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
1616 if ((DisableHoistingToHotterBlocks == UseBFI::All ||
1617 (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
1618 isTgtHotterThanSrc(SrcBlock, TgtBlock: Preheader)) {
1619 ++NumNotHoistedDueToHotness;
1620 return HoistResult::NotHoisted;
1621 }
1622 // First check whether we should hoist this instruction.
1623 bool HasExtractHoistableLoad = false;
1624 if (!IsLoopInvariantInst(I&: *MI, CurLoop) ||
1625 !IsProfitableToHoist(MI&: *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(BB: 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(A: Map.first, B: MI->getParent())) {
1662 DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1663 Map.second.find(Val: 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(Where: Preheader->getFirstTerminator(),Other: MI->getParent(),From: 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(Reg: MO.getReg());
1692
1693 CSEMap[Preheader][Opcode].push_back(x: MI);
1694 }
1695
1696 ++NumHoisted;
1697 Changed = true;
1698
1699 if (HasCSEDone || HasExtractHoistableLoad)
1700 return HoistResult::Hoisted | HoistResult::ErasedMI;
1701 return HoistResult::Hoisted;
1702}
1703
1704/// Get the preheader for the current loop, splitting a critical edge if needed.
1705MachineBasicBlock *MachineLICMImpl::getOrCreatePreheader(MachineLoop *CurLoop) {
1706 // Determine the block to which to hoist instructions. If we can't find a
1707 // suitable loop predecessor, we can't do any hoisting.
1708 if (MachineBasicBlock *Preheader = CurLoop->getLoopPreheader())
1709 return Preheader;
1710
1711 // Try forming a preheader by splitting the critical edge between the single
1712 // predecessor and the loop header.
1713 if (MachineBasicBlock *Pred = CurLoop->getLoopPredecessor()) {
1714 MachineBasicBlock *NewPreheader = Pred->SplitCriticalEdge(
1715 Succ: CurLoop->getHeader(), P: LegacyPass, MFAM, LiveInSets: nullptr, MDTU);
1716 if (NewPreheader)
1717 Changed = true;
1718 return NewPreheader;
1719 }
1720
1721 return nullptr;
1722}
1723
1724/// Is the target basic block at least "BlockFrequencyRatioThreshold"
1725/// times hotter than the source basic block.
1726bool MachineLICMImpl::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
1727 MachineBasicBlock *TgtBlock) {
1728 // Parse source and target basic block frequency from MBFI
1729 uint64_t SrcBF = MBFI->getBlockFreq(MBB: SrcBlock).getFrequency();
1730 uint64_t DstBF = MBFI->getBlockFreq(MBB: 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>
1743PreservedAnalyses MachineLICMBasePass<DerivedT, PreRegAlloc>::run(
1744 MachineFunction &MF, MachineFunctionAnalysisManager &MFAM) {
1745 bool Changed = MachineLICMImpl(PreRegAlloc, nullptr, &MFAM).run(MF);
1746 if (!Changed)
1747 return PreservedAnalyses::all();
1748 auto PA = getMachineFunctionPassPreservedAnalyses();
1749 PA.preserve<MachineLoopAnalysis>();
1750 return PA;
1751}
1752
1753template class llvm::MachineLICMBasePass<EarlyMachineLICMPass, true>;
1754template class llvm::MachineLICMBasePass<MachineLICMPass, false>;
1755