1 //===- llvm/CodeGen/SlotIndexes.h - Slot indexes representation -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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 //===----------------------------------------------------------------------===//
19 #ifndef LLVM_CODEGEN_SLOTINDEXES_H
20 #define LLVM_CODEGEN_SLOTINDEXES_H
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/Support/Allocator.h"
32 /// This class represents an entry in the slot index list held in the
33 /// SlotIndexes pass. It should not be used directly. See the
34 /// SlotIndex & SlotIndexes classes for the public interface to this
36 class IndexListEntry {
37 IndexListEntry *next, *prev;
43 IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
45 MachineInstr* getInstr() const { return mi; }
46 void setInstr(MachineInstr *mi) {
50 unsigned getIndex() const { return index; }
51 void setIndex(unsigned index) {
55 IndexListEntry* getNext() { return next; }
56 const IndexListEntry* getNext() const { return next; }
57 void setNext(IndexListEntry *next) {
61 IndexListEntry* getPrev() { return prev; }
62 const IndexListEntry* getPrev() const { return prev; }
63 void setPrev(IndexListEntry *prev) {
68 // Specialize PointerLikeTypeTraits for IndexListEntry.
70 class PointerLikeTypeTraits<IndexListEntry*> {
72 static inline void* getAsVoidPointer(IndexListEntry *p) {
75 static inline IndexListEntry* getFromVoidPointer(void *p) {
76 return static_cast<IndexListEntry*>(p);
78 enum { NumLowBitsAvailable = 3 };
81 /// SlotIndex - An opaque wrapper around machine indexes.
83 friend class SlotIndexes;
84 friend struct DenseMapInfo<SlotIndex>;
86 enum Slot { LOAD, USE, DEF, STORE, NUM };
88 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
90 SlotIndex(IndexListEntry *entry, unsigned slot)
93 IndexListEntry& entry() const {
94 assert(isValid() && "Attempt to compare reserved index.");
95 return *lie.getPointer();
98 int getIndex() const {
99 return entry().getIndex() | getSlot();
102 /// Returns the slot for this SlotIndex.
103 Slot getSlot() const {
104 return static_cast<Slot>(lie.getInt());
107 static inline unsigned getHashValue(const SlotIndex &v) {
108 void *ptrVal = v.lie.getOpaqueValue();
109 return (unsigned((intptr_t)ptrVal)) ^ (unsigned((intptr_t)ptrVal) >> 9);
114 /// The default distance between instructions as returned by distance().
115 /// This may vary as instructions are inserted and removed.
119 static inline SlotIndex getEmptyKey() {
120 return SlotIndex(0, 1);
123 static inline SlotIndex getTombstoneKey() {
124 return SlotIndex(0, 2);
127 /// Construct an invalid index.
128 SlotIndex() : lie(0, 0) {}
130 // Construct a new slot index from the given one, and set the slot.
131 SlotIndex(const SlotIndex &li, Slot s)
132 : lie(&li.entry(), unsigned(s)) {
133 assert(lie.getPointer() != 0 &&
134 "Attempt to construct index with 0 pointer.");
137 /// Returns true if this is a valid index. Invalid indicies do
138 /// not point into an index table, and cannot be compared.
139 bool isValid() const {
140 return lie.getPointer();
143 /// Print this index to the given raw_ostream.
144 void print(raw_ostream &os) const;
146 /// Dump this index to stderr.
149 /// Compare two SlotIndex objects for equality.
150 bool operator==(SlotIndex other) const {
151 return lie == other.lie;
153 /// Compare two SlotIndex objects for inequality.
154 bool operator!=(SlotIndex other) const {
155 return lie != other.lie;
158 /// Compare two SlotIndex objects. Return true if the first index
159 /// is strictly lower than the second.
160 bool operator<(SlotIndex other) const {
161 return getIndex() < other.getIndex();
163 /// Compare two SlotIndex objects. Return true if the first index
164 /// is lower than, or equal to, the second.
165 bool operator<=(SlotIndex other) const {
166 return getIndex() <= other.getIndex();
169 /// Compare two SlotIndex objects. Return true if the first index
170 /// is greater than the second.
171 bool operator>(SlotIndex other) const {
172 return getIndex() > other.getIndex();
175 /// Compare two SlotIndex objects. Return true if the first index
176 /// is greater than, or equal to, the second.
177 bool operator>=(SlotIndex other) const {
178 return getIndex() >= other.getIndex();
181 /// isSameInstr - Return true if A and B refer to the same instruction.
182 static bool isSameInstr(SlotIndex A, SlotIndex B) {
183 return A.lie.getPointer() == B.lie.getPointer();
186 /// Return the distance from this index to the given one.
187 int distance(SlotIndex other) const {
188 return other.getIndex() - getIndex();
191 /// isLoad - Return true if this is a LOAD slot.
192 bool isLoad() const {
193 return getSlot() == LOAD;
196 /// isDef - Return true if this is a DEF slot.
198 return getSlot() == DEF;
201 /// isUse - Return true if this is a USE slot.
203 return getSlot() == USE;
206 /// isStore - Return true if this is a STORE slot.
207 bool isStore() const {
208 return getSlot() == STORE;
211 /// Returns the base index for associated with this index. The base index
212 /// is the one associated with the LOAD slot for the instruction pointed to
214 SlotIndex getBaseIndex() const {
215 return getLoadIndex();
218 /// Returns the boundary index for associated with this index. The boundary
219 /// index is the one associated with the LOAD slot for the instruction
220 /// pointed to by this index.
221 SlotIndex getBoundaryIndex() const {
222 return getStoreIndex();
225 /// Returns the index of the LOAD slot for the instruction pointed to by
227 SlotIndex getLoadIndex() const {
228 return SlotIndex(&entry(), SlotIndex::LOAD);
231 /// Returns the index of the USE slot for the instruction pointed to by
233 SlotIndex getUseIndex() const {
234 return SlotIndex(&entry(), SlotIndex::USE);
237 /// Returns the index of the DEF slot for the instruction pointed to by
239 SlotIndex getDefIndex() const {
240 return SlotIndex(&entry(), SlotIndex::DEF);
243 /// Returns the index of the STORE slot for the instruction pointed to by
245 SlotIndex getStoreIndex() const {
246 return SlotIndex(&entry(), SlotIndex::STORE);
249 /// Returns the next slot in the index list. This could be either the
250 /// next slot for the instruction pointed to by this index or, if this
251 /// index is a STORE, the first slot for the next instruction.
252 /// WARNING: This method is considerably more expensive than the methods
253 /// that return specific slots (getUseIndex(), etc). If you can - please
254 /// use one of those methods.
255 SlotIndex getNextSlot() const {
257 if (s == SlotIndex::STORE) {
258 return SlotIndex(entry().getNext(), SlotIndex::LOAD);
260 return SlotIndex(&entry(), s + 1);
263 /// Returns the next index. This is the index corresponding to the this
264 /// index's slot, but for the next instruction.
265 SlotIndex getNextIndex() const {
266 return SlotIndex(entry().getNext(), getSlot());
269 /// Returns the previous slot in the index list. This could be either the
270 /// previous slot for the instruction pointed to by this index or, if this
271 /// index is a LOAD, the last slot for the previous instruction.
272 /// WARNING: This method is considerably more expensive than the methods
273 /// that return specific slots (getUseIndex(), etc). If you can - please
274 /// use one of those methods.
275 SlotIndex getPrevSlot() const {
277 if (s == SlotIndex::LOAD) {
278 return SlotIndex(entry().getPrev(), SlotIndex::STORE);
280 return SlotIndex(&entry(), s - 1);
283 /// Returns the previous index. This is the index corresponding to this
284 /// index's slot, but for the previous instruction.
285 SlotIndex getPrevIndex() const {
286 return SlotIndex(entry().getPrev(), getSlot());
291 /// DenseMapInfo specialization for SlotIndex.
293 struct DenseMapInfo<SlotIndex> {
294 static inline SlotIndex getEmptyKey() {
295 return SlotIndex::getEmptyKey();
297 static inline SlotIndex getTombstoneKey() {
298 return SlotIndex::getTombstoneKey();
300 static inline unsigned getHashValue(const SlotIndex &v) {
301 return SlotIndex::getHashValue(v);
303 static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
308 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
311 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
316 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
318 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
322 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
326 struct Idx2MBBCompare {
327 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
328 return LHS.first < RHS.first;
332 /// SlotIndexes pass.
334 /// This pass assigns indexes to each instruction.
335 class SlotIndexes : public MachineFunctionPass {
339 IndexListEntry *indexListHead;
340 unsigned functionSize;
342 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
345 /// MBBRanges - Map MBB number to (start, stop) indexes.
346 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
348 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
350 SmallVector<IdxMBBPair, 8> idx2MBBMap;
352 // IndexListEntry allocator.
353 BumpPtrAllocator ileAllocator;
355 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
356 IndexListEntry *entry =
357 static_cast<IndexListEntry*>(
358 ileAllocator.Allocate(sizeof(IndexListEntry),
359 alignOf<IndexListEntry>()));
361 new (entry) IndexListEntry(mi, index);
367 assert(indexListHead == 0 && "Zero entry non-null at initialisation.");
368 indexListHead = createEntry(0, ~0U);
369 indexListHead->setNext(0);
370 indexListHead->setPrev(indexListHead);
375 ileAllocator.Reset();
378 IndexListEntry* getTail() {
379 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
380 return indexListHead->getPrev();
383 const IndexListEntry* getTail() const {
384 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
385 return indexListHead->getPrev();
388 // Returns true if the index list is empty.
389 bool empty() const { return (indexListHead == getTail()); }
391 IndexListEntry* front() {
392 assert(!empty() && "front() called on empty index list.");
393 return indexListHead;
396 const IndexListEntry* front() const {
397 assert(!empty() && "front() called on empty index list.");
398 return indexListHead;
401 IndexListEntry* back() {
402 assert(!empty() && "back() called on empty index list.");
403 return getTail()->getPrev();
406 const IndexListEntry* back() const {
407 assert(!empty() && "back() called on empty index list.");
408 return getTail()->getPrev();
411 /// Insert a new entry before itr.
412 void insert(IndexListEntry *itr, IndexListEntry *val) {
413 assert(itr != 0 && "itr should not be null.");
414 IndexListEntry *prev = itr->getPrev();
418 if (itr != indexListHead) {
427 /// Push a new entry on to the end of the list.
428 void push_back(IndexListEntry *val) {
429 insert(getTail(), val);
432 /// Renumber locally after inserting newEntry.
433 void renumberIndexes(IndexListEntry *newEntry);
438 SlotIndexes() : MachineFunctionPass(ID), indexListHead(0) {
439 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
442 virtual void getAnalysisUsage(AnalysisUsage &au) const;
443 virtual void releaseMemory();
445 virtual bool runOnMachineFunction(MachineFunction &fn);
447 /// Dump the indexes.
450 /// Renumber the index list, providing space for new instructions.
451 void renumberIndexes();
453 /// Returns the zero index for this analysis.
454 SlotIndex getZeroIndex() {
455 assert(front()->getIndex() == 0 && "First index is not 0?");
456 return SlotIndex(front(), 0);
459 /// Returns the base index of the last slot in this analysis.
460 SlotIndex getLastIndex() {
461 return SlotIndex(back(), 0);
464 /// Returns the invalid index marker for this analysis.
465 SlotIndex getInvalidIndex() {
466 return getZeroIndex();
469 /// Returns the distance between the highest and lowest indexes allocated
471 unsigned getIndexesLength() const {
472 assert(front()->getIndex() == 0 &&
473 "Initial index isn't zero?");
475 return back()->getIndex();
478 /// Returns the number of instructions in the function.
479 unsigned getFunctionSize() const {
483 /// Returns true if the given machine instr is mapped to an index,
484 /// otherwise returns false.
485 bool hasIndex(const MachineInstr *instr) const {
486 return (mi2iMap.find(instr) != mi2iMap.end());
489 /// Returns the base index for the given instruction.
490 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
491 Mi2IndexMap::const_iterator itr = mi2iMap.find(instr);
492 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
496 /// Returns the instruction for the given index, or null if the given
497 /// index has no instruction associated with it.
498 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
499 return index.isValid() ? index.entry().getInstr() : 0;
502 /// Returns the next non-null index.
503 SlotIndex getNextNonNullIndex(SlotIndex index) {
504 SlotIndex nextNonNull = index.getNextIndex();
506 while (&nextNonNull.entry() != getTail() &&
507 getInstructionFromIndex(nextNonNull) == 0) {
508 nextNonNull = nextNonNull.getNextIndex();
514 /// getIndexBefore - Returns the index of the last indexed instruction
515 /// before MI, or the the start index of its basic block.
516 /// MI is not required to have an index.
517 SlotIndex getIndexBefore(const MachineInstr *MI) const {
518 const MachineBasicBlock *MBB = MI->getParent();
519 assert(MBB && "MI must be inserted inna basic block");
520 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
523 return getMBBStartIdx(MBB);
525 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
526 if (MapItr != mi2iMap.end())
527 return MapItr->second;
531 /// getIndexAfter - Returns the index of the first indexed instruction
532 /// after MI, or the end index of its basic block.
533 /// MI is not required to have an index.
534 SlotIndex getIndexAfter(const MachineInstr *MI) const {
535 const MachineBasicBlock *MBB = MI->getParent();
536 assert(MBB && "MI must be inserted inna basic block");
537 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
541 return getMBBEndIdx(MBB);
542 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
543 if (MapItr != mi2iMap.end())
544 return MapItr->second;
548 /// Return the (start,end) range of the given basic block number.
549 const std::pair<SlotIndex, SlotIndex> &
550 getMBBRange(unsigned Num) const {
551 return MBBRanges[Num];
554 /// Return the (start,end) range of the given basic block.
555 const std::pair<SlotIndex, SlotIndex> &
556 getMBBRange(const MachineBasicBlock *MBB) const {
557 return getMBBRange(MBB->getNumber());
560 /// Returns the first index in the given basic block number.
561 SlotIndex getMBBStartIdx(unsigned Num) const {
562 return getMBBRange(Num).first;
565 /// Returns the first index in the given basic block.
566 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
567 return getMBBRange(mbb).first;
570 /// Returns the last index in the given basic block number.
571 SlotIndex getMBBEndIdx(unsigned Num) const {
572 return getMBBRange(Num).second;
575 /// Returns the last index in the given basic block.
576 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
577 return getMBBRange(mbb).second;
580 /// Returns the basic block which the given index falls in.
581 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
582 if (MachineInstr *MI = getInstructionFromIndex(index))
583 return MI->getParent();
584 SmallVectorImpl<IdxMBBPair>::const_iterator I =
585 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
586 // Take the pair containing the index
587 SmallVectorImpl<IdxMBBPair>::const_iterator J =
588 ((I != idx2MBBMap.end() && I->first > index) ||
589 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
591 assert(J != idx2MBBMap.end() && J->first <= index &&
592 index < getMBBEndIdx(J->second) &&
593 "index does not correspond to an MBB");
597 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
598 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
599 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
600 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
603 while (itr != idx2MBBMap.end()) {
604 if (itr->first >= end)
606 mbbs.push_back(itr->second);
613 /// Returns the MBB covering the given range, or null if the range covers
614 /// more than one basic block.
615 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
617 assert(start < end && "Backwards ranges not allowed.");
619 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
620 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
622 if (itr == idx2MBBMap.end()) {
627 // Check that we don't cross the boundary into this block.
628 if (itr->first < end)
633 if (itr->first <= start)
639 /// Insert the given machine instruction into the mapping. Returns the
641 /// If Late is set and there are null indexes between mi's neighboring
642 /// instructions, create the new index after the null indexes instead of
644 SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
645 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
646 // Numbering DBG_VALUE instructions could cause code generation to be
647 // affected by debug information.
648 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
650 MachineBasicBlock *mbb = mi->getParent();
652 assert(mbb != 0 && "Instr must be added to function.");
654 // Get the entries where mi should be inserted.
655 IndexListEntry *prevEntry, *nextEntry;
657 // Insert mi's index immediately before the following instruction.
658 nextEntry = &getIndexAfter(mi).entry();
659 prevEntry = nextEntry->getPrev();
661 // Insert mi's index immediately after the preceeding instruction.
662 prevEntry = &getIndexBefore(mi).entry();
663 nextEntry = prevEntry->getNext();
666 // Get a number for the new instr, or 0 if there's no room currently.
667 // In the latter case we'll force a renumber later.
668 unsigned dist = ((nextEntry->getIndex() - prevEntry->getIndex())/2) & ~3u;
669 unsigned newNumber = prevEntry->getIndex() + dist;
671 // Insert a new list entry for mi.
672 IndexListEntry *newEntry = createEntry(mi, newNumber);
673 insert(nextEntry, newEntry);
675 // Renumber locally if we need to.
677 renumberIndexes(newEntry);
679 SlotIndex newIndex(newEntry, SlotIndex::LOAD);
680 mi2iMap.insert(std::make_pair(mi, newIndex));
684 /// Remove the given machine instruction from the mapping.
685 void removeMachineInstrFromMaps(MachineInstr *mi) {
686 // remove index -> MachineInstr and
687 // MachineInstr -> index mappings
688 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
689 if (mi2iItr != mi2iMap.end()) {
690 IndexListEntry *miEntry(&mi2iItr->second.entry());
691 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
692 // FIXME: Eventually we want to actually delete these indexes.
693 miEntry->setInstr(0);
694 mi2iMap.erase(mi2iItr);
698 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
699 /// maps used by register allocator.
700 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
701 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
702 if (mi2iItr == mi2iMap.end())
704 SlotIndex replaceBaseIndex = mi2iItr->second;
705 IndexListEntry *miEntry(&replaceBaseIndex.entry());
706 assert(miEntry->getInstr() == mi &&
707 "Mismatched instruction in index tables.");
708 miEntry->setInstr(newMI);
709 mi2iMap.erase(mi2iItr);
710 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
713 /// Add the given MachineBasicBlock into the maps.
714 void insertMBBInMaps(MachineBasicBlock *mbb) {
715 MachineFunction::iterator nextMBB =
716 llvm::next(MachineFunction::iterator(mbb));
717 IndexListEntry *startEntry = createEntry(0, 0);
718 IndexListEntry *stopEntry = createEntry(0, 0);
719 IndexListEntry *nextEntry = 0;
721 if (nextMBB == mbb->getParent()->end()) {
722 nextEntry = getTail();
724 nextEntry = &getMBBStartIdx(nextMBB).entry();
727 insert(nextEntry, startEntry);
728 insert(nextEntry, stopEntry);
730 SlotIndex startIdx(startEntry, SlotIndex::LOAD);
731 SlotIndex endIdx(nextEntry, SlotIndex::LOAD);
733 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
734 "Blocks must be added in order");
735 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
737 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
740 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
746 // Specialize IntervalMapInfo for half-open slot index intervals.
747 template <typename> struct IntervalMapInfo;
748 template <> struct IntervalMapInfo<SlotIndex> {
749 static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
752 static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
755 static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
762 #endif // LLVM_CODEGEN_LIVEINDEX_H