LiveIntervalAnalysis.cpp revision e8850f476eba1b839b24bd926bab2dfd8b452307
1//===-- LiveIntervals.cpp - Live Interval Analysis ------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the LiveInterval analysis pass which is used 11// by the Linear Scan Register allocator. This pass linearizes the 12// basic blocks of the function in DFS order and uses the 13// LiveVariables pass to conservatively compute live intervals for 14// each virtual and physical register. 15// 16//===----------------------------------------------------------------------===// 17 18#define DEBUG_TYPE "liveintervals" 19#include "LiveIntervals.h" 20#include "llvm/Value.h" 21#include "llvm/Analysis/LoopInfo.h" 22#include "llvm/CodeGen/LiveVariables.h" 23#include "llvm/CodeGen/MachineFrameInfo.h" 24#include "llvm/CodeGen/MachineInstr.h" 25#include "llvm/CodeGen/Passes.h" 26#include "llvm/CodeGen/SSARegMap.h" 27#include "llvm/Target/MRegisterInfo.h" 28#include "llvm/Target/TargetInstrInfo.h" 29#include "llvm/Target/TargetMachine.h" 30#include "Support/CommandLine.h" 31#include "Support/Debug.h" 32#include "Support/Statistic.h" 33#include "Support/STLExtras.h" 34#include "VirtRegMap.h" 35#include <cmath> 36 37using namespace llvm; 38 39namespace { 40 RegisterAnalysis<LiveIntervals> X("liveintervals", 41 "Live Interval Analysis"); 42 43 Statistic<> numIntervals 44 ("liveintervals", "Number of original intervals"); 45 46 Statistic<> numIntervalsAfter 47 ("liveintervals", "Number of intervals after coalescing"); 48 49 Statistic<> numJoins 50 ("liveintervals", "Number of interval joins performed"); 51 52 Statistic<> numPeep 53 ("liveintervals", "Number of identity moves eliminated after coalescing"); 54 55 Statistic<> numFolded 56 ("liveintervals", "Number of loads/stores folded into instructions"); 57 58 cl::opt<bool> 59 EnableJoining("join-liveintervals", 60 cl::desc("Join compatible live intervals"), 61 cl::init(true)); 62}; 63 64void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const 65{ 66 AU.addPreserved<LiveVariables>(); 67 AU.addRequired<LiveVariables>(); 68 AU.addPreservedID(PHIEliminationID); 69 AU.addRequiredID(PHIEliminationID); 70 AU.addRequiredID(TwoAddressInstructionPassID); 71 AU.addRequired<LoopInfo>(); 72 MachineFunctionPass::getAnalysisUsage(AU); 73} 74 75void LiveIntervals::releaseMemory() 76{ 77 mi2iMap_.clear(); 78 i2miMap_.clear(); 79 r2iMap_.clear(); 80 r2rMap_.clear(); 81 intervals_.clear(); 82} 83 84 85/// runOnMachineFunction - Register allocate the whole function 86/// 87bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) { 88 mf_ = &fn; 89 tm_ = &fn.getTarget(); 90 mri_ = tm_->getRegisterInfo(); 91 lv_ = &getAnalysis<LiveVariables>(); 92 93 // number MachineInstrs 94 unsigned miIndex = 0; 95 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end(); 96 mbb != mbbEnd; ++mbb) 97 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end(); 98 mi != miEnd; ++mi) { 99 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second; 100 assert(inserted && "multiple MachineInstr -> index mappings"); 101 i2miMap_.push_back(mi); 102 miIndex += InstrSlots::NUM; 103 } 104 105 computeIntervals(); 106 107 numIntervals += intervals_.size(); 108 109 // join intervals if requested 110 if (EnableJoining) joinIntervals(); 111 112 numIntervalsAfter += intervals_.size(); 113 114 // perform a final pass over the instructions and compute spill 115 // weights, coalesce virtual registers and remove identity moves 116 const LoopInfo& loopInfo = getAnalysis<LoopInfo>(); 117 const TargetInstrInfo& tii = *tm_->getInstrInfo(); 118 119 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end(); 120 mbbi != mbbe; ++mbbi) { 121 MachineBasicBlock* mbb = mbbi; 122 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock()); 123 124 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end(); 125 mii != mie; ) { 126 // if the move will be an identity move delete it 127 unsigned srcReg, dstReg; 128 if (tii.isMoveInstr(*mii, srcReg, dstReg) && 129 rep(srcReg) == rep(dstReg)) { 130 // remove from def list 131 LiveInterval& interval = getOrCreateInterval(rep(dstReg)); 132 // remove index -> MachineInstr and 133 // MachineInstr -> index mappings 134 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii); 135 if (mi2i != mi2iMap_.end()) { 136 i2miMap_[mi2i->second/InstrSlots::NUM] = 0; 137 mi2iMap_.erase(mi2i); 138 } 139 mii = mbbi->erase(mii); 140 ++numPeep; 141 } 142 else { 143 for (unsigned i = 0; i < mii->getNumOperands(); ++i) { 144 const MachineOperand& mop = mii->getOperand(i); 145 if (mop.isRegister() && mop.getReg() && 146 MRegisterInfo::isVirtualRegister(mop.getReg())) { 147 // replace register with representative register 148 unsigned reg = rep(mop.getReg()); 149 mii->SetMachineOperandReg(i, reg); 150 151 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg); 152 assert(r2iit != r2iMap_.end()); 153 r2iit->second->weight += 154 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth); 155 } 156 } 157 ++mii; 158 } 159 } 160 } 161 162 DEBUG(std::cerr << "********** INTERVALS **********\n"); 163 DEBUG(std::copy(intervals_.begin(), intervals_.end(), 164 std::ostream_iterator<LiveInterval>(std::cerr, "\n"))); 165 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n"); 166 DEBUG( 167 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end(); 168 mbbi != mbbe; ++mbbi) { 169 std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n"; 170 for (MachineBasicBlock::iterator mii = mbbi->begin(), 171 mie = mbbi->end(); mii != mie; ++mii) { 172 std::cerr << getInstructionIndex(mii) << '\t'; 173 mii->print(std::cerr, tm_); 174 } 175 }); 176 177 return true; 178} 179 180std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills( 181 const LiveInterval& li, 182 VirtRegMap& vrm, 183 int slot) 184{ 185 std::vector<LiveInterval*> added; 186 187 assert(li.weight != HUGE_VAL && 188 "attempt to spill already spilled interval!"); 189 190 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: " 191 << li << '\n'); 192 193 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg); 194 195 for (LiveInterval::Ranges::const_iterator 196 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) { 197 unsigned index = getBaseIndex(i->first); 198 unsigned end = getBaseIndex(i->second-1) + InstrSlots::NUM; 199 for (; index != end; index += InstrSlots::NUM) { 200 // skip deleted instructions 201 while (index != end && !getInstructionFromIndex(index)) 202 index += InstrSlots::NUM; 203 if (index == end) break; 204 205 MachineBasicBlock::iterator mi = getInstructionFromIndex(index); 206 207 for_operand: 208 for (unsigned i = 0; i != mi->getNumOperands(); ++i) { 209 MachineOperand& mop = mi->getOperand(i); 210 if (mop.isRegister() && mop.getReg() == li.reg) { 211 if (MachineInstr* fmi = 212 mri_->foldMemoryOperand(mi, i, slot)) { 213 lv_->instructionChanged(mi, fmi); 214 vrm.virtFolded(li.reg, mi, fmi); 215 mi2iMap_.erase(mi); 216 i2miMap_[index/InstrSlots::NUM] = fmi; 217 mi2iMap_[fmi] = index; 218 MachineBasicBlock& mbb = *mi->getParent(); 219 mi = mbb.insert(mbb.erase(mi), fmi); 220 ++numFolded; 221 goto for_operand; 222 } 223 else { 224 // This is tricky. We need to add information in 225 // the interval about the spill code so we have to 226 // use our extra load/store slots. 227 // 228 // If we have a use we are going to have a load so 229 // we start the interval from the load slot 230 // onwards. Otherwise we start from the def slot. 231 unsigned start = (mop.isUse() ? 232 getLoadIndex(index) : 233 getDefIndex(index)); 234 // If we have a def we are going to have a store 235 // right after it so we end the interval after the 236 // use of the next instruction. Otherwise we end 237 // after the use of this instruction. 238 unsigned end = 1 + (mop.isDef() ? 239 getStoreIndex(index) : 240 getUseIndex(index)); 241 242 // create a new register for this spill 243 unsigned nReg = 244 mf_->getSSARegMap()->createVirtualRegister(rc); 245 mi->SetMachineOperandReg(i, nReg); 246 vrm.grow(); 247 vrm.assignVirt2StackSlot(nReg, slot); 248 LiveInterval& nI = getOrCreateInterval(nReg); 249 assert(nI.empty()); 250 // the spill weight is now infinity as it 251 // cannot be spilled again 252 nI.weight = HUGE_VAL; 253 nI.addRange(start, end); 254 added.push_back(&nI); 255 // update live variables 256 lv_->addVirtualRegisterKilled(nReg, mi); 257 DEBUG(std::cerr << "\t\t\t\tadded new interval: " 258 << nI << '\n'); 259 } 260 } 261 } 262 } 263 } 264 265 return added; 266} 267 268void LiveIntervals::printRegName(unsigned reg) const 269{ 270 if (MRegisterInfo::isPhysicalRegister(reg)) 271 std::cerr << mri_->getName(reg); 272 else 273 std::cerr << "%reg" << reg; 274} 275 276void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb, 277 MachineBasicBlock::iterator mi, 278 LiveInterval& interval) 279{ 280 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg)); 281 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg); 282 283 // Virtual registers may be defined multiple times (due to phi 284 // elimination and 2-addr elimination). Much of what we do only has to be 285 // done once for the vreg. We use an empty interval to detect the first 286 // time we see a vreg. 287 if (interval.empty()) { 288 // Get the Idx of the defining instructions. 289 unsigned defIndex = getDefIndex(getInstructionIndex(mi)); 290 291 // Loop over all of the blocks that the vreg is defined in. There are 292 // two cases we have to handle here. The most common case is a vreg 293 // whose lifetime is contained within a basic block. In this case there 294 // will be a single kill, in MBB, which comes after the definition. 295 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) { 296 // FIXME: what about dead vars? 297 unsigned killIdx; 298 if (vi.Kills[0] != mi) 299 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1; 300 else 301 killIdx = defIndex+1; 302 303 // If the kill happens after the definition, we have an intra-block 304 // live range. 305 if (killIdx > defIndex) { 306 assert(vi.AliveBlocks.empty() && 307 "Shouldn't be alive across any blocks!"); 308 interval.addRange(defIndex, killIdx); 309 DEBUG(std::cerr << "\n"); 310 return; 311 } 312 } 313 314 // The other case we handle is when a virtual register lives to the end 315 // of the defining block, potentially live across some blocks, then is 316 // live into some number of blocks, but gets killed. Start by adding a 317 // range that goes from this definition to the end of the defining block. 318 interval.addRange(defIndex, 319 getInstructionIndex(&mbb->back()) + InstrSlots::NUM); 320 321 // Iterate over all of the blocks that the variable is completely 322 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the 323 // live interval. 324 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) { 325 if (vi.AliveBlocks[i]) { 326 MachineBasicBlock* mbb = mf_->getBlockNumbered(i); 327 if (!mbb->empty()) { 328 interval.addRange( 329 getInstructionIndex(&mbb->front()), 330 getInstructionIndex(&mbb->back()) + InstrSlots::NUM); 331 } 332 } 333 } 334 335 // Finally, this virtual register is live from the start of any killing 336 // block to the 'use' slot of the killing instruction. 337 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) { 338 MachineInstr *Kill = vi.Kills[i]; 339 interval.addRange(getInstructionIndex(Kill->getParent()->begin()), 340 getUseIndex(getInstructionIndex(Kill))+1); 341 } 342 343 } else { 344 // If this is the second time we see a virtual register definition, it 345 // must be due to phi elimination or two addr elimination. If this is 346 // the result of two address elimination, then the vreg is the first 347 // operand, and is a def-and-use. 348 if (mi->getOperand(0).isRegister() && 349 mi->getOperand(0).getReg() == interval.reg && 350 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) { 351 // If this is a two-address definition, just ignore it. 352 } else { 353 // Otherwise, this must be because of phi elimination. In this case, 354 // the defined value will be live until the end of the basic block it 355 // is defined in. 356 unsigned defIndex = getDefIndex(getInstructionIndex(mi)); 357 interval.addRange(defIndex, 358 getInstructionIndex(&mbb->back()) + InstrSlots::NUM); 359 } 360 } 361 362 DEBUG(std::cerr << '\n'); 363} 364 365void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb, 366 MachineBasicBlock::iterator mi, 367 LiveInterval& interval) 368{ 369 // A physical register cannot be live across basic block, so its 370 // lifetime must end somewhere in its defining basic block. 371 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg)); 372 typedef LiveVariables::killed_iterator KillIter; 373 374 MachineBasicBlock::iterator e = mbb->end(); 375 unsigned baseIndex = getInstructionIndex(mi); 376 unsigned start = getDefIndex(baseIndex); 377 unsigned end = start; 378 379 // If it is not used after definition, it is considered dead at 380 // the instruction defining it. Hence its interval is: 381 // [defSlot(def), defSlot(def)+1) 382 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi); 383 ki != ke; ++ki) { 384 if (interval.reg == ki->second) { 385 DEBUG(std::cerr << " dead"); 386 end = getDefIndex(start) + 1; 387 goto exit; 388 } 389 } 390 391 // If it is not dead on definition, it must be killed by a 392 // subsequent instruction. Hence its interval is: 393 // [defSlot(def), useSlot(kill)+1) 394 do { 395 ++mi; 396 baseIndex += InstrSlots::NUM; 397 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi); 398 ki != ke; ++ki) { 399 if (interval.reg == ki->second) { 400 DEBUG(std::cerr << " killed"); 401 end = getUseIndex(baseIndex) + 1; 402 goto exit; 403 } 404 } 405 } while (mi != e); 406 407exit: 408 assert(start < end && "did not find end of interval?"); 409 interval.addRange(start, end); 410 DEBUG(std::cerr << '\n'); 411} 412 413void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb, 414 MachineBasicBlock::iterator mi, 415 unsigned reg) 416{ 417 if (MRegisterInfo::isPhysicalRegister(reg)) { 418 if (lv_->getAllocatablePhysicalRegisters()[reg]) { 419 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg)); 420 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) 421 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as)); 422 } 423 } 424 else 425 handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg)); 426} 427 428unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const 429{ 430 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr); 431 return (it == mi2iMap_.end() ? 432 std::numeric_limits<unsigned>::max() : 433 it->second); 434} 435 436MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const 437{ 438 index /= InstrSlots::NUM; // convert index to vector index 439 assert(index < i2miMap_.size() && 440 "index does not correspond to an instruction"); 441 return i2miMap_[index]; 442} 443 444/// computeIntervals - computes the live intervals for virtual 445/// registers. for some ordering of the machine instructions [1,N] a 446/// live interval is an interval [i, j) where 1 <= i <= j < N for 447/// which a variable is live 448void LiveIntervals::computeIntervals() 449{ 450 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n"); 451 DEBUG(std::cerr << "********** Function: " 452 << ((Value*)mf_->getFunction())->getName() << '\n'); 453 454 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); 455 I != E; ++I) { 456 MachineBasicBlock* mbb = I; 457 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n"); 458 459 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end(); 460 mi != miEnd; ++mi) { 461 const TargetInstrDescriptor& tid = 462 tm_->getInstrInfo()->get(mi->getOpcode()); 463 DEBUG(std::cerr << getInstructionIndex(mi) << "\t"; 464 mi->print(std::cerr, tm_)); 465 466 // handle implicit defs 467 for (const unsigned* id = tid.ImplicitDefs; *id; ++id) 468 handleRegisterDef(mbb, mi, *id); 469 470 // handle explicit defs 471 for (int i = mi->getNumOperands() - 1; i >= 0; --i) { 472 MachineOperand& mop = mi->getOperand(i); 473 // handle register defs - build intervals 474 if (mop.isRegister() && mop.getReg() && mop.isDef()) 475 handleRegisterDef(mbb, mi, mop.getReg()); 476 } 477 } 478 } 479} 480 481unsigned LiveIntervals::rep(unsigned reg) 482{ 483 Reg2RegMap::iterator it = r2rMap_.find(reg); 484 if (it != r2rMap_.end()) 485 return it->second = rep(it->second); 486 return reg; 487} 488 489void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) { 490 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n"); 491 const TargetInstrInfo& tii = *tm_->getInstrInfo(); 492 493 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end(); 494 mi != mie; ++mi) { 495 const TargetInstrDescriptor& tid = tii.get(mi->getOpcode()); 496 DEBUG(std::cerr << getInstructionIndex(mi) << '\t'; 497 mi->print(std::cerr, tm_);); 498 499 // we only join virtual registers with allocatable 500 // physical registers since we do not have liveness information 501 // on not allocatable physical registers 502 unsigned regA, regB; 503 if (tii.isMoveInstr(*mi, regA, regB) && 504 (MRegisterInfo::isVirtualRegister(regA) || 505 lv_->getAllocatablePhysicalRegisters()[regA]) && 506 (MRegisterInfo::isVirtualRegister(regB) || 507 lv_->getAllocatablePhysicalRegisters()[regB])) { 508 509 // get representative registers 510 regA = rep(regA); 511 regB = rep(regB); 512 513 // if they are already joined we continue 514 if (regA == regB) 515 continue; 516 517 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA); 518 assert(r2iA != r2iMap_.end() && 519 "Found unknown vreg in 'isMoveInstr' instruction"); 520 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB); 521 assert(r2iB != r2iMap_.end() && 522 "Found unknown vreg in 'isMoveInstr' instruction"); 523 524 Intervals::iterator intA = r2iA->second; 525 Intervals::iterator intB = r2iB->second; 526 527 // both A and B are virtual registers 528 if (MRegisterInfo::isVirtualRegister(intA->reg) && 529 MRegisterInfo::isVirtualRegister(intB->reg)) { 530 531 const TargetRegisterClass *rcA, *rcB; 532 rcA = mf_->getSSARegMap()->getRegClass(intA->reg); 533 rcB = mf_->getSSARegMap()->getRegClass(intB->reg); 534 // if they are not of the same register class we continue 535 if (rcA != rcB) 536 continue; 537 538 // if their intervals do not overlap we join them 539 if (!intB->overlaps(*intA)) { 540 intA->join(*intB); 541 r2iB->second = r2iA->second; 542 r2rMap_.insert(std::make_pair(intB->reg, intA->reg)); 543 intervals_.erase(intB); 544 } 545 } else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^ 546 MRegisterInfo::isPhysicalRegister(intB->reg)) { 547 if (MRegisterInfo::isPhysicalRegister(intB->reg)) { 548 std::swap(regA, regB); 549 std::swap(intA, intB); 550 std::swap(r2iA, r2iB); 551 } 552 553 assert(MRegisterInfo::isPhysicalRegister(intA->reg) && 554 MRegisterInfo::isVirtualRegister(intB->reg) && 555 "A must be physical and B must be virtual"); 556 557 const TargetRegisterClass *rcA, *rcB; 558 rcA = mri_->getRegClass(intA->reg); 559 rcB = mf_->getSSARegMap()->getRegClass(intB->reg); 560 // if they are not of the same register class we continue 561 if (rcA != rcB) 562 continue; 563 564 if (!intA->overlaps(*intB) && 565 !overlapsAliases(*intA, *intB)) { 566 intA->join(*intB); 567 r2iB->second = r2iA->second; 568 r2rMap_.insert(std::make_pair(intB->reg, intA->reg)); 569 intervals_.erase(intB); 570 } 571 } 572 } 573 } 574} 575 576namespace { 577 // DepthMBBCompare - Comparison predicate that sort first based on the loop 578 // depth of the basic block (the unsigned), and then on the MBB number. 579 struct DepthMBBCompare { 580 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair; 581 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const { 582 if (LHS.first > RHS.first) return true; // Deeper loops first 583 return LHS.first == RHS.first && 584 LHS.second->getNumber() < RHS.second->getNumber(); 585 } 586 }; 587} 588 589void LiveIntervals::joinIntervals() { 590 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n"); 591 592 const LoopInfo &LI = getAnalysis<LoopInfo>(); 593 if (LI.begin() == LI.end()) { 594 // If there are no loops in the function, join intervals in function order. 595 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); 596 I != E; ++I) 597 joinIntervalsInMachineBB(I); 598 } else { 599 // Otherwise, join intervals in inner loops before other intervals. 600 // Unfortunately we can't just iterate over loop hierarchy here because 601 // there may be more MBB's than BB's. Collect MBB's for sorting. 602 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs; 603 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); 604 I != E; ++I) 605 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I)); 606 607 // Sort by loop depth. 608 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare()); 609 610 // Finally, join intervals in loop nest order. 611 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) 612 joinIntervalsInMachineBB(MBBs[i].second); 613 } 614} 615 616bool LiveIntervals::overlapsAliases(const LiveInterval& lhs, 617 const LiveInterval& rhs) const 618{ 619 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) && 620 "first interval must describe a physical register"); 621 622 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) { 623 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as); 624 assert(r2i != r2iMap_.end() && "alias does not have interval?"); 625 if (rhs.overlaps(*r2i->second)) 626 return true; 627 } 628 629 return false; 630} 631 632LiveInterval& LiveIntervals::getOrCreateInterval(unsigned reg) 633{ 634 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg); 635 if (r2iit == r2iMap_.end() || r2iit->first != reg) { 636 intervals_.push_back(LiveInterval(reg)); 637 r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end())); 638 } 639 640 return *r2iit->second; 641} 642 643LiveInterval::LiveInterval(unsigned r) 644 : reg(r), 645 weight((MRegisterInfo::isPhysicalRegister(r) ? HUGE_VAL : 0.0F)) 646{ 647} 648 649bool LiveInterval::spilled() const 650{ 651 return (weight == HUGE_VAL && 652 MRegisterInfo::isVirtualRegister(reg)); 653} 654 655// An example for liveAt(): 656// 657// this = [1,4), liveAt(0) will return false. The instruction defining 658// this spans slots [0,3]. The interval belongs to an spilled 659// definition of the variable it represents. This is because slot 1 is 660// used (def slot) and spans up to slot 3 (store slot). 661// 662bool LiveInterval::liveAt(unsigned index) const 663{ 664 Range dummy(index, index+1); 665 Ranges::const_iterator r = std::upper_bound(ranges.begin(), 666 ranges.end(), 667 dummy); 668 if (r == ranges.begin()) 669 return false; 670 671 --r; 672 return index >= r->first && index < r->second; 673} 674 675// An example for overlaps(): 676// 677// 0: A = ... 678// 4: B = ... 679// 8: C = A + B ;; last use of A 680// 681// The live intervals should look like: 682// 683// A = [3, 11) 684// B = [7, x) 685// C = [11, y) 686// 687// A->overlaps(C) should return false since we want to be able to join 688// A and C. 689bool LiveInterval::overlaps(const LiveInterval& other) const 690{ 691 Ranges::const_iterator i = ranges.begin(); 692 Ranges::const_iterator ie = ranges.end(); 693 Ranges::const_iterator j = other.ranges.begin(); 694 Ranges::const_iterator je = other.ranges.end(); 695 if (i->first < j->first) { 696 i = std::upper_bound(i, ie, *j); 697 if (i != ranges.begin()) --i; 698 } 699 else if (j->first < i->first) { 700 j = std::upper_bound(j, je, *i); 701 if (j != other.ranges.begin()) --j; 702 } 703 704 while (i != ie && j != je) { 705 if (i->first == j->first) { 706 return true; 707 } 708 else { 709 if (i->first > j->first) { 710 swap(i, j); 711 swap(ie, je); 712 } 713 assert(i->first < j->first); 714 715 if (i->second > j->first) { 716 return true; 717 } 718 else { 719 ++i; 720 } 721 } 722 } 723 724 return false; 725} 726 727void LiveInterval::addRange(unsigned start, unsigned end) 728{ 729 assert(start < end && "Invalid range to add!"); 730 DEBUG(std::cerr << " +[" << start << ',' << end << ")"); 731 //assert(start < end && "invalid range?"); 732 Range range = std::make_pair(start, end); 733 Ranges::iterator it = 734 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range), 735 range); 736 737 it = mergeRangesForward(it); 738 it = mergeRangesBackward(it); 739} 740 741void LiveInterval::join(const LiveInterval& other) 742{ 743 DEBUG(std::cerr << "\t\tjoining " << *this << " with " << other); 744 Ranges::iterator cur = ranges.begin(); 745 746 for (Ranges::const_iterator i = other.ranges.begin(), 747 e = other.ranges.end(); i != e; ++i) { 748 cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i); 749 cur = mergeRangesForward(cur); 750 cur = mergeRangesBackward(cur); 751 } 752 weight += other.weight; 753 ++numJoins; 754 DEBUG(std::cerr << ". Result = " << *this << "\n"); 755} 756 757LiveInterval::Ranges::iterator LiveInterval:: 758mergeRangesForward(Ranges::iterator it) 759{ 760 Ranges::iterator n; 761 while ((n = next(it)) != ranges.end()) { 762 if (n->first > it->second) 763 break; 764 it->second = std::max(it->second, n->second); 765 n = ranges.erase(n); 766 } 767 return it; 768} 769 770LiveInterval::Ranges::iterator LiveInterval:: 771mergeRangesBackward(Ranges::iterator it) 772{ 773 while (it != ranges.begin()) { 774 Ranges::iterator p = prior(it); 775 if (it->first > p->second) 776 break; 777 778 it->first = std::min(it->first, p->first); 779 it->second = std::max(it->second, p->second); 780 it = ranges.erase(p); 781 } 782 783 return it; 784} 785 786std::ostream& llvm::operator<<(std::ostream& os, const LiveInterval& li) 787{ 788 os << "%reg" << li.reg << ',' << li.weight; 789 if (li.empty()) 790 return os << "EMPTY"; 791 792 os << " = "; 793 for (LiveInterval::Ranges::const_iterator 794 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) { 795 os << "[" << i->first << "," << i->second << ")"; 796 } 797 return os; 798} 799