LLVM API Documentation
00001 //===---- LiveRangeCalc.cpp - Calculate 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 // Implementation of the LiveRangeCalc class. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "LiveRangeCalc.h" 00015 #include "llvm/CodeGen/MachineDominators.h" 00016 #include "llvm/CodeGen/MachineRegisterInfo.h" 00017 00018 using namespace llvm; 00019 00020 #define DEBUG_TYPE "regalloc" 00021 00022 void LiveRangeCalc::reset(const MachineFunction *mf, 00023 SlotIndexes *SI, 00024 MachineDominatorTree *MDT, 00025 VNInfo::Allocator *VNIA) { 00026 MF = mf; 00027 MRI = &MF->getRegInfo(); 00028 Indexes = SI; 00029 DomTree = MDT; 00030 Alloc = VNIA; 00031 00032 unsigned N = MF->getNumBlockIDs(); 00033 Seen.clear(); 00034 Seen.resize(N); 00035 LiveOut.resize(N); 00036 LiveIn.clear(); 00037 } 00038 00039 00040 void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) { 00041 assert(MRI && Indexes && "call reset() first"); 00042 00043 // Visit all def operands. If the same instruction has multiple defs of Reg, 00044 // LR.createDeadDef() will deduplicate. 00045 for (MachineOperand &MO : MRI->def_operands(Reg)) { 00046 const MachineInstr *MI = MO.getParent(); 00047 // Find the corresponding slot index. 00048 SlotIndex Idx; 00049 if (MI->isPHI()) 00050 // PHI defs begin at the basic block start index. 00051 Idx = Indexes->getMBBStartIdx(MI->getParent()); 00052 else 00053 // Instructions are either normal 'r', or early clobber 'e'. 00054 Idx = Indexes->getInstructionIndex(MI) 00055 .getRegSlot(MO.isEarlyClobber()); 00056 00057 // Create the def in LR. This may find an existing def. 00058 LR.createDeadDef(Idx, *Alloc); 00059 } 00060 } 00061 00062 00063 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg) { 00064 assert(MRI && Indexes && "call reset() first"); 00065 00066 // Visit all operands that read Reg. This may include partial defs. 00067 for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) { 00068 // Clear all kill flags. They will be reinserted after register allocation 00069 // by LiveIntervalAnalysis::addKillFlags(). 00070 if (MO.isUse()) 00071 MO.setIsKill(false); 00072 if (!MO.readsReg()) 00073 continue; 00074 // MI is reading Reg. We may have visited MI before if it happens to be 00075 // reading Reg multiple times. That is OK, extend() is idempotent. 00076 const MachineInstr *MI = MO.getParent(); 00077 unsigned OpNo = (&MO - &MI->getOperand(0)); 00078 00079 // Find the SlotIndex being read. 00080 SlotIndex Idx; 00081 if (MI->isPHI()) { 00082 assert(!MO.isDef() && "Cannot handle PHI def of partial register."); 00083 // PHI operands are paired: (Reg, PredMBB). 00084 // Extend the live range to be live-out from PredMBB. 00085 Idx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB()); 00086 } else { 00087 // This is a normal instruction. 00088 Idx = Indexes->getInstructionIndex(MI).getRegSlot(); 00089 // Check for early-clobber redefs. 00090 unsigned DefIdx; 00091 if (MO.isDef()) { 00092 if (MO.isEarlyClobber()) 00093 Idx = Idx.getRegSlot(true); 00094 } else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) { 00095 // FIXME: This would be a lot easier if tied early-clobber uses also 00096 // had an early-clobber flag. 00097 if (MI->getOperand(DefIdx).isEarlyClobber()) 00098 Idx = Idx.getRegSlot(true); 00099 } 00100 } 00101 extend(LR, Idx, Reg); 00102 } 00103 } 00104 00105 00106 // Transfer information from the LiveIn vector to the live ranges. 00107 void LiveRangeCalc::updateLiveIns() { 00108 LiveRangeUpdater Updater; 00109 for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(), 00110 E = LiveIn.end(); I != E; ++I) { 00111 if (!I->DomNode) 00112 continue; 00113 MachineBasicBlock *MBB = I->DomNode->getBlock(); 00114 assert(I->Value && "No live-in value found"); 00115 SlotIndex Start, End; 00116 std::tie(Start, End) = Indexes->getMBBRange(MBB); 00117 00118 if (I->Kill.isValid()) 00119 // Value is killed inside this block. 00120 End = I->Kill; 00121 else { 00122 // The value is live-through, update LiveOut as well. 00123 // Defer the Domtree lookup until it is needed. 00124 assert(Seen.test(MBB->getNumber())); 00125 LiveOut[MBB] = LiveOutPair(I->Value, (MachineDomTreeNode *)nullptr); 00126 } 00127 Updater.setDest(&I->LR); 00128 Updater.add(Start, End, I->Value); 00129 } 00130 LiveIn.clear(); 00131 } 00132 00133 00134 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Kill, unsigned PhysReg) { 00135 assert(Kill.isValid() && "Invalid SlotIndex"); 00136 assert(Indexes && "Missing SlotIndexes"); 00137 assert(DomTree && "Missing dominator tree"); 00138 00139 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot()); 00140 assert(KillMBB && "No MBB at Kill"); 00141 00142 // Is there a def in the same MBB we can extend? 00143 if (LR.extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill)) 00144 return; 00145 00146 // Find the single reaching def, or determine if Kill is jointly dominated by 00147 // multiple values, and we may need to create even more phi-defs to preserve 00148 // VNInfo SSA form. Perform a search for all predecessor blocks where we 00149 // know the dominating VNInfo. 00150 if (findReachingDefs(LR, *KillMBB, Kill, PhysReg)) 00151 return; 00152 00153 // When there were multiple different values, we may need new PHIs. 00154 calculateValues(); 00155 } 00156 00157 00158 // This function is called by a client after using the low-level API to add 00159 // live-out and live-in blocks. The unique value optimization is not 00160 // available, SplitEditor::transferValues handles that case directly anyway. 00161 void LiveRangeCalc::calculateValues() { 00162 assert(Indexes && "Missing SlotIndexes"); 00163 assert(DomTree && "Missing dominator tree"); 00164 updateSSA(); 00165 updateLiveIns(); 00166 } 00167 00168 00169 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &KillMBB, 00170 SlotIndex Kill, unsigned PhysReg) { 00171 unsigned KillMBBNum = KillMBB.getNumber(); 00172 00173 // Block numbers where LR should be live-in. 00174 SmallVector<unsigned, 16> WorkList(1, KillMBBNum); 00175 00176 // Remember if we have seen more than one value. 00177 bool UniqueVNI = true; 00178 VNInfo *TheVNI = nullptr; 00179 00180 // Using Seen as a visited set, perform a BFS for all reaching defs. 00181 for (unsigned i = 0; i != WorkList.size(); ++i) { 00182 MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]); 00183 00184 #ifndef NDEBUG 00185 if (MBB->pred_empty()) { 00186 MBB->getParent()->verify(); 00187 llvm_unreachable("Use not jointly dominated by defs."); 00188 } 00189 00190 if (TargetRegisterInfo::isPhysicalRegister(PhysReg) && 00191 !MBB->isLiveIn(PhysReg)) { 00192 MBB->getParent()->verify(); 00193 errs() << "The register needs to be live in to BB#" << MBB->getNumber() 00194 << ", but is missing from the live-in list.\n"; 00195 llvm_unreachable("Invalid global physical register"); 00196 } 00197 #endif 00198 00199 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 00200 PE = MBB->pred_end(); PI != PE; ++PI) { 00201 MachineBasicBlock *Pred = *PI; 00202 00203 // Is this a known live-out block? 00204 if (Seen.test(Pred->getNumber())) { 00205 if (VNInfo *VNI = LiveOut[Pred].first) { 00206 if (TheVNI && TheVNI != VNI) 00207 UniqueVNI = false; 00208 TheVNI = VNI; 00209 } 00210 continue; 00211 } 00212 00213 SlotIndex Start, End; 00214 std::tie(Start, End) = Indexes->getMBBRange(Pred); 00215 00216 // First time we see Pred. Try to determine the live-out value, but set 00217 // it as null if Pred is live-through with an unknown value. 00218 VNInfo *VNI = LR.extendInBlock(Start, End); 00219 setLiveOutValue(Pred, VNI); 00220 if (VNI) { 00221 if (TheVNI && TheVNI != VNI) 00222 UniqueVNI = false; 00223 TheVNI = VNI; 00224 continue; 00225 } 00226 00227 // No, we need a live-in value for Pred as well 00228 if (Pred != &KillMBB) 00229 WorkList.push_back(Pred->getNumber()); 00230 else 00231 // Loopback to KillMBB, so value is really live through. 00232 Kill = SlotIndex(); 00233 } 00234 } 00235 00236 LiveIn.clear(); 00237 00238 // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but 00239 // neither require it. Skip the sorting overhead for small updates. 00240 if (WorkList.size() > 4) 00241 array_pod_sort(WorkList.begin(), WorkList.end()); 00242 00243 // If a unique reaching def was found, blit in the live ranges immediately. 00244 if (UniqueVNI) { 00245 LiveRangeUpdater Updater(&LR); 00246 for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(), 00247 E = WorkList.end(); I != E; ++I) { 00248 SlotIndex Start, End; 00249 std::tie(Start, End) = Indexes->getMBBRange(*I); 00250 // Trim the live range in KillMBB. 00251 if (*I == KillMBBNum && Kill.isValid()) 00252 End = Kill; 00253 else 00254 LiveOut[MF->getBlockNumbered(*I)] = 00255 LiveOutPair(TheVNI, nullptr); 00256 Updater.add(Start, End, TheVNI); 00257 } 00258 return true; 00259 } 00260 00261 // Multiple values were found, so transfer the work list to the LiveIn array 00262 // where UpdateSSA will use it as a work list. 00263 LiveIn.reserve(WorkList.size()); 00264 for (SmallVectorImpl<unsigned>::const_iterator 00265 I = WorkList.begin(), E = WorkList.end(); I != E; ++I) { 00266 MachineBasicBlock *MBB = MF->getBlockNumbered(*I); 00267 addLiveInBlock(LR, DomTree->getNode(MBB)); 00268 if (MBB == &KillMBB) 00269 LiveIn.back().Kill = Kill; 00270 } 00271 00272 return false; 00273 } 00274 00275 00276 // This is essentially the same iterative algorithm that SSAUpdater uses, 00277 // except we already have a dominator tree, so we don't have to recompute it. 00278 void LiveRangeCalc::updateSSA() { 00279 assert(Indexes && "Missing SlotIndexes"); 00280 assert(DomTree && "Missing dominator tree"); 00281 00282 // Interate until convergence. 00283 unsigned Changes; 00284 do { 00285 Changes = 0; 00286 // Propagate live-out values down the dominator tree, inserting phi-defs 00287 // when necessary. 00288 for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(), 00289 E = LiveIn.end(); I != E; ++I) { 00290 MachineDomTreeNode *Node = I->DomNode; 00291 // Skip block if the live-in value has already been determined. 00292 if (!Node) 00293 continue; 00294 MachineBasicBlock *MBB = Node->getBlock(); 00295 MachineDomTreeNode *IDom = Node->getIDom(); 00296 LiveOutPair IDomValue; 00297 00298 // We need a live-in value to a block with no immediate dominator? 00299 // This is probably an unreachable block that has survived somehow. 00300 bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber()); 00301 00302 // IDom dominates all of our predecessors, but it may not be their 00303 // immediate dominator. Check if any of them have live-out values that are 00304 // properly dominated by IDom. If so, we need a phi-def here. 00305 if (!needPHI) { 00306 IDomValue = LiveOut[IDom->getBlock()]; 00307 00308 // Cache the DomTree node that defined the value. 00309 if (IDomValue.first && !IDomValue.second) 00310 LiveOut[IDom->getBlock()].second = IDomValue.second = 00311 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def)); 00312 00313 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 00314 PE = MBB->pred_end(); PI != PE; ++PI) { 00315 LiveOutPair &Value = LiveOut[*PI]; 00316 if (!Value.first || Value.first == IDomValue.first) 00317 continue; 00318 00319 // Cache the DomTree node that defined the value. 00320 if (!Value.second) 00321 Value.second = 00322 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def)); 00323 00324 // This predecessor is carrying something other than IDomValue. 00325 // It could be because IDomValue hasn't propagated yet, or it could be 00326 // because MBB is in the dominance frontier of that value. 00327 if (DomTree->dominates(IDom, Value.second)) { 00328 needPHI = true; 00329 break; 00330 } 00331 } 00332 } 00333 00334 // The value may be live-through even if Kill is set, as can happen when 00335 // we are called from extendRange. In that case LiveOutSeen is true, and 00336 // LiveOut indicates a foreign or missing value. 00337 LiveOutPair &LOP = LiveOut[MBB]; 00338 00339 // Create a phi-def if required. 00340 if (needPHI) { 00341 ++Changes; 00342 assert(Alloc && "Need VNInfo allocator to create PHI-defs"); 00343 SlotIndex Start, End; 00344 std::tie(Start, End) = Indexes->getMBBRange(MBB); 00345 LiveRange &LR = I->LR; 00346 VNInfo *VNI = LR.getNextValue(Start, *Alloc); 00347 I->Value = VNI; 00348 // This block is done, we know the final value. 00349 I->DomNode = nullptr; 00350 00351 // Add liveness since updateLiveIns now skips this node. 00352 if (I->Kill.isValid()) 00353 LR.addSegment(LiveInterval::Segment(Start, I->Kill, VNI)); 00354 else { 00355 LR.addSegment(LiveInterval::Segment(Start, End, VNI)); 00356 LOP = LiveOutPair(VNI, Node); 00357 } 00358 } else if (IDomValue.first) { 00359 // No phi-def here. Remember incoming value. 00360 I->Value = IDomValue.first; 00361 00362 // If the IDomValue is killed in the block, don't propagate through. 00363 if (I->Kill.isValid()) 00364 continue; 00365 00366 // Propagate IDomValue if it isn't killed: 00367 // MBB is live-out and doesn't define its own value. 00368 if (LOP.first == IDomValue.first) 00369 continue; 00370 ++Changes; 00371 LOP = IDomValue; 00372 } 00373 } 00374 } while (Changes); 00375 }