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