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       llvm_unreachable("Use not jointly dominated by defs.");
00276     }
00277 
00278     if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
00279         !MBB->isLiveIn(PhysReg)) {
00280       MBB->getParent()->verify();
00281       errs() << "The register needs to be live in to BB#" << MBB->getNumber()
00282              << ", but is missing from the live-in list.\n";
00283       llvm_unreachable("Invalid global physical register");
00284     }
00285 #endif
00286 
00287     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00288          PE = MBB->pred_end(); PI != PE; ++PI) {
00289        MachineBasicBlock *Pred = *PI;
00290 
00291        // Is this a known live-out block?
00292        if (Seen.test(Pred->getNumber())) {
00293          if (VNInfo *VNI = Map[Pred].first) {
00294            if (TheVNI && TheVNI != VNI)
00295              UniqueVNI = false;
00296            TheVNI = VNI;
00297          }
00298          continue;
00299        }
00300 
00301        SlotIndex Start, End;
00302        std::tie(Start, End) = Indexes->getMBBRange(Pred);
00303 
00304        // First time we see Pred.  Try to determine the live-out value, but set
00305        // it as null if Pred is live-through with an unknown value.
00306        VNInfo *VNI = LR.extendInBlock(Start, End);
00307        setLiveOutValue(Pred, VNI);
00308        if (VNI) {
00309          if (TheVNI && TheVNI != VNI)
00310            UniqueVNI = false;
00311          TheVNI = VNI;
00312          continue;
00313        }
00314 
00315        // No, we need a live-in value for Pred as well
00316        if (Pred != &UseMBB)
00317           WorkList.push_back(Pred->getNumber());
00318        else
00319           // Loopback to UseMBB, so value is really live through.
00320          Use = SlotIndex();
00321     }
00322   }
00323 
00324   LiveIn.clear();
00325 
00326   // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
00327   // neither require it. Skip the sorting overhead for small updates.
00328   if (WorkList.size() > 4)
00329     array_pod_sort(WorkList.begin(), WorkList.end());
00330 
00331   // If a unique reaching def was found, blit in the live ranges immediately.
00332   if (UniqueVNI) {
00333     LiveRangeUpdater Updater(&LR);
00334     for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
00335          E = WorkList.end(); I != E; ++I) {
00336        SlotIndex Start, End;
00337        std::tie(Start, End) = Indexes->getMBBRange(*I);
00338        // Trim the live range in UseMBB.
00339        if (*I == UseMBBNum && Use.isValid())
00340          End = Use;
00341        else
00342          Map[MF->getBlockNumbered(*I)] = LiveOutPair(TheVNI, nullptr);
00343        Updater.add(Start, End, TheVNI);
00344     }
00345     return true;
00346   }
00347 
00348   // Multiple values were found, so transfer the work list to the LiveIn array
00349   // where UpdateSSA will use it as a work list.
00350   LiveIn.reserve(WorkList.size());
00351   for (SmallVectorImpl<unsigned>::const_iterator
00352        I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
00353     MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
00354     addLiveInBlock(LR, DomTree->getNode(MBB));
00355     if (MBB == &UseMBB)
00356       LiveIn.back().Kill = Use;
00357   }
00358 
00359   return false;
00360 }
00361 
00362 
00363 // This is essentially the same iterative algorithm that SSAUpdater uses,
00364 // except we already have a dominator tree, so we don't have to recompute it.
00365 void LiveRangeCalc::updateSSA() {
00366   assert(Indexes && "Missing SlotIndexes");
00367   assert(DomTree && "Missing dominator tree");
00368 
00369   // Interate until convergence.
00370   unsigned Changes;
00371   do {
00372     Changes = 0;
00373     // Propagate live-out values down the dominator tree, inserting phi-defs
00374     // when necessary.
00375     for (LiveInBlock &I : LiveIn) {
00376       MachineDomTreeNode *Node = I.DomNode;
00377       // Skip block if the live-in value has already been determined.
00378       if (!Node)
00379         continue;
00380       MachineBasicBlock *MBB = Node->getBlock();
00381       MachineDomTreeNode *IDom = Node->getIDom();
00382       LiveOutPair IDomValue;
00383 
00384       // We need a live-in value to a block with no immediate dominator?
00385       // This is probably an unreachable block that has survived somehow.
00386       bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
00387 
00388       // IDom dominates all of our predecessors, but it may not be their
00389       // immediate dominator. Check if any of them have live-out values that are
00390       // properly dominated by IDom. If so, we need a phi-def here.
00391       if (!needPHI) {
00392         IDomValue = Map[IDom->getBlock()];
00393 
00394         // Cache the DomTree node that defined the value.
00395         if (IDomValue.first && !IDomValue.second)
00396           Map[IDom->getBlock()].second = IDomValue.second =
00397             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
00398 
00399         for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00400                PE = MBB->pred_end(); PI != PE; ++PI) {
00401           LiveOutPair &Value = Map[*PI];
00402           if (!Value.first || Value.first == IDomValue.first)
00403             continue;
00404 
00405           // Cache the DomTree node that defined the value.
00406           if (!Value.second)
00407             Value.second =
00408               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
00409 
00410           // This predecessor is carrying something other than IDomValue.
00411           // It could be because IDomValue hasn't propagated yet, or it could be
00412           // because MBB is in the dominance frontier of that value.
00413           if (DomTree->dominates(IDom, Value.second)) {
00414             needPHI = true;
00415             break;
00416           }
00417         }
00418       }
00419 
00420       // The value may be live-through even if Kill is set, as can happen when
00421       // we are called from extendRange. In that case LiveOutSeen is true, and
00422       // LiveOut indicates a foreign or missing value.
00423       LiveOutPair &LOP = Map[MBB];
00424 
00425       // Create a phi-def if required.
00426       if (needPHI) {
00427         ++Changes;
00428         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
00429         SlotIndex Start, End;
00430         std::tie(Start, End) = Indexes->getMBBRange(MBB);
00431         LiveRange &LR = I.LR;
00432         VNInfo *VNI = LR.getNextValue(Start, *Alloc);
00433         I.Value = VNI;
00434         // This block is done, we know the final value.
00435         I.DomNode = nullptr;
00436 
00437         // Add liveness since updateFromLiveIns now skips this node.
00438         if (I.Kill.isValid())
00439           LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
00440         else {
00441           LR.addSegment(LiveInterval::Segment(Start, End, VNI));
00442           LOP = LiveOutPair(VNI, Node);
00443         }
00444       } else if (IDomValue.first) {
00445         // No phi-def here. Remember incoming value.
00446         I.Value = IDomValue.first;
00447 
00448         // If the IDomValue is killed in the block, don't propagate through.
00449         if (I.Kill.isValid())
00450           continue;
00451 
00452         // Propagate IDomValue if it isn't killed:
00453         // MBB is live-out and doesn't define its own value.
00454         if (LOP.first == IDomValue.first)
00455           continue;
00456         ++Changes;
00457         LOP = IDomValue;
00458       }
00459     }
00460   } while (Changes);
00461 }