1//===-- SlotIndexes.cpp - Slot Indexes Pass ------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/CodeGen/SlotIndexes.h"
10#include "llvm/ADT/Statistic.h"
11#include "llvm/CodeGen/MachineFunction.h"
12#include "llvm/Config/llvm-config.h"
13#include "llvm/InitializePasses.h"
14#include "llvm/Support/Debug.h"
15#include "llvm/Support/raw_ostream.h"
16
17using namespace llvm;
18
19#define DEBUG_TYPE "slotindexes"
20
21AnalysisKey SlotIndexesAnalysis::Key;
22
23SlotIndexesAnalysis::Result
24SlotIndexesAnalysis::run(MachineFunction &MF,
25 MachineFunctionAnalysisManager &) {
26 return Result(MF);
27}
28
29PreservedAnalyses
30SlotIndexesPrinterPass::run(MachineFunction &MF,
31 MachineFunctionAnalysisManager &MFAM) {
32 OS << "Slot indexes in machine function: " << MF.getName() << '\n';
33 MFAM.getResult<SlotIndexesAnalysis>(IR&: MF).print(OS);
34 return PreservedAnalyses::all();
35}
36char SlotIndexesWrapperPass::ID = 0;
37
38SlotIndexesWrapperPass::SlotIndexesWrapperPass() : MachineFunctionPass(ID) {}
39
40SlotIndexes::~SlotIndexes() {
41 // The indexList's nodes are all allocated in the BumpPtrAllocator.
42 indexList.clear();
43}
44
45INITIALIZE_PASS(SlotIndexesWrapperPass, DEBUG_TYPE, "Slot index numbering",
46 false, false)
47
48STATISTIC(NumLocalRenum, "Number of local renumberings");
49
50void SlotIndexesWrapperPass::getAnalysisUsage(AnalysisUsage &au) const {
51 au.setPreservesAll();
52 MachineFunctionPass::getAnalysisUsage(AU&: au);
53}
54
55void SlotIndexes::clear() {
56 mi2iMap.clear();
57 MBBRanges.clear();
58 idx2MBBMap.clear();
59 indexList.clear();
60 ileAllocator.Reset();
61}
62
63void SlotIndexes::analyze(MachineFunction &fn) {
64
65 // Compute numbering as follows:
66 // Grab an iterator to the start of the index list.
67 // Iterate over all MBBs, and within each MBB all MIs, keeping the MI
68 // iterator in lock-step (though skipping it over indexes which have
69 // null pointers in the instruction field).
70 // At each iteration assert that the instruction pointed to in the index
71 // is the same one pointed to by the MI iterator. This
72
73 // FIXME: This can be simplified. The mi2iMap_, Idx2MBBMap, etc. should
74 // only need to be set up once after the first numbering is computed.
75
76 mf = &fn;
77
78 // Check that the list contains only the sentinel.
79 assert(indexList.empty() && "Index list non-empty at initial numbering?");
80 assert(idx2MBBMap.empty() &&
81 "Index -> MBB mapping non-empty at initial numbering?");
82 assert(MBBRanges.empty() &&
83 "MBB -> Index mapping non-empty at initial numbering?");
84 assert(mi2iMap.empty() &&
85 "MachineInstr -> Index mapping non-empty at initial numbering?");
86
87 unsigned index = 0;
88 MBBRanges.resize(N: mf->getMaxAnalysisBlockNumber());
89 idx2MBBMap.reserve(N: mf->size());
90
91 indexList.push_back(Node&: *createEntry(mi: nullptr, index));
92
93 // Iterate over the function.
94 for (MachineBasicBlock &MBB : *mf) {
95 // Insert an index for the MBB start.
96 SlotIndex blockStartIndex(&indexList.back(), SlotIndex::Slot_Block);
97
98 for (MachineInstr &MI : MBB) {
99 if (MI.isDebugOrPseudoInstr())
100 continue;
101
102 // Insert a store index for the instr.
103 indexList.push_back(Node&: *createEntry(mi: &MI, index: index += SlotIndex::InstrDist));
104
105 // Save this base index in the maps.
106 mi2iMap.insert(KV: std::make_pair(
107 x: &MI, y: SlotIndex(&indexList.back(), SlotIndex::Slot_Block)));
108 }
109
110 // We insert one blank instructions between basic blocks.
111 indexList.push_back(Node&: *createEntry(mi: nullptr, index: index += SlotIndex::InstrDist));
112
113 MBBRanges[MBB.getAnalysisNumber()].first = blockStartIndex;
114 MBBRanges[MBB.getAnalysisNumber()].second =
115 SlotIndex(&indexList.back(), SlotIndex::Slot_Block);
116 idx2MBBMap.push_back(Elt: IdxMBBPair(blockStartIndex, &MBB));
117 }
118
119 // Sort the Idx2MBBMap
120 llvm::sort(C&: idx2MBBMap, Comp: less_first());
121
122 LLVM_DEBUG(mf->print(dbgs(), this));
123}
124
125void SlotIndexes::removeMachineInstrFromMaps(MachineInstr &MI,
126 bool AllowBundled) {
127 assert((AllowBundled || !MI.isBundledWithPred()) &&
128 "Use removeSingleMachineInstrFromMaps() instead");
129 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(Val: &MI);
130 if (mi2iItr == mi2iMap.end())
131 return;
132
133 SlotIndex MIIndex = mi2iItr->second;
134 IndexListEntry &MIEntry = *MIIndex.listEntry();
135 assert(MIEntry.getInstr() == &MI && "Instruction indexes broken.");
136 mi2iMap.erase(I: mi2iItr);
137 // FIXME: Eventually we want to actually delete these indexes.
138 MIEntry.setInstr(nullptr);
139}
140
141void SlotIndexes::removeSingleMachineInstrFromMaps(MachineInstr &MI) {
142 Mi2IndexMap::iterator mi2iItr = mi2iMap.find(Val: &MI);
143 if (mi2iItr == mi2iMap.end())
144 return;
145
146 SlotIndex MIIndex = mi2iItr->second;
147 IndexListEntry &MIEntry = *MIIndex.listEntry();
148 assert(MIEntry.getInstr() == &MI && "Instruction indexes broken.");
149 mi2iMap.erase(I: mi2iItr);
150
151 // When removing the first instruction of a bundle update mapping to next
152 // instruction.
153 if (MI.isBundledWithSucc()) {
154 // Only the first instruction of a bundle should have an index assigned.
155 assert(!MI.isBundledWithPred() && "Should be first bundle instruction");
156
157 MachineBasicBlock::instr_iterator Next = std::next(x: MI.getIterator());
158 MachineInstr &NextMI = *Next;
159 MIEntry.setInstr(&NextMI);
160 mi2iMap.insert(KV: std::make_pair(x: &NextMI, y&: MIIndex));
161 return;
162 } else {
163 // FIXME: Eventually we want to actually delete these indexes.
164 MIEntry.setInstr(nullptr);
165 }
166}
167
168void SlotIndexes::removeMBBFromMaps(MachineBasicBlock &MBB) {
169 assert(&MBB != &MBB.getParent()->front() &&
170 "Can't remove the first block of a function.");
171
172 unsigned Num = MBB.getAnalysisNumber();
173 SlotIndex StartIdx = MBBRanges[Num].first;
174 SlotIndex EndIdx = MBBRanges[Num].second;
175
176 // Give MBB's slot range to its layout predecessor so blocks stay contiguous.
177 auto PrevMBB = std::prev(x: MBB.getIterator());
178 MBBRanges[PrevMBB->getAnalysisNumber()].second = EndIdx;
179
180 // Drop MBB's index -> MBB entry, which would dangle once MBB is erased.
181 auto It = getMBBLowerBound(Idx: StartIdx);
182 assert(It != MBBIndexEnd() && It->first == StartIdx && It->second == &MBB &&
183 "MBB not found in index -> MBB map");
184 idx2MBBMap.erase(CI: It);
185
186 // Clear the block-start boundary entry. MBBRanges is never renumbered, so
187 // MBB's now-stale slot is simply left in place.
188 StartIdx.listEntry()->setInstr(nullptr);
189}
190
191// Renumber indexes locally after curItr was inserted, but failed to get a new
192// index.
193void SlotIndexes::renumberIndexes(IndexList::iterator curItr) {
194 // Number indexes with half the default spacing so we can catch up quickly.
195 const unsigned Space = SlotIndex::InstrDist/2;
196 static_assert((Space & 3) == 0, "InstrDist must be a multiple of 2*NUM");
197
198 IndexList::iterator startItr = std::prev(x: curItr);
199 unsigned index = startItr->getIndex();
200 unsigned BeginIndex = index;
201 do {
202 curItr->setIndex(index += Space);
203 ++curItr;
204 // If the next index is bigger, we have caught up.
205 } while (curItr != indexList.end() && curItr->getIndex() <= index);
206
207 LLVM_DEBUG(dbgs() << "\n*** Renumbered SlotIndexes " << startItr->getIndex()
208 << '-' << index << " ***\n");
209
210 // If we repack more than 20% of a function, add spacing in between the
211 // instructions so that future renumberings are able to catch up
212 // without also renumbering so much.
213 if (index - BeginIndex >
214 (getLastIndex().getIndex() - getZeroIndex().getIndex()) / 5)
215 packIndexes();
216
217 ++NumLocalRenum;
218}
219
220// Repair indexes after adding and removing instructions.
221void SlotIndexes::repairIndexesInRange(MachineBasicBlock *MBB,
222 MachineBasicBlock::iterator Begin,
223 MachineBasicBlock::iterator End) {
224 bool includeStart = (Begin == MBB->begin());
225 SlotIndex startIdx;
226 if (includeStart)
227 startIdx = getMBBStartIdx(mbb: MBB);
228 else
229 startIdx = getInstructionIndex(MI: *--Begin);
230
231 SlotIndex endIdx;
232 if (End == MBB->end())
233 endIdx = getMBBEndIdx(mbb: MBB);
234 else
235 endIdx = getInstructionIndex(MI: *End);
236
237 // FIXME: Conceptually, this code is implementing an iterator on MBB that
238 // optionally includes an additional position prior to MBB->begin(), indicated
239 // by the includeStart flag. This is done so that we can iterate MIs in a MBB
240 // in parallel with SlotIndexes, but there should be a better way to do this.
241 IndexList::iterator ListB = startIdx.listEntry()->getIterator();
242 IndexList::iterator ListI = endIdx.listEntry()->getIterator();
243 MachineBasicBlock::iterator MBBI = End;
244 bool pastStart = false;
245 bool OldIndexesRemoved = false;
246 while (ListI != ListB || MBBI != Begin || (includeStart && !pastStart)) {
247 assert(ListI->getIndex() >= startIdx.getIndex() &&
248 (includeStart || !pastStart) &&
249 "Decremented past the beginning of region to repair.");
250
251 MachineInstr *SlotMI = ListI->getInstr();
252 MachineInstr *MI = (MBBI != MBB->end() && !pastStart) ? &*MBBI : nullptr;
253 bool MBBIAtBegin = MBBI == Begin && (!includeStart || pastStart);
254 bool MIIndexNotFound = MI && !mi2iMap.contains(Val: MI);
255 bool SlotMIRemoved = false;
256
257 if (SlotMI == MI && !MBBIAtBegin) {
258 --ListI;
259 if (MBBI != Begin)
260 --MBBI;
261 else
262 pastStart = true;
263 } else if (MIIndexNotFound || OldIndexesRemoved) {
264 if (MBBI != Begin)
265 --MBBI;
266 else
267 pastStart = true;
268 } else {
269 // We ran through all the indexes on the interval
270 // -> The only thing left is to go through all the
271 // remaining MBB instructions and update their indexes
272 if (ListI == ListB)
273 OldIndexesRemoved = true;
274 else
275 --ListI;
276 if (SlotMI) {
277 removeMachineInstrFromMaps(MI&: *SlotMI);
278 SlotMIRemoved = true;
279 }
280 }
281
282 MachineInstr *InstrToInsert = SlotMIRemoved ? SlotMI : MI;
283
284 // Insert instruction back into the maps after passing it/removing the index
285 if ((MIIndexNotFound || SlotMIRemoved) && InstrToInsert->getParent() &&
286 !InstrToInsert->isDebugOrPseudoInstr())
287 insertMachineInstrInMaps(MI&: *InstrToInsert);
288 }
289}
290
291void SlotIndexes::packIndexes() {
292 for (auto [Index, Entry] : enumerate(First&: indexList))
293 Entry.setIndex(Index * SlotIndex::InstrDist);
294}
295
296void SlotIndexes::print(raw_ostream &OS) const {
297 for (const IndexListEntry &ILE : indexList) {
298 OS << ILE.getIndex() << ' ';
299
300 if (ILE.getInstr())
301 OS << *ILE.getInstr();
302 else
303 OS << '\n';
304 }
305
306 for (const MachineBasicBlock &MBB : *mf)
307 OS << printMBBReference(MBB) << "\t[" << getMBBStartIdx(mbb: &MBB) << ';'
308 << getMBBEndIdx(mbb: &MBB) << ")\n";
309}
310
311#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
312LLVM_DUMP_METHOD void SlotIndexes::dump() const { print(dbgs()); }
313#endif
314
315// Print a SlotIndex to a raw_ostream.
316void SlotIndex::print(raw_ostream &os) const {
317 if (isValid())
318 os << listEntry()->getIndex() << "Berd"[getSlot()];
319 else
320 os << "invalid";
321}
322
323#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
324// Dump a SlotIndex to stderr.
325LLVM_DUMP_METHOD void SlotIndex::dump() const {
326 print(dbgs());
327 dbgs() << "\n";
328}
329#endif
330