1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the SplitAnalysis class as well as mutator functions for 11 // live range splitting. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #define DEBUG_TYPE "regalloc" 16 #include "SplitKit.h" 17 #include "LiveRangeEdit.h" 18 #include "VirtRegMap.h" 19 #include "llvm/CodeGen/CalcSpillWeights.h" 20 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 21 #include "llvm/CodeGen/MachineDominators.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineRegisterInfo.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include "llvm/Target/TargetInstrInfo.h" 28 #include "llvm/Target/TargetMachine.h" 29 30 using namespace llvm; 31 32 static cl::opt<bool> 33 AllowSplit("spiller-splits-edges", 34 cl::desc("Allow critical edge splitting during spilling")); 35 36 //===----------------------------------------------------------------------===// 37 // Split Analysis 38 //===----------------------------------------------------------------------===// 39 40 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, 41 const LiveIntervals &lis, 42 const MachineLoopInfo &mli) 43 : MF(vrm.getMachineFunction()), 44 VRM(vrm), 45 LIS(lis), 46 Loops(mli), 47 TII(*MF.getTarget().getInstrInfo()), 48 CurLI(0) {} 49 50 void SplitAnalysis::clear() { 51 UseSlots.clear(); 52 UsingInstrs.clear(); 53 UsingBlocks.clear(); 54 LiveBlocks.clear(); 55 CurLI = 0; 56 } 57 58 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) { 59 MachineBasicBlock *T, *F; 60 SmallVector<MachineOperand, 4> Cond; 61 return !TII.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond); 62 } 63 64 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. 65 void SplitAnalysis::analyzeUses() { 66 const MachineRegisterInfo &MRI = MF.getRegInfo(); 67 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(CurLI->reg), 68 E = MRI.reg_end(); I != E; ++I) { 69 MachineOperand &MO = I.getOperand(); 70 if (MO.isUse() && MO.isUndef()) 71 continue; 72 MachineInstr *MI = MO.getParent(); 73 if (MI->isDebugValue() || !UsingInstrs.insert(MI)) 74 continue; 75 UseSlots.push_back(LIS.getInstructionIndex(MI).getDefIndex()); 76 MachineBasicBlock *MBB = MI->getParent(); 77 UsingBlocks[MBB]++; 78 } 79 array_pod_sort(UseSlots.begin(), UseSlots.end()); 80 calcLiveBlockInfo(); 81 DEBUG(dbgs() << " counted " 82 << UsingInstrs.size() << " instrs, " 83 << UsingBlocks.size() << " blocks.\n"); 84 } 85 86 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks 87 /// where CurLI is live. 88 void SplitAnalysis::calcLiveBlockInfo() { 89 if (CurLI->empty()) 90 return; 91 92 LiveInterval::const_iterator LVI = CurLI->begin(); 93 LiveInterval::const_iterator LVE = CurLI->end(); 94 95 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE; 96 UseI = UseSlots.begin(); 97 UseE = UseSlots.end(); 98 99 // Loop over basic blocks where CurLI is live. 100 MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start); 101 for (;;) { 102 BlockInfo BI; 103 BI.MBB = MFI; 104 SlotIndex Start, Stop; 105 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 106 107 // The last split point is the latest possible insertion point that dominates 108 // all successor blocks. If interference reaches LastSplitPoint, it is not 109 // possible to insert a split or reload that makes CurLI live in the 110 // outgoing bundle. 111 MachineBasicBlock::iterator LSP = LIS.getLastSplitPoint(*CurLI, BI.MBB); 112 if (LSP == BI.MBB->end()) 113 BI.LastSplitPoint = Stop; 114 else 115 BI.LastSplitPoint = LIS.getInstructionIndex(LSP); 116 117 // LVI is the first live segment overlapping MBB. 118 BI.LiveIn = LVI->start <= Start; 119 if (!BI.LiveIn) 120 BI.Def = LVI->start; 121 122 // Find the first and last uses in the block. 123 BI.Uses = hasUses(MFI); 124 if (BI.Uses && UseI != UseE) { 125 BI.FirstUse = *UseI; 126 assert(BI.FirstUse >= Start); 127 do ++UseI; 128 while (UseI != UseE && *UseI < Stop); 129 BI.LastUse = UseI[-1]; 130 assert(BI.LastUse < Stop); 131 } 132 133 // Look for gaps in the live range. 134 bool hasGap = false; 135 BI.LiveOut = true; 136 while (LVI->end < Stop) { 137 SlotIndex LastStop = LVI->end; 138 if (++LVI == LVE || LVI->start >= Stop) { 139 BI.Kill = LastStop; 140 BI.LiveOut = false; 141 break; 142 } 143 if (LastStop < LVI->start) { 144 hasGap = true; 145 BI.Kill = LastStop; 146 BI.Def = LVI->start; 147 } 148 } 149 150 // Don't set LiveThrough when the block has a gap. 151 BI.LiveThrough = !hasGap && BI.LiveIn && BI.LiveOut; 152 LiveBlocks.push_back(BI); 153 154 // LVI is now at LVE or LVI->end >= Stop. 155 if (LVI == LVE) 156 break; 157 158 // Live segment ends exactly at Stop. Move to the next segment. 159 if (LVI->end == Stop && ++LVI == LVE) 160 break; 161 162 // Pick the next basic block. 163 if (LVI->start < Stop) 164 ++MFI; 165 else 166 MFI = LIS.getMBBFromIndex(LVI->start); 167 } 168 } 169 170 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const { 171 unsigned OrigReg = VRM.getOriginal(CurLI->reg); 172 const LiveInterval &Orig = LIS.getInterval(OrigReg); 173 assert(!Orig.empty() && "Splitting empty interval?"); 174 LiveInterval::const_iterator I = Orig.find(Idx); 175 176 // Range containing Idx should begin at Idx. 177 if (I != Orig.end() && I->start <= Idx) 178 return I->start == Idx; 179 180 // Range does not contain Idx, previous must end at Idx. 181 return I != Orig.begin() && (--I)->end == Idx; 182 } 183 184 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const { 185 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) { 186 unsigned count = UsingBlocks.lookup(*I); 187 OS << " BB#" << (*I)->getNumber(); 188 if (count) 189 OS << '(' << count << ')'; 190 } 191 } 192 193 void SplitAnalysis::analyze(const LiveInterval *li) { 194 clear(); 195 CurLI = li; 196 analyzeUses(); 197 } 198 199 200 //===----------------------------------------------------------------------===// 201 // LiveIntervalMap 202 //===----------------------------------------------------------------------===// 203 204 // Work around the fact that the std::pair constructors are broken for pointer 205 // pairs in some implementations. makeVV(x, 0) works. 206 static inline std::pair<const VNInfo*, VNInfo*> 207 makeVV(const VNInfo *a, VNInfo *b) { 208 return std::make_pair(a, b); 209 } 210 211 void LiveIntervalMap::reset(LiveInterval *li) { 212 LI = li; 213 LiveOutCache.clear(); 214 } 215 216 217 // mapValue - Find the mapped value for ParentVNI at Idx. 218 // Potentially create phi-def values. 219 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx, 220 bool *simple) { 221 assert(LI && "call reset first"); 222 assert(ParentVNI && "Mapping NULL value"); 223 assert(Idx.isValid() && "Invalid SlotIndex"); 224 assert(ParentLI.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI"); 225 226 // This is a complex mapped value. There may be multiple defs, and we may need 227 // to create phi-defs. 228 if (simple) *simple = false; 229 MachineBasicBlock *IdxMBB = LIS.getMBBFromIndex(Idx); 230 assert(IdxMBB && "No MBB at Idx"); 231 232 // Is there a def in the same MBB we can extend? 233 if (VNInfo *VNI = LI->extendInBlock(LIS.getMBBStartIdx(IdxMBB), Idx)) 234 return VNI; 235 236 // Now for the fun part. We know that ParentVNI potentially has multiple defs, 237 // and we may need to create even more phi-defs to preserve VNInfo SSA form. 238 // Perform a search for all predecessor blocks where we know the dominating 239 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB. 240 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber() 241 << " at " << Idx << " in " << *LI << '\n'); 242 243 // Blocks where LI should be live-in. 244 SmallVector<MachineDomTreeNode*, 16> LiveIn; 245 LiveIn.push_back(MDT[IdxMBB]); 246 247 // Using LiveOutCache as a visited set, perform a BFS for all reaching defs. 248 for (unsigned i = 0; i != LiveIn.size(); ++i) { 249 MachineBasicBlock *MBB = LiveIn[i]->getBlock(); 250 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 251 PE = MBB->pred_end(); PI != PE; ++PI) { 252 MachineBasicBlock *Pred = *PI; 253 // Is this a known live-out block? 254 std::pair<LiveOutMap::iterator,bool> LOIP = 255 LiveOutCache.insert(std::make_pair(Pred, LiveOutPair())); 256 // Yes, we have been here before. 257 if (!LOIP.second) { 258 DEBUG(if (VNInfo *VNI = LOIP.first->second.first) 259 dbgs() << " known valno #" << VNI->id 260 << " at BB#" << Pred->getNumber() << '\n'); 261 continue; 262 } 263 264 // Does Pred provide a live-out value? 265 SlotIndex Start, Last; 266 tie(Start, Last) = LIS.getSlotIndexes()->getMBBRange(Pred); 267 Last = Last.getPrevSlot(); 268 if (VNInfo *VNI = LI->extendInBlock(Start, Last)) { 269 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(VNI->def); 270 DEBUG(dbgs() << " found valno #" << VNI->id 271 << " from BB#" << DefMBB->getNumber() 272 << " at BB#" << Pred->getNumber() << '\n'); 273 LiveOutPair &LOP = LOIP.first->second; 274 LOP.first = VNI; 275 LOP.second = MDT[DefMBB]; 276 continue; 277 } 278 // No, we need a live-in value for Pred as well 279 if (Pred != IdxMBB) 280 LiveIn.push_back(MDT[Pred]); 281 } 282 } 283 284 // We may need to add phi-def values to preserve the SSA form. 285 // This is essentially the same iterative algorithm that SSAUpdater uses, 286 // except we already have a dominator tree, so we don't have to recompute it. 287 VNInfo *IdxVNI = 0; 288 unsigned Changes; 289 do { 290 Changes = 0; 291 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n"); 292 // Propagate live-out values down the dominator tree, inserting phi-defs when 293 // necessary. Since LiveIn was created by a BFS, going backwards makes it more 294 // likely for us to visit immediate dominators before their children. 295 for (unsigned i = LiveIn.size(); i; --i) { 296 MachineDomTreeNode *Node = LiveIn[i-1]; 297 MachineBasicBlock *MBB = Node->getBlock(); 298 MachineDomTreeNode *IDom = Node->getIDom(); 299 LiveOutPair IDomValue; 300 // We need a live-in value to a block with no immediate dominator? 301 // This is probably an unreachable block that has survived somehow. 302 bool needPHI = !IDom; 303 304 // Get the IDom live-out value. 305 if (!needPHI) { 306 LiveOutMap::iterator I = LiveOutCache.find(IDom->getBlock()); 307 if (I != LiveOutCache.end()) 308 IDomValue = I->second; 309 else 310 // If IDom is outside our set of live-out blocks, there must be new 311 // defs, and we need a phi-def here. 312 needPHI = true; 313 } 314 315 // IDom dominates all of our predecessors, but it may not be the immediate 316 // dominator. Check if any of them have live-out values that are properly 317 // dominated by IDom. If so, we need a phi-def here. 318 if (!needPHI) { 319 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 320 PE = MBB->pred_end(); PI != PE; ++PI) { 321 LiveOutPair Value = LiveOutCache[*PI]; 322 if (!Value.first || Value.first == IDomValue.first) 323 continue; 324 // This predecessor is carrying something other than IDomValue. 325 // It could be because IDomValue hasn't propagated yet, or it could be 326 // because MBB is in the dominance frontier of that value. 327 if (MDT.dominates(IDom, Value.second)) { 328 needPHI = true; 329 break; 330 } 331 } 332 } 333 334 // Create a phi-def if required. 335 if (needPHI) { 336 ++Changes; 337 SlotIndex Start = LIS.getMBBStartIdx(MBB); 338 VNInfo *VNI = LI->getNextValue(Start, 0, LIS.getVNInfoAllocator()); 339 VNI->setIsPHIDef(true); 340 DEBUG(dbgs() << " - BB#" << MBB->getNumber() 341 << " phi-def #" << VNI->id << " at " << Start << '\n'); 342 // We no longer need LI to be live-in. 343 LiveIn.erase(LiveIn.begin()+(i-1)); 344 // Blocks in LiveIn are either IdxMBB, or have a value live-through. 345 if (MBB == IdxMBB) 346 IdxVNI = VNI; 347 // Check if we need to update live-out info. 348 LiveOutMap::iterator I = LiveOutCache.find(MBB); 349 if (I == LiveOutCache.end() || I->second.second == Node) { 350 // We already have a live-out defined in MBB, so this must be IdxMBB. 351 assert(MBB == IdxMBB && "Adding phi-def to known live-out"); 352 LI->addRange(LiveRange(Start, Idx.getNextSlot(), VNI)); 353 } else { 354 // This phi-def is also live-out, so color the whole block. 355 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI)); 356 I->second = LiveOutPair(VNI, Node); 357 } 358 } else if (IDomValue.first) { 359 // No phi-def here. Remember incoming value for IdxMBB. 360 if (MBB == IdxMBB) 361 IdxVNI = IDomValue.first; 362 // Propagate IDomValue if needed: 363 // MBB is live-out and doesn't define its own value. 364 LiveOutMap::iterator I = LiveOutCache.find(MBB); 365 if (I != LiveOutCache.end() && I->second.second != Node && 366 I->second.first != IDomValue.first) { 367 ++Changes; 368 I->second = IDomValue; 369 DEBUG(dbgs() << " - BB#" << MBB->getNumber() 370 << " idom valno #" << IDomValue.first->id 371 << " from BB#" << IDom->getBlock()->getNumber() << '\n'); 372 } 373 } 374 } 375 DEBUG(dbgs() << " - made " << Changes << " changes.\n"); 376 } while (Changes); 377 378 assert(IdxVNI && "Didn't find value for Idx"); 379 380 #ifndef NDEBUG 381 // Check the LiveOutCache invariants. 382 for (LiveOutMap::iterator I = LiveOutCache.begin(), E = LiveOutCache.end(); 383 I != E; ++I) { 384 assert(I->first && "Null MBB entry in cache"); 385 assert(I->second.first && "Null VNInfo in cache"); 386 assert(I->second.second && "Null DomTreeNode in cache"); 387 if (I->second.second->getBlock() == I->first) 388 continue; 389 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(), 390 PE = I->first->pred_end(); PI != PE; ++PI) 391 assert(LiveOutCache.lookup(*PI) == I->second && "Bad invariant"); 392 } 393 #endif 394 395 // Since we went through the trouble of a full BFS visiting all reaching defs, 396 // the values in LiveIn are now accurate. No more phi-defs are needed 397 // for these blocks, so we can color the live ranges. 398 // This makes the next mapValue call much faster. 399 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) { 400 MachineBasicBlock *MBB = LiveIn[i]->getBlock(); 401 SlotIndex Start = LIS.getMBBStartIdx(MBB); 402 VNInfo *VNI = LiveOutCache.lookup(MBB).first; 403 404 // Anything in LiveIn other than IdxMBB is live-through. 405 // In IdxMBB, we should stop at Idx unless the same value is live-out. 406 if (MBB == IdxMBB && IdxVNI != VNI) 407 LI->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI)); 408 else 409 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI)); 410 } 411 412 return IdxVNI; 413 } 414 415 #ifndef NDEBUG 416 void LiveIntervalMap::dumpCache() { 417 for (LiveOutMap::iterator I = LiveOutCache.begin(), E = LiveOutCache.end(); 418 I != E; ++I) { 419 assert(I->first && "Null MBB entry in cache"); 420 assert(I->second.first && "Null VNInfo in cache"); 421 assert(I->second.second && "Null DomTreeNode in cache"); 422 dbgs() << " cache: BB#" << I->first->getNumber() 423 << " has valno #" << I->second.first->id << " from BB#" 424 << I->second.second->getBlock()->getNumber() << ", preds"; 425 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(), 426 PE = I->first->pred_end(); PI != PE; ++PI) 427 dbgs() << " BB#" << (*PI)->getNumber(); 428 dbgs() << '\n'; 429 } 430 dbgs() << " cache: " << LiveOutCache.size() << " entries.\n"; 431 } 432 #endif 433 434 435 //===----------------------------------------------------------------------===// 436 // Split Editor 437 //===----------------------------------------------------------------------===// 438 439 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 440 SplitEditor::SplitEditor(SplitAnalysis &sa, 441 LiveIntervals &lis, 442 VirtRegMap &vrm, 443 MachineDominatorTree &mdt, 444 LiveRangeEdit &edit) 445 : SA(sa), LIS(lis), VRM(vrm), 446 MRI(vrm.getMachineFunction().getRegInfo()), 447 MDT(mdt), 448 TII(*vrm.getMachineFunction().getTarget().getInstrInfo()), 449 TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()), 450 Edit(edit), 451 OpenIdx(0), 452 RegAssign(Allocator) 453 { 454 // We don't need an AliasAnalysis since we will only be performing 455 // cheap-as-a-copy remats anyway. 456 Edit.anyRematerializable(LIS, TII, 0); 457 } 458 459 void SplitEditor::dump() const { 460 if (RegAssign.empty()) { 461 dbgs() << " empty\n"; 462 return; 463 } 464 465 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) 466 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value(); 467 dbgs() << '\n'; 468 } 469 470 VNInfo *SplitEditor::defValue(unsigned RegIdx, 471 const VNInfo *ParentVNI, 472 SlotIndex Idx) { 473 assert(ParentVNI && "Mapping NULL value"); 474 assert(Idx.isValid() && "Invalid SlotIndex"); 475 assert(Edit.getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI"); 476 LiveInterval *LI = Edit.get(RegIdx); 477 478 // Create a new value. 479 VNInfo *VNI = LI->getNextValue(Idx, 0, LIS.getVNInfoAllocator()); 480 481 // Preserve the PHIDef bit. 482 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def) 483 VNI->setIsPHIDef(true); 484 485 // Use insert for lookup, so we can add missing values with a second lookup. 486 std::pair<ValueMap::iterator, bool> InsP = 487 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), VNI)); 488 489 // This was the first time (RegIdx, ParentVNI) was mapped. 490 // Keep it as a simple def without any liveness. 491 if (InsP.second) 492 return VNI; 493 494 // If the previous value was a simple mapping, add liveness for it now. 495 if (VNInfo *OldVNI = InsP.first->second) { 496 SlotIndex Def = OldVNI->def; 497 LI->addRange(LiveRange(Def, Def.getNextSlot(), OldVNI)); 498 // No longer a simple mapping. 499 InsP.first->second = 0; 500 } 501 502 // This is a complex mapping, add liveness for VNI 503 SlotIndex Def = VNI->def; 504 LI->addRange(LiveRange(Def, Def.getNextSlot(), VNI)); 505 506 return VNI; 507 } 508 509 void SplitEditor::markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI) { 510 assert(ParentVNI && "Mapping NULL value"); 511 VNInfo *&VNI = Values[std::make_pair(RegIdx, ParentVNI->id)]; 512 513 // ParentVNI was either unmapped or already complex mapped. Either way. 514 if (!VNI) 515 return; 516 517 // This was previously a single mapping. Make sure the old def is represented 518 // by a trivial live range. 519 SlotIndex Def = VNI->def; 520 Edit.get(RegIdx)->addRange(LiveRange(Def, Def.getNextSlot(), VNI)); 521 VNI = 0; 522 } 523 524 VNInfo *SplitEditor::defFromParent(unsigned RegIdx, 525 VNInfo *ParentVNI, 526 SlotIndex UseIdx, 527 MachineBasicBlock &MBB, 528 MachineBasicBlock::iterator I) { 529 MachineInstr *CopyMI = 0; 530 SlotIndex Def; 531 LiveInterval *LI = Edit.get(RegIdx); 532 533 // Attempt cheap-as-a-copy rematerialization. 534 LiveRangeEdit::Remat RM(ParentVNI); 535 if (Edit.canRematerializeAt(RM, UseIdx, true, LIS)) { 536 Def = Edit.rematerializeAt(MBB, I, LI->reg, RM, LIS, TII, TRI); 537 } else { 538 // Can't remat, just insert a copy from parent. 539 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg) 540 .addReg(Edit.getReg()); 541 Def = LIS.InsertMachineInstrInMaps(CopyMI).getDefIndex(); 542 } 543 544 // Temporarily mark all values as complex mapped. 545 markComplexMapped(RegIdx, ParentVNI); 546 547 // Define the value in Reg. 548 VNInfo *VNI = defValue(RegIdx, ParentVNI, Def); 549 VNI->setCopy(CopyMI); 550 return VNI; 551 } 552 553 /// Create a new virtual register and live interval. 554 void SplitEditor::openIntv() { 555 assert(!OpenIdx && "Previous LI not closed before openIntv"); 556 557 // Create the complement as index 0. 558 if (Edit.empty()) { 559 Edit.create(MRI, LIS, VRM); 560 LIMappers.push_back(LiveIntervalMap(LIS, MDT, Edit.getParent())); 561 LIMappers.back().reset(Edit.get(0)); 562 } 563 564 // Create the open interval. 565 OpenIdx = Edit.size(); 566 Edit.create(MRI, LIS, VRM); 567 LIMappers.push_back(LiveIntervalMap(LIS, MDT, Edit.getParent())); 568 LIMappers[OpenIdx].reset(Edit.get(OpenIdx)); 569 } 570 571 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 572 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 573 DEBUG(dbgs() << " enterIntvBefore " << Idx); 574 Idx = Idx.getBaseIndex(); 575 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 576 if (!ParentVNI) { 577 DEBUG(dbgs() << ": not live\n"); 578 return Idx; 579 } 580 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 581 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 582 assert(MI && "enterIntvBefore called with invalid index"); 583 584 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 585 return VNI->def; 586 } 587 588 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 589 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 590 SlotIndex End = LIS.getMBBEndIdx(&MBB); 591 SlotIndex Last = End.getPrevSlot(); 592 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last); 593 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Last); 594 if (!ParentVNI) { 595 DEBUG(dbgs() << ": not live\n"); 596 return End; 597 } 598 DEBUG(dbgs() << ": valno " << ParentVNI->id); 599 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 600 LIS.getLastSplitPoint(Edit.getParent(), &MBB)); 601 RegAssign.insert(VNI->def, End, OpenIdx); 602 DEBUG(dump()); 603 return VNI->def; 604 } 605 606 /// useIntv - indicate that all instructions in MBB should use OpenLI. 607 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 608 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 609 } 610 611 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 612 assert(OpenIdx && "openIntv not called before useIntv"); 613 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 614 RegAssign.insert(Start, End, OpenIdx); 615 DEBUG(dump()); 616 } 617 618 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 619 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 620 DEBUG(dbgs() << " leaveIntvAfter " << Idx); 621 622 // The interval must be live beyond the instruction at Idx. 623 Idx = Idx.getBoundaryIndex(); 624 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 625 if (!ParentVNI) { 626 DEBUG(dbgs() << ": not live\n"); 627 return Idx.getNextSlot(); 628 } 629 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 630 631 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 632 assert(MI && "No instruction at index"); 633 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), 634 llvm::next(MachineBasicBlock::iterator(MI))); 635 return VNI->def; 636 } 637 638 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 639 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 640 DEBUG(dbgs() << " leaveIntvBefore " << Idx); 641 642 // The interval must be live into the instruction at Idx. 643 Idx = Idx.getBoundaryIndex(); 644 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 645 if (!ParentVNI) { 646 DEBUG(dbgs() << ": not live\n"); 647 return Idx.getNextSlot(); 648 } 649 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 650 651 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 652 assert(MI && "No instruction at index"); 653 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 654 return VNI->def; 655 } 656 657 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 658 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 659 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 660 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start); 661 662 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Start); 663 if (!ParentVNI) { 664 DEBUG(dbgs() << ": not live\n"); 665 return Start; 666 } 667 668 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, 669 MBB.SkipPHIsAndLabels(MBB.begin())); 670 RegAssign.insert(Start, VNI->def, OpenIdx); 671 DEBUG(dump()); 672 return VNI->def; 673 } 674 675 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 676 assert(OpenIdx && "openIntv not called before overlapIntv"); 677 assert(Edit.getParent().getVNInfoAt(Start) == 678 Edit.getParent().getVNInfoAt(End.getPrevSlot()) && 679 "Parent changes value in extended range"); 680 assert(Edit.get(0)->getVNInfoAt(Start) && "Start must come from leaveIntv*"); 681 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 682 "Range cannot span basic blocks"); 683 684 // Treat this as useIntv() for now. The complement interval will be extended 685 // as needed by mapValue(). 686 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 687 RegAssign.insert(Start, End, OpenIdx); 688 DEBUG(dump()); 689 } 690 691 /// closeIntv - Indicate that we are done editing the currently open 692 /// LiveInterval, and ranges can be trimmed. 693 void SplitEditor::closeIntv() { 694 assert(OpenIdx && "openIntv not called before closeIntv"); 695 OpenIdx = 0; 696 } 697 698 /// rewriteAssigned - Rewrite all uses of Edit.getReg(). 699 void SplitEditor::rewriteAssigned() { 700 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit.getReg()), 701 RE = MRI.reg_end(); RI != RE;) { 702 MachineOperand &MO = RI.getOperand(); 703 MachineInstr *MI = MO.getParent(); 704 ++RI; 705 // LiveDebugVariables should have handled all DBG_VALUE instructions. 706 if (MI->isDebugValue()) { 707 DEBUG(dbgs() << "Zapping " << *MI); 708 MO.setReg(0); 709 continue; 710 } 711 712 // <undef> operands don't really read the register, so just assign them to 713 // the complement. 714 if (MO.isUse() && MO.isUndef()) { 715 MO.setReg(Edit.get(0)->reg); 716 continue; 717 } 718 719 SlotIndex Idx = LIS.getInstructionIndex(MI); 720 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex(); 721 722 // Rewrite to the mapped register at Idx. 723 unsigned RegIdx = RegAssign.lookup(Idx); 724 MO.setReg(Edit.get(RegIdx)->reg); 725 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t' 726 << Idx << ':' << RegIdx << '\t' << *MI); 727 728 // Extend liveness to Idx. 729 const VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 730 LIMappers[RegIdx].mapValue(ParentVNI, Idx); 731 } 732 } 733 734 /// rewriteSplit - Rewrite uses of Intvs[0] according to the ConEQ mapping. 735 void SplitEditor::rewriteComponents(const SmallVectorImpl<LiveInterval*> &Intvs, 736 const ConnectedVNInfoEqClasses &ConEq) { 737 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Intvs[0]->reg), 738 RE = MRI.reg_end(); RI != RE;) { 739 MachineOperand &MO = RI.getOperand(); 740 MachineInstr *MI = MO.getParent(); 741 ++RI; 742 if (MO.isUse() && MO.isUndef()) 743 continue; 744 // DBG_VALUE instructions should have been eliminated earlier. 745 SlotIndex Idx = LIS.getInstructionIndex(MI); 746 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex(); 747 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t' 748 << Idx << ':'); 749 const VNInfo *VNI = Intvs[0]->getVNInfoAt(Idx); 750 assert(VNI && "Interval not live at use."); 751 MO.setReg(Intvs[ConEq.getEqClass(VNI)]->reg); 752 DEBUG(dbgs() << VNI->id << '\t' << *MI); 753 } 754 } 755 756 void SplitEditor::finish() { 757 assert(OpenIdx == 0 && "Previous LI not closed before rewrite"); 758 759 // At this point, the live intervals in Edit contain VNInfos corresponding to 760 // the inserted copies. 761 762 // Add the original defs from the parent interval. 763 for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(), 764 E = Edit.getParent().vni_end(); I != E; ++I) { 765 const VNInfo *ParentVNI = *I; 766 if (ParentVNI->isUnused()) 767 continue; 768 unsigned RegIdx = RegAssign.lookup(ParentVNI->def); 769 // Mark all values as complex to force liveness computation. 770 // This should really only be necessary for remat victims, but we are lazy. 771 markComplexMapped(RegIdx, ParentVNI); 772 defValue(RegIdx, ParentVNI, ParentVNI->def); 773 } 774 775 #ifndef NDEBUG 776 // Every new interval must have a def by now, otherwise the split is bogus. 777 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I) 778 assert((*I)->hasAtLeastOneValue() && "Split interval has no value"); 779 #endif 780 781 // FIXME: Don't recompute the liveness of all values, infer it from the 782 // overlaps between the parent live interval and RegAssign. 783 // The mapValue algorithm is only necessary when: 784 // - The parent value maps to multiple defs, and new phis are needed, or 785 // - The value has been rematerialized before some uses, and we want to 786 // minimize the live range so it only reaches the remaining uses. 787 // All other values have simple liveness that can be computed from RegAssign 788 // and the parent live interval. 789 790 // Extend live ranges to be live-out for successor PHI values. 791 for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(), 792 E = Edit.getParent().vni_end(); I != E; ++I) { 793 const VNInfo *PHIVNI = *I; 794 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef()) 795 continue; 796 unsigned RegIdx = RegAssign.lookup(PHIVNI->def); 797 LiveIntervalMap &LIM = LIMappers[RegIdx]; 798 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def); 799 DEBUG(dbgs() << " map phi in BB#" << MBB->getNumber() << '@' << PHIVNI->def 800 << " -> " << RegIdx << '\n'); 801 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 802 PE = MBB->pred_end(); PI != PE; ++PI) { 803 SlotIndex End = LIS.getMBBEndIdx(*PI).getPrevSlot(); 804 DEBUG(dbgs() << " pred BB#" << (*PI)->getNumber() << '@' << End); 805 // The predecessor may not have a live-out value. That is OK, like an 806 // undef PHI operand. 807 if (VNInfo *VNI = Edit.getParent().getVNInfoAt(End)) { 808 DEBUG(dbgs() << " has parent valno #" << VNI->id << " live out\n"); 809 assert(RegAssign.lookup(End) == RegIdx && 810 "Different register assignment in phi predecessor"); 811 LIM.mapValue(VNI, End); 812 } 813 else 814 DEBUG(dbgs() << " is not live-out\n"); 815 } 816 DEBUG(dbgs() << " " << *LIM.getLI() << '\n'); 817 } 818 819 // Rewrite instructions. 820 rewriteAssigned(); 821 822 // FIXME: Delete defs that were rematted everywhere. 823 824 // Get rid of unused values and set phi-kill flags. 825 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I) 826 (*I)->RenumberValues(LIS); 827 828 // Now check if any registers were separated into multiple components. 829 ConnectedVNInfoEqClasses ConEQ(LIS); 830 for (unsigned i = 0, e = Edit.size(); i != e; ++i) { 831 // Don't use iterators, they are invalidated by create() below. 832 LiveInterval *li = Edit.get(i); 833 unsigned NumComp = ConEQ.Classify(li); 834 if (NumComp <= 1) 835 continue; 836 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n'); 837 SmallVector<LiveInterval*, 8> dups; 838 dups.push_back(li); 839 for (unsigned i = 1; i != NumComp; ++i) 840 dups.push_back(&Edit.create(MRI, LIS, VRM)); 841 rewriteComponents(dups, ConEQ); 842 ConEQ.Distribute(&dups[0]); 843 } 844 845 // Calculate spill weight and allocation hints for new intervals. 846 VirtRegAuxInfo vrai(VRM.getMachineFunction(), LIS, SA.Loops); 847 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I){ 848 LiveInterval &li = **I; 849 vrai.CalculateRegClass(li.reg); 850 vrai.CalculateWeightAndHint(li); 851 DEBUG(dbgs() << " new interval " << MRI.getRegClass(li.reg)->getName() 852 << ":" << li << '\n'); 853 } 854 } 855 856 857 //===----------------------------------------------------------------------===// 858 // Single Block Splitting 859 //===----------------------------------------------------------------------===// 860 861 /// getMultiUseBlocks - if CurLI has more than one use in a basic block, it 862 /// may be an advantage to split CurLI for the duration of the block. 863 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) { 864 // If CurLI is local to one block, there is no point to splitting it. 865 if (LiveBlocks.size() <= 1) 866 return false; 867 // Add blocks with multiple uses. 868 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) { 869 const BlockInfo &BI = LiveBlocks[i]; 870 if (!BI.Uses) 871 continue; 872 unsigned Instrs = UsingBlocks.lookup(BI.MBB); 873 if (Instrs <= 1) 874 continue; 875 if (Instrs == 2 && BI.LiveIn && BI.LiveOut && !BI.LiveThrough) 876 continue; 877 Blocks.insert(BI.MBB); 878 } 879 return !Blocks.empty(); 880 } 881 882 /// splitSingleBlocks - Split CurLI into a separate live interval inside each 883 /// basic block in Blocks. 884 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) { 885 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n"); 886 887 for (unsigned i = 0, e = SA.LiveBlocks.size(); i != e; ++i) { 888 const SplitAnalysis::BlockInfo &BI = SA.LiveBlocks[i]; 889 if (!BI.Uses || !Blocks.count(BI.MBB)) 890 continue; 891 892 openIntv(); 893 SlotIndex SegStart = enterIntvBefore(BI.FirstUse); 894 if (!BI.LiveOut || BI.LastUse < BI.LastSplitPoint) { 895 useIntv(SegStart, leaveIntvAfter(BI.LastUse)); 896 } else { 897 // The last use is after the last valid split point. 898 SlotIndex SegStop = leaveIntvBefore(BI.LastSplitPoint); 899 useIntv(SegStart, SegStop); 900 overlapIntv(SegStop, BI.LastUse); 901 } 902 closeIntv(); 903 } 904 finish(); 905 } 906