LLVM API Documentation
00001 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file contains the SplitAnalysis class as well as mutator functions for 00011 // live range splitting. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "regalloc" 00016 #include "SplitKit.h" 00017 #include "llvm/ADT/Statistic.h" 00018 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 00019 #include "llvm/CodeGen/LiveRangeEdit.h" 00020 #include "llvm/CodeGen/MachineDominators.h" 00021 #include "llvm/CodeGen/MachineInstrBuilder.h" 00022 #include "llvm/CodeGen/MachineLoopInfo.h" 00023 #include "llvm/CodeGen/MachineRegisterInfo.h" 00024 #include "llvm/CodeGen/VirtRegMap.h" 00025 #include "llvm/Support/Debug.h" 00026 #include "llvm/Support/raw_ostream.h" 00027 #include "llvm/Target/TargetInstrInfo.h" 00028 #include "llvm/Target/TargetMachine.h" 00029 00030 using namespace llvm; 00031 00032 STATISTIC(NumFinished, "Number of splits finished"); 00033 STATISTIC(NumSimple, "Number of splits that were simple"); 00034 STATISTIC(NumCopies, "Number of copies inserted for splitting"); 00035 STATISTIC(NumRemats, "Number of rematerialized defs for splitting"); 00036 STATISTIC(NumRepairs, "Number of invalid live ranges repaired"); 00037 00038 //===----------------------------------------------------------------------===// 00039 // Split Analysis 00040 //===----------------------------------------------------------------------===// 00041 00042 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, 00043 const LiveIntervals &lis, 00044 const MachineLoopInfo &mli) 00045 : MF(vrm.getMachineFunction()), 00046 VRM(vrm), 00047 LIS(lis), 00048 Loops(mli), 00049 TII(*MF.getTarget().getInstrInfo()), 00050 CurLI(0), 00051 LastSplitPoint(MF.getNumBlockIDs()) {} 00052 00053 void SplitAnalysis::clear() { 00054 UseSlots.clear(); 00055 UseBlocks.clear(); 00056 ThroughBlocks.clear(); 00057 CurLI = 0; 00058 DidRepairRange = false; 00059 } 00060 00061 SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) { 00062 const MachineBasicBlock *MBB = MF.getBlockNumbered(Num); 00063 const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor(); 00064 std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num]; 00065 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB); 00066 00067 // Compute split points on the first call. The pair is independent of the 00068 // current live interval. 00069 if (!LSP.first.isValid()) { 00070 MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator(); 00071 if (FirstTerm == MBB->end()) 00072 LSP.first = MBBEnd; 00073 else 00074 LSP.first = LIS.getInstructionIndex(FirstTerm); 00075 00076 // If there is a landing pad successor, also find the call instruction. 00077 if (!LPad) 00078 return LSP.first; 00079 // There may not be a call instruction (?) in which case we ignore LPad. 00080 LSP.second = LSP.first; 00081 for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin(); 00082 I != E;) { 00083 --I; 00084 if (I->isCall()) { 00085 LSP.second = LIS.getInstructionIndex(I); 00086 break; 00087 } 00088 } 00089 } 00090 00091 // If CurLI is live into a landing pad successor, move the last split point 00092 // back to the call that may throw. 00093 if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad)) 00094 return LSP.first; 00095 00096 // Find the value leaving MBB. 00097 const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd); 00098 if (!VNI) 00099 return LSP.first; 00100 00101 // If the value leaving MBB was defined after the call in MBB, it can't 00102 // really be live-in to the landing pad. This can happen if the landing pad 00103 // has a PHI, and this register is undef on the exceptional edge. 00104 // <rdar://problem/10664933> 00105 if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd) 00106 return LSP.first; 00107 00108 // Value is properly live-in to the landing pad. 00109 // Only allow splits before the call. 00110 return LSP.second; 00111 } 00112 00113 MachineBasicBlock::iterator 00114 SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) { 00115 SlotIndex LSP = getLastSplitPoint(MBB->getNumber()); 00116 if (LSP == LIS.getMBBEndIdx(MBB)) 00117 return MBB->end(); 00118 return LIS.getInstructionFromIndex(LSP); 00119 } 00120 00121 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. 00122 void SplitAnalysis::analyzeUses() { 00123 assert(UseSlots.empty() && "Call clear first"); 00124 00125 // First get all the defs from the interval values. This provides the correct 00126 // slots for early clobbers. 00127 for (LiveInterval::const_vni_iterator I = CurLI->vni_begin(), 00128 E = CurLI->vni_end(); I != E; ++I) 00129 if (!(*I)->isPHIDef() && !(*I)->isUnused()) 00130 UseSlots.push_back((*I)->def); 00131 00132 // Get use slots form the use-def chain. 00133 const MachineRegisterInfo &MRI = MF.getRegInfo(); 00134 for (MachineRegisterInfo::use_nodbg_iterator 00135 I = MRI.use_nodbg_begin(CurLI->reg), E = MRI.use_nodbg_end(); I != E; 00136 ++I) 00137 if (!I.getOperand().isUndef()) 00138 UseSlots.push_back(LIS.getInstructionIndex(&*I).getRegSlot()); 00139 00140 array_pod_sort(UseSlots.begin(), UseSlots.end()); 00141 00142 // Remove duplicates, keeping the smaller slot for each instruction. 00143 // That is what we want for early clobbers. 00144 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(), 00145 SlotIndex::isSameInstr), 00146 UseSlots.end()); 00147 00148 // Compute per-live block info. 00149 if (!calcLiveBlockInfo()) { 00150 // FIXME: calcLiveBlockInfo found inconsistencies in the live range. 00151 // I am looking at you, RegisterCoalescer! 00152 DidRepairRange = true; 00153 ++NumRepairs; 00154 DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n"); 00155 const_cast<LiveIntervals&>(LIS) 00156 .shrinkToUses(const_cast<LiveInterval*>(CurLI)); 00157 UseBlocks.clear(); 00158 ThroughBlocks.clear(); 00159 bool fixed = calcLiveBlockInfo(); 00160 (void)fixed; 00161 assert(fixed && "Couldn't fix broken live interval"); 00162 } 00163 00164 DEBUG(dbgs() << "Analyze counted " 00165 << UseSlots.size() << " instrs in " 00166 << UseBlocks.size() << " blocks, through " 00167 << NumThroughBlocks << " blocks.\n"); 00168 } 00169 00170 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks 00171 /// where CurLI is live. 00172 bool SplitAnalysis::calcLiveBlockInfo() { 00173 ThroughBlocks.resize(MF.getNumBlockIDs()); 00174 NumThroughBlocks = NumGapBlocks = 0; 00175 if (CurLI->empty()) 00176 return true; 00177 00178 LiveInterval::const_iterator LVI = CurLI->begin(); 00179 LiveInterval::const_iterator LVE = CurLI->end(); 00180 00181 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE; 00182 UseI = UseSlots.begin(); 00183 UseE = UseSlots.end(); 00184 00185 // Loop over basic blocks where CurLI is live. 00186 MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start); 00187 for (;;) { 00188 BlockInfo BI; 00189 BI.MBB = MFI; 00190 SlotIndex Start, Stop; 00191 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 00192 00193 // If the block contains no uses, the range must be live through. At one 00194 // point, RegisterCoalescer could create dangling ranges that ended 00195 // mid-block. 00196 if (UseI == UseE || *UseI >= Stop) { 00197 ++NumThroughBlocks; 00198 ThroughBlocks.set(BI.MBB->getNumber()); 00199 // The range shouldn't end mid-block if there are no uses. This shouldn't 00200 // happen. 00201 if (LVI->end < Stop) 00202 return false; 00203 } else { 00204 // This block has uses. Find the first and last uses in the block. 00205 BI.FirstInstr = *UseI; 00206 assert(BI.FirstInstr >= Start); 00207 do ++UseI; 00208 while (UseI != UseE && *UseI < Stop); 00209 BI.LastInstr = UseI[-1]; 00210 assert(BI.LastInstr < Stop); 00211 00212 // LVI is the first live segment overlapping MBB. 00213 BI.LiveIn = LVI->start <= Start; 00214 00215 // When not live in, the first use should be a def. 00216 if (!BI.LiveIn) { 00217 assert(LVI->start == LVI->valno->def && "Dangling LiveRange start"); 00218 assert(LVI->start == BI.FirstInstr && "First instr should be a def"); 00219 BI.FirstDef = BI.FirstInstr; 00220 } 00221 00222 // Look for gaps in the live range. 00223 BI.LiveOut = true; 00224 while (LVI->end < Stop) { 00225 SlotIndex LastStop = LVI->end; 00226 if (++LVI == LVE || LVI->start >= Stop) { 00227 BI.LiveOut = false; 00228 BI.LastInstr = LastStop; 00229 break; 00230 } 00231 00232 if (LastStop < LVI->start) { 00233 // There is a gap in the live range. Create duplicate entries for the 00234 // live-in snippet and the live-out snippet. 00235 ++NumGapBlocks; 00236 00237 // Push the Live-in part. 00238 BI.LiveOut = false; 00239 UseBlocks.push_back(BI); 00240 UseBlocks.back().LastInstr = LastStop; 00241 00242 // Set up BI for the live-out part. 00243 BI.LiveIn = false; 00244 BI.LiveOut = true; 00245 BI.FirstInstr = BI.FirstDef = LVI->start; 00246 } 00247 00248 // A LiveRange that starts in the middle of the block must be a def. 00249 assert(LVI->start == LVI->valno->def && "Dangling LiveRange start"); 00250 if (!BI.FirstDef) 00251 BI.FirstDef = LVI->start; 00252 } 00253 00254 UseBlocks.push_back(BI); 00255 00256 // LVI is now at LVE or LVI->end >= Stop. 00257 if (LVI == LVE) 00258 break; 00259 } 00260 00261 // Live segment ends exactly at Stop. Move to the next segment. 00262 if (LVI->end == Stop && ++LVI == LVE) 00263 break; 00264 00265 // Pick the next basic block. 00266 if (LVI->start < Stop) 00267 ++MFI; 00268 else 00269 MFI = LIS.getMBBFromIndex(LVI->start); 00270 } 00271 00272 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count"); 00273 return true; 00274 } 00275 00276 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const { 00277 if (cli->empty()) 00278 return 0; 00279 LiveInterval *li = const_cast<LiveInterval*>(cli); 00280 LiveInterval::iterator LVI = li->begin(); 00281 LiveInterval::iterator LVE = li->end(); 00282 unsigned Count = 0; 00283 00284 // Loop over basic blocks where li is live. 00285 MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start); 00286 SlotIndex Stop = LIS.getMBBEndIdx(MFI); 00287 for (;;) { 00288 ++Count; 00289 LVI = li->advanceTo(LVI, Stop); 00290 if (LVI == LVE) 00291 return Count; 00292 do { 00293 ++MFI; 00294 Stop = LIS.getMBBEndIdx(MFI); 00295 } while (Stop <= LVI->start); 00296 } 00297 } 00298 00299 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const { 00300 unsigned OrigReg = VRM.getOriginal(CurLI->reg); 00301 const LiveInterval &Orig = LIS.getInterval(OrigReg); 00302 assert(!Orig.empty() && "Splitting empty interval?"); 00303 LiveInterval::const_iterator I = Orig.find(Idx); 00304 00305 // Range containing Idx should begin at Idx. 00306 if (I != Orig.end() && I->start <= Idx) 00307 return I->start == Idx; 00308 00309 // Range does not contain Idx, previous must end at Idx. 00310 return I != Orig.begin() && (--I)->end == Idx; 00311 } 00312 00313 void SplitAnalysis::analyze(const LiveInterval *li) { 00314 clear(); 00315 CurLI = li; 00316 analyzeUses(); 00317 } 00318 00319 00320 //===----------------------------------------------------------------------===// 00321 // Split Editor 00322 //===----------------------------------------------------------------------===// 00323 00324 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 00325 SplitEditor::SplitEditor(SplitAnalysis &sa, 00326 LiveIntervals &lis, 00327 VirtRegMap &vrm, 00328 MachineDominatorTree &mdt, 00329 MachineBlockFrequencyInfo &mbfi) 00330 : SA(sa), LIS(lis), VRM(vrm), 00331 MRI(vrm.getMachineFunction().getRegInfo()), 00332 MDT(mdt), 00333 TII(*vrm.getMachineFunction().getTarget().getInstrInfo()), 00334 TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()), 00335 MBFI(mbfi), 00336 Edit(0), 00337 OpenIdx(0), 00338 SpillMode(SM_Partition), 00339 RegAssign(Allocator) 00340 {} 00341 00342 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) { 00343 Edit = &LRE; 00344 SpillMode = SM; 00345 OpenIdx = 0; 00346 RegAssign.clear(); 00347 Values.clear(); 00348 00349 // Reset the LiveRangeCalc instances needed for this spill mode. 00350 LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 00351 &LIS.getVNInfoAllocator()); 00352 if (SpillMode) 00353 LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 00354 &LIS.getVNInfoAllocator()); 00355 00356 // We don't need an AliasAnalysis since we will only be performing 00357 // cheap-as-a-copy remats anyway. 00358 Edit->anyRematerializable(0); 00359 } 00360 00361 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 00362 void SplitEditor::dump() const { 00363 if (RegAssign.empty()) { 00364 dbgs() << " empty\n"; 00365 return; 00366 } 00367 00368 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) 00369 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value(); 00370 dbgs() << '\n'; 00371 } 00372 #endif 00373 00374 VNInfo *SplitEditor::defValue(unsigned RegIdx, 00375 const VNInfo *ParentVNI, 00376 SlotIndex Idx) { 00377 assert(ParentVNI && "Mapping NULL value"); 00378 assert(Idx.isValid() && "Invalid SlotIndex"); 00379 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI"); 00380 LiveInterval *LI = Edit->get(RegIdx); 00381 00382 // Create a new value. 00383 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator()); 00384 00385 // Use insert for lookup, so we can add missing values with a second lookup. 00386 std::pair<ValueMap::iterator, bool> InsP = 00387 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), 00388 ValueForcePair(VNI, false))); 00389 00390 // This was the first time (RegIdx, ParentVNI) was mapped. 00391 // Keep it as a simple def without any liveness. 00392 if (InsP.second) 00393 return VNI; 00394 00395 // If the previous value was a simple mapping, add liveness for it now. 00396 if (VNInfo *OldVNI = InsP.first->second.getPointer()) { 00397 SlotIndex Def = OldVNI->def; 00398 LI->addRange(LiveRange(Def, Def.getDeadSlot(), OldVNI)); 00399 // No longer a simple mapping. Switch to a complex, non-forced mapping. 00400 InsP.first->second = ValueForcePair(); 00401 } 00402 00403 // This is a complex mapping, add liveness for VNI 00404 SlotIndex Def = VNI->def; 00405 LI->addRange(LiveRange(Def, Def.getDeadSlot(), VNI)); 00406 00407 return VNI; 00408 } 00409 00410 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) { 00411 assert(ParentVNI && "Mapping NULL value"); 00412 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)]; 00413 VNInfo *VNI = VFP.getPointer(); 00414 00415 // ParentVNI was either unmapped or already complex mapped. Either way, just 00416 // set the force bit. 00417 if (!VNI) { 00418 VFP.setInt(true); 00419 return; 00420 } 00421 00422 // This was previously a single mapping. Make sure the old def is represented 00423 // by a trivial live range. 00424 SlotIndex Def = VNI->def; 00425 Edit->get(RegIdx)->addRange(LiveRange(Def, Def.getDeadSlot(), VNI)); 00426 // Mark as complex mapped, forced. 00427 VFP = ValueForcePair(0, true); 00428 } 00429 00430 VNInfo *SplitEditor::defFromParent(unsigned RegIdx, 00431 VNInfo *ParentVNI, 00432 SlotIndex UseIdx, 00433 MachineBasicBlock &MBB, 00434 MachineBasicBlock::iterator I) { 00435 MachineInstr *CopyMI = 0; 00436 SlotIndex Def; 00437 LiveInterval *LI = Edit->get(RegIdx); 00438 00439 // We may be trying to avoid interference that ends at a deleted instruction, 00440 // so always begin RegIdx 0 early and all others late. 00441 bool Late = RegIdx != 0; 00442 00443 // Attempt cheap-as-a-copy rematerialization. 00444 LiveRangeEdit::Remat RM(ParentVNI); 00445 if (Edit->canRematerializeAt(RM, UseIdx, true)) { 00446 Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late); 00447 ++NumRemats; 00448 } else { 00449 // Can't remat, just insert a copy from parent. 00450 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg) 00451 .addReg(Edit->getReg()); 00452 Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late) 00453 .getRegSlot(); 00454 ++NumCopies; 00455 } 00456 00457 // Define the value in Reg. 00458 return defValue(RegIdx, ParentVNI, Def); 00459 } 00460 00461 /// Create a new virtual register and live interval. 00462 unsigned SplitEditor::openIntv() { 00463 // Create the complement as index 0. 00464 if (Edit->empty()) 00465 Edit->create(); 00466 00467 // Create the open interval. 00468 OpenIdx = Edit->size(); 00469 Edit->create(); 00470 return OpenIdx; 00471 } 00472 00473 void SplitEditor::selectIntv(unsigned Idx) { 00474 assert(Idx != 0 && "Cannot select the complement interval"); 00475 assert(Idx < Edit->size() && "Can only select previously opened interval"); 00476 DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n'); 00477 OpenIdx = Idx; 00478 } 00479 00480 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 00481 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 00482 DEBUG(dbgs() << " enterIntvBefore " << Idx); 00483 Idx = Idx.getBaseIndex(); 00484 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 00485 if (!ParentVNI) { 00486 DEBUG(dbgs() << ": not live\n"); 00487 return Idx; 00488 } 00489 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 00490 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 00491 assert(MI && "enterIntvBefore called with invalid index"); 00492 00493 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 00494 return VNI->def; 00495 } 00496 00497 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) { 00498 assert(OpenIdx && "openIntv not called before enterIntvAfter"); 00499 DEBUG(dbgs() << " enterIntvAfter " << Idx); 00500 Idx = Idx.getBoundaryIndex(); 00501 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 00502 if (!ParentVNI) { 00503 DEBUG(dbgs() << ": not live\n"); 00504 return Idx; 00505 } 00506 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 00507 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 00508 assert(MI && "enterIntvAfter called with invalid index"); 00509 00510 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), 00511 llvm::next(MachineBasicBlock::iterator(MI))); 00512 return VNI->def; 00513 } 00514 00515 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 00516 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 00517 SlotIndex End = LIS.getMBBEndIdx(&MBB); 00518 SlotIndex Last = End.getPrevSlot(); 00519 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last); 00520 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last); 00521 if (!ParentVNI) { 00522 DEBUG(dbgs() << ": not live\n"); 00523 return End; 00524 } 00525 DEBUG(dbgs() << ": valno " << ParentVNI->id); 00526 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 00527 SA.getLastSplitPointIter(&MBB)); 00528 RegAssign.insert(VNI->def, End, OpenIdx); 00529 DEBUG(dump()); 00530 return VNI->def; 00531 } 00532 00533 /// useIntv - indicate that all instructions in MBB should use OpenLI. 00534 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 00535 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 00536 } 00537 00538 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 00539 assert(OpenIdx && "openIntv not called before useIntv"); 00540 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 00541 RegAssign.insert(Start, End, OpenIdx); 00542 DEBUG(dump()); 00543 } 00544 00545 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 00546 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 00547 DEBUG(dbgs() << " leaveIntvAfter " << Idx); 00548 00549 // The interval must be live beyond the instruction at Idx. 00550 SlotIndex Boundary = Idx.getBoundaryIndex(); 00551 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary); 00552 if (!ParentVNI) { 00553 DEBUG(dbgs() << ": not live\n"); 00554 return Boundary.getNextSlot(); 00555 } 00556 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 00557 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary); 00558 assert(MI && "No instruction at index"); 00559 00560 // In spill mode, make live ranges as short as possible by inserting the copy 00561 // before MI. This is only possible if that instruction doesn't redefine the 00562 // value. The inserted COPY is not a kill, and we don't need to recompute 00563 // the source live range. The spiller also won't try to hoist this copy. 00564 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) && 00565 MI->readsVirtualRegister(Edit->getReg())) { 00566 forceRecompute(0, ParentVNI); 00567 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 00568 return Idx; 00569 } 00570 00571 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(), 00572 llvm::next(MachineBasicBlock::iterator(MI))); 00573 return VNI->def; 00574 } 00575 00576 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 00577 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 00578 DEBUG(dbgs() << " leaveIntvBefore " << Idx); 00579 00580 // The interval must be live into the instruction at Idx. 00581 Idx = Idx.getBaseIndex(); 00582 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 00583 if (!ParentVNI) { 00584 DEBUG(dbgs() << ": not live\n"); 00585 return Idx.getNextSlot(); 00586 } 00587 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 00588 00589 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 00590 assert(MI && "No instruction at index"); 00591 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 00592 return VNI->def; 00593 } 00594 00595 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 00596 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 00597 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 00598 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start); 00599 00600 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 00601 if (!ParentVNI) { 00602 DEBUG(dbgs() << ": not live\n"); 00603 return Start; 00604 } 00605 00606 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, 00607 MBB.SkipPHIsAndLabels(MBB.begin())); 00608 RegAssign.insert(Start, VNI->def, OpenIdx); 00609 DEBUG(dump()); 00610 return VNI->def; 00611 } 00612 00613 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 00614 assert(OpenIdx && "openIntv not called before overlapIntv"); 00615 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 00616 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) && 00617 "Parent changes value in extended range"); 00618 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 00619 "Range cannot span basic blocks"); 00620 00621 // The complement interval will be extended as needed by LRCalc.extend(). 00622 if (ParentVNI) 00623 forceRecompute(0, ParentVNI); 00624 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 00625 RegAssign.insert(Start, End, OpenIdx); 00626 DEBUG(dump()); 00627 } 00628 00629 //===----------------------------------------------------------------------===// 00630 // Spill modes 00631 //===----------------------------------------------------------------------===// 00632 00633 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) { 00634 LiveInterval *LI = Edit->get(0); 00635 DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n"); 00636 RegAssignMap::iterator AssignI; 00637 AssignI.setMap(RegAssign); 00638 00639 for (unsigned i = 0, e = Copies.size(); i != e; ++i) { 00640 VNInfo *VNI = Copies[i]; 00641 SlotIndex Def = VNI->def; 00642 MachineInstr *MI = LIS.getInstructionFromIndex(Def); 00643 assert(MI && "No instruction for back-copy"); 00644 00645 MachineBasicBlock *MBB = MI->getParent(); 00646 MachineBasicBlock::iterator MBBI(MI); 00647 bool AtBegin; 00648 do AtBegin = MBBI == MBB->begin(); 00649 while (!AtBegin && (--MBBI)->isDebugValue()); 00650 00651 DEBUG(dbgs() << "Removing " << Def << '\t' << *MI); 00652 LI->removeValNo(VNI); 00653 LIS.RemoveMachineInstrFromMaps(MI); 00654 MI->eraseFromParent(); 00655 00656 // Adjust RegAssign if a register assignment is killed at VNI->def. We 00657 // want to avoid calculating the live range of the source register if 00658 // possible. 00659 AssignI.find(Def.getPrevSlot()); 00660 if (!AssignI.valid() || AssignI.start() >= Def) 00661 continue; 00662 // If MI doesn't kill the assigned register, just leave it. 00663 if (AssignI.stop() != Def) 00664 continue; 00665 unsigned RegIdx = AssignI.value(); 00666 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) { 00667 DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n'); 00668 forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def)); 00669 } else { 00670 SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot(); 00671 DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI); 00672 AssignI.setStop(Kill); 00673 } 00674 } 00675 } 00676 00677 MachineBasicBlock* 00678 SplitEditor::findShallowDominator(MachineBasicBlock *MBB, 00679 MachineBasicBlock *DefMBB) { 00680 if (MBB == DefMBB) 00681 return MBB; 00682 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def."); 00683 00684 const MachineLoopInfo &Loops = SA.Loops; 00685 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB); 00686 MachineDomTreeNode *DefDomNode = MDT[DefMBB]; 00687 00688 // Best candidate so far. 00689 MachineBasicBlock *BestMBB = MBB; 00690 unsigned BestDepth = UINT_MAX; 00691 00692 for (;;) { 00693 const MachineLoop *Loop = Loops.getLoopFor(MBB); 00694 00695 // MBB isn't in a loop, it doesn't get any better. All dominators have a 00696 // higher frequency by definition. 00697 if (!Loop) { 00698 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 00699 << MBB->getNumber() << " at depth 0\n"); 00700 return MBB; 00701 } 00702 00703 // We'll never be able to exit the DefLoop. 00704 if (Loop == DefLoop) { 00705 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 00706 << MBB->getNumber() << " in the same loop\n"); 00707 return MBB; 00708 } 00709 00710 // Least busy dominator seen so far. 00711 unsigned Depth = Loop->getLoopDepth(); 00712 if (Depth < BestDepth) { 00713 BestMBB = MBB; 00714 BestDepth = Depth; 00715 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 00716 << MBB->getNumber() << " at depth " << Depth << '\n'); 00717 } 00718 00719 // Leave loop by going to the immediate dominator of the loop header. 00720 // This is a bigger stride than simply walking up the dominator tree. 00721 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom(); 00722 00723 // Too far up the dominator tree? 00724 if (!IDom || !MDT.dominates(DefDomNode, IDom)) 00725 return BestMBB; 00726 00727 MBB = IDom->getBlock(); 00728 } 00729 } 00730 00731 void SplitEditor::hoistCopiesForSize() { 00732 // Get the complement interval, always RegIdx 0. 00733 LiveInterval *LI = Edit->get(0); 00734 LiveInterval *Parent = &Edit->getParent(); 00735 00736 // Track the nearest common dominator for all back-copies for each ParentVNI, 00737 // indexed by ParentVNI->id. 00738 typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair; 00739 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums()); 00740 00741 // Find the nearest common dominator for parent values with multiple 00742 // back-copies. If a single back-copy dominates, put it in DomPair.second. 00743 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end(); 00744 VI != VE; ++VI) { 00745 VNInfo *VNI = *VI; 00746 if (VNI->isUnused()) 00747 continue; 00748 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 00749 assert(ParentVNI && "Parent not live at complement def"); 00750 00751 // Don't hoist remats. The complement is probably going to disappear 00752 // completely anyway. 00753 if (Edit->didRematerialize(ParentVNI)) 00754 continue; 00755 00756 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def); 00757 DomPair &Dom = NearestDom[ParentVNI->id]; 00758 00759 // Keep directly defined parent values. This is either a PHI or an 00760 // instruction in the complement range. All other copies of ParentVNI 00761 // should be eliminated. 00762 if (VNI->def == ParentVNI->def) { 00763 DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n'); 00764 Dom = DomPair(ValMBB, VNI->def); 00765 continue; 00766 } 00767 // Skip the singly mapped values. There is nothing to gain from hoisting a 00768 // single back-copy. 00769 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) { 00770 DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n'); 00771 continue; 00772 } 00773 00774 if (!Dom.first) { 00775 // First time we see ParentVNI. VNI dominates itself. 00776 Dom = DomPair(ValMBB, VNI->def); 00777 } else if (Dom.first == ValMBB) { 00778 // Two defs in the same block. Pick the earlier def. 00779 if (!Dom.second.isValid() || VNI->def < Dom.second) 00780 Dom.second = VNI->def; 00781 } else { 00782 // Different basic blocks. Check if one dominates. 00783 MachineBasicBlock *Near = 00784 MDT.findNearestCommonDominator(Dom.first, ValMBB); 00785 if (Near == ValMBB) 00786 // Def ValMBB dominates. 00787 Dom = DomPair(ValMBB, VNI->def); 00788 else if (Near != Dom.first) 00789 // None dominate. Hoist to common dominator, need new def. 00790 Dom = DomPair(Near, SlotIndex()); 00791 } 00792 00793 DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def 00794 << " for parent " << ParentVNI->id << '@' << ParentVNI->def 00795 << " hoist to BB#" << Dom.first->getNumber() << ' ' 00796 << Dom.second << '\n'); 00797 } 00798 00799 // Insert the hoisted copies. 00800 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 00801 DomPair &Dom = NearestDom[i]; 00802 if (!Dom.first || Dom.second.isValid()) 00803 continue; 00804 // This value needs a hoisted copy inserted at the end of Dom.first. 00805 VNInfo *ParentVNI = Parent->getValNumInfo(i); 00806 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def); 00807 // Get a less loopy dominator than Dom.first. 00808 Dom.first = findShallowDominator(Dom.first, DefMBB); 00809 SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot(); 00810 Dom.second = 00811 defFromParent(0, ParentVNI, Last, *Dom.first, 00812 SA.getLastSplitPointIter(Dom.first))->def; 00813 } 00814 00815 // Remove redundant back-copies that are now known to be dominated by another 00816 // def with the same value. 00817 SmallVector<VNInfo*, 8> BackCopies; 00818 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end(); 00819 VI != VE; ++VI) { 00820 VNInfo *VNI = *VI; 00821 if (VNI->isUnused()) 00822 continue; 00823 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 00824 const DomPair &Dom = NearestDom[ParentVNI->id]; 00825 if (!Dom.first || Dom.second == VNI->def) 00826 continue; 00827 BackCopies.push_back(VNI); 00828 forceRecompute(0, ParentVNI); 00829 } 00830 removeBackCopies(BackCopies); 00831 } 00832 00833 00834 /// transferValues - Transfer all possible values to the new live ranges. 00835 /// Values that were rematerialized are left alone, they need LRCalc.extend(). 00836 bool SplitEditor::transferValues() { 00837 bool Skipped = false; 00838 RegAssignMap::const_iterator AssignI = RegAssign.begin(); 00839 for (LiveInterval::const_iterator ParentI = Edit->getParent().begin(), 00840 ParentE = Edit->getParent().end(); ParentI != ParentE; ++ParentI) { 00841 DEBUG(dbgs() << " blit " << *ParentI << ':'); 00842 VNInfo *ParentVNI = ParentI->valno; 00843 // RegAssign has holes where RegIdx 0 should be used. 00844 SlotIndex Start = ParentI->start; 00845 AssignI.advanceTo(Start); 00846 do { 00847 unsigned RegIdx; 00848 SlotIndex End = ParentI->end; 00849 if (!AssignI.valid()) { 00850 RegIdx = 0; 00851 } else if (AssignI.start() <= Start) { 00852 RegIdx = AssignI.value(); 00853 if (AssignI.stop() < End) { 00854 End = AssignI.stop(); 00855 ++AssignI; 00856 } 00857 } else { 00858 RegIdx = 0; 00859 End = std::min(End, AssignI.start()); 00860 } 00861 00862 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI. 00863 DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx); 00864 LiveInterval *LI = Edit->get(RegIdx); 00865 00866 // Check for a simply defined value that can be blitted directly. 00867 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id)); 00868 if (VNInfo *VNI = VFP.getPointer()) { 00869 DEBUG(dbgs() << ':' << VNI->id); 00870 LI->addRange(LiveRange(Start, End, VNI)); 00871 Start = End; 00872 continue; 00873 } 00874 00875 // Skip values with forced recomputation. 00876 if (VFP.getInt()) { 00877 DEBUG(dbgs() << "(recalc)"); 00878 Skipped = true; 00879 Start = End; 00880 continue; 00881 } 00882 00883 LiveRangeCalc &LRC = getLRCalc(RegIdx); 00884 00885 // This value has multiple defs in RegIdx, but it wasn't rematerialized, 00886 // so the live range is accurate. Add live-in blocks in [Start;End) to the 00887 // LiveInBlocks. 00888 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start); 00889 SlotIndex BlockStart, BlockEnd; 00890 tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB); 00891 00892 // The first block may be live-in, or it may have its own def. 00893 if (Start != BlockStart) { 00894 VNInfo *VNI = LI->extendInBlock(BlockStart, std::min(BlockEnd, End)); 00895 assert(VNI && "Missing def for complex mapped value"); 00896 DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber()); 00897 // MBB has its own def. Is it also live-out? 00898 if (BlockEnd <= End) 00899 LRC.setLiveOutValue(MBB, VNI); 00900 00901 // Skip to the next block for live-in. 00902 ++MBB; 00903 BlockStart = BlockEnd; 00904 } 00905 00906 // Handle the live-in blocks covered by [Start;End). 00907 assert(Start <= BlockStart && "Expected live-in block"); 00908 while (BlockStart < End) { 00909 DEBUG(dbgs() << ">BB#" << MBB->getNumber()); 00910 BlockEnd = LIS.getMBBEndIdx(MBB); 00911 if (BlockStart == ParentVNI->def) { 00912 // This block has the def of a parent PHI, so it isn't live-in. 00913 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?"); 00914 VNInfo *VNI = LI->extendInBlock(BlockStart, std::min(BlockEnd, End)); 00915 assert(VNI && "Missing def for complex mapped parent PHI"); 00916 if (End >= BlockEnd) 00917 LRC.setLiveOutValue(MBB, VNI); // Live-out as well. 00918 } else { 00919 // This block needs a live-in value. The last block covered may not 00920 // be live-out. 00921 if (End < BlockEnd) 00922 LRC.addLiveInBlock(LI, MDT[MBB], End); 00923 else { 00924 // Live-through, and we don't know the value. 00925 LRC.addLiveInBlock(LI, MDT[MBB]); 00926 LRC.setLiveOutValue(MBB, 0); 00927 } 00928 } 00929 BlockStart = BlockEnd; 00930 ++MBB; 00931 } 00932 Start = End; 00933 } while (Start != ParentI->end); 00934 DEBUG(dbgs() << '\n'); 00935 } 00936 00937 LRCalc[0].calculateValues(); 00938 if (SpillMode) 00939 LRCalc[1].calculateValues(); 00940 00941 return Skipped; 00942 } 00943 00944 void SplitEditor::extendPHIKillRanges() { 00945 // Extend live ranges to be live-out for successor PHI values. 00946 for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(), 00947 E = Edit->getParent().vni_end(); I != E; ++I) { 00948 const VNInfo *PHIVNI = *I; 00949 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef()) 00950 continue; 00951 unsigned RegIdx = RegAssign.lookup(PHIVNI->def); 00952 LiveInterval *LI = Edit->get(RegIdx); 00953 LiveRangeCalc &LRC = getLRCalc(RegIdx); 00954 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def); 00955 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 00956 PE = MBB->pred_end(); PI != PE; ++PI) { 00957 SlotIndex End = LIS.getMBBEndIdx(*PI); 00958 SlotIndex LastUse = End.getPrevSlot(); 00959 // The predecessor may not have a live-out value. That is OK, like an 00960 // undef PHI operand. 00961 if (Edit->getParent().liveAt(LastUse)) { 00962 assert(RegAssign.lookup(LastUse) == RegIdx && 00963 "Different register assignment in phi predecessor"); 00964 LRC.extend(LI, End); 00965 } 00966 } 00967 } 00968 } 00969 00970 /// rewriteAssigned - Rewrite all uses of Edit->getReg(). 00971 void SplitEditor::rewriteAssigned(bool ExtendRanges) { 00972 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()), 00973 RE = MRI.reg_end(); RI != RE;) { 00974 MachineOperand &MO = RI.getOperand(); 00975 MachineInstr *MI = MO.getParent(); 00976 ++RI; 00977 // LiveDebugVariables should have handled all DBG_VALUE instructions. 00978 if (MI->isDebugValue()) { 00979 DEBUG(dbgs() << "Zapping " << *MI); 00980 MO.setReg(0); 00981 continue; 00982 } 00983 00984 // <undef> operands don't really read the register, so it doesn't matter 00985 // which register we choose. When the use operand is tied to a def, we must 00986 // use the same register as the def, so just do that always. 00987 SlotIndex Idx = LIS.getInstructionIndex(MI); 00988 if (MO.isDef() || MO.isUndef()) 00989 Idx = Idx.getRegSlot(MO.isEarlyClobber()); 00990 00991 // Rewrite to the mapped register at Idx. 00992 unsigned RegIdx = RegAssign.lookup(Idx); 00993 LiveInterval *LI = Edit->get(RegIdx); 00994 MO.setReg(LI->reg); 00995 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t' 00996 << Idx << ':' << RegIdx << '\t' << *MI); 00997 00998 // Extend liveness to Idx if the instruction reads reg. 00999 if (!ExtendRanges || MO.isUndef()) 01000 continue; 01001 01002 // Skip instructions that don't read Reg. 01003 if (MO.isDef()) { 01004 if (!MO.getSubReg() && !MO.isEarlyClobber()) 01005 continue; 01006 // We may wan't to extend a live range for a partial redef, or for a use 01007 // tied to an early clobber. 01008 Idx = Idx.getPrevSlot(); 01009 if (!Edit->getParent().liveAt(Idx)) 01010 continue; 01011 } else 01012 Idx = Idx.getRegSlot(true); 01013 01014 getLRCalc(RegIdx).extend(LI, Idx.getNextSlot()); 01015 } 01016 } 01017 01018 void SplitEditor::deleteRematVictims() { 01019 SmallVector<MachineInstr*, 8> Dead; 01020 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){ 01021 LiveInterval *LI = *I; 01022 for (LiveInterval::const_iterator LII = LI->begin(), LIE = LI->end(); 01023 LII != LIE; ++LII) { 01024 // Dead defs end at the dead slot. 01025 if (LII->end != LII->valno->def.getDeadSlot()) 01026 continue; 01027 MachineInstr *MI = LIS.getInstructionFromIndex(LII->valno->def); 01028 assert(MI && "Missing instruction for dead def"); 01029 MI->addRegisterDead(LI->reg, &TRI); 01030 01031 if (!MI->allDefsAreDead()) 01032 continue; 01033 01034 DEBUG(dbgs() << "All defs dead: " << *MI); 01035 Dead.push_back(MI); 01036 } 01037 } 01038 01039 if (Dead.empty()) 01040 return; 01041 01042 Edit->eliminateDeadDefs(Dead); 01043 } 01044 01045 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) { 01046 ++NumFinished; 01047 01048 // At this point, the live intervals in Edit contain VNInfos corresponding to 01049 // the inserted copies. 01050 01051 // Add the original defs from the parent interval. 01052 for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(), 01053 E = Edit->getParent().vni_end(); I != E; ++I) { 01054 const VNInfo *ParentVNI = *I; 01055 if (ParentVNI->isUnused()) 01056 continue; 01057 unsigned RegIdx = RegAssign.lookup(ParentVNI->def); 01058 defValue(RegIdx, ParentVNI, ParentVNI->def); 01059 01060 // Force rematted values to be recomputed everywhere. 01061 // The new live ranges may be truncated. 01062 if (Edit->didRematerialize(ParentVNI)) 01063 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 01064 forceRecompute(i, ParentVNI); 01065 } 01066 01067 // Hoist back-copies to the complement interval when in spill mode. 01068 switch (SpillMode) { 01069 case SM_Partition: 01070 // Leave all back-copies as is. 01071 break; 01072 case SM_Size: 01073 hoistCopiesForSize(); 01074 break; 01075 case SM_Speed: 01076 llvm_unreachable("Spill mode 'speed' not implemented yet"); 01077 } 01078 01079 // Transfer the simply mapped values, check if any are skipped. 01080 bool Skipped = transferValues(); 01081 if (Skipped) 01082 extendPHIKillRanges(); 01083 else 01084 ++NumSimple; 01085 01086 // Rewrite virtual registers, possibly extending ranges. 01087 rewriteAssigned(Skipped); 01088 01089 // Delete defs that were rematted everywhere. 01090 if (Skipped) 01091 deleteRematVictims(); 01092 01093 // Get rid of unused values and set phi-kill flags. 01094 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) 01095 (*I)->RenumberValues(LIS); 01096 01097 // Provide a reverse mapping from original indices to Edit ranges. 01098 if (LRMap) { 01099 LRMap->clear(); 01100 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 01101 LRMap->push_back(i); 01102 } 01103 01104 // Now check if any registers were separated into multiple components. 01105 ConnectedVNInfoEqClasses ConEQ(LIS); 01106 for (unsigned i = 0, e = Edit->size(); i != e; ++i) { 01107 // Don't use iterators, they are invalidated by create() below. 01108 LiveInterval *li = Edit->get(i); 01109 unsigned NumComp = ConEQ.Classify(li); 01110 if (NumComp <= 1) 01111 continue; 01112 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n'); 01113 SmallVector<LiveInterval*, 8> dups; 01114 dups.push_back(li); 01115 for (unsigned j = 1; j != NumComp; ++j) 01116 dups.push_back(&Edit->create()); 01117 ConEQ.Distribute(&dups[0], MRI); 01118 // The new intervals all map back to i. 01119 if (LRMap) 01120 LRMap->resize(Edit->size(), i); 01121 } 01122 01123 // Calculate spill weight and allocation hints for new intervals. 01124 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI); 01125 01126 assert(!LRMap || LRMap->size() == Edit->size()); 01127 } 01128 01129 01130 //===----------------------------------------------------------------------===// 01131 // Single Block Splitting 01132 //===----------------------------------------------------------------------===// 01133 01134 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI, 01135 bool SingleInstrs) const { 01136 // Always split for multiple instructions. 01137 if (!BI.isOneInstr()) 01138 return true; 01139 // Don't split for single instructions unless explicitly requested. 01140 if (!SingleInstrs) 01141 return false; 01142 // Splitting a live-through range always makes progress. 01143 if (BI.LiveIn && BI.LiveOut) 01144 return true; 01145 // No point in isolating a copy. It has no register class constraints. 01146 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike()) 01147 return false; 01148 // Finally, don't isolate an end point that was created by earlier splits. 01149 return isOriginalEndpoint(BI.FirstInstr); 01150 } 01151 01152 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) { 01153 openIntv(); 01154 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber()); 01155 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr, 01156 LastSplitPoint)); 01157 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) { 01158 useIntv(SegStart, leaveIntvAfter(BI.LastInstr)); 01159 } else { 01160 // The last use is after the last valid split point. 01161 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint); 01162 useIntv(SegStart, SegStop); 01163 overlapIntv(SegStop, BI.LastInstr); 01164 } 01165 } 01166 01167 01168 //===----------------------------------------------------------------------===// 01169 // Global Live Range Splitting Support 01170 //===----------------------------------------------------------------------===// 01171 01172 // These methods support a method of global live range splitting that uses a 01173 // global algorithm to decide intervals for CFG edges. They will insert split 01174 // points and color intervals in basic blocks while avoiding interference. 01175 // 01176 // Note that splitSingleBlock is also useful for blocks where both CFG edges 01177 // are on the stack. 01178 01179 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum, 01180 unsigned IntvIn, SlotIndex LeaveBefore, 01181 unsigned IntvOut, SlotIndex EnterAfter){ 01182 SlotIndex Start, Stop; 01183 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum); 01184 01185 DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop 01186 << ") intf " << LeaveBefore << '-' << EnterAfter 01187 << ", live-through " << IntvIn << " -> " << IntvOut); 01188 01189 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks"); 01190 01191 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block"); 01192 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf"); 01193 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block"); 01194 01195 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum); 01196 01197 if (!IntvOut) { 01198 DEBUG(dbgs() << ", spill on entry.\n"); 01199 // 01200 // <<<<<<<<< Possible LeaveBefore interference. 01201 // |-----------| Live through. 01202 // -____________ Spill on entry. 01203 // 01204 selectIntv(IntvIn); 01205 SlotIndex Idx = leaveIntvAtTop(*MBB); 01206 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 01207 (void)Idx; 01208 return; 01209 } 01210 01211 if (!IntvIn) { 01212 DEBUG(dbgs() << ", reload on exit.\n"); 01213 // 01214 // >>>>>>> Possible EnterAfter interference. 01215 // |-----------| Live through. 01216 // ___________-- Reload on exit. 01217 // 01218 selectIntv(IntvOut); 01219 SlotIndex Idx = enterIntvAtEnd(*MBB); 01220 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 01221 (void)Idx; 01222 return; 01223 } 01224 01225 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) { 01226 DEBUG(dbgs() << ", straight through.\n"); 01227 // 01228 // |-----------| Live through. 01229 // ------------- Straight through, same intv, no interference. 01230 // 01231 selectIntv(IntvOut); 01232 useIntv(Start, Stop); 01233 return; 01234 } 01235 01236 // We cannot legally insert splits after LSP. 01237 SlotIndex LSP = SA.getLastSplitPoint(MBBNum); 01238 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf"); 01239 01240 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter || 01241 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) { 01242 DEBUG(dbgs() << ", switch avoiding interference.\n"); 01243 // 01244 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference. 01245 // |-----------| Live through. 01246 // ------======= Switch intervals between interference. 01247 // 01248 selectIntv(IntvOut); 01249 SlotIndex Idx; 01250 if (LeaveBefore && LeaveBefore < LSP) { 01251 Idx = enterIntvBefore(LeaveBefore); 01252 useIntv(Idx, Stop); 01253 } else { 01254 Idx = enterIntvAtEnd(*MBB); 01255 } 01256 selectIntv(IntvIn); 01257 useIntv(Start, Idx); 01258 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 01259 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 01260 return; 01261 } 01262 01263 DEBUG(dbgs() << ", create local intv for interference.\n"); 01264 // 01265 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference. 01266 // |-----------| Live through. 01267 // ==---------== Switch intervals before/after interference. 01268 // 01269 assert(LeaveBefore <= EnterAfter && "Missed case"); 01270 01271 selectIntv(IntvOut); 01272 SlotIndex Idx = enterIntvAfter(EnterAfter); 01273 useIntv(Idx, Stop); 01274 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 01275 01276 selectIntv(IntvIn); 01277 Idx = leaveIntvBefore(LeaveBefore); 01278 useIntv(Start, Idx); 01279 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 01280 } 01281 01282 01283 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI, 01284 unsigned IntvIn, SlotIndex LeaveBefore) { 01285 SlotIndex Start, Stop; 01286 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 01287 01288 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop 01289 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr 01290 << ", reg-in " << IntvIn << ", leave before " << LeaveBefore 01291 << (BI.LiveOut ? ", stack-out" : ", killed in block")); 01292 01293 assert(IntvIn && "Must have register in"); 01294 assert(BI.LiveIn && "Must be live-in"); 01295 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference"); 01296 01297 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) { 01298 DEBUG(dbgs() << " before interference.\n"); 01299 // 01300 // <<< Interference after kill. 01301 // |---o---x | Killed in block. 01302 // ========= Use IntvIn everywhere. 01303 // 01304 selectIntv(IntvIn); 01305 useIntv(Start, BI.LastInstr); 01306 return; 01307 } 01308 01309 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 01310 01311 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) { 01312 // 01313 // <<< Possible interference after last use. 01314 // |---o---o---| Live-out on stack. 01315 // =========____ Leave IntvIn after last use. 01316 // 01317 // < Interference after last use. 01318 // |---o---o--o| Live-out on stack, late last use. 01319 // ============ Copy to stack after LSP, overlap IntvIn. 01320 // \_____ Stack interval is live-out. 01321 // 01322 if (BI.LastInstr < LSP) { 01323 DEBUG(dbgs() << ", spill after last use before interference.\n"); 01324 selectIntv(IntvIn); 01325 SlotIndex Idx = leaveIntvAfter(BI.LastInstr); 01326 useIntv(Start, Idx); 01327 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 01328 } else { 01329 DEBUG(dbgs() << ", spill before last split point.\n"); 01330 selectIntv(IntvIn); 01331 SlotIndex Idx = leaveIntvBefore(LSP); 01332 overlapIntv(Idx, BI.LastInstr); 01333 useIntv(Start, Idx); 01334 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 01335 } 01336 return; 01337 } 01338 01339 // The interference is overlapping somewhere we wanted to use IntvIn. That 01340 // means we need to create a local interval that can be allocated a 01341 // different register. 01342 unsigned LocalIntv = openIntv(); 01343 (void)LocalIntv; 01344 DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n"); 01345 01346 if (!BI.LiveOut || BI.LastInstr < LSP) { 01347 // 01348 // <<<<<<< Interference overlapping uses. 01349 // |---o---o---| Live-out on stack. 01350 // =====----____ Leave IntvIn before interference, then spill. 01351 // 01352 SlotIndex To = leaveIntvAfter(BI.LastInstr); 01353 SlotIndex From = enterIntvBefore(LeaveBefore); 01354 useIntv(From, To); 01355 selectIntv(IntvIn); 01356 useIntv(Start, From); 01357 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 01358 return; 01359 } 01360 01361 // <<<<<<< Interference overlapping uses. 01362 // |---o---o--o| Live-out on stack, late last use. 01363 // =====------- Copy to stack before LSP, overlap LocalIntv. 01364 // \_____ Stack interval is live-out. 01365 // 01366 SlotIndex To = leaveIntvBefore(LSP); 01367 overlapIntv(To, BI.LastInstr); 01368 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore)); 01369 useIntv(From, To); 01370 selectIntv(IntvIn); 01371 useIntv(Start, From); 01372 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 01373 } 01374 01375 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI, 01376 unsigned IntvOut, SlotIndex EnterAfter) { 01377 SlotIndex Start, Stop; 01378 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 01379 01380 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop 01381 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr 01382 << ", reg-out " << IntvOut << ", enter after " << EnterAfter 01383 << (BI.LiveIn ? ", stack-in" : ", defined in block")); 01384 01385 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 01386 01387 assert(IntvOut && "Must have register out"); 01388 assert(BI.LiveOut && "Must be live-out"); 01389 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference"); 01390 01391 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) { 01392 DEBUG(dbgs() << " after interference.\n"); 01393 // 01394 // >>>> Interference before def. 01395 // | o---o---| Defined in block. 01396 // ========= Use IntvOut everywhere. 01397 // 01398 selectIntv(IntvOut); 01399 useIntv(BI.FirstInstr, Stop); 01400 return; 01401 } 01402 01403 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) { 01404 DEBUG(dbgs() << ", reload after interference.\n"); 01405 // 01406 // >>>> Interference before def. 01407 // |---o---o---| Live-through, stack-in. 01408 // ____========= Enter IntvOut before first use. 01409 // 01410 selectIntv(IntvOut); 01411 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr)); 01412 useIntv(Idx, Stop); 01413 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 01414 return; 01415 } 01416 01417 // The interference is overlapping somewhere we wanted to use IntvOut. That 01418 // means we need to create a local interval that can be allocated a 01419 // different register. 01420 DEBUG(dbgs() << ", interference overlaps uses.\n"); 01421 // 01422 // >>>>>>> Interference overlapping uses. 01423 // |---o---o---| Live-through, stack-in. 01424 // ____---====== Create local interval for interference range. 01425 // 01426 selectIntv(IntvOut); 01427 SlotIndex Idx = enterIntvAfter(EnterAfter); 01428 useIntv(Idx, Stop); 01429 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 01430 01431 openIntv(); 01432 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr)); 01433 useIntv(From, Idx); 01434 }