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/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"
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
38 class IndexListEntry : public ilist_node<IndexListEntry> {
44 IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
46 MachineInstr* getInstr() const { return mi; }
47 void setInstr(MachineInstr *mi) {
51 unsigned getIndex() const { return index; }
52 void setIndex(unsigned index) {
56 #ifdef EXPENSIVE_CHECKS
57 // When EXPENSIVE_CHECKS is defined, "erased" index list entries will
58 // actually be moved to a "graveyard" list, and have their pointers
59 // poisoned, so that dangling SlotIndex access can be reliably detected.
61 intptr_t tmp = reinterpret_cast<intptr_t>(mi);
62 assert(((tmp & 0x1) == 0x0) && "Pointer already poisoned?");
64 mi = reinterpret_cast<MachineInstr*>(tmp);
67 bool isPoisoned() const { return (reinterpret_cast<intptr_t>(mi) & 0x1) == 0x1; }
68 #endif // EXPENSIVE_CHECKS
73 struct ilist_traits<IndexListEntry> : public ilist_default_traits<IndexListEntry> {
75 mutable ilist_half_node<IndexListEntry> Sentinel;
77 IndexListEntry *createSentinel() const {
78 return static_cast<IndexListEntry*>(&Sentinel);
80 void destroySentinel(IndexListEntry *) const {}
82 IndexListEntry *provideInitialHead() const { return createSentinel(); }
83 IndexListEntry *ensureHead(IndexListEntry*) const { return createSentinel(); }
84 static void noteHead(IndexListEntry*, IndexListEntry*) {}
85 void deleteNode(IndexListEntry *N) {}
88 void createNode(const IndexListEntry &);
91 /// SlotIndex - An opaque wrapper around machine indexes.
93 friend class SlotIndexes;
96 /// Basic block boundary. Used for live ranges entering and leaving a
97 /// block without being live in the layout neighbor. Also used as the
98 /// def slot of PHI-defs.
101 /// Early-clobber register use/def slot. A live range defined at
102 /// Slot_EarlyCLobber interferes with normal live ranges killed at
103 /// Slot_Register. Also used as the kill slot for live ranges tied to an
104 /// early-clobber def.
107 /// Normal register use/def slot. Normal instructions kill and define
108 /// register live ranges at this slot.
111 /// Dead def kill point. Kill slot for a live range that is defined by
112 /// the same instruction (Slot_Register or Slot_EarlyClobber), but isn't
119 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
121 SlotIndex(IndexListEntry *entry, unsigned slot)
122 : lie(entry, slot) {}
124 IndexListEntry* listEntry() const {
125 assert(isValid() && "Attempt to compare reserved index.");
126 #ifdef EXPENSIVE_CHECKS
127 assert(!lie.getPointer()->isPoisoned() &&
128 "Attempt to access deleted list-entry.");
129 #endif // EXPENSIVE_CHECKS
130 return lie.getPointer();
133 unsigned getIndex() const {
134 return listEntry()->getIndex() | getSlot();
137 /// Returns the slot for this SlotIndex.
138 Slot getSlot() const {
139 return static_cast<Slot>(lie.getInt());
144 /// The default distance between instructions as returned by distance().
145 /// This may vary as instructions are inserted and removed.
146 InstrDist = 4 * Slot_Count
149 /// Construct an invalid index.
150 SlotIndex() : lie(0, 0) {}
152 // Construct a new slot index from the given one, and set the slot.
153 SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
154 assert(lie.getPointer() != 0 &&
155 "Attempt to construct index with 0 pointer.");
158 /// Returns true if this is a valid index. Invalid indicies do
159 /// not point into an index table, and cannot be compared.
160 bool isValid() const {
161 return lie.getPointer();
164 /// Return true for a valid index.
165 LLVM_EXPLICIT operator bool() const { return isValid(); }
167 /// Print this index to the given raw_ostream.
168 void print(raw_ostream &os) const;
170 /// Dump this index to stderr.
173 /// Compare two SlotIndex objects for equality.
174 bool operator==(SlotIndex other) const {
175 return lie == other.lie;
177 /// Compare two SlotIndex objects for inequality.
178 bool operator!=(SlotIndex other) const {
179 return lie != other.lie;
182 /// Compare two SlotIndex objects. Return true if the first index
183 /// is strictly lower than the second.
184 bool operator<(SlotIndex other) const {
185 return getIndex() < other.getIndex();
187 /// Compare two SlotIndex objects. Return true if the first index
188 /// is lower than, or equal to, the second.
189 bool operator<=(SlotIndex other) const {
190 return getIndex() <= other.getIndex();
193 /// Compare two SlotIndex objects. Return true if the first index
194 /// is greater than the second.
195 bool operator>(SlotIndex other) const {
196 return getIndex() > other.getIndex();
199 /// Compare two SlotIndex objects. Return true if the first index
200 /// is greater than, or equal to, the second.
201 bool operator>=(SlotIndex other) const {
202 return getIndex() >= other.getIndex();
205 /// isSameInstr - Return true if A and B refer to the same instruction.
206 static bool isSameInstr(SlotIndex A, SlotIndex B) {
207 return A.lie.getPointer() == B.lie.getPointer();
210 /// isEarlierInstr - Return true if A refers to an instruction earlier than
211 /// B. This is equivalent to A < B && !isSameInstr(A, B).
212 static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
213 return A.listEntry()->getIndex() < B.listEntry()->getIndex();
216 /// Return the distance from this index to the given one.
217 int distance(SlotIndex other) const {
218 return other.getIndex() - getIndex();
221 /// isBlock - Returns true if this is a block boundary slot.
222 bool isBlock() const { return getSlot() == Slot_Block; }
224 /// isEarlyClobber - Returns true if this is an early-clobber slot.
225 bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
227 /// isRegister - Returns true if this is a normal register use/def slot.
228 /// Note that early-clobber slots may also be used for uses and defs.
229 bool isRegister() const { return getSlot() == Slot_Register; }
231 /// isDead - Returns true if this is a dead def kill slot.
232 bool isDead() const { return getSlot() == Slot_Dead; }
234 /// Returns the base index for associated with this index. The base index
235 /// is the one associated with the Slot_Block slot for the instruction
236 /// pointed to by this index.
237 SlotIndex getBaseIndex() const {
238 return SlotIndex(listEntry(), Slot_Block);
241 /// Returns the boundary index for associated with this index. The boundary
242 /// index is the one associated with the Slot_Block slot for the instruction
243 /// pointed to by this index.
244 SlotIndex getBoundaryIndex() const {
245 return SlotIndex(listEntry(), Slot_Dead);
248 /// Returns the register use/def slot in the current instruction for a
249 /// normal or early-clobber def.
250 SlotIndex getRegSlot(bool EC = false) const {
251 return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
254 /// Returns the dead def kill slot for the current instruction.
255 SlotIndex getDeadSlot() const {
256 return SlotIndex(listEntry(), Slot_Dead);
259 /// Returns the next slot in the index list. This could be either the
260 /// next slot for the instruction pointed to by this index or, if this
261 /// index is a STORE, the first slot for the next instruction.
262 /// WARNING: This method is considerably more expensive than the methods
263 /// that return specific slots (getUseIndex(), etc). If you can - please
264 /// use one of those methods.
265 SlotIndex getNextSlot() const {
267 if (s == Slot_Dead) {
268 return SlotIndex(listEntry()->getNextNode(), Slot_Block);
270 return SlotIndex(listEntry(), s + 1);
273 /// Returns the next index. This is the index corresponding to the this
274 /// index's slot, but for the next instruction.
275 SlotIndex getNextIndex() const {
276 return SlotIndex(listEntry()->getNextNode(), getSlot());
279 /// Returns the previous slot in the index list. This could be either the
280 /// previous slot for the instruction pointed to by this index or, if this
281 /// index is a Slot_Block, the last slot for the previous instruction.
282 /// WARNING: This method is considerably more expensive than the methods
283 /// that return specific slots (getUseIndex(), etc). If you can - please
284 /// use one of those methods.
285 SlotIndex getPrevSlot() const {
287 if (s == Slot_Block) {
288 return SlotIndex(listEntry()->getPrevNode(), Slot_Dead);
290 return SlotIndex(listEntry(), s - 1);
293 /// Returns the previous index. This is the index corresponding to this
294 /// index's slot, but for the previous instruction.
295 SlotIndex getPrevIndex() const {
296 return SlotIndex(listEntry()->getPrevNode(), getSlot());
301 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
303 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
308 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
310 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
314 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
318 struct Idx2MBBCompare {
319 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
320 return LHS.first < RHS.first;
324 /// SlotIndexes pass.
326 /// This pass assigns indexes to each instruction.
327 class SlotIndexes : public MachineFunctionPass {
330 typedef ilist<IndexListEntry> IndexList;
333 #ifdef EXPENSIVE_CHECKS
334 IndexList graveyardList;
335 #endif // EXPENSIVE_CHECKS
339 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
342 /// MBBRanges - Map MBB number to (start, stop) indexes.
343 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
345 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
347 SmallVector<IdxMBBPair, 8> idx2MBBMap;
349 // IndexListEntry allocator.
350 BumpPtrAllocator ileAllocator;
352 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
353 IndexListEntry *entry =
354 static_cast<IndexListEntry*>(
355 ileAllocator.Allocate(sizeof(IndexListEntry),
356 alignOf<IndexListEntry>()));
358 new (entry) IndexListEntry(mi, index);
363 /// Renumber locally after inserting curItr.
364 void renumberIndexes(IndexList::iterator curItr);
369 SlotIndexes() : MachineFunctionPass(ID) {
370 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
373 virtual void getAnalysisUsage(AnalysisUsage &au) const;
374 virtual void releaseMemory();
376 virtual bool runOnMachineFunction(MachineFunction &fn);
378 /// Dump the indexes.
381 /// Renumber the index list, providing space for new instructions.
382 void renumberIndexes();
384 /// Repair indexes after adding and removing instructions.
385 void repairIndexesInRange(MachineBasicBlock *MBB,
386 MachineBasicBlock::iterator Begin,
387 MachineBasicBlock::iterator End);
389 /// Returns the zero index for this analysis.
390 SlotIndex getZeroIndex() {
391 assert(indexList.front().getIndex() == 0 && "First index is not 0?");
392 return SlotIndex(&indexList.front(), 0);
395 /// Returns the base index of the last slot in this analysis.
396 SlotIndex getLastIndex() {
397 return SlotIndex(&indexList.back(), 0);
400 /// Returns true if the given machine instr is mapped to an index,
401 /// otherwise returns false.
402 bool hasIndex(const MachineInstr *instr) const {
403 return mi2iMap.count(instr);
406 /// Returns the base index for the given instruction.
407 SlotIndex getInstructionIndex(const MachineInstr *MI) const {
408 // Instructions inside a bundle have the same number as the bundle itself.
409 Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
410 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
414 /// Returns the instruction for the given index, or null if the given
415 /// index has no instruction associated with it.
416 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
417 return index.isValid() ? index.listEntry()->getInstr() : 0;
420 /// Returns the next non-null index, if one exists.
421 /// Otherwise returns getLastIndex().
422 SlotIndex getNextNonNullIndex(SlotIndex Index) {
423 IndexList::iterator I = Index.listEntry();
424 IndexList::iterator E = indexList.end();
427 return SlotIndex(I, Index.getSlot());
428 // We reached the end of the function.
429 return getLastIndex();
432 /// getIndexBefore - Returns the index of the last indexed instruction
433 /// before MI, or the start index of its basic block.
434 /// MI is not required to have an index.
435 SlotIndex getIndexBefore(const MachineInstr *MI) const {
436 const MachineBasicBlock *MBB = MI->getParent();
437 assert(MBB && "MI must be inserted inna basic block");
438 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
441 return getMBBStartIdx(MBB);
443 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
444 if (MapItr != mi2iMap.end())
445 return MapItr->second;
449 /// getIndexAfter - Returns the index of the first indexed instruction
450 /// after MI, or the end index of its basic block.
451 /// MI is not required to have an index.
452 SlotIndex getIndexAfter(const MachineInstr *MI) const {
453 const MachineBasicBlock *MBB = MI->getParent();
454 assert(MBB && "MI must be inserted inna basic block");
455 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
459 return getMBBEndIdx(MBB);
460 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
461 if (MapItr != mi2iMap.end())
462 return MapItr->second;
466 /// Return the (start,end) range of the given basic block number.
467 const std::pair<SlotIndex, SlotIndex> &
468 getMBBRange(unsigned Num) const {
469 return MBBRanges[Num];
472 /// Return the (start,end) range of the given basic block.
473 const std::pair<SlotIndex, SlotIndex> &
474 getMBBRange(const MachineBasicBlock *MBB) const {
475 return getMBBRange(MBB->getNumber());
478 /// Returns the first index in the given basic block number.
479 SlotIndex getMBBStartIdx(unsigned Num) const {
480 return getMBBRange(Num).first;
483 /// Returns the first index in the given basic block.
484 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
485 return getMBBRange(mbb).first;
488 /// Returns the last index in the given basic block number.
489 SlotIndex getMBBEndIdx(unsigned Num) const {
490 return getMBBRange(Num).second;
493 /// Returns the last index in the given basic block.
494 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
495 return getMBBRange(mbb).second;
498 /// Returns the basic block which the given index falls in.
499 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
500 if (MachineInstr *MI = getInstructionFromIndex(index))
501 return MI->getParent();
502 SmallVectorImpl<IdxMBBPair>::const_iterator I =
503 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
504 // Take the pair containing the index
505 SmallVectorImpl<IdxMBBPair>::const_iterator J =
506 ((I != idx2MBBMap.end() && I->first > index) ||
507 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
509 assert(J != idx2MBBMap.end() && J->first <= index &&
510 index < getMBBEndIdx(J->second) &&
511 "index does not correspond to an MBB");
515 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
516 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
517 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
518 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
521 while (itr != idx2MBBMap.end()) {
522 if (itr->first >= end)
524 mbbs.push_back(itr->second);
531 /// Returns the MBB covering the given range, or null if the range covers
532 /// more than one basic block.
533 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
535 assert(start < end && "Backwards ranges not allowed.");
537 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
538 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
540 if (itr == idx2MBBMap.end()) {
545 // Check that we don't cross the boundary into this block.
546 if (itr->first < end)
551 if (itr->first <= start)
557 /// Insert the given machine instruction into the mapping. Returns the
559 /// If Late is set and there are null indexes between mi's neighboring
560 /// instructions, create the new index after the null indexes instead of
562 SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
563 assert(!mi->isInsideBundle() &&
564 "Instructions inside bundles should use bundle start's slot.");
565 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
566 // Numbering DBG_VALUE instructions could cause code generation to be
567 // affected by debug information.
568 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
570 assert(mi->getParent() != 0 && "Instr must be added to function.");
572 // Get the entries where mi should be inserted.
573 IndexList::iterator prevItr, nextItr;
575 // Insert mi's index immediately before the following instruction.
576 nextItr = getIndexAfter(mi).listEntry();
577 prevItr = prior(nextItr);
579 // Insert mi's index immediately after the preceding instruction.
580 prevItr = getIndexBefore(mi).listEntry();
581 nextItr = llvm::next(prevItr);
584 // Get a number for the new instr, or 0 if there's no room currently.
585 // In the latter case we'll force a renumber later.
586 unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
587 unsigned newNumber = prevItr->getIndex() + dist;
589 // Insert a new list entry for mi.
590 IndexList::iterator newItr =
591 indexList.insert(nextItr, createEntry(mi, newNumber));
593 // Renumber locally if we need to.
595 renumberIndexes(newItr);
597 SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
598 mi2iMap.insert(std::make_pair(mi, newIndex));
602 /// Remove the given machine instruction from the mapping.
603 void removeMachineInstrFromMaps(MachineInstr *mi) {
604 // remove index -> MachineInstr and
605 // MachineInstr -> index mappings
606 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
607 if (mi2iItr != mi2iMap.end()) {
608 IndexListEntry *miEntry(mi2iItr->second.listEntry());
609 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
610 // FIXME: Eventually we want to actually delete these indexes.
611 miEntry->setInstr(0);
612 mi2iMap.erase(mi2iItr);
616 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
617 /// maps used by register allocator.
618 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
619 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
620 if (mi2iItr == mi2iMap.end())
622 SlotIndex replaceBaseIndex = mi2iItr->second;
623 IndexListEntry *miEntry(replaceBaseIndex.listEntry());
624 assert(miEntry->getInstr() == mi &&
625 "Mismatched instruction in index tables.");
626 miEntry->setInstr(newMI);
627 mi2iMap.erase(mi2iItr);
628 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
631 /// Add the given MachineBasicBlock into the maps.
632 void insertMBBInMaps(MachineBasicBlock *mbb) {
633 MachineFunction::iterator nextMBB =
634 llvm::next(MachineFunction::iterator(mbb));
636 IndexListEntry *startEntry = 0;
637 IndexListEntry *endEntry = 0;
638 IndexList::iterator newItr;
639 if (nextMBB == mbb->getParent()->end()) {
640 startEntry = &indexList.back();
641 endEntry = createEntry(0, 0);
642 newItr = indexList.insertAfter(startEntry, endEntry);
644 startEntry = createEntry(0, 0);
645 endEntry = getMBBStartIdx(nextMBB).listEntry();
646 newItr = indexList.insert(endEntry, startEntry);
649 SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
650 SlotIndex endIdx(endEntry, SlotIndex::Slot_Block);
652 MachineFunction::iterator prevMBB(mbb);
653 assert(prevMBB != mbb->getParent()->end() &&
654 "Can't insert a new block at the beginning of a function.");
656 MBBRanges[prevMBB->getNumber()].second = startIdx;
658 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
659 "Blocks must be added in order");
660 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
661 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
663 renumberIndexes(newItr);
664 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
667 /// \brief Free the resources that were required to maintain a SlotIndex.
669 /// Once an index is no longer needed (for instance because the instruction
670 /// at that index has been moved), the resources required to maintain the
671 /// index can be relinquished to reduce memory use and improve renumbering
672 /// performance. Any remaining SlotIndex objects that point to the same
673 /// index are left 'dangling' (much the same as a dangling pointer to a
674 /// freed object) and should not be accessed, except to destruct them.
676 /// Like dangling pointers, access to dangling SlotIndexes can cause
677 /// painful-to-track-down bugs, especially if the memory for the index
678 /// previously pointed to has been re-used. To detect dangling SlotIndex
679 /// bugs, build with EXPENSIVE_CHECKS=1. This will cause "erased" indexes to
680 /// be retained in a graveyard instead of being freed. Operations on indexes
681 /// in the graveyard will trigger an assertion.
682 void eraseIndex(SlotIndex index) {
683 IndexListEntry *entry = index.listEntry();
684 #ifdef EXPENSIVE_CHECKS
685 indexList.remove(entry);
686 graveyardList.push_back(entry);
689 indexList.erase(entry);
696 // Specialize IntervalMapInfo for half-open slot index intervals.
698 struct IntervalMapInfo<SlotIndex> : IntervalMapHalfOpenInfo<SlotIndex> {
703 #endif // LLVM_CODEGEN_SLOTINDEXES_H