Remove isPod() from DenseMapInfo, splitting it out to its own
[oota-llvm.git] / include / llvm / CodeGen / SlotIndexes.h
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 purpuse 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. The SlotIndex
17 // class does hold a PHI bit, which determines whether the index relates to a
18 // PHI use or def point, or an actual instruction. See the SlotIndex class
19 // description for futher information.
20 //===----------------------------------------------------------------------===//
21
22 #ifndef LLVM_CODEGEN_SLOTINDEXES_H
23 #define LLVM_CODEGEN_SLOTINDEXES_H
24
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/ErrorHandling.h"
32
33 namespace llvm {
34
35   /// This class represents an entry in the slot index list held in the
36   /// SlotIndexes pass. It should not be used directly. See the
37   /// SlotIndex & SlotIndexes classes for the public interface to this
38   /// information.
39   class IndexListEntry {
40   private:
41
42     static const unsigned EMPTY_KEY_INDEX = ~0U & ~3U,
43                           TOMBSTONE_KEY_INDEX = ~0U & ~7U;
44
45     IndexListEntry *next, *prev;
46     MachineInstr *mi;
47     unsigned index;
48
49   protected:
50
51     typedef enum { EMPTY_KEY, TOMBSTONE_KEY } ReservedEntryType;
52
53     // This constructor is only to be used by getEmptyKeyEntry
54     // & getTombstoneKeyEntry. It sets index to the given
55     // value and mi to zero.
56     IndexListEntry(ReservedEntryType r) : mi(0) {
57       switch(r) {
58         case EMPTY_KEY: index = EMPTY_KEY_INDEX; break;
59         case TOMBSTONE_KEY: index = TOMBSTONE_KEY_INDEX; break;
60         default: assert(false && "Invalid value for constructor."); 
61       }
62       next = this;
63       prev = this;
64     }
65
66   public:
67
68     IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {
69       if (index == EMPTY_KEY_INDEX || index == TOMBSTONE_KEY_INDEX) {
70         llvm_report_error("Attempt to create invalid index. "
71                           "Available indexes may have been exhausted?.");
72       }
73     }
74
75     MachineInstr* getInstr() const { return mi; }
76     void setInstr(MachineInstr *mi) {
77       assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
78              "Attempt to modify reserved index.");
79       this->mi = mi;
80     }
81
82     unsigned getIndex() const { return index; }
83     void setIndex(unsigned index) {
84       assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
85              "Attempt to set index to invalid value.");
86       assert(this->index != EMPTY_KEY_INDEX &&
87              this->index != TOMBSTONE_KEY_INDEX &&
88              "Attempt to reset reserved index value.");
89       this->index = index;
90     }
91     
92     IndexListEntry* getNext() { return next; }
93     const IndexListEntry* getNext() const { return next; }
94     void setNext(IndexListEntry *next) {
95       assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
96              "Attempt to modify reserved index.");
97       this->next = next;
98     }
99
100     IndexListEntry* getPrev() { return prev; }
101     const IndexListEntry* getPrev() const { return prev; }
102     void setPrev(IndexListEntry *prev) {
103       assert(index != EMPTY_KEY_INDEX && index != TOMBSTONE_KEY_INDEX &&
104              "Attempt to modify reserved index.");
105       this->prev = prev;
106     }
107
108     // This function returns the index list entry that is to be used for empty
109     // SlotIndex keys.
110     static IndexListEntry* getEmptyKeyEntry();
111
112     // This function returns the index list entry that is to be used for
113     // tombstone SlotIndex keys.
114     static IndexListEntry* getTombstoneKeyEntry();
115   };
116
117   // Specialize PointerLikeTypeTraits for IndexListEntry.
118   template <>
119   class PointerLikeTypeTraits<IndexListEntry*> { 
120   public:
121     static inline void* getAsVoidPointer(IndexListEntry *p) {
122       return p;
123     }
124     static inline IndexListEntry* getFromVoidPointer(void *p) {
125       return static_cast<IndexListEntry*>(p);
126     }
127     enum { NumLowBitsAvailable = 3 };
128   };
129
130   /// SlotIndex - An opaque wrapper around machine indexes.
131   class SlotIndex {
132     friend class SlotIndexes;
133     friend struct DenseMapInfo<SlotIndex>;
134
135   private:
136     static const unsigned PHI_BIT = 1 << 2;
137
138     PointerIntPair<IndexListEntry*, 3, unsigned> lie;
139
140     SlotIndex(IndexListEntry *entry, unsigned phiAndSlot)
141       : lie(entry, phiAndSlot) {
142       assert(entry != 0 && "Attempt to construct index with 0 pointer.");
143     }
144
145     IndexListEntry& entry() const {
146       return *lie.getPointer();
147     }
148
149     int getIndex() const {
150       return entry().getIndex() | getSlot();
151     }
152
153     static inline unsigned getHashValue(const SlotIndex &v) {
154       IndexListEntry *ptrVal = &v.entry();
155       return (unsigned((intptr_t)ptrVal) >> 4) ^
156              (unsigned((intptr_t)ptrVal) >> 9);
157     }
158
159   public:
160
161     // FIXME: Ugh. This is public because LiveIntervalAnalysis is still using it
162     // for some spill weight stuff. Fix that, then make this private.
163     enum Slot { LOAD, USE, DEF, STORE, NUM };
164
165     static inline SlotIndex getEmptyKey() {
166       return SlotIndex(IndexListEntry::getEmptyKeyEntry(), 0);
167     }
168
169     static inline SlotIndex getTombstoneKey() {
170       return SlotIndex(IndexListEntry::getTombstoneKeyEntry(), 0);
171     }
172     
173     /// Construct an invalid index.
174     SlotIndex() : lie(IndexListEntry::getEmptyKeyEntry(), 0) {}
175
176     // Construct a new slot index from the given one, set the phi flag on the
177     // new index to the value of the phi parameter.
178     SlotIndex(const SlotIndex &li, bool phi)
179       : lie(&li.entry(), phi ? PHI_BIT & li.getSlot() : (unsigned)li.getSlot()){
180       assert(lie.getPointer() != 0 &&
181              "Attempt to construct index with 0 pointer.");
182     }
183
184     // Construct a new slot index from the given one, set the phi flag on the
185     // new index to the value of the phi parameter, and the slot to the new slot.
186     SlotIndex(const SlotIndex &li, bool phi, Slot s)
187       : lie(&li.entry(), phi ? PHI_BIT & s : (unsigned)s) {
188       assert(lie.getPointer() != 0 &&
189              "Attempt to construct index with 0 pointer.");
190     }
191
192     /// Returns true if this is a valid index. Invalid indicies do
193     /// not point into an index table, and cannot be compared.
194     bool isValid() const {
195       return (lie.getPointer() != 0) && (lie.getPointer()->getIndex() != 0);
196     }
197
198     /// Print this index to the given raw_ostream.
199     void print(raw_ostream &os) const;
200
201     /// Dump this index to stderr.
202     void dump() const;
203
204     /// Compare two SlotIndex objects for equality.
205     bool operator==(SlotIndex other) const {
206       return getIndex() == other.getIndex();
207     }
208     /// Compare two SlotIndex objects for inequality.
209     bool operator!=(SlotIndex other) const {
210       return getIndex() != other.getIndex(); 
211     }
212    
213     /// Compare two SlotIndex objects. Return true if the first index
214     /// is strictly lower than the second.
215     bool operator<(SlotIndex other) const {
216       return getIndex() < other.getIndex();
217     }
218     /// Compare two SlotIndex objects. Return true if the first index
219     /// is lower than, or equal to, the second.
220     bool operator<=(SlotIndex other) const {
221       return getIndex() <= other.getIndex();
222     }
223
224     /// Compare two SlotIndex objects. Return true if the first index
225     /// is greater than the second.
226     bool operator>(SlotIndex other) const {
227       return getIndex() > other.getIndex();
228     }
229
230     /// Compare two SlotIndex objects. Return true if the first index
231     /// is greater than, or equal to, the second.
232     bool operator>=(SlotIndex other) const {
233       return getIndex() >= other.getIndex();
234     }
235
236     /// Return the distance from this index to the given one.
237     int distance(SlotIndex other) const {
238       return other.getIndex() - getIndex();
239     }
240
241     /// Returns the slot for this SlotIndex.
242     Slot getSlot() const {
243       return static_cast<Slot>(lie.getInt()  & ~PHI_BIT);
244     }
245
246     /// Returns the state of the PHI bit.
247     bool isPHI() const {
248       return lie.getInt() & PHI_BIT;
249     }
250
251     /// Returns the base index for associated with this index. The base index
252     /// is the one associated with the LOAD slot for the instruction pointed to
253     /// by this index.
254     SlotIndex getBaseIndex() const {
255       return getLoadIndex();
256     }
257
258     /// Returns the boundary index for associated with this index. The boundary
259     /// index is the one associated with the LOAD slot for the instruction
260     /// pointed to by this index.
261     SlotIndex getBoundaryIndex() const {
262       return getStoreIndex();
263     }
264
265     /// Returns the index of the LOAD slot for the instruction pointed to by
266     /// this index.
267     SlotIndex getLoadIndex() const {
268       return SlotIndex(&entry(), SlotIndex::LOAD);
269     }    
270
271     /// Returns the index of the USE slot for the instruction pointed to by
272     /// this index.
273     SlotIndex getUseIndex() const {
274       return SlotIndex(&entry(), SlotIndex::USE);
275     }
276
277     /// Returns the index of the DEF slot for the instruction pointed to by
278     /// this index.
279     SlotIndex getDefIndex() const {
280       return SlotIndex(&entry(), SlotIndex::DEF);
281     }
282
283     /// Returns the index of the STORE slot for the instruction pointed to by
284     /// this index.
285     SlotIndex getStoreIndex() const {
286       return SlotIndex(&entry(), SlotIndex::STORE);
287     }    
288
289     /// Returns the next slot in the index list. This could be either the
290     /// next slot for the instruction pointed to by this index or, if this
291     /// index is a STORE, the first slot for the next instruction.
292     /// WARNING: This method is considerably more expensive than the methods
293     /// that return specific slots (getUseIndex(), etc). If you can - please
294     /// use one of those methods.
295     SlotIndex getNextSlot() const {
296       Slot s = getSlot();
297       if (s == SlotIndex::STORE) {
298         return SlotIndex(entry().getNext(), SlotIndex::LOAD);
299       }
300       return SlotIndex(&entry(), s + 1);
301     }
302
303     /// Returns the next index. This is the index corresponding to the this
304     /// index's slot, but for the next instruction.
305     SlotIndex getNextIndex() const {
306       return SlotIndex(entry().getNext(), getSlot());
307     }
308
309     /// Returns the previous slot in the index list. This could be either the
310     /// previous slot for the instruction pointed to by this index or, if this
311     /// index is a LOAD, the last slot for the previous instruction.
312     /// WARNING: This method is considerably more expensive than the methods
313     /// that return specific slots (getUseIndex(), etc). If you can - please
314     /// use one of those methods.
315     SlotIndex getPrevSlot() const {
316       Slot s = getSlot();
317       if (s == SlotIndex::LOAD) {
318         return SlotIndex(entry().getPrev(), SlotIndex::STORE);
319       }
320       return SlotIndex(&entry(), s - 1);
321     }
322
323     /// Returns the previous index. This is the index corresponding to this
324     /// index's slot, but for the previous instruction.
325     SlotIndex getPrevIndex() const {
326       return SlotIndex(entry().getPrev(), getSlot());
327     }
328
329   };
330
331   /// DenseMapInfo specialization for SlotIndex.
332   /// TODO: Not a POD?
333   template <>
334   struct DenseMapInfo<SlotIndex> {
335     static inline SlotIndex getEmptyKey() {
336       return SlotIndex::getEmptyKey();
337     }
338     static inline SlotIndex getTombstoneKey() {
339       return SlotIndex::getTombstoneKey();
340     }
341     static inline unsigned getHashValue(const SlotIndex &v) {
342       return SlotIndex::getHashValue(v);
343     }
344     static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
345       return (LHS == RHS);
346     }
347   };
348
349   inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
350     li.print(os);
351     return os;
352   }
353
354   typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
355
356   inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
357     return V < IM.first;
358   }
359
360   inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
361     return IM.first < V;
362   }
363
364   struct Idx2MBBCompare {
365     bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
366       return LHS.first < RHS.first;
367     }
368   };
369
370   /// SlotIndexes pass.
371   ///
372   /// This pass assigns indexes to each instruction.
373   class SlotIndexes : public MachineFunctionPass {
374   private:
375
376     MachineFunction *mf;
377     IndexListEntry *indexListHead;
378     unsigned functionSize;
379
380     typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
381     Mi2IndexMap mi2iMap;
382
383     /// MBB2IdxMap - The indexes of the first and last instructions in the
384     /// specified basic block.
385     typedef DenseMap<const MachineBasicBlock*,
386                      std::pair<SlotIndex, SlotIndex> > MBB2IdxMap;
387     MBB2IdxMap mbb2IdxMap;
388
389     /// Idx2MBBMap - Sorted list of pairs of index of first instruction
390     /// and MBB id.
391     std::vector<IdxMBBPair> idx2MBBMap;
392
393     typedef DenseMap<const MachineBasicBlock*, SlotIndex> TerminatorGapsMap;
394     TerminatorGapsMap terminatorGaps;
395
396     // IndexListEntry allocator.
397     BumpPtrAllocator ileAllocator;
398
399     IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
400       IndexListEntry *entry =
401         static_cast<IndexListEntry*>(
402           ileAllocator.Allocate(sizeof(IndexListEntry),
403           alignof<IndexListEntry>()));
404
405       new (entry) IndexListEntry(mi, index);
406
407       return entry;
408     }
409
410     void initList() {
411       assert(indexListHead == 0 && "Zero entry non-null at initialisation.");
412       indexListHead = createEntry(0, ~0U);
413       indexListHead->setNext(0);
414       indexListHead->setPrev(indexListHead);
415     }
416
417     void clearList() {
418       indexListHead = 0;
419       ileAllocator.Reset();
420     }
421
422     IndexListEntry* getTail() {
423       assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
424       return indexListHead->getPrev();
425     }
426
427     const IndexListEntry* getTail() const {
428       assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
429       return indexListHead->getPrev();
430     }
431
432     // Returns true if the index list is empty.
433     bool empty() const { return (indexListHead == getTail()); }
434
435     IndexListEntry* front() {
436       assert(!empty() && "front() called on empty index list.");
437       return indexListHead;
438     }
439
440     const IndexListEntry* front() const {
441       assert(!empty() && "front() called on empty index list.");
442       return indexListHead;
443     }
444
445     IndexListEntry* back() {
446       assert(!empty() && "back() called on empty index list.");
447       return getTail()->getPrev();
448     }
449
450     const IndexListEntry* back() const {
451       assert(!empty() && "back() called on empty index list.");
452       return getTail()->getPrev();
453     }
454
455     /// Insert a new entry before itr.
456     void insert(IndexListEntry *itr, IndexListEntry *val) {
457       assert(itr != 0 && "itr should not be null.");
458       IndexListEntry *prev = itr->getPrev();
459       val->setNext(itr);
460       val->setPrev(prev);
461       
462       if (itr != indexListHead) {
463         prev->setNext(val);
464       }
465       else {
466         indexListHead = val;
467       }
468       itr->setPrev(val);
469     }
470
471     /// Push a new entry on to the end of the list.
472     void push_back(IndexListEntry *val) {
473       insert(getTail(), val);
474     }
475
476   public:
477     static char ID;
478
479     SlotIndexes() : MachineFunctionPass(&ID), indexListHead(0) {}
480
481     virtual void getAnalysisUsage(AnalysisUsage &au) const;
482     virtual void releaseMemory(); 
483
484     virtual bool runOnMachineFunction(MachineFunction &fn);
485
486     /// Dump the indexes.
487     void dump() const;
488
489     /// Renumber the index list, providing space for new instructions.
490     void renumberIndexes();
491
492     /// Returns the zero index for this analysis.
493     SlotIndex getZeroIndex() {
494       assert(front()->getIndex() == 0 && "First index is not 0?");
495       return SlotIndex(front(), 0);
496     }
497
498     /// Returns the invalid index marker for this analysis.
499     SlotIndex getInvalidIndex() {
500       return getZeroIndex();
501     }
502
503     /// Returns the distance between the highest and lowest indexes allocated
504     /// so far.
505     unsigned getIndexesLength() const {
506       assert(front()->getIndex() == 0 &&
507              "Initial index isn't zero?");
508
509       return back()->getIndex();
510     }
511
512     /// Returns the number of instructions in the function.
513     unsigned getFunctionSize() const {
514       return functionSize;
515     }
516
517     /// Returns true if the given machine instr is mapped to an index,
518     /// otherwise returns false.
519     bool hasIndex(const MachineInstr *instr) const {
520       return (mi2iMap.find(instr) != mi2iMap.end());
521     }
522
523     /// Returns the base index for the given instruction.
524     SlotIndex getInstructionIndex(const MachineInstr *instr) const {
525       Mi2IndexMap::const_iterator itr = mi2iMap.find(instr);
526       assert(itr != mi2iMap.end() && "Instruction not found in maps.");
527       return itr->second;
528     }
529
530     /// Returns the instruction for the given index, or null if the given
531     /// index has no instruction associated with it.
532     MachineInstr* getInstructionFromIndex(SlotIndex index) const {
533       return index.entry().getInstr();
534     }
535
536     /// Returns the next non-null index.
537     SlotIndex getNextNonNullIndex(SlotIndex index) {
538       SlotIndex nextNonNull = index.getNextIndex();
539
540       while (&nextNonNull.entry() != getTail() &&
541              getInstructionFromIndex(nextNonNull) == 0) {
542         nextNonNull = nextNonNull.getNextIndex();
543       }
544
545       return nextNonNull;
546     }
547
548     /// Returns the first index in the given basic block.
549     SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
550       MBB2IdxMap::const_iterator itr = mbb2IdxMap.find(mbb);
551       assert(itr != mbb2IdxMap.end() && "MBB not found in maps.");
552       return itr->second.first;
553     }
554
555     /// Returns the last index in the given basic block.
556     SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
557       MBB2IdxMap::const_iterator itr = mbb2IdxMap.find(mbb);
558       assert(itr != mbb2IdxMap.end() && "MBB not found in maps.");
559       return itr->second.second;
560     }
561
562     /// Returns the terminator gap for the given index.
563     SlotIndex getTerminatorGap(const MachineBasicBlock *mbb) {
564       TerminatorGapsMap::iterator itr = terminatorGaps.find(mbb);
565       assert(itr != terminatorGaps.end() &&
566              "All MBBs should have terminator gaps in their indexes.");
567       return itr->second;
568     }
569
570     /// Returns the basic block which the given index falls in.
571     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
572       std::vector<IdxMBBPair>::const_iterator I =
573         std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
574       // Take the pair containing the index
575       std::vector<IdxMBBPair>::const_iterator J =
576         ((I != idx2MBBMap.end() && I->first > index) ||
577          (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
578
579       assert(J != idx2MBBMap.end() && J->first <= index &&
580              index <= getMBBEndIdx(J->second) &&
581              "index does not correspond to an MBB");
582       return J->second;
583     }
584
585     bool findLiveInMBBs(SlotIndex start, SlotIndex end,
586                         SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
587       std::vector<IdxMBBPair>::const_iterator itr =
588         std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
589       bool resVal = false;
590
591       while (itr != idx2MBBMap.end()) {
592         if (itr->first >= end)
593           break;
594         mbbs.push_back(itr->second);
595         resVal = true;
596         ++itr;
597       }
598       return resVal;
599     }
600
601     /// Return a list of MBBs that can be reach via any branches or
602     /// fall-throughs.
603     bool findReachableMBBs(SlotIndex start, SlotIndex end,
604                            SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
605       std::vector<IdxMBBPair>::const_iterator itr =
606         std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
607
608       bool resVal = false;
609       while (itr != idx2MBBMap.end()) {
610         if (itr->first > end)
611           break;
612         MachineBasicBlock *mbb = itr->second;
613         if (getMBBEndIdx(mbb) > end)
614           break;
615         for (MachineBasicBlock::succ_iterator si = mbb->succ_begin(),
616              se = mbb->succ_end(); si != se; ++si)
617           mbbs.push_back(*si);
618         resVal = true;
619         ++itr;
620       }
621       return resVal;
622     }
623
624     /// Returns the MBB covering the given range, or null if the range covers
625     /// more than one basic block.
626     MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
627
628       assert(start < end && "Backwards ranges not allowed.");
629
630       std::vector<IdxMBBPair>::const_iterator itr =
631         std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
632
633       if (itr == idx2MBBMap.end()) {
634         itr = prior(itr);
635         return itr->second;
636       }
637
638       // Check that we don't cross the boundary into this block.
639       if (itr->first < end)
640         return 0;
641
642       itr = prior(itr);
643
644       if (itr->first <= start)
645         return itr->second;
646
647       return 0;
648     }
649
650     /// Insert the given machine instruction into the mapping. Returns the
651     /// assigned index.
652     SlotIndex insertMachineInstrInMaps(MachineInstr *mi,
653                                         bool *deferredRenumber = 0) {
654       assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
655
656       MachineBasicBlock *mbb = mi->getParent();
657
658       assert(mbb != 0 && "Instr must be added to function.");
659
660       MBB2IdxMap::iterator mbbRangeItr = mbb2IdxMap.find(mbb);
661
662       assert(mbbRangeItr != mbb2IdxMap.end() &&
663              "Instruction's parent MBB has not been added to SlotIndexes.");
664
665       MachineBasicBlock::iterator miItr(mi);
666       bool needRenumber = false;
667       IndexListEntry *newEntry;
668
669       IndexListEntry *prevEntry;
670       if (miItr == mbb->begin()) {
671         // If mi is at the mbb beginning, get the prev index from the mbb.
672         prevEntry = &mbbRangeItr->second.first.entry();
673       } else {
674         // Otherwise get it from the previous instr.
675         MachineBasicBlock::iterator pItr(prior(miItr));
676         prevEntry = &getInstructionIndex(pItr).entry();
677       }
678
679       // Get next entry from previous entry.
680       IndexListEntry *nextEntry = prevEntry->getNext();
681
682       // Get a number for the new instr, or 0 if there's no room currently.
683       // In the latter case we'll force a renumber later.
684       unsigned dist = nextEntry->getIndex() - prevEntry->getIndex();
685       unsigned newNumber = dist > SlotIndex::NUM ?
686         prevEntry->getIndex() + ((dist >> 1) & ~3U) : 0;
687
688       if (newNumber == 0) {
689         needRenumber = true;
690       }
691
692       // Insert a new list entry for mi.
693       newEntry = createEntry(mi, newNumber);
694       insert(nextEntry, newEntry);
695   
696       SlotIndex newIndex(newEntry, SlotIndex::LOAD);
697       mi2iMap.insert(std::make_pair(mi, newIndex));
698
699       if (miItr == mbb->end()) {
700         // If this is the last instr in the MBB then we need to fix up the bb
701         // range:
702         mbbRangeItr->second.second = SlotIndex(newEntry, SlotIndex::STORE);
703       }
704
705       // Renumber if we need to.
706       if (needRenumber) {
707         if (deferredRenumber == 0)
708           renumberIndexes();
709         else
710           *deferredRenumber = true;
711       }
712
713       return newIndex;
714     }
715
716     /// Add all instructions in the vector to the index list. This method will
717     /// defer renumbering until all instrs have been added, and should be 
718     /// preferred when adding multiple instrs.
719     void insertMachineInstrsInMaps(SmallVectorImpl<MachineInstr*> &mis) {
720       bool renumber = false;
721
722       for (SmallVectorImpl<MachineInstr*>::iterator
723            miItr = mis.begin(), miEnd = mis.end();
724            miItr != miEnd; ++miItr) {
725         insertMachineInstrInMaps(*miItr, &renumber);
726       }
727
728       if (renumber)
729         renumberIndexes();
730     }
731
732
733     /// Remove the given machine instruction from the mapping.
734     void removeMachineInstrFromMaps(MachineInstr *mi) {
735       // remove index -> MachineInstr and
736       // MachineInstr -> index mappings
737       Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
738       if (mi2iItr != mi2iMap.end()) {
739         IndexListEntry *miEntry(&mi2iItr->second.entry());        
740         assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
741         // FIXME: Eventually we want to actually delete these indexes.
742         miEntry->setInstr(0);
743         mi2iMap.erase(mi2iItr);
744       }
745     }
746
747     /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
748     /// maps used by register allocator.
749     void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
750       Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
751       if (mi2iItr == mi2iMap.end())
752         return;
753       SlotIndex replaceBaseIndex = mi2iItr->second;
754       IndexListEntry *miEntry(&replaceBaseIndex.entry());
755       assert(miEntry->getInstr() == mi &&
756              "Mismatched instruction in index tables.");
757       miEntry->setInstr(newMI);
758       mi2iMap.erase(mi2iItr);
759       mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
760     }
761
762   };
763
764
765 }
766
767 #endif // LLVM_CODEGEN_LIVEINDEX_H