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