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