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