1//===- llvm/CodeGen/SlotIndexes.h - Slot indexes representation -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements SlotIndex and related classes. The purpose of SlotIndex
11// is to describe a position at which a register can become live, or cease to
12// be live.
13//
14// SlotIndex is mostly a proxy for entries of the SlotIndexList, a class which
15// is held is LiveIntervals and provides the real numbering. This allows
16// LiveIntervals to perform largely transparent renumbering.
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_CODEGEN_SLOTINDEXES_H
20#define LLVM_CODEGEN_SLOTINDEXES_H
21
22#include "llvm/CodeGen/MachineInstrBundle.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/ilist.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/Support/Allocator.h"
30
31namespace llvm {
32
33  /// This class represents an entry in the slot index list held in the
34  /// SlotIndexes pass. It should not be used directly. See the
35  /// SlotIndex & SlotIndexes classes for the public interface to this
36  /// information.
37  class IndexListEntry : public ilist_node<IndexListEntry> {
38    MachineInstr *mi;
39    unsigned index;
40
41  public:
42
43    IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
44
45    MachineInstr* getInstr() const { return mi; }
46    void setInstr(MachineInstr *mi) {
47      this->mi = mi;
48    }
49
50    unsigned getIndex() const { return index; }
51    void setIndex(unsigned index) {
52      this->index = index;
53    }
54
55  };
56
57  template <>
58  struct ilist_traits<IndexListEntry> : public ilist_default_traits<IndexListEntry> {
59  private:
60    mutable ilist_half_node<IndexListEntry> Sentinel;
61  public:
62    IndexListEntry *createSentinel() const {
63      return static_cast<IndexListEntry*>(&Sentinel);
64    }
65    void destroySentinel(IndexListEntry *) const {}
66
67    IndexListEntry *provideInitialHead() const { return createSentinel(); }
68    IndexListEntry *ensureHead(IndexListEntry*) const { return createSentinel(); }
69    static void noteHead(IndexListEntry*, IndexListEntry*) {}
70    void deleteNode(IndexListEntry *N) {}
71
72  private:
73    void createNode(const IndexListEntry &);
74  };
75
76  /// SlotIndex - An opaque wrapper around machine indexes.
77  class SlotIndex {
78    friend class SlotIndexes;
79
80    enum Slot {
81      /// Basic block boundary.  Used for live ranges entering and leaving a
82      /// block without being live in the layout neighbor.  Also used as the
83      /// def slot of PHI-defs.
84      Slot_Block,
85
86      /// Early-clobber register use/def slot.  A live range defined at
87      /// Slot_EarlyCLobber interferes with normal live ranges killed at
88      /// Slot_Register.  Also used as the kill slot for live ranges tied to an
89      /// early-clobber def.
90      Slot_EarlyClobber,
91
92      /// Normal register use/def slot.  Normal instructions kill and define
93      /// register live ranges at this slot.
94      Slot_Register,
95
96      /// Dead def kill point.  Kill slot for a live range that is defined by
97      /// the same instruction (Slot_Register or Slot_EarlyClobber), but isn't
98      /// used anywhere.
99      Slot_Dead,
100
101      Slot_Count
102    };
103
104    PointerIntPair<IndexListEntry*, 2, unsigned> lie;
105
106    SlotIndex(IndexListEntry *entry, unsigned slot)
107      : lie(entry, slot) {}
108
109    IndexListEntry* listEntry() const {
110      assert(isValid() && "Attempt to compare reserved index.");
111      return lie.getPointer();
112    }
113
114    int getIndex() const {
115      return listEntry()->getIndex() | getSlot();
116    }
117
118    /// Returns the slot for this SlotIndex.
119    Slot getSlot() const {
120      return static_cast<Slot>(lie.getInt());
121    }
122
123  public:
124    enum {
125      /// The default distance between instructions as returned by distance().
126      /// This may vary as instructions are inserted and removed.
127      InstrDist = 4 * Slot_Count
128    };
129
130    /// Construct an invalid index.
131    SlotIndex() : lie(0, 0) {}
132
133    // Construct a new slot index from the given one, and set the slot.
134    SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
135      assert(lie.getPointer() != 0 &&
136             "Attempt to construct index with 0 pointer.");
137    }
138
139    /// Returns true if this is a valid index. Invalid indicies do
140    /// not point into an index table, and cannot be compared.
141    bool isValid() const {
142      return lie.getPointer();
143    }
144
145    /// Return true for a valid index.
146    operator bool() const { return isValid(); }
147
148    /// Print this index to the given raw_ostream.
149    void print(raw_ostream &os) const;
150
151    /// Dump this index to stderr.
152    void dump() const;
153
154    /// Compare two SlotIndex objects for equality.
155    bool operator==(SlotIndex other) const {
156      return lie == other.lie;
157    }
158    /// Compare two SlotIndex objects for inequality.
159    bool operator!=(SlotIndex other) const {
160      return lie != other.lie;
161    }
162
163    /// Compare two SlotIndex objects. Return true if the first index
164    /// is strictly lower than the second.
165    bool operator<(SlotIndex other) const {
166      return getIndex() < other.getIndex();
167    }
168    /// Compare two SlotIndex objects. Return true if the first index
169    /// is lower than, or equal to, the second.
170    bool operator<=(SlotIndex other) const {
171      return getIndex() <= other.getIndex();
172    }
173
174    /// Compare two SlotIndex objects. Return true if the first index
175    /// is greater than the second.
176    bool operator>(SlotIndex other) const {
177      return getIndex() > other.getIndex();
178    }
179
180    /// Compare two SlotIndex objects. Return true if the first index
181    /// is greater than, or equal to, the second.
182    bool operator>=(SlotIndex other) const {
183      return getIndex() >= other.getIndex();
184    }
185
186    /// isSameInstr - Return true if A and B refer to the same instruction.
187    static bool isSameInstr(SlotIndex A, SlotIndex B) {
188      return A.lie.getPointer() == B.lie.getPointer();
189    }
190
191    /// isEarlierInstr - Return true if A refers to an instruction earlier than
192    /// B. This is equivalent to A < B && !isSameInstr(A, B).
193    static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
194      return A.listEntry()->getIndex() < B.listEntry()->getIndex();
195    }
196
197    /// Return the distance from this index to the given one.
198    int distance(SlotIndex other) const {
199      return other.getIndex() - getIndex();
200    }
201
202    /// isBlock - Returns true if this is a block boundary slot.
203    bool isBlock() const { return getSlot() == Slot_Block; }
204
205    /// isEarlyClobber - Returns true if this is an early-clobber slot.
206    bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
207
208    /// isRegister - Returns true if this is a normal register use/def slot.
209    /// Note that early-clobber slots may also be used for uses and defs.
210    bool isRegister() const { return getSlot() == Slot_Register; }
211
212    /// isDead - Returns true if this is a dead def kill slot.
213    bool isDead() const { return getSlot() == Slot_Dead; }
214
215    /// Returns the base index for associated with this index. The base index
216    /// is the one associated with the Slot_Block slot for the instruction
217    /// pointed to by this index.
218    SlotIndex getBaseIndex() const {
219      return SlotIndex(listEntry(), Slot_Block);
220    }
221
222    /// Returns the boundary index for associated with this index. The boundary
223    /// index is the one associated with the Slot_Block slot for the instruction
224    /// pointed to by this index.
225    SlotIndex getBoundaryIndex() const {
226      return SlotIndex(listEntry(), Slot_Dead);
227    }
228
229    /// Returns the register use/def slot in the current instruction for a
230    /// normal or early-clobber def.
231    SlotIndex getRegSlot(bool EC = false) const {
232      return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
233    }
234
235    /// Returns the dead def kill slot for the current instruction.
236    SlotIndex getDeadSlot() const {
237      return SlotIndex(listEntry(), Slot_Dead);
238    }
239
240    /// Returns the next slot in the index list. This could be either the
241    /// next slot for the instruction pointed to by this index or, if this
242    /// index is a STORE, the first slot for the next instruction.
243    /// WARNING: This method is considerably more expensive than the methods
244    /// that return specific slots (getUseIndex(), etc). If you can - please
245    /// use one of those methods.
246    SlotIndex getNextSlot() const {
247      Slot s = getSlot();
248      if (s == Slot_Dead) {
249        return SlotIndex(listEntry()->getNextNode(), Slot_Block);
250      }
251      return SlotIndex(listEntry(), s + 1);
252    }
253
254    /// Returns the next index. This is the index corresponding to the this
255    /// index's slot, but for the next instruction.
256    SlotIndex getNextIndex() const {
257      return SlotIndex(listEntry()->getNextNode(), getSlot());
258    }
259
260    /// Returns the previous slot in the index list. This could be either the
261    /// previous slot for the instruction pointed to by this index or, if this
262    /// index is a Slot_Block, the last slot for the previous instruction.
263    /// WARNING: This method is considerably more expensive than the methods
264    /// that return specific slots (getUseIndex(), etc). If you can - please
265    /// use one of those methods.
266    SlotIndex getPrevSlot() const {
267      Slot s = getSlot();
268      if (s == Slot_Block) {
269        return SlotIndex(listEntry()->getPrevNode(), Slot_Dead);
270      }
271      return SlotIndex(listEntry(), s - 1);
272    }
273
274    /// Returns the previous index. This is the index corresponding to this
275    /// index's slot, but for the previous instruction.
276    SlotIndex getPrevIndex() const {
277      return SlotIndex(listEntry()->getPrevNode(), getSlot());
278    }
279
280  };
281
282  template <> struct isPodLike<SlotIndex> { static const bool value = true; };
283
284
285  inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
286    li.print(os);
287    return os;
288  }
289
290  typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
291
292  inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
293    return V < IM.first;
294  }
295
296  inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
297    return IM.first < V;
298  }
299
300  struct Idx2MBBCompare {
301    bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
302      return LHS.first < RHS.first;
303    }
304  };
305
306  /// SlotIndexes pass.
307  ///
308  /// This pass assigns indexes to each instruction.
309  class SlotIndexes : public MachineFunctionPass {
310  private:
311
312    typedef ilist<IndexListEntry> IndexList;
313    IndexList indexList;
314
315    MachineFunction *mf;
316
317    typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
318    Mi2IndexMap mi2iMap;
319
320    /// MBBRanges - Map MBB number to (start, stop) indexes.
321    SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
322
323    /// Idx2MBBMap - Sorted list of pairs of index of first instruction
324    /// and MBB id.
325    SmallVector<IdxMBBPair, 8> idx2MBBMap;
326
327    // IndexListEntry allocator.
328    BumpPtrAllocator ileAllocator;
329
330    IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
331      IndexListEntry *entry =
332        static_cast<IndexListEntry*>(
333          ileAllocator.Allocate(sizeof(IndexListEntry),
334          alignOf<IndexListEntry>()));
335
336      new (entry) IndexListEntry(mi, index);
337
338      return entry;
339    }
340
341    /// Renumber locally after inserting curItr.
342    void renumberIndexes(IndexList::iterator curItr);
343
344  public:
345    static char ID;
346
347    SlotIndexes() : MachineFunctionPass(ID) {
348      initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
349    }
350
351    virtual void getAnalysisUsage(AnalysisUsage &au) const;
352    virtual void releaseMemory();
353
354    virtual bool runOnMachineFunction(MachineFunction &fn);
355
356    /// Dump the indexes.
357    void dump() const;
358
359    /// Renumber the index list, providing space for new instructions.
360    void renumberIndexes();
361
362    /// Returns the zero index for this analysis.
363    SlotIndex getZeroIndex() {
364      assert(indexList.front().getIndex() == 0 && "First index is not 0?");
365      return SlotIndex(&indexList.front(), 0);
366    }
367
368    /// Returns the base index of the last slot in this analysis.
369    SlotIndex getLastIndex() {
370      return SlotIndex(&indexList.back(), 0);
371    }
372
373    /// Returns true if the given machine instr is mapped to an index,
374    /// otherwise returns false.
375    bool hasIndex(const MachineInstr *instr) const {
376      return mi2iMap.count(instr);
377    }
378
379    /// Returns the base index for the given instruction.
380    SlotIndex getInstructionIndex(const MachineInstr *MI) const {
381      // Instructions inside a bundle have the same number as the bundle itself.
382      Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
383      assert(itr != mi2iMap.end() && "Instruction not found in maps.");
384      return itr->second;
385    }
386
387    /// Returns the instruction for the given index, or null if the given
388    /// index has no instruction associated with it.
389    MachineInstr* getInstructionFromIndex(SlotIndex index) const {
390      return index.isValid() ? index.listEntry()->getInstr() : 0;
391    }
392
393    /// Returns the next non-null index.
394    SlotIndex getNextNonNullIndex(SlotIndex index) {
395      IndexList::iterator itr(index.listEntry());
396      ++itr;
397      while (itr != indexList.end() && itr->getInstr() == 0) { ++itr; }
398      return SlotIndex(itr, index.getSlot());
399    }
400
401    /// getIndexBefore - Returns the index of the last indexed instruction
402    /// before MI, or the start index of its basic block.
403    /// MI is not required to have an index.
404    SlotIndex getIndexBefore(const MachineInstr *MI) const {
405      const MachineBasicBlock *MBB = MI->getParent();
406      assert(MBB && "MI must be inserted inna basic block");
407      MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
408      for (;;) {
409        if (I == B)
410          return getMBBStartIdx(MBB);
411        --I;
412        Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
413        if (MapItr != mi2iMap.end())
414          return MapItr->second;
415      }
416    }
417
418    /// getIndexAfter - Returns the index of the first indexed instruction
419    /// after MI, or the end index of its basic block.
420    /// MI is not required to have an index.
421    SlotIndex getIndexAfter(const MachineInstr *MI) const {
422      const MachineBasicBlock *MBB = MI->getParent();
423      assert(MBB && "MI must be inserted inna basic block");
424      MachineBasicBlock::const_iterator I = MI, E = MBB->end();
425      for (;;) {
426        ++I;
427        if (I == E)
428          return getMBBEndIdx(MBB);
429        Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
430        if (MapItr != mi2iMap.end())
431          return MapItr->second;
432      }
433    }
434
435    /// Return the (start,end) range of the given basic block number.
436    const std::pair<SlotIndex, SlotIndex> &
437    getMBBRange(unsigned Num) const {
438      return MBBRanges[Num];
439    }
440
441    /// Return the (start,end) range of the given basic block.
442    const std::pair<SlotIndex, SlotIndex> &
443    getMBBRange(const MachineBasicBlock *MBB) const {
444      return getMBBRange(MBB->getNumber());
445    }
446
447    /// Returns the first index in the given basic block number.
448    SlotIndex getMBBStartIdx(unsigned Num) const {
449      return getMBBRange(Num).first;
450    }
451
452    /// Returns the first index in the given basic block.
453    SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
454      return getMBBRange(mbb).first;
455    }
456
457    /// Returns the last index in the given basic block number.
458    SlotIndex getMBBEndIdx(unsigned Num) const {
459      return getMBBRange(Num).second;
460    }
461
462    /// Returns the last index in the given basic block.
463    SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
464      return getMBBRange(mbb).second;
465    }
466
467    /// Returns the basic block which the given index falls in.
468    MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
469      if (MachineInstr *MI = getInstructionFromIndex(index))
470        return MI->getParent();
471      SmallVectorImpl<IdxMBBPair>::const_iterator I =
472        std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
473      // Take the pair containing the index
474      SmallVectorImpl<IdxMBBPair>::const_iterator J =
475        ((I != idx2MBBMap.end() && I->first > index) ||
476         (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
477
478      assert(J != idx2MBBMap.end() && J->first <= index &&
479             index < getMBBEndIdx(J->second) &&
480             "index does not correspond to an MBB");
481      return J->second;
482    }
483
484    bool findLiveInMBBs(SlotIndex start, SlotIndex end,
485                        SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
486      SmallVectorImpl<IdxMBBPair>::const_iterator itr =
487        std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
488      bool resVal = false;
489
490      while (itr != idx2MBBMap.end()) {
491        if (itr->first >= end)
492          break;
493        mbbs.push_back(itr->second);
494        resVal = true;
495        ++itr;
496      }
497      return resVal;
498    }
499
500    /// Returns the MBB covering the given range, or null if the range covers
501    /// more than one basic block.
502    MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
503
504      assert(start < end && "Backwards ranges not allowed.");
505
506      SmallVectorImpl<IdxMBBPair>::const_iterator itr =
507        std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
508
509      if (itr == idx2MBBMap.end()) {
510        itr = prior(itr);
511        return itr->second;
512      }
513
514      // Check that we don't cross the boundary into this block.
515      if (itr->first < end)
516        return 0;
517
518      itr = prior(itr);
519
520      if (itr->first <= start)
521        return itr->second;
522
523      return 0;
524    }
525
526    /// Insert the given machine instruction into the mapping. Returns the
527    /// assigned index.
528    /// If Late is set and there are null indexes between mi's neighboring
529    /// instructions, create the new index after the null indexes instead of
530    /// before them.
531    SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
532      assert(!mi->isInsideBundle() &&
533             "Instructions inside bundles should use bundle start's slot.");
534      assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
535      // Numbering DBG_VALUE instructions could cause code generation to be
536      // affected by debug information.
537      assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
538
539      assert(mi->getParent() != 0 && "Instr must be added to function.");
540
541      // Get the entries where mi should be inserted.
542      IndexList::iterator prevItr, nextItr;
543      if (Late) {
544        // Insert mi's index immediately before the following instruction.
545        nextItr = getIndexAfter(mi).listEntry();
546        prevItr = prior(nextItr);
547      } else {
548        // Insert mi's index immediately after the preceding instruction.
549        prevItr = getIndexBefore(mi).listEntry();
550        nextItr = llvm::next(prevItr);
551      }
552
553      // Get a number for the new instr, or 0 if there's no room currently.
554      // In the latter case we'll force a renumber later.
555      unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
556      unsigned newNumber = prevItr->getIndex() + dist;
557
558      // Insert a new list entry for mi.
559      IndexList::iterator newItr =
560        indexList.insert(nextItr, createEntry(mi, newNumber));
561
562      // Renumber locally if we need to.
563      if (dist == 0)
564        renumberIndexes(newItr);
565
566      SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
567      mi2iMap.insert(std::make_pair(mi, newIndex));
568      return newIndex;
569    }
570
571    /// Remove the given machine instruction from the mapping.
572    void removeMachineInstrFromMaps(MachineInstr *mi) {
573      // remove index -> MachineInstr and
574      // MachineInstr -> index mappings
575      Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
576      if (mi2iItr != mi2iMap.end()) {
577        IndexListEntry *miEntry(mi2iItr->second.listEntry());
578        assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
579        // FIXME: Eventually we want to actually delete these indexes.
580        miEntry->setInstr(0);
581        mi2iMap.erase(mi2iItr);
582      }
583    }
584
585    /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
586    /// maps used by register allocator.
587    void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
588      Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
589      if (mi2iItr == mi2iMap.end())
590        return;
591      SlotIndex replaceBaseIndex = mi2iItr->second;
592      IndexListEntry *miEntry(replaceBaseIndex.listEntry());
593      assert(miEntry->getInstr() == mi &&
594             "Mismatched instruction in index tables.");
595      miEntry->setInstr(newMI);
596      mi2iMap.erase(mi2iItr);
597      mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
598    }
599
600    /// Add the given MachineBasicBlock into the maps.
601    void insertMBBInMaps(MachineBasicBlock *mbb) {
602      MachineFunction::iterator nextMBB =
603        llvm::next(MachineFunction::iterator(mbb));
604      IndexListEntry *startEntry = createEntry(0, 0);
605      IndexListEntry *stopEntry = createEntry(0, 0);
606      IndexListEntry *nextEntry = 0;
607
608      if (nextMBB == mbb->getParent()->end()) {
609        nextEntry = indexList.end();
610      } else {
611        nextEntry = getMBBStartIdx(nextMBB).listEntry();
612      }
613
614      indexList.insert(nextEntry, startEntry);
615      indexList.insert(nextEntry, stopEntry);
616
617      SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
618      SlotIndex endIdx(nextEntry, SlotIndex::Slot_Block);
619
620      assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
621             "Blocks must be added in order");
622      MBBRanges.push_back(std::make_pair(startIdx, endIdx));
623
624      idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
625
626      renumberIndexes();
627      std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
628    }
629
630  };
631
632
633  // Specialize IntervalMapInfo for half-open slot index intervals.
634  template <typename> struct IntervalMapInfo;
635  template <> struct IntervalMapInfo<SlotIndex> {
636    static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
637      return x < a;
638    }
639    static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
640      return b <= x;
641    }
642    static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
643      return a == b;
644    }
645  };
646
647}
648
649#endif // LLVM_CODEGEN_SLOTINDEXES_H
650