LLVM  mainline
LiveRangeCalc.cpp
Go to the documentation of this file.
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::resetLiveOutMap() {
00023   unsigned NumBlocks = MF->getNumBlockIDs();
00024   Seen.clear();
00025   Seen.resize(NumBlocks);
00026   Map.resize(NumBlocks);
00027 }
00028 
00029 void LiveRangeCalc::reset(const MachineFunction *mf,
00030                           SlotIndexes *SI,
00031                           MachineDominatorTree *MDT,
00032                           VNInfo::Allocator *VNIA) {
00033   MF = mf;
00034   MRI = &MF->getRegInfo();
00035   Indexes = SI;
00036   DomTree = MDT;
00037   Alloc = VNIA;
00038   resetLiveOutMap();
00039   LiveIn.clear();
00040 }
00041 
00042 
00043 static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
00044                           LiveRange &LR, const MachineOperand &MO) {
00045     const MachineInstr *MI = MO.getParent();
00046     SlotIndex DefIdx =
00047         Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
00048 
00049     // Create the def in LR. This may find an existing def.
00050     LR.createDeadDef(DefIdx, Alloc);
00051 }
00052 
00053 void LiveRangeCalc::calculate(LiveInterval &LI, bool TrackSubRegs) {
00054   assert(MRI && Indexes && "call reset() first");
00055 
00056   // Step 1: Create minimal live segments for every definition of Reg.
00057   // Visit all def operands. If the same instruction has multiple defs of Reg,
00058   // createDeadDef() will deduplicate.
00059   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
00060   unsigned Reg = LI.reg;
00061   for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
00062     if (!MO.isDef() && !MO.readsReg())
00063       continue;
00064 
00065     unsigned SubReg = MO.getSubReg();
00066     if (LI.hasSubRanges() || (SubReg != 0 && TrackSubRegs)) {
00067       unsigned Mask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
00068                                   : MRI->getMaxLaneMaskForVReg(Reg);
00069 
00070       // If this is the first time we see a subregister def, initialize
00071       // subranges by creating a copy of the main range.
00072       if (!LI.hasSubRanges() && !LI.empty()) {
00073         unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
00074         LI.createSubRangeFrom(*Alloc, ClassMask, LI);
00075       }
00076 
00077       for (LiveInterval::SubRange &S : LI.subranges()) {
00078         // A Mask for subregs common to the existing subrange and current def.
00079         unsigned Common = S.LaneMask & Mask;
00080         if (Common == 0)
00081           continue;
00082         // A Mask for subregs covered by the subrange but not the current def.
00083         unsigned LRest = S.LaneMask & ~Mask;
00084         LiveInterval::SubRange *CommonRange;
00085         if (LRest != 0) {
00086           // Split current subrange into Common and LRest ranges.
00087           S.LaneMask = LRest;
00088           CommonRange = LI.createSubRangeFrom(*Alloc, Common, S);
00089         } else {
00090           assert(Common == S.LaneMask);
00091           CommonRange = &S;
00092         }
00093         if (MO.isDef())
00094           createDeadDef(*Indexes, *Alloc, *CommonRange, MO);
00095         Mask &= ~Common;
00096       }
00097       // Create a new SubRange for subregs we did not cover yet.
00098       if (Mask != 0) {
00099         LiveInterval::SubRange *NewRange = LI.createSubRange(*Alloc, Mask);
00100         if (MO.isDef())
00101           createDeadDef(*Indexes, *Alloc, *NewRange, MO);
00102       }
00103     }
00104 
00105     // Create the def in the main liverange. We do not have to do this if
00106     // subranges are tracked as we recreate the main range later in this case.
00107     if (MO.isDef() && !LI.hasSubRanges())
00108       createDeadDef(*Indexes, *Alloc, LI, MO);
00109   }
00110 
00111   // We may have created empty live ranges for partially undefined uses, we
00112   // can't keep them because we won't find defs in them later.
00113   LI.removeEmptySubRanges();
00114 
00115   // Step 2: Extend live segments to all uses, constructing SSA form as
00116   // necessary.
00117   if (LI.hasSubRanges()) {
00118     for (LiveInterval::SubRange &S : LI.subranges()) {
00119       resetLiveOutMap();
00120       extendToUses(S, Reg, S.LaneMask);
00121     }
00122     LI.clear();
00123     LI.constructMainRangeFromSubranges(*Indexes, *Alloc);
00124   } else {
00125     resetLiveOutMap();
00126     extendToUses(LI, Reg, ~0u);
00127   }
00128 }
00129 
00130 
00131 void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
00132   assert(MRI && Indexes && "call reset() first");
00133 
00134   // Visit all def operands. If the same instruction has multiple defs of Reg,
00135   // LR.createDeadDef() will deduplicate.
00136   for (MachineOperand &MO : MRI->def_operands(Reg))
00137     createDeadDef(*Indexes, *Alloc, LR, MO);
00138 }
00139 
00140 
00141 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, unsigned Mask) {
00142   // Visit all operands that read Reg. This may include partial defs.
00143   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
00144   for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
00145     // Clear all kill flags. They will be reinserted after register allocation
00146     // by LiveIntervalAnalysis::addKillFlags().
00147     if (MO.isUse())
00148       MO.setIsKill(false);
00149     else {
00150       // We only care about uses, but on the main range (mask ~0u) this includes
00151       // the "virtual" reads happening for subregister defs.
00152       if (Mask != ~0u)
00153         continue;
00154     }
00155 
00156     if (!MO.readsReg())
00157       continue;
00158     unsigned SubReg = MO.getSubReg();
00159     if (SubReg != 0) {
00160       unsigned SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
00161       // Ignore uses not covering the current subrange.
00162       if ((SubRegMask & Mask) == 0)
00163         continue;
00164     }
00165 
00166     // Determine the actual place of the use.
00167     const MachineInstr *MI = MO.getParent();
00168     unsigned OpNo = (&MO - &MI->getOperand(0));
00169     SlotIndex UseIdx;
00170     if (MI->isPHI()) {
00171       assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
00172       // The actual place where a phi operand is used is the end of the pred
00173       // MBB. PHI operands are paired: (Reg, PredMBB).
00174       UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
00175     } else {
00176       // Check for early-clobber redefs.
00177       bool isEarlyClobber = false;
00178       unsigned DefIdx;
00179       if (MO.isDef())
00180         isEarlyClobber = MO.isEarlyClobber();
00181       else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
00182         // FIXME: This would be a lot easier if tied early-clobber uses also
00183         // had an early-clobber flag.
00184         isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
00185       }
00186       UseIdx = Indexes->getInstructionIndex(MI).getRegSlot(isEarlyClobber);
00187     }
00188 
00189     // MI is reading Reg. We may have visited MI before if it happens to be
00190     // reading Reg multiple times. That is OK, extend() is idempotent.
00191     extend(LR, UseIdx, Reg);
00192   }
00193 }
00194 
00195 
00196 void LiveRangeCalc::updateFromLiveIns() {
00197   LiveRangeUpdater Updater;
00198   for (const LiveInBlock &I : LiveIn) {
00199     if (!I.DomNode)
00200       continue;
00201     MachineBasicBlock *MBB = I.DomNode->getBlock();
00202     assert(I.Value && "No live-in value found");
00203     SlotIndex Start, End;
00204     std::tie(Start, End) = Indexes->getMBBRange(MBB);
00205 
00206     if (I.Kill.isValid())
00207       // Value is killed inside this block.
00208       End = I.Kill;
00209     else {
00210       // The value is live-through, update LiveOut as well.
00211       // Defer the Domtree lookup until it is needed.
00212       assert(Seen.test(MBB->getNumber()));
00213       Map[MBB] = LiveOutPair(I.Value, nullptr);
00214     }
00215     Updater.setDest(&I.LR);
00216     Updater.add(Start, End, I.Value);
00217   }
00218   LiveIn.clear();
00219 }
00220 
00221 
00222 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg) {
00223   assert(Use.isValid() && "Invalid SlotIndex");
00224   assert(Indexes && "Missing SlotIndexes");
00225   assert(DomTree && "Missing dominator tree");
00226 
00227   MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
00228   assert(UseMBB && "No MBB at Use");
00229 
00230   // Is there a def in the same MBB we can extend?
00231   if (LR.extendInBlock(Indexes->getMBBStartIdx(UseMBB), Use))
00232     return;
00233 
00234   // Find the single reaching def, or determine if Use is jointly dominated by
00235   // multiple values, and we may need to create even more phi-defs to preserve
00236   // VNInfo SSA form.  Perform a search for all predecessor blocks where we
00237   // know the dominating VNInfo.
00238   if (findReachingDefs(LR, *UseMBB, Use, PhysReg))
00239     return;
00240 
00241   // When there were multiple different values, we may need new PHIs.
00242   calculateValues();
00243 }
00244 
00245 
00246 // This function is called by a client after using the low-level API to add
00247 // live-out and live-in blocks.  The unique value optimization is not
00248 // available, SplitEditor::transferValues handles that case directly anyway.
00249 void LiveRangeCalc::calculateValues() {
00250   assert(Indexes && "Missing SlotIndexes");
00251   assert(DomTree && "Missing dominator tree");
00252   updateSSA();
00253   updateFromLiveIns();
00254 }
00255 
00256 
00257 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
00258                                      SlotIndex Use, unsigned PhysReg) {
00259   unsigned UseMBBNum = UseMBB.getNumber();
00260 
00261   // Block numbers where LR should be live-in.
00262   SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
00263 
00264   // Remember if we have seen more than one value.
00265   bool UniqueVNI = true;
00266   VNInfo *TheVNI = nullptr;
00267 
00268   // Using Seen as a visited set, perform a BFS for all reaching defs.
00269   for (unsigned i = 0; i != WorkList.size(); ++i) {
00270     MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
00271 
00272 #ifndef NDEBUG
00273     if (MBB->pred_empty()) {
00274       MBB->getParent()->verify();
00275       errs() << "Use of " << PrintReg(PhysReg)
00276              << " does not have a corresponding definition on every path:\n";
00277       const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
00278       if (MI != nullptr)
00279         errs() << Use << " " << *MI;
00280       llvm_unreachable("Use not jointly dominated by defs.");
00281     }
00282 
00283     if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
00284         !MBB->isLiveIn(PhysReg)) {
00285       MBB->getParent()->verify();
00286       errs() << "The register " << PrintReg(PhysReg)
00287              << " needs to be live in to BB#" << MBB->getNumber()
00288              << ", but is missing from the live-in list.\n";
00289       llvm_unreachable("Invalid global physical register");
00290     }
00291 #endif
00292 
00293     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00294          PE = MBB->pred_end(); PI != PE; ++PI) {
00295        MachineBasicBlock *Pred = *PI;
00296 
00297        // Is this a known live-out block?
00298        if (Seen.test(Pred->getNumber())) {
00299          if (VNInfo *VNI = Map[Pred].first) {
00300            if (TheVNI && TheVNI != VNI)
00301              UniqueVNI = false;
00302            TheVNI = VNI;
00303          }
00304          continue;
00305        }
00306 
00307        SlotIndex Start, End;
00308        std::tie(Start, End) = Indexes->getMBBRange(Pred);
00309 
00310        // First time we see Pred.  Try to determine the live-out value, but set
00311        // it as null if Pred is live-through with an unknown value.
00312        VNInfo *VNI = LR.extendInBlock(Start, End);
00313        setLiveOutValue(Pred, VNI);
00314        if (VNI) {
00315          if (TheVNI && TheVNI != VNI)
00316            UniqueVNI = false;
00317          TheVNI = VNI;
00318          continue;
00319        }
00320 
00321        // No, we need a live-in value for Pred as well
00322        if (Pred != &UseMBB)
00323           WorkList.push_back(Pred->getNumber());
00324        else
00325           // Loopback to UseMBB, so value is really live through.
00326          Use = SlotIndex();
00327     }
00328   }
00329 
00330   LiveIn.clear();
00331 
00332   // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
00333   // neither require it. Skip the sorting overhead for small updates.
00334   if (WorkList.size() > 4)
00335     array_pod_sort(WorkList.begin(), WorkList.end());
00336 
00337   // If a unique reaching def was found, blit in the live ranges immediately.
00338   if (UniqueVNI) {
00339     LiveRangeUpdater Updater(&LR);
00340     for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
00341          E = WorkList.end(); I != E; ++I) {
00342        SlotIndex Start, End;
00343        std::tie(Start, End) = Indexes->getMBBRange(*I);
00344        // Trim the live range in UseMBB.
00345        if (*I == UseMBBNum && Use.isValid())
00346          End = Use;
00347        else
00348          Map[MF->getBlockNumbered(*I)] = LiveOutPair(TheVNI, nullptr);
00349        Updater.add(Start, End, TheVNI);
00350     }
00351     return true;
00352   }
00353 
00354   // Multiple values were found, so transfer the work list to the LiveIn array
00355   // where UpdateSSA will use it as a work list.
00356   LiveIn.reserve(WorkList.size());
00357   for (SmallVectorImpl<unsigned>::const_iterator
00358        I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
00359     MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
00360     addLiveInBlock(LR, DomTree->getNode(MBB));
00361     if (MBB == &UseMBB)
00362       LiveIn.back().Kill = Use;
00363   }
00364 
00365   return false;
00366 }
00367 
00368 
00369 // This is essentially the same iterative algorithm that SSAUpdater uses,
00370 // except we already have a dominator tree, so we don't have to recompute it.
00371 void LiveRangeCalc::updateSSA() {
00372   assert(Indexes && "Missing SlotIndexes");
00373   assert(DomTree && "Missing dominator tree");
00374 
00375   // Interate until convergence.
00376   unsigned Changes;
00377   do {
00378     Changes = 0;
00379     // Propagate live-out values down the dominator tree, inserting phi-defs
00380     // when necessary.
00381     for (LiveInBlock &I : LiveIn) {
00382       MachineDomTreeNode *Node = I.DomNode;
00383       // Skip block if the live-in value has already been determined.
00384       if (!Node)
00385         continue;
00386       MachineBasicBlock *MBB = Node->getBlock();
00387       MachineDomTreeNode *IDom = Node->getIDom();
00388       LiveOutPair IDomValue;
00389 
00390       // We need a live-in value to a block with no immediate dominator?
00391       // This is probably an unreachable block that has survived somehow.
00392       bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
00393 
00394       // IDom dominates all of our predecessors, but it may not be their
00395       // immediate dominator. Check if any of them have live-out values that are
00396       // properly dominated by IDom. If so, we need a phi-def here.
00397       if (!needPHI) {
00398         IDomValue = Map[IDom->getBlock()];
00399 
00400         // Cache the DomTree node that defined the value.
00401         if (IDomValue.first && !IDomValue.second)
00402           Map[IDom->getBlock()].second = IDomValue.second =
00403             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
00404 
00405         for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00406                PE = MBB->pred_end(); PI != PE; ++PI) {
00407           LiveOutPair &Value = Map[*PI];
00408           if (!Value.first || Value.first == IDomValue.first)
00409             continue;
00410 
00411           // Cache the DomTree node that defined the value.
00412           if (!Value.second)
00413             Value.second =
00414               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
00415 
00416           // This predecessor is carrying something other than IDomValue.
00417           // It could be because IDomValue hasn't propagated yet, or it could be
00418           // because MBB is in the dominance frontier of that value.
00419           if (DomTree->dominates(IDom, Value.second)) {
00420             needPHI = true;
00421             break;
00422           }
00423         }
00424       }
00425 
00426       // The value may be live-through even if Kill is set, as can happen when
00427       // we are called from extendRange. In that case LiveOutSeen is true, and
00428       // LiveOut indicates a foreign or missing value.
00429       LiveOutPair &LOP = Map[MBB];
00430 
00431       // Create a phi-def if required.
00432       if (needPHI) {
00433         ++Changes;
00434         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
00435         SlotIndex Start, End;
00436         std::tie(Start, End) = Indexes->getMBBRange(MBB);
00437         LiveRange &LR = I.LR;
00438         VNInfo *VNI = LR.getNextValue(Start, *Alloc);
00439         I.Value = VNI;
00440         // This block is done, we know the final value.
00441         I.DomNode = nullptr;
00442 
00443         // Add liveness since updateFromLiveIns now skips this node.
00444         if (I.Kill.isValid())
00445           LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
00446         else {
00447           LR.addSegment(LiveInterval::Segment(Start, End, VNI));
00448           LOP = LiveOutPair(VNI, Node);
00449         }
00450       } else if (IDomValue.first) {
00451         // No phi-def here. Remember incoming value.
00452         I.Value = IDomValue.first;
00453 
00454         // If the IDomValue is killed in the block, don't propagate through.
00455         if (I.Kill.isValid())
00456           continue;
00457 
00458         // Propagate IDomValue if it isn't killed:
00459         // MBB is live-out and doesn't define its own value.
00460         if (LOP.first == IDomValue.first)
00461           continue;
00462         ++Changes;
00463         LOP = IDomValue;
00464       }
00465     }
00466   } while (Changes);
00467 }