1 //===--- HexagonBlockRanges.cpp -------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #define DEBUG_TYPE "hbr"
11 
12 #include "HexagonBlockRanges.h"
13 #include "HexagonInstrInfo.h"
14 #include "HexagonSubtarget.h"
15 
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetRegisterInfo.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 
27 #include <map>
28 #include <vector>
29 
30 using namespace llvm;
31 
32 bool HexagonBlockRanges::IndexRange::overlaps(const IndexRange &A) const {
33   // If A contains start(), or "this" contains A.start(), then overlap.
34   IndexType S = start(), E = end(), AS = A.start(), AE = A.end();
35   if (AS == S)
36     return true;
37   bool SbAE = (S < AE) || (S == AE && A.TiedEnd);  // S-before-AE.
38   bool ASbE = (AS < E) || (AS == E && TiedEnd);    // AS-before-E.
39   if ((AS < S && SbAE) || (S < AS && ASbE))
40     return true;
41   // Otherwise no overlap.
42   return false;
43 }
44 
45 
46 bool HexagonBlockRanges::IndexRange::contains(const IndexRange &A) const {
47   if (start() <= A.start()) {
48     // Treat "None" in the range end as equal to the range start.
49     IndexType E = (end() != IndexType::None) ? end() : start();
50     IndexType AE = (A.end() != IndexType::None) ? A.end() : A.start();
51     if (AE <= E)
52       return true;
53   }
54   return false;
55 }
56 
57 
58 void HexagonBlockRanges::IndexRange::merge(const IndexRange &A) {
59   // Allow merging adjacent ranges.
60   assert(end() == A.start() || overlaps(A));
61   IndexType AS = A.start(), AE = A.end();
62   if (AS < start() || start() == IndexType::None)
63     setStart(AS);
64   if (end() < AE || end() == IndexType::None) {
65     setEnd(AE);
66     TiedEnd = A.TiedEnd;
67   } else {
68     if (end() == AE)
69       TiedEnd |= A.TiedEnd;
70   }
71   if (A.Fixed)
72     Fixed = true;
73 }
74 
75 
76 void HexagonBlockRanges::RangeList::include(const RangeList &RL) {
77   for (auto &R : RL)
78     if (std::find(begin(), end(), R) == end())
79       push_back(R);
80 }
81 
82 
83 // Merge all overlapping ranges in the list, so that all that remains
84 // is a list of disjoint ranges.
85 void HexagonBlockRanges::RangeList::unionize(bool MergeAdjacent) {
86   if (empty())
87     return;
88 
89   std::sort(begin(), end());
90   iterator Iter = begin();
91 
92   while (Iter != end()-1) {
93     iterator Next = std::next(Iter);
94     // If MergeAdjacent is true, merge ranges A and B, where A.end == B.start.
95     // This allows merging dead ranges, but is not valid for live ranges.
96     bool Merge = MergeAdjacent && (Iter->end() == Next->start());
97     if (Merge || Iter->overlaps(*Next)) {
98       Iter->merge(*Next);
99       erase(Next);
100       continue;
101     }
102     ++Iter;
103   }
104 }
105 
106 
107 // Compute a range A-B and add it to the list.
108 void HexagonBlockRanges::RangeList::addsub(const IndexRange &A,
109       const IndexRange &B) {
110   // Exclusion of non-overlapping ranges makes some checks simpler
111   // later in this function.
112   if (!A.overlaps(B)) {
113     // A - B = A.
114     add(A);
115     return;
116   }
117 
118   IndexType AS = A.start(), AE = A.end();
119   IndexType BS = B.start(), BE = B.end();
120 
121   // If AE is None, then A is included in B, since A and B overlap.
122   // The result of subtraction if empty, so just return.
123   if (AE == IndexType::None)
124     return;
125 
126   if (AS < BS) {
127     // A starts before B.
128     // AE cannot be None since A and B overlap.
129     assert(AE != IndexType::None);
130     // Add the part of A that extends on the "less" side of B.
131     add(AS, BS, A.Fixed, false);
132   }
133 
134   if (BE < AE) {
135     // BE cannot be Exit here.
136     if (BE == IndexType::None)
137       add(BS, AE, A.Fixed, false);
138     else
139       add(BE, AE, A.Fixed, false);
140   }
141 }
142 
143 
144 // Subtract a given range from each element in the list.
145 void HexagonBlockRanges::RangeList::subtract(const IndexRange &Range) {
146   // Cannot assume that the list is unionized (i.e. contains only non-
147   // overlapping ranges.
148   RangeList T;
149   for (iterator Next, I = begin(); I != end(); I = Next) {
150     IndexRange &Rg = *I;
151     if (Rg.overlaps(Range)) {
152       T.addsub(Rg, Range);
153       Next = this->erase(I);
154     } else {
155       Next = std::next(I);
156     }
157   }
158   include(T);
159 }
160 
161 
162 HexagonBlockRanges::InstrIndexMap::InstrIndexMap(MachineBasicBlock &B)
163     : Block(B) {
164   IndexType Idx = IndexType::First;
165   First = Idx;
166   for (auto &In : B) {
167     if (In.isDebugValue())
168       continue;
169     assert(getIndex(&In) == IndexType::None && "Instruction already in map");
170     Map.insert(std::make_pair(Idx, &In));
171     ++Idx;
172   }
173   Last = B.empty() ? IndexType::None : unsigned(Idx)-1;
174 }
175 
176 
177 MachineInstr *HexagonBlockRanges::InstrIndexMap::getInstr(IndexType Idx) const {
178   auto F = Map.find(Idx);
179   return (F != Map.end()) ? F->second : 0;
180 }
181 
182 
183 HexagonBlockRanges::IndexType HexagonBlockRanges::InstrIndexMap::getIndex(
184       MachineInstr *MI) const {
185   for (auto &I : Map)
186     if (I.second == MI)
187       return I.first;
188   return IndexType::None;
189 }
190 
191 
192 HexagonBlockRanges::IndexType HexagonBlockRanges::InstrIndexMap::getPrevIndex(
193       IndexType Idx) const {
194   assert (Idx != IndexType::None);
195   if (Idx == IndexType::Entry)
196     return IndexType::None;
197   if (Idx == IndexType::Exit)
198     return Last;
199   if (Idx == First)
200     return IndexType::Entry;
201   return unsigned(Idx)-1;
202 }
203 
204 
205 HexagonBlockRanges::IndexType HexagonBlockRanges::InstrIndexMap::getNextIndex(
206       IndexType Idx) const {
207   assert (Idx != IndexType::None);
208   if (Idx == IndexType::Entry)
209     return IndexType::First;
210   if (Idx == IndexType::Exit || Idx == Last)
211     return IndexType::None;
212   return unsigned(Idx)+1;
213 }
214 
215 
216 void HexagonBlockRanges::InstrIndexMap::replaceInstr(MachineInstr *OldMI,
217       MachineInstr *NewMI) {
218   for (auto &I : Map) {
219     if (I.second != OldMI)
220       continue;
221     if (NewMI != nullptr)
222       I.second = NewMI;
223     else
224       Map.erase(I.first);
225     break;
226   }
227 }
228 
229 
230 HexagonBlockRanges::HexagonBlockRanges(MachineFunction &mf)
231   : MF(mf), HST(mf.getSubtarget<HexagonSubtarget>()),
232     TII(*HST.getInstrInfo()), TRI(*HST.getRegisterInfo()),
233     Reserved(TRI.getReservedRegs(mf)) {
234   // Consider all non-allocatable registers as reserved.
235   for (auto I = TRI.regclass_begin(), E = TRI.regclass_end(); I != E; ++I) {
236     auto *RC = *I;
237     if (RC->isAllocatable())
238       continue;
239     for (unsigned R : *RC)
240       Reserved[R] = true;
241   }
242 }
243 
244 
245 HexagonBlockRanges::RegisterSet HexagonBlockRanges::getLiveIns(
246       const MachineBasicBlock &B) {
247   RegisterSet LiveIns;
248   for (auto I : B.liveins())
249     if (!Reserved[I.PhysReg])
250       LiveIns.insert({I.PhysReg, 0});
251   return LiveIns;
252 }
253 
254 
255 HexagonBlockRanges::RegisterSet HexagonBlockRanges::expandToSubRegs(
256       RegisterRef R, const MachineRegisterInfo &MRI,
257       const TargetRegisterInfo &TRI) {
258   RegisterSet SRs;
259 
260   if (R.Sub != 0) {
261     SRs.insert(R);
262     return SRs;
263   }
264 
265   if (TargetRegisterInfo::isPhysicalRegister(R.Reg)) {
266     MCSubRegIterator I(R.Reg, &TRI);
267     if (!I.isValid())
268       SRs.insert({R.Reg, 0});
269     for (; I.isValid(); ++I)
270       SRs.insert({*I, 0});
271   } else {
272     assert(TargetRegisterInfo::isVirtualRegister(R.Reg));
273     auto &RC = *MRI.getRegClass(R.Reg);
274     unsigned PReg = *RC.begin();
275     MCSubRegIndexIterator I(PReg, &TRI);
276     if (!I.isValid())
277       SRs.insert({R.Reg, 0});
278     for (; I.isValid(); ++I)
279       SRs.insert({R.Reg, I.getSubRegIndex()});
280   }
281   return SRs;
282 }
283 
284 
285 void HexagonBlockRanges::computeInitialLiveRanges(InstrIndexMap &IndexMap,
286       RegToRangeMap &LiveMap) {
287   std::map<RegisterRef,IndexType> LastDef, LastUse;
288   RegisterSet LiveOnEntry;
289   MachineBasicBlock &B = IndexMap.getBlock();
290   MachineRegisterInfo &MRI = B.getParent()->getRegInfo();
291 
292   for (auto R : getLiveIns(B))
293     for (auto S : expandToSubRegs(R, MRI, TRI))
294       LiveOnEntry.insert(S);
295 
296   for (auto R : LiveOnEntry)
297     LastDef[R] = IndexType::Entry;
298 
299   auto closeRange = [&LastUse,&LastDef,&LiveMap] (RegisterRef R) -> void {
300     auto LD = LastDef[R], LU = LastUse[R];
301     if (LD == IndexType::None)
302       LD = IndexType::Entry;
303     if (LU == IndexType::None)
304       LU = IndexType::Exit;
305     LiveMap[R].add(LD, LU, false, false);
306     LastUse[R] = LastDef[R] = IndexType::None;
307   };
308 
309   for (auto &In : B) {
310     if (In.isDebugValue())
311       continue;
312     IndexType Index = IndexMap.getIndex(&In);
313     // Process uses first.
314     for (auto &Op : In.operands()) {
315       if (!Op.isReg() || !Op.isUse() || Op.isUndef())
316         continue;
317       RegisterRef R = { Op.getReg(), Op.getSubReg() };
318       if (TargetRegisterInfo::isPhysicalRegister(R.Reg) && Reserved[R.Reg])
319         continue;
320       bool IsKill = Op.isKill();
321       for (auto S : expandToSubRegs(R, MRI, TRI)) {
322         LastUse[S] = Index;
323         if (IsKill)
324           closeRange(S);
325       }
326     }
327     // Process defs.
328     for (auto &Op : In.operands()) {
329       if (!Op.isReg() || !Op.isDef() || Op.isUndef())
330         continue;
331       RegisterRef R = { Op.getReg(), Op.getSubReg() };
332       if (TargetRegisterInfo::isPhysicalRegister(R.Reg) && Reserved[R.Reg])
333         continue;
334       for (auto S : expandToSubRegs(R, MRI, TRI)) {
335         if (LastDef[S] != IndexType::None)
336           closeRange(S);
337         LastDef[S] = Index;
338       }
339     }
340   }
341 
342   // Collect live-on-exit.
343   RegisterSet LiveOnExit;
344   for (auto *SB : B.successors())
345     for (auto R : getLiveIns(*SB))
346       for (auto S : expandToSubRegs(R, MRI, TRI))
347         LiveOnExit.insert(S);
348 
349   for (auto R : LiveOnExit)
350     LastUse[R] = IndexType::Exit;
351 
352   // Process remaining registers.
353   RegisterSet Left;
354   for (auto &I : LastUse)
355     if (I.second != IndexType::None)
356       Left.insert(I.first);
357   for (auto &I : LastDef)
358     if (I.second != IndexType::None)
359       Left.insert(I.first);
360   for (auto R : Left)
361     closeRange(R);
362 
363   // Finalize the live ranges.
364   for (auto &P : LiveMap)
365     P.second.unionize();
366 }
367 
368 
369 HexagonBlockRanges::RegToRangeMap HexagonBlockRanges::computeLiveMap(
370       InstrIndexMap &IndexMap) {
371   RegToRangeMap LiveMap;
372   DEBUG(dbgs() << LLVM_FUNCTION_NAME << ": index map\n" << IndexMap << '\n');
373   computeInitialLiveRanges(IndexMap, LiveMap);
374   DEBUG(dbgs() << LLVM_FUNCTION_NAME << ": live map\n"
375                << PrintRangeMap(LiveMap, TRI) << '\n');
376   return LiveMap;
377 }
378 
379 
380 HexagonBlockRanges::RegToRangeMap HexagonBlockRanges::computeDeadMap(
381       InstrIndexMap &IndexMap, RegToRangeMap &LiveMap) {
382   RegToRangeMap DeadMap;
383 
384   auto addDeadRanges = [&IndexMap,&LiveMap,&DeadMap] (RegisterRef R) -> void {
385     auto F = LiveMap.find(R);
386     if (F == LiveMap.end() || F->second.empty()) {
387       DeadMap[R].add(IndexType::Entry, IndexType::Exit, false, false);
388       return;
389     }
390 
391     RangeList &RL = F->second;
392     RangeList::iterator A = RL.begin(), Z = RL.end()-1;
393 
394     // Try to create the initial range.
395     if (A->start() != IndexType::Entry) {
396       IndexType DE = IndexMap.getPrevIndex(A->start());
397       if (DE != IndexType::Entry)
398         DeadMap[R].add(IndexType::Entry, DE, false, false);
399     }
400 
401     while (A != Z) {
402       // Creating a dead range that follows A.  Pay attention to empty
403       // ranges (i.e. those ending with "None").
404       IndexType AE = (A->end() == IndexType::None) ? A->start() : A->end();
405       IndexType DS = IndexMap.getNextIndex(AE);
406       ++A;
407       IndexType DE = IndexMap.getPrevIndex(A->start());
408       if (DS < DE)
409         DeadMap[R].add(DS, DE, false, false);
410     }
411 
412     // Try to create the final range.
413     if (Z->end() != IndexType::Exit) {
414       IndexType ZE = (Z->end() == IndexType::None) ? Z->start() : Z->end();
415       IndexType DS = IndexMap.getNextIndex(ZE);
416       if (DS < IndexType::Exit)
417         DeadMap[R].add(DS, IndexType::Exit, false, false);
418     }
419   };
420 
421   MachineFunction &MF = *IndexMap.getBlock().getParent();
422   auto &MRI = MF.getRegInfo();
423   unsigned NumRegs = TRI.getNumRegs();
424   BitVector Visited(NumRegs);
425   for (unsigned R = 1; R < NumRegs; ++R) {
426     for (auto S : expandToSubRegs({R,0}, MRI, TRI)) {
427       if (Reserved[S.Reg] || Visited[S.Reg])
428         continue;
429       addDeadRanges(S);
430       Visited[S.Reg] = true;
431     }
432   }
433   for (auto &P : LiveMap)
434     if (TargetRegisterInfo::isVirtualRegister(P.first.Reg))
435       addDeadRanges(P.first);
436 
437   DEBUG(dbgs() << LLVM_FUNCTION_NAME << ": dead map\n"
438                << PrintRangeMap(DeadMap, TRI) << '\n');
439   return DeadMap;
440 }
441 
442 
443 raw_ostream &operator<< (raw_ostream &OS, HexagonBlockRanges::IndexType Idx) {
444   if (Idx == HexagonBlockRanges::IndexType::None)
445     return OS << '-';
446   if (Idx == HexagonBlockRanges::IndexType::Entry)
447     return OS << 'n';
448   if (Idx == HexagonBlockRanges::IndexType::Exit)
449     return OS << 'x';
450   return OS << unsigned(Idx)-HexagonBlockRanges::IndexType::First+1;
451 }
452 
453 // A mapping to translate between instructions and their indices.
454 raw_ostream &operator<< (raw_ostream &OS,
455       const HexagonBlockRanges::IndexRange &IR) {
456   OS << '[' << IR.start() << ':' << IR.end() << (IR.TiedEnd ? '}' : ']');
457   if (IR.Fixed)
458     OS << '!';
459   return OS;
460 }
461 
462 raw_ostream &operator<< (raw_ostream &OS,
463       const HexagonBlockRanges::RangeList &RL) {
464   for (auto &R : RL)
465     OS << R << " ";
466   return OS;
467 }
468 
469 raw_ostream &operator<< (raw_ostream &OS,
470       const HexagonBlockRanges::InstrIndexMap &M) {
471   for (auto &In : M.Block) {
472     HexagonBlockRanges::IndexType Idx = M.getIndex(&In);
473     OS << Idx << (Idx == M.Last ? ". " : "  ") << In;
474   }
475   return OS;
476 }
477 
478 raw_ostream &operator<< (raw_ostream &OS,
479       const HexagonBlockRanges::PrintRangeMap &P) {
480   for (auto &I : P.Map) {
481     const HexagonBlockRanges::RangeList &RL = I.second;
482     OS << PrintReg(I.first.Reg, &P.TRI, I.first.Sub) << " -> " << RL << "\n";
483   }
484   return OS;
485 }
486