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 purpose 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/MachineInstrBundle.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/ilist.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/Support/Allocator.h"
33 /// This class represents an entry in the slot index list held in the
34 /// SlotIndexes pass. It should not be used directly. See the
35 /// SlotIndex & SlotIndexes classes for the public interface to this
37 class IndexListEntry : public ilist_node<IndexListEntry> {
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) {
58 struct ilist_traits<IndexListEntry> : public ilist_default_traits<IndexListEntry> {
60 mutable ilist_half_node<IndexListEntry> Sentinel;
62 IndexListEntry *createSentinel() const {
63 return static_cast<IndexListEntry*>(&Sentinel);
65 void destroySentinel(IndexListEntry *) const {}
67 IndexListEntry *provideInitialHead() const { return createSentinel(); }
68 IndexListEntry *ensureHead(IndexListEntry*) const { return createSentinel(); }
69 static void noteHead(IndexListEntry*, IndexListEntry*) {}
70 void deleteNode(IndexListEntry *N) {}
73 void createNode(const IndexListEntry &);
76 /// SlotIndex - An opaque wrapper around machine indexes.
78 friend class SlotIndexes;
79 friend struct DenseMapInfo<SlotIndex>;
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.
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.
93 /// Normal register use/def slot. Normal instructions kill and define
94 /// register live ranges at this slot.
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
105 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
107 SlotIndex(IndexListEntry *entry, unsigned slot)
108 : lie(entry, slot) {}
110 IndexListEntry* listEntry() const {
111 assert(isValid() && "Attempt to compare reserved index.");
112 return lie.getPointer();
115 int getIndex() const {
116 return listEntry()->getIndex() | getSlot();
119 /// Returns the slot for this SlotIndex.
120 Slot getSlot() const {
121 return static_cast<Slot>(lie.getInt());
124 static inline unsigned getHashValue(const SlotIndex &v) {
125 void *ptrVal = v.lie.getOpaqueValue();
126 return (unsigned((intptr_t)ptrVal)) ^ (unsigned((intptr_t)ptrVal) >> 9);
131 /// The default distance between instructions as returned by distance().
132 /// This may vary as instructions are inserted and removed.
133 InstrDist = 4 * Slot_Count
136 static inline SlotIndex getEmptyKey() {
137 return SlotIndex(0, 1);
140 static inline SlotIndex getTombstoneKey() {
141 return SlotIndex(0, 2);
144 /// Construct an invalid index.
145 SlotIndex() : lie(0, 0) {}
147 // Construct a new slot index from the given one, and set the slot.
148 SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
149 assert(lie.getPointer() != 0 &&
150 "Attempt to construct index with 0 pointer.");
153 /// Returns true if this is a valid index. Invalid indicies do
154 /// not point into an index table, and cannot be compared.
155 bool isValid() const {
156 return lie.getPointer();
159 /// Return true for a valid index.
160 operator bool() const { return isValid(); }
162 /// Print this index to the given raw_ostream.
163 void print(raw_ostream &os) const;
165 /// Dump this index to stderr.
168 /// Compare two SlotIndex objects for equality.
169 bool operator==(SlotIndex other) const {
170 return lie == other.lie;
172 /// Compare two SlotIndex objects for inequality.
173 bool operator!=(SlotIndex other) const {
174 return lie != other.lie;
177 /// Compare two SlotIndex objects. Return true if the first index
178 /// is strictly lower than the second.
179 bool operator<(SlotIndex other) const {
180 return getIndex() < other.getIndex();
182 /// Compare two SlotIndex objects. Return true if the first index
183 /// is lower than, or equal to, the second.
184 bool operator<=(SlotIndex other) const {
185 return getIndex() <= other.getIndex();
188 /// Compare two SlotIndex objects. Return true if the first index
189 /// is greater than the second.
190 bool operator>(SlotIndex other) const {
191 return getIndex() > other.getIndex();
194 /// Compare two SlotIndex objects. Return true if the first index
195 /// is greater than, or equal to, the second.
196 bool operator>=(SlotIndex other) const {
197 return getIndex() >= other.getIndex();
200 /// isSameInstr - Return true if A and B refer to the same instruction.
201 static bool isSameInstr(SlotIndex A, SlotIndex B) {
202 return A.lie.getPointer() == B.lie.getPointer();
205 /// isEarlierInstr - Return true if A refers to an instruction earlier than
206 /// B. This is equivalent to A < B && !isSameInstr(A, B).
207 static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
208 return A.listEntry()->getIndex() < B.listEntry()->getIndex();
211 /// Return the distance from this index to the given one.
212 int distance(SlotIndex other) const {
213 return other.getIndex() - getIndex();
216 /// isBlock - Returns true if this is a block boundary slot.
217 bool isBlock() const { return getSlot() == Slot_Block; }
219 /// isEarlyClobber - Returns true if this is an early-clobber slot.
220 bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
222 /// isRegister - Returns true if this is a normal register use/def slot.
223 /// Note that early-clobber slots may also be used for uses and defs.
224 bool isRegister() const { return getSlot() == Slot_Register; }
226 /// isDead - Returns true if this is a dead def kill slot.
227 bool isDead() const { return getSlot() == Slot_Dead; }
229 /// Returns the base index for associated with this index. The base index
230 /// is the one associated with the Slot_Block slot for the instruction
231 /// pointed to by this index.
232 SlotIndex getBaseIndex() const {
233 return SlotIndex(listEntry(), Slot_Block);
236 /// Returns the boundary index for associated with this index. The boundary
237 /// index is the one associated with the Slot_Block slot for the instruction
238 /// pointed to by this index.
239 SlotIndex getBoundaryIndex() const {
240 return SlotIndex(listEntry(), Slot_Dead);
243 /// Returns the register use/def slot in the current instruction for a
244 /// normal or early-clobber def.
245 SlotIndex getRegSlot(bool EC = false) const {
246 return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
249 /// Returns the dead def kill slot for the current instruction.
250 SlotIndex getDeadSlot() const {
251 return SlotIndex(listEntry(), Slot_Dead);
254 /// Returns the next slot in the index list. This could be either the
255 /// next slot for the instruction pointed to by this index or, if this
256 /// index is a STORE, the first slot for the next instruction.
257 /// WARNING: This method is considerably more expensive than the methods
258 /// that return specific slots (getUseIndex(), etc). If you can - please
259 /// use one of those methods.
260 SlotIndex getNextSlot() const {
262 if (s == Slot_Dead) {
263 return SlotIndex(listEntry()->getNextNode(), Slot_Block);
265 return SlotIndex(listEntry(), s + 1);
268 /// Returns the next index. This is the index corresponding to the this
269 /// index's slot, but for the next instruction.
270 SlotIndex getNextIndex() const {
271 return SlotIndex(listEntry()->getNextNode(), getSlot());
274 /// Returns the previous slot in the index list. This could be either the
275 /// previous slot for the instruction pointed to by this index or, if this
276 /// index is a Slot_Block, the last slot for the previous instruction.
277 /// WARNING: This method is considerably more expensive than the methods
278 /// that return specific slots (getUseIndex(), etc). If you can - please
279 /// use one of those methods.
280 SlotIndex getPrevSlot() const {
282 if (s == Slot_Block) {
283 return SlotIndex(listEntry()->getPrevNode(), Slot_Dead);
285 return SlotIndex(listEntry(), s - 1);
288 /// Returns the previous index. This is the index corresponding to this
289 /// index's slot, but for the previous instruction.
290 SlotIndex getPrevIndex() const {
291 return SlotIndex(listEntry()->getPrevNode(), getSlot());
296 /// DenseMapInfo specialization for SlotIndex.
298 struct DenseMapInfo<SlotIndex> {
299 static inline SlotIndex getEmptyKey() {
300 return SlotIndex::getEmptyKey();
302 static inline SlotIndex getTombstoneKey() {
303 return SlotIndex::getTombstoneKey();
305 static inline unsigned getHashValue(const SlotIndex &v) {
306 return SlotIndex::getHashValue(v);
308 static inline bool isEqual(const SlotIndex &LHS, const SlotIndex &RHS) {
313 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
316 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
321 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
323 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
327 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
331 struct Idx2MBBCompare {
332 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
333 return LHS.first < RHS.first;
337 /// SlotIndexes pass.
339 /// This pass assigns indexes to each instruction.
340 class SlotIndexes : public MachineFunctionPass {
343 typedef ilist<IndexListEntry> IndexList;
347 unsigned functionSize;
349 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
352 /// MBBRanges - Map MBB number to (start, stop) indexes.
353 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
355 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
357 SmallVector<IdxMBBPair, 8> idx2MBBMap;
359 // IndexListEntry allocator.
360 BumpPtrAllocator ileAllocator;
362 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
363 IndexListEntry *entry =
364 static_cast<IndexListEntry*>(
365 ileAllocator.Allocate(sizeof(IndexListEntry),
366 alignOf<IndexListEntry>()));
368 new (entry) IndexListEntry(mi, index);
373 /// Renumber locally after inserting curItr.
374 void renumberIndexes(IndexList::iterator curItr);
379 SlotIndexes() : MachineFunctionPass(ID) {
380 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
383 virtual void getAnalysisUsage(AnalysisUsage &au) const;
384 virtual void releaseMemory();
386 virtual bool runOnMachineFunction(MachineFunction &fn);
388 /// Dump the indexes.
391 /// Renumber the index list, providing space for new instructions.
392 void renumberIndexes();
394 /// Returns the zero index for this analysis.
395 SlotIndex getZeroIndex() {
396 assert(indexList.front().getIndex() == 0 && "First index is not 0?");
397 return SlotIndex(&indexList.front(), 0);
400 /// Returns the base index of the last slot in this analysis.
401 SlotIndex getLastIndex() {
402 return SlotIndex(&indexList.back(), 0);
405 /// Returns the distance between the highest and lowest indexes allocated
407 unsigned getIndexesLength() const {
408 assert(indexList.front().getIndex() == 0 &&
409 "Initial index isn't zero?");
410 return indexList.back().getIndex();
413 /// Returns the number of instructions in the function.
414 unsigned getFunctionSize() const {
418 /// Returns true if the given machine instr is mapped to an index,
419 /// otherwise returns false.
420 bool hasIndex(const MachineInstr *instr) const {
421 return mi2iMap.count(instr);
424 /// Returns the base index for the given instruction.
425 SlotIndex getInstructionIndex(const MachineInstr *MI) const {
426 // Instructions inside a bundle have the same number as the bundle itself.
427 Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
428 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
432 /// Returns the instruction for the given index, or null if the given
433 /// index has no instruction associated with it.
434 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
435 return index.isValid() ? index.listEntry()->getInstr() : 0;
438 /// Returns the next non-null index.
439 SlotIndex getNextNonNullIndex(SlotIndex index) {
440 IndexList::iterator itr(index.listEntry());
442 while (itr != indexList.end() && itr->getInstr() == 0) { ++itr; }
443 return SlotIndex(itr, index.getSlot());
446 /// getIndexBefore - Returns the index of the last indexed instruction
447 /// before MI, or the the start index of its basic block.
448 /// MI is not required to have an index.
449 SlotIndex getIndexBefore(const MachineInstr *MI) const {
450 const MachineBasicBlock *MBB = MI->getParent();
451 assert(MBB && "MI must be inserted inna basic block");
452 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
455 return getMBBStartIdx(MBB);
457 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
458 if (MapItr != mi2iMap.end())
459 return MapItr->second;
463 /// getIndexAfter - Returns the index of the first indexed instruction
464 /// after MI, or the end index of its basic block.
465 /// MI is not required to have an index.
466 SlotIndex getIndexAfter(const MachineInstr *MI) const {
467 const MachineBasicBlock *MBB = MI->getParent();
468 assert(MBB && "MI must be inserted inna basic block");
469 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
473 return getMBBEndIdx(MBB);
474 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
475 if (MapItr != mi2iMap.end())
476 return MapItr->second;
480 /// Return the (start,end) range of the given basic block number.
481 const std::pair<SlotIndex, SlotIndex> &
482 getMBBRange(unsigned Num) const {
483 return MBBRanges[Num];
486 /// Return the (start,end) range of the given basic block.
487 const std::pair<SlotIndex, SlotIndex> &
488 getMBBRange(const MachineBasicBlock *MBB) const {
489 return getMBBRange(MBB->getNumber());
492 /// Returns the first index in the given basic block number.
493 SlotIndex getMBBStartIdx(unsigned Num) const {
494 return getMBBRange(Num).first;
497 /// Returns the first index in the given basic block.
498 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
499 return getMBBRange(mbb).first;
502 /// Returns the last index in the given basic block number.
503 SlotIndex getMBBEndIdx(unsigned Num) const {
504 return getMBBRange(Num).second;
507 /// Returns the last index in the given basic block.
508 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
509 return getMBBRange(mbb).second;
512 /// Returns the basic block which the given index falls in.
513 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
514 if (MachineInstr *MI = getInstructionFromIndex(index))
515 return MI->getParent();
516 SmallVectorImpl<IdxMBBPair>::const_iterator I =
517 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
518 // Take the pair containing the index
519 SmallVectorImpl<IdxMBBPair>::const_iterator J =
520 ((I != idx2MBBMap.end() && I->first > index) ||
521 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
523 assert(J != idx2MBBMap.end() && J->first <= index &&
524 index < getMBBEndIdx(J->second) &&
525 "index does not correspond to an MBB");
529 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
530 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
531 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
532 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
535 while (itr != idx2MBBMap.end()) {
536 if (itr->first >= end)
538 mbbs.push_back(itr->second);
545 /// Returns the MBB covering the given range, or null if the range covers
546 /// more than one basic block.
547 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
549 assert(start < end && "Backwards ranges not allowed.");
551 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
552 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
554 if (itr == idx2MBBMap.end()) {
559 // Check that we don't cross the boundary into this block.
560 if (itr->first < end)
565 if (itr->first <= start)
571 /// Insert the given machine instruction into the mapping. Returns the
573 /// If Late is set and there are null indexes between mi's neighboring
574 /// instructions, create the new index after the null indexes instead of
576 SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
577 assert(!mi->isInsideBundle() &&
578 "Instructions inside bundles should use bundle start's slot.");
579 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
580 // Numbering DBG_VALUE instructions could cause code generation to be
581 // affected by debug information.
582 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
584 assert(mi->getParent() != 0 && "Instr must be added to function.");
586 // Get the entries where mi should be inserted.
587 IndexList::iterator prevItr, nextItr;
589 // Insert mi's index immediately before the following instruction.
590 nextItr = getIndexAfter(mi).listEntry();
591 prevItr = prior(nextItr);
593 // Insert mi's index immediately after the preceeding instruction.
594 prevItr = getIndexBefore(mi).listEntry();
595 nextItr = llvm::next(prevItr);
598 // Get a number for the new instr, or 0 if there's no room currently.
599 // In the latter case we'll force a renumber later.
600 unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
601 unsigned newNumber = prevItr->getIndex() + dist;
603 // Insert a new list entry for mi.
604 IndexList::iterator newItr =
605 indexList.insert(nextItr, createEntry(mi, newNumber));
607 // Renumber locally if we need to.
609 renumberIndexes(newItr);
611 SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
612 mi2iMap.insert(std::make_pair(mi, newIndex));
616 /// Remove the given machine instruction from the mapping.
617 void removeMachineInstrFromMaps(MachineInstr *mi) {
618 // remove index -> MachineInstr and
619 // MachineInstr -> index mappings
620 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
621 if (mi2iItr != mi2iMap.end()) {
622 IndexListEntry *miEntry(mi2iItr->second.listEntry());
623 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
624 // FIXME: Eventually we want to actually delete these indexes.
625 miEntry->setInstr(0);
626 mi2iMap.erase(mi2iItr);
630 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
631 /// maps used by register allocator.
632 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
633 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
634 if (mi2iItr == mi2iMap.end())
636 SlotIndex replaceBaseIndex = mi2iItr->second;
637 IndexListEntry *miEntry(replaceBaseIndex.listEntry());
638 assert(miEntry->getInstr() == mi &&
639 "Mismatched instruction in index tables.");
640 miEntry->setInstr(newMI);
641 mi2iMap.erase(mi2iItr);
642 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
645 /// Add the given MachineBasicBlock into the maps.
646 void insertMBBInMaps(MachineBasicBlock *mbb) {
647 MachineFunction::iterator nextMBB =
648 llvm::next(MachineFunction::iterator(mbb));
649 IndexListEntry *startEntry = createEntry(0, 0);
650 IndexListEntry *stopEntry = createEntry(0, 0);
651 IndexListEntry *nextEntry = 0;
653 if (nextMBB == mbb->getParent()->end()) {
654 nextEntry = indexList.end();
656 nextEntry = getMBBStartIdx(nextMBB).listEntry();
659 indexList.insert(nextEntry, startEntry);
660 indexList.insert(nextEntry, stopEntry);
662 SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
663 SlotIndex endIdx(nextEntry, SlotIndex::Slot_Block);
665 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
666 "Blocks must be added in order");
667 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
669 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
672 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
678 // Specialize IntervalMapInfo for half-open slot index intervals.
679 template <typename> struct IntervalMapInfo;
680 template <> struct IntervalMapInfo<SlotIndex> {
681 static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
684 static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
687 static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
694 #endif // LLVM_CODEGEN_SLOTINDEXES_H