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;
81 /// Basic block boundary. Used for live ranges entering and leaving a
82 /// block without being live in the layout neighbor. Also used as the
83 /// def slot of PHI-defs.
86 /// Early-clobber register use/def slot. A live range defined at
87 /// Slot_EarlyCLobber interferes with normal live ranges killed at
88 /// Slot_Register. Also used as the kill slot for live ranges tied to an
89 /// early-clobber def.
92 /// Normal register use/def slot. Normal instructions kill and define
93 /// register live ranges at this slot.
96 /// Dead def kill point. Kill slot for a live range that is defined by
97 /// the same instruction (Slot_Register or Slot_EarlyClobber), but isn't
104 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
106 SlotIndex(IndexListEntry *entry, unsigned slot)
107 : lie(entry, slot) {}
109 IndexListEntry* listEntry() const {
110 assert(isValid() && "Attempt to compare reserved index.");
111 return lie.getPointer();
114 int getIndex() const {
115 return listEntry()->getIndex() | getSlot();
118 /// Returns the slot for this SlotIndex.
119 Slot getSlot() const {
120 return static_cast<Slot>(lie.getInt());
125 /// The default distance between instructions as returned by distance().
126 /// This may vary as instructions are inserted and removed.
127 InstrDist = 4 * Slot_Count
130 /// Construct an invalid index.
131 SlotIndex() : lie(0, 0) {}
133 // Construct a new slot index from the given one, and set the slot.
134 SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
135 assert(lie.getPointer() != 0 &&
136 "Attempt to construct index with 0 pointer.");
139 /// Returns true if this is a valid index. Invalid indicies do
140 /// not point into an index table, and cannot be compared.
141 bool isValid() const {
142 return lie.getPointer();
145 /// Return true for a valid index.
146 operator bool() const { return isValid(); }
148 /// Print this index to the given raw_ostream.
149 void print(raw_ostream &os) const;
151 /// Dump this index to stderr.
154 /// Compare two SlotIndex objects for equality.
155 bool operator==(SlotIndex other) const {
156 return lie == other.lie;
158 /// Compare two SlotIndex objects for inequality.
159 bool operator!=(SlotIndex other) const {
160 return lie != other.lie;
163 /// Compare two SlotIndex objects. Return true if the first index
164 /// is strictly lower than the second.
165 bool operator<(SlotIndex other) const {
166 return getIndex() < other.getIndex();
168 /// Compare two SlotIndex objects. Return true if the first index
169 /// is lower than, or equal to, the second.
170 bool operator<=(SlotIndex other) const {
171 return getIndex() <= other.getIndex();
174 /// Compare two SlotIndex objects. Return true if the first index
175 /// is greater than the second.
176 bool operator>(SlotIndex other) const {
177 return getIndex() > other.getIndex();
180 /// Compare two SlotIndex objects. Return true if the first index
181 /// is greater than, or equal to, the second.
182 bool operator>=(SlotIndex other) const {
183 return getIndex() >= other.getIndex();
186 /// isSameInstr - Return true if A and B refer to the same instruction.
187 static bool isSameInstr(SlotIndex A, SlotIndex B) {
188 return A.lie.getPointer() == B.lie.getPointer();
191 /// isEarlierInstr - Return true if A refers to an instruction earlier than
192 /// B. This is equivalent to A < B && !isSameInstr(A, B).
193 static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
194 return A.listEntry()->getIndex() < B.listEntry()->getIndex();
197 /// Return the distance from this index to the given one.
198 int distance(SlotIndex other) const {
199 return other.getIndex() - getIndex();
202 /// isBlock - Returns true if this is a block boundary slot.
203 bool isBlock() const { return getSlot() == Slot_Block; }
205 /// isEarlyClobber - Returns true if this is an early-clobber slot.
206 bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
208 /// isRegister - Returns true if this is a normal register use/def slot.
209 /// Note that early-clobber slots may also be used for uses and defs.
210 bool isRegister() const { return getSlot() == Slot_Register; }
212 /// isDead - Returns true if this is a dead def kill slot.
213 bool isDead() const { return getSlot() == Slot_Dead; }
215 /// Returns the base index for associated with this index. The base index
216 /// is the one associated with the Slot_Block slot for the instruction
217 /// pointed to by this index.
218 SlotIndex getBaseIndex() const {
219 return SlotIndex(listEntry(), Slot_Block);
222 /// Returns the boundary index for associated with this index. The boundary
223 /// index is the one associated with the Slot_Block slot for the instruction
224 /// pointed to by this index.
225 SlotIndex getBoundaryIndex() const {
226 return SlotIndex(listEntry(), Slot_Dead);
229 /// Returns the register use/def slot in the current instruction for a
230 /// normal or early-clobber def.
231 SlotIndex getRegSlot(bool EC = false) const {
232 return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
235 /// Returns the dead def kill slot for the current instruction.
236 SlotIndex getDeadSlot() const {
237 return SlotIndex(listEntry(), Slot_Dead);
240 /// Returns the next slot in the index list. This could be either the
241 /// next slot for the instruction pointed to by this index or, if this
242 /// index is a STORE, the first slot for the next instruction.
243 /// WARNING: This method is considerably more expensive than the methods
244 /// that return specific slots (getUseIndex(), etc). If you can - please
245 /// use one of those methods.
246 SlotIndex getNextSlot() const {
248 if (s == Slot_Dead) {
249 return SlotIndex(listEntry()->getNextNode(), Slot_Block);
251 return SlotIndex(listEntry(), s + 1);
254 /// Returns the next index. This is the index corresponding to the this
255 /// index's slot, but for the next instruction.
256 SlotIndex getNextIndex() const {
257 return SlotIndex(listEntry()->getNextNode(), getSlot());
260 /// Returns the previous slot in the index list. This could be either the
261 /// previous slot for the instruction pointed to by this index or, if this
262 /// index is a Slot_Block, the last slot for the previous instruction.
263 /// WARNING: This method is considerably more expensive than the methods
264 /// that return specific slots (getUseIndex(), etc). If you can - please
265 /// use one of those methods.
266 SlotIndex getPrevSlot() const {
268 if (s == Slot_Block) {
269 return SlotIndex(listEntry()->getPrevNode(), Slot_Dead);
271 return SlotIndex(listEntry(), s - 1);
274 /// Returns the previous index. This is the index corresponding to this
275 /// index's slot, but for the previous instruction.
276 SlotIndex getPrevIndex() const {
277 return SlotIndex(listEntry()->getPrevNode(), getSlot());
282 template <> struct isPodLike<SlotIndex> { static const bool value = true; };
285 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
290 typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
292 inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
296 inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
300 struct Idx2MBBCompare {
301 bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
302 return LHS.first < RHS.first;
306 /// SlotIndexes pass.
308 /// This pass assigns indexes to each instruction.
309 class SlotIndexes : public MachineFunctionPass {
312 typedef ilist<IndexListEntry> IndexList;
317 typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
320 /// MBBRanges - Map MBB number to (start, stop) indexes.
321 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
323 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
325 SmallVector<IdxMBBPair, 8> idx2MBBMap;
327 // IndexListEntry allocator.
328 BumpPtrAllocator ileAllocator;
330 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
331 IndexListEntry *entry =
332 static_cast<IndexListEntry*>(
333 ileAllocator.Allocate(sizeof(IndexListEntry),
334 alignOf<IndexListEntry>()));
336 new (entry) IndexListEntry(mi, index);
341 /// Renumber locally after inserting curItr.
342 void renumberIndexes(IndexList::iterator curItr);
347 SlotIndexes() : MachineFunctionPass(ID) {
348 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
351 virtual void getAnalysisUsage(AnalysisUsage &au) const;
352 virtual void releaseMemory();
354 virtual bool runOnMachineFunction(MachineFunction &fn);
356 /// Dump the indexes.
359 /// Renumber the index list, providing space for new instructions.
360 void renumberIndexes();
362 /// Returns the zero index for this analysis.
363 SlotIndex getZeroIndex() {
364 assert(indexList.front().getIndex() == 0 && "First index is not 0?");
365 return SlotIndex(&indexList.front(), 0);
368 /// Returns the base index of the last slot in this analysis.
369 SlotIndex getLastIndex() {
370 return SlotIndex(&indexList.back(), 0);
373 /// Returns true if the given machine instr is mapped to an index,
374 /// otherwise returns false.
375 bool hasIndex(const MachineInstr *instr) const {
376 return mi2iMap.count(instr);
379 /// Returns the base index for the given instruction.
380 SlotIndex getInstructionIndex(const MachineInstr *MI) const {
381 // Instructions inside a bundle have the same number as the bundle itself.
382 Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
383 assert(itr != mi2iMap.end() && "Instruction not found in maps.");
387 /// Returns the instruction for the given index, or null if the given
388 /// index has no instruction associated with it.
389 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
390 return index.isValid() ? index.listEntry()->getInstr() : 0;
393 /// Returns the next non-null index.
394 SlotIndex getNextNonNullIndex(SlotIndex index) {
395 IndexList::iterator itr(index.listEntry());
397 while (itr != indexList.end() && itr->getInstr() == 0) { ++itr; }
398 return SlotIndex(itr, index.getSlot());
401 /// getIndexBefore - Returns the index of the last indexed instruction
402 /// before MI, or the start index of its basic block.
403 /// MI is not required to have an index.
404 SlotIndex getIndexBefore(const MachineInstr *MI) const {
405 const MachineBasicBlock *MBB = MI->getParent();
406 assert(MBB && "MI must be inserted inna basic block");
407 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
410 return getMBBStartIdx(MBB);
412 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
413 if (MapItr != mi2iMap.end())
414 return MapItr->second;
418 /// getIndexAfter - Returns the index of the first indexed instruction
419 /// after MI, or the end index of its basic block.
420 /// MI is not required to have an index.
421 SlotIndex getIndexAfter(const MachineInstr *MI) const {
422 const MachineBasicBlock *MBB = MI->getParent();
423 assert(MBB && "MI must be inserted inna basic block");
424 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
428 return getMBBEndIdx(MBB);
429 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
430 if (MapItr != mi2iMap.end())
431 return MapItr->second;
435 /// Return the (start,end) range of the given basic block number.
436 const std::pair<SlotIndex, SlotIndex> &
437 getMBBRange(unsigned Num) const {
438 return MBBRanges[Num];
441 /// Return the (start,end) range of the given basic block.
442 const std::pair<SlotIndex, SlotIndex> &
443 getMBBRange(const MachineBasicBlock *MBB) const {
444 return getMBBRange(MBB->getNumber());
447 /// Returns the first index in the given basic block number.
448 SlotIndex getMBBStartIdx(unsigned Num) const {
449 return getMBBRange(Num).first;
452 /// Returns the first index in the given basic block.
453 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
454 return getMBBRange(mbb).first;
457 /// Returns the last index in the given basic block number.
458 SlotIndex getMBBEndIdx(unsigned Num) const {
459 return getMBBRange(Num).second;
462 /// Returns the last index in the given basic block.
463 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
464 return getMBBRange(mbb).second;
467 /// Returns the basic block which the given index falls in.
468 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
469 if (MachineInstr *MI = getInstructionFromIndex(index))
470 return MI->getParent();
471 SmallVectorImpl<IdxMBBPair>::const_iterator I =
472 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
473 // Take the pair containing the index
474 SmallVectorImpl<IdxMBBPair>::const_iterator J =
475 ((I != idx2MBBMap.end() && I->first > index) ||
476 (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
478 assert(J != idx2MBBMap.end() && J->first <= index &&
479 index < getMBBEndIdx(J->second) &&
480 "index does not correspond to an MBB");
484 bool findLiveInMBBs(SlotIndex start, SlotIndex end,
485 SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
486 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
487 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
490 while (itr != idx2MBBMap.end()) {
491 if (itr->first >= end)
493 mbbs.push_back(itr->second);
500 /// Returns the MBB covering the given range, or null if the range covers
501 /// more than one basic block.
502 MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
504 assert(start < end && "Backwards ranges not allowed.");
506 SmallVectorImpl<IdxMBBPair>::const_iterator itr =
507 std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
509 if (itr == idx2MBBMap.end()) {
514 // Check that we don't cross the boundary into this block.
515 if (itr->first < end)
520 if (itr->first <= start)
526 /// Insert the given machine instruction into the mapping. Returns the
528 /// If Late is set and there are null indexes between mi's neighboring
529 /// instructions, create the new index after the null indexes instead of
531 SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
532 assert(!mi->isInsideBundle() &&
533 "Instructions inside bundles should use bundle start's slot.");
534 assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
535 // Numbering DBG_VALUE instructions could cause code generation to be
536 // affected by debug information.
537 assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
539 assert(mi->getParent() != 0 && "Instr must be added to function.");
541 // Get the entries where mi should be inserted.
542 IndexList::iterator prevItr, nextItr;
544 // Insert mi's index immediately before the following instruction.
545 nextItr = getIndexAfter(mi).listEntry();
546 prevItr = prior(nextItr);
548 // Insert mi's index immediately after the preceding instruction.
549 prevItr = getIndexBefore(mi).listEntry();
550 nextItr = llvm::next(prevItr);
553 // Get a number for the new instr, or 0 if there's no room currently.
554 // In the latter case we'll force a renumber later.
555 unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
556 unsigned newNumber = prevItr->getIndex() + dist;
558 // Insert a new list entry for mi.
559 IndexList::iterator newItr =
560 indexList.insert(nextItr, createEntry(mi, newNumber));
562 // Renumber locally if we need to.
564 renumberIndexes(newItr);
566 SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
567 mi2iMap.insert(std::make_pair(mi, newIndex));
571 /// Remove the given machine instruction from the mapping.
572 void removeMachineInstrFromMaps(MachineInstr *mi) {
573 // remove index -> MachineInstr and
574 // MachineInstr -> index mappings
575 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
576 if (mi2iItr != mi2iMap.end()) {
577 IndexListEntry *miEntry(mi2iItr->second.listEntry());
578 assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
579 // FIXME: Eventually we want to actually delete these indexes.
580 miEntry->setInstr(0);
581 mi2iMap.erase(mi2iItr);
585 /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
586 /// maps used by register allocator.
587 void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
588 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
589 if (mi2iItr == mi2iMap.end())
591 SlotIndex replaceBaseIndex = mi2iItr->second;
592 IndexListEntry *miEntry(replaceBaseIndex.listEntry());
593 assert(miEntry->getInstr() == mi &&
594 "Mismatched instruction in index tables.");
595 miEntry->setInstr(newMI);
596 mi2iMap.erase(mi2iItr);
597 mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
600 /// Add the given MachineBasicBlock into the maps.
601 void insertMBBInMaps(MachineBasicBlock *mbb) {
602 MachineFunction::iterator nextMBB =
603 llvm::next(MachineFunction::iterator(mbb));
604 IndexListEntry *startEntry = createEntry(0, 0);
605 IndexListEntry *stopEntry = createEntry(0, 0);
606 IndexListEntry *nextEntry = 0;
608 if (nextMBB == mbb->getParent()->end()) {
609 nextEntry = indexList.end();
611 nextEntry = getMBBStartIdx(nextMBB).listEntry();
614 indexList.insert(nextEntry, startEntry);
615 indexList.insert(nextEntry, stopEntry);
617 SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
618 SlotIndex endIdx(nextEntry, SlotIndex::Slot_Block);
620 assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
621 "Blocks must be added in order");
622 MBBRanges.push_back(std::make_pair(startIdx, endIdx));
624 idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
627 std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
633 // Specialize IntervalMapInfo for half-open slot index intervals.
634 template <typename> struct IntervalMapInfo;
635 template <> struct IntervalMapInfo<SlotIndex> {
636 static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
639 static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
642 static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
649 #endif // LLVM_CODEGEN_SLOTINDEXES_H