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 /// Return the distance from this index to the given one.
182 int distance(SlotIndex other) const {
183 return other.getIndex() - getIndex();
186 /// isLoad - Return true if this is a LOAD slot.
187 bool isLoad() const {
188 return getSlot() == LOAD;
191 /// isDef - Return true if this is a DEF slot.
193 return getSlot() == DEF;
196 /// isUse - Return true if this is a USE slot.
198 return getSlot() == USE;
201 /// isStore - Return true if this is a STORE slot.
202 bool isStore() const {
203 return getSlot() == STORE;
206 /// Returns the base index for associated with this index. The base index
207 /// is the one associated with the LOAD slot for the instruction pointed to
209 SlotIndex getBaseIndex() const {
210 return getLoadIndex();
213 /// Returns the boundary index for associated with this index. The boundary
214 /// index is the one associated with the LOAD slot for the instruction
215 /// pointed to by this index.
216 SlotIndex getBoundaryIndex() const {
217 return getStoreIndex();
220 /// Returns the index of the LOAD slot for the instruction pointed to by
222 SlotIndex getLoadIndex() const {
223 return SlotIndex(&entry(), SlotIndex::LOAD);
226 /// Returns the index of the USE slot for the instruction pointed to by
228 SlotIndex getUseIndex() const {
229 return SlotIndex(&entry(), SlotIndex::USE);
232 /// Returns the index of the DEF slot for the instruction pointed to by
234 SlotIndex getDefIndex() const {
235 return SlotIndex(&entry(), SlotIndex::DEF);
238 /// Returns the index of the STORE slot for the instruction pointed to by
240 SlotIndex getStoreIndex() const {
241 return SlotIndex(&entry(), SlotIndex::STORE);
244 /// Returns the next slot in the index list. This could be either the
245 /// next slot for the instruction pointed to by this index or, if this
246 /// index is a STORE, the first slot for the next instruction.
247 /// WARNING: This method is considerably more expensive than the methods
248 /// that return specific slots (getUseIndex(), etc). If you can - please
249 /// use one of those methods.
250 SlotIndex getNextSlot() const {
252 if (s == SlotIndex::STORE) {
253 return SlotIndex(entry().getNext(), SlotIndex::LOAD);
255 return SlotIndex(&entry(), s + 1);
258 /// Returns the next index. This is the index corresponding to the this
259 /// index's slot, but for the next instruction.
260 SlotIndex getNextIndex() const {
261 return SlotIndex(entry().getNext(), getSlot());
264 /// Returns the previous slot in the index list. This could be either the
265 /// previous slot for the instruction pointed to by this index or, if this
266 /// index is a LOAD, the last slot for the previous instruction.
267 /// WARNING: This method is considerably more expensive than the methods
268 /// that return specific slots (getUseIndex(), etc). If you can - please
269 /// use one of those methods.
270 SlotIndex getPrevSlot() const {
272 if (s == SlotIndex::LOAD) {
273 return SlotIndex(entry().getPrev(), SlotIndex::STORE);
275 return SlotIndex(&entry(), s - 1);
278 /// Returns the previous index. This is the index corresponding to this
279 /// index's slot, but for the previous instruction.
280 SlotIndex getPrevIndex() const {
281 return SlotIndex(entry().getPrev(), getSlot());
286 /// DenseMapInfo specialization for SlotIndex.
288 struct DenseMapInfo<SlotIndex> {
289 static inline SlotIndex getEmptyKey() {
290 return SlotIndex::getEmptyKey();
292 static inline SlotIndex getTombstoneKey() {
293 return SlotIndex::getTombstoneKey();
295 static inline unsigned getHashValue(const SlotIndex &v) {
296 return SlotIndex::getHashValue(v);
298 static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
303 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
306 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
311 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
313 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
317 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
321 struct Idx2MBBCompare {
322 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
323 return LHS.first < RHS.first;
327 /// SlotIndexes pass.
329 /// This pass assigns indexes to each instruction.
330 class SlotIndexes : public MachineFunctionPass {
334 IndexListEntry *indexListHead;
335 unsigned functionSize;
337 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
340 /// MBB2IdxMap - The indexes of the first and last instructions in the
341 /// specified basic block.
342 typedef DenseMap<const MachineBasicBlock*,
343 std::pair<SlotIndex, SlotIndex> > MBB2IdxMap;
344 MBB2IdxMap mbb2IdxMap;
346 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
348 std::vector<IdxMBBPair> idx2MBBMap;
350 // IndexListEntry allocator.
351 BumpPtrAllocator ileAllocator;
353 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
354 IndexListEntry *entry =
355 static_cast<IndexListEntry*>(
356 ileAllocator.Allocate(sizeof(IndexListEntry),
357 alignOf<IndexListEntry>()));
359 new (entry) IndexListEntry(mi, index);
365 assert(indexListHead == 0 && "Zero entry non-null at initialisation.");
366 indexListHead = createEntry(0, ~0U);
367 indexListHead->setNext(0);
368 indexListHead->setPrev(indexListHead);
373 ileAllocator.Reset();
376 IndexListEntry* getTail() {
377 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
378 return indexListHead->getPrev();
381 const IndexListEntry* getTail() const {
382 assert(indexListHead != 0 && "Call to getTail on uninitialized list.");
383 return indexListHead->getPrev();
386 // Returns true if the index list is empty.
387 bool empty() const { return (indexListHead == getTail()); }
389 IndexListEntry* front() {
390 assert(!empty() && "front() called on empty index list.");
391 return indexListHead;
394 const IndexListEntry* front() const {
395 assert(!empty() && "front() called on empty index list.");
396 return indexListHead;
399 IndexListEntry* back() {
400 assert(!empty() && "back() called on empty index list.");
401 return getTail()->getPrev();
404 const IndexListEntry* back() const {
405 assert(!empty() && "back() called on empty index list.");
406 return getTail()->getPrev();
409 /// Insert a new entry before itr.
410 void insert(IndexListEntry *itr, IndexListEntry *val) {
411 assert(itr != 0 && "itr should not be null.");
412 IndexListEntry *prev = itr->getPrev();
416 if (itr != indexListHead) {
425 /// Push a new entry on to the end of the list.
426 void push_back(IndexListEntry *val) {
427 insert(getTail(), val);
430 /// Renumber locally after inserting newEntry.
431 void renumberIndexes(IndexListEntry *newEntry);
436 SlotIndexes() : MachineFunctionPass(ID), indexListHead(0) {
437 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
440 virtual void getAnalysisUsage(AnalysisUsage &au) const;
441 virtual void releaseMemory();
443 virtual bool runOnMachineFunction(MachineFunction &fn);
445 /// Dump the indexes.
448 /// Renumber the index list, providing space for new instructions.
449 void renumberIndexes();
451 /// Returns the zero index for this analysis.
452 SlotIndex getZeroIndex() {
453 assert(front()->getIndex() == 0 && "First index is not 0?");
454 return SlotIndex(front(), 0);
457 /// Returns the base index of the last slot in this analysis.
458 SlotIndex getLastIndex() {
459 return SlotIndex(back(), 0);
462 /// Returns the invalid index marker for this analysis.
463 SlotIndex getInvalidIndex() {
464 return getZeroIndex();
467 /// Returns the distance between the highest and lowest indexes allocated
469 unsigned getIndexesLength() const {
470 assert(front()->getIndex() == 0 &&
471 "Initial index isn't zero?");
473 return back()->getIndex();
476 /// Returns the number of instructions in the function.
477 unsigned getFunctionSize() const {
481 /// Returns true if the given machine instr is mapped to an index,
482 /// otherwise returns false.
483 bool hasIndex(const MachineInstr *instr) const {
484 return (mi2iMap.find(instr) != mi2iMap.end());
487 /// Returns the base index for the given instruction.
488 SlotIndex getInstructionIndex(const MachineInstr *instr) const {
489 Mi2IndexMap::const_iterator itr = mi2iMap.find(instr);
490 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
494 /// Returns the instruction for the given index, or null if the given
495 /// index has no instruction associated with it.
496 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
497 return index.isValid() ? index.entry().getInstr() : 0;
500 /// Returns the next non-null index.
501 SlotIndex getNextNonNullIndex(SlotIndex index) {
502 SlotIndex nextNonNull = index.getNextIndex();
504 while (&nextNonNull.entry() != getTail() &&
505 getInstructionFromIndex(nextNonNull) == 0) {
506 nextNonNull = nextNonNull.getNextIndex();
512 /// Return the (start,end) range of the given basic block.
513 const std::pair<SlotIndex, SlotIndex> &
514 getMBBRange(const MachineBasicBlock *mbb) const {
515 MBB2IdxMap::const_iterator itr = mbb2IdxMap.find(mbb);
516 assert(itr != mbb2IdxMap.end() && "MBB not found in maps.");
520 /// Returns the first index in the given basic block.
521 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
522 return getMBBRange(mbb).first;
525 /// Returns the last index in the given basic block.
526 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
527 return getMBBRange(mbb).second;
530 /// Returns the basic block which the given index falls in.
531 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
532 std::vector<IdxMBBPair>::const_iterator I =
533 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
534 // Take the pair containing the index
535 std::vector<IdxMBBPair>::const_iterator J =
536 ((I != idx2MBBMap.end() && I->first > index) ||
537 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
539 assert(J != idx2MBBMap.end() && J->first <= index &&
540 index < getMBBEndIdx(J->second) &&
541 "index does not correspond to an MBB");
545 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
546 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
547 std::vector<IdxMBBPair>::const_iterator itr =
548 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
551 while (itr != idx2MBBMap.end()) {
552 if (itr->first >= end)
554 mbbs.push_back(itr->second);
561 /// Returns the MBB covering the given range, or null if the range covers
562 /// more than one basic block.
563 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
565 assert(start < end && "Backwards ranges not allowed.");
567 std::vector<IdxMBBPair>::const_iterator itr =
568 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
570 if (itr == idx2MBBMap.end()) {
575 // Check that we don't cross the boundary into this block.
576 if (itr->first < end)
581 if (itr->first <= start)
587 /// Insert the given machine instruction into the mapping. Returns the
589 SlotIndex insertMachineInstrInMaps(MachineInstr *mi) {
590 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
591 // Numbering DBG_VALUE instructions could cause code generation to be
592 // affected by debug information.
593 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
595 MachineBasicBlock *mbb = mi->getParent();
597 assert(mbb != 0 && "Instr must be added to function.");
599 MBB2IdxMap::iterator mbbRangeItr = mbb2IdxMap.find(mbb);
601 assert(mbbRangeItr != mbb2IdxMap.end() &&
602 "Instruction's parent MBB has not been added to SlotIndexes.");
604 MachineBasicBlock::iterator miItr(mi);
605 IndexListEntry *newEntry;
606 // Get previous index, considering that not all instructions are indexed.
607 IndexListEntry *prevEntry;
609 // If mi is at the mbb beginning, get the prev index from the mbb.
610 if (miItr == mbb->begin()) {
611 prevEntry = &mbbRangeItr->second.first.entry();
614 // Otherwise rewind until we find a mapped instruction.
615 Mi2IndexMap::const_iterator itr = mi2iMap.find(--miItr);
616 if (itr != mi2iMap.end()) {
617 prevEntry = &itr->second.entry();
622 // Get next entry from previous entry.
623 IndexListEntry *nextEntry = prevEntry->getNext();
625 // Get a number for the new instr, or 0 if there's no room currently.
626 // In the latter case we'll force a renumber later.
627 unsigned dist = ((nextEntry->getIndex() - prevEntry->getIndex())/2) & ~3u;
628 unsigned newNumber = prevEntry->getIndex() + dist;
630 // Insert a new list entry for mi.
631 newEntry = createEntry(mi, newNumber);
632 insert(nextEntry, newEntry);
634 // Renumber locally if we need to.
636 renumberIndexes(newEntry);
638 SlotIndex newIndex(newEntry, SlotIndex::LOAD);
639 mi2iMap.insert(std::make_pair(mi, newIndex));
643 /// Remove the given machine instruction from the mapping.
644 void removeMachineInstrFromMaps(MachineInstr *mi) {
645 // remove index -> MachineInstr and
646 // MachineInstr -> index mappings
647 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
648 if (mi2iItr != mi2iMap.end()) {
649 IndexListEntry *miEntry(&mi2iItr->second.entry());
650 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
651 // FIXME: Eventually we want to actually delete these indexes.
652 miEntry->setInstr(0);
653 mi2iMap.erase(mi2iItr);
657 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
658 /// maps used by register allocator.
659 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
660 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
661 if (mi2iItr == mi2iMap.end())
663 SlotIndex replaceBaseIndex = mi2iItr->second;
664 IndexListEntry *miEntry(&replaceBaseIndex.entry());
665 assert(miEntry->getInstr() == mi &&
666 "Mismatched instruction in index tables.");
667 miEntry->setInstr(newMI);
668 mi2iMap.erase(mi2iItr);
669 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
672 /// Add the given MachineBasicBlock into the maps.
673 void insertMBBInMaps(MachineBasicBlock *mbb) {
674 MachineFunction::iterator nextMBB =
675 llvm::next(MachineFunction::iterator(mbb));
676 IndexListEntry *startEntry = createEntry(0, 0);
677 IndexListEntry *stopEntry = createEntry(0, 0);
678 IndexListEntry *nextEntry = 0;
680 if (nextMBB == mbb->getParent()->end()) {
681 nextEntry = getTail();
683 nextEntry = &getMBBStartIdx(nextMBB).entry();
686 insert(nextEntry, startEntry);
687 insert(nextEntry, stopEntry);
689 SlotIndex startIdx(startEntry, SlotIndex::LOAD);
690 SlotIndex endIdx(nextEntry, SlotIndex::LOAD);
693 std::make_pair(mbb, std::make_pair(startIdx, endIdx)));
695 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
697 if (MachineFunction::iterator(mbb) != mbb->getParent()->begin()) {
698 // Have to update the end index of the previous block.
699 MachineBasicBlock *priorMBB =
700 llvm::prior(MachineFunction::iterator(mbb));
701 mbb2IdxMap[priorMBB].second = startIdx;
705 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
712 // Specialize IntervalMapInfo for half-open slot index intervals.
713 template <typename> struct IntervalMapInfo;
714 template <> struct IntervalMapInfo<SlotIndex> {
715 static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
718 static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
721 static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
728 #endif // LLVM_CODEGEN_LIVEINDEX_H