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