xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AggressiveAntiDepBreaker.cpp (revision dd41de95a84d979615a2ef11df6850622bf6184e)
1 //===- AggressiveAntiDepBreaker.cpp - Anti-dep breaker --------------------===//
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 // This file implements the AggressiveAntiDepBreaker class, which
10 // implements register anti-dependence breaking during post-RA
11 // scheduling. It attempts to break all anti-dependencies within a
12 // block.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AggressiveAntiDepBreaker.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/RegisterClassInfo.h"
27 #include "llvm/CodeGen/ScheduleDAG.h"
28 #include "llvm/CodeGen/TargetInstrInfo.h"
29 #include "llvm/CodeGen/TargetRegisterInfo.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MachineValueType.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cassert>
37 #include <utility>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "post-RA-sched"
42 
43 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
44 static cl::opt<int>
45 DebugDiv("agg-antidep-debugdiv",
46          cl::desc("Debug control for aggressive anti-dep breaker"),
47          cl::init(0), cl::Hidden);
48 
49 static cl::opt<int>
50 DebugMod("agg-antidep-debugmod",
51          cl::desc("Debug control for aggressive anti-dep breaker"),
52          cl::init(0), cl::Hidden);
53 
54 AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs,
55                                                MachineBasicBlock *BB)
56     : NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0),
57       GroupNodeIndices(TargetRegs, 0), KillIndices(TargetRegs, 0),
58       DefIndices(TargetRegs, 0) {
59   const unsigned BBSize = BB->size();
60   for (unsigned i = 0; i < NumTargetRegs; ++i) {
61     // Initialize all registers to be in their own group. Initially we
62     // assign the register to the same-indexed GroupNode.
63     GroupNodeIndices[i] = i;
64     // Initialize the indices to indicate that no registers are live.
65     KillIndices[i] = ~0u;
66     DefIndices[i] = BBSize;
67   }
68 }
69 
70 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg) {
71   unsigned Node = GroupNodeIndices[Reg];
72   while (GroupNodes[Node] != Node)
73     Node = GroupNodes[Node];
74 
75   return Node;
76 }
77 
78 void AggressiveAntiDepState::GetGroupRegs(
79   unsigned Group,
80   std::vector<unsigned> &Regs,
81   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
82 {
83   for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
84     if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
85       Regs.push_back(Reg);
86   }
87 }
88 
89 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2) {
90   assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
91   assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
92 
93   // find group for each register
94   unsigned Group1 = GetGroup(Reg1);
95   unsigned Group2 = GetGroup(Reg2);
96 
97   // if either group is 0, then that must become the parent
98   unsigned Parent = (Group1 == 0) ? Group1 : Group2;
99   unsigned Other = (Parent == Group1) ? Group2 : Group1;
100   GroupNodes.at(Other) = Parent;
101   return Parent;
102 }
103 
104 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg) {
105   // Create a new GroupNode for Reg. Reg's existing GroupNode must
106   // stay as is because there could be other GroupNodes referring to
107   // it.
108   unsigned idx = GroupNodes.size();
109   GroupNodes.push_back(idx);
110   GroupNodeIndices[Reg] = idx;
111   return idx;
112 }
113 
114 bool AggressiveAntiDepState::IsLive(unsigned Reg) {
115   // KillIndex must be defined and DefIndex not defined for a register
116   // to be live.
117   return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
118 }
119 
120 AggressiveAntiDepBreaker::AggressiveAntiDepBreaker(
121     MachineFunction &MFi, const RegisterClassInfo &RCI,
122     TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
123     : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
124       TII(MF.getSubtarget().getInstrInfo()),
125       TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI) {
126   /* Collect a bitset of all registers that are only broken if they
127      are on the critical path. */
128   for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
129     BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
130     if (CriticalPathSet.none())
131       CriticalPathSet = CPSet;
132     else
133       CriticalPathSet |= CPSet;
134    }
135 
136    LLVM_DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
137    LLVM_DEBUG(for (unsigned r
138                    : CriticalPathSet.set_bits()) dbgs()
139               << " " << printReg(r, TRI));
140    LLVM_DEBUG(dbgs() << '\n');
141 }
142 
143 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
144   delete State;
145 }
146 
147 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
148   assert(!State);
149   State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
150 
151   bool IsReturnBlock = BB->isReturnBlock();
152   std::vector<unsigned> &KillIndices = State->GetKillIndices();
153   std::vector<unsigned> &DefIndices = State->GetDefIndices();
154 
155   // Examine the live-in regs of all successors.
156   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
157          SE = BB->succ_end(); SI != SE; ++SI)
158     for (const auto &LI : (*SI)->liveins()) {
159       for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
160         unsigned Reg = *AI;
161         State->UnionGroups(Reg, 0);
162         KillIndices[Reg] = BB->size();
163         DefIndices[Reg] = ~0u;
164       }
165     }
166 
167   // Mark live-out callee-saved registers. In a return block this is
168   // all callee-saved registers. In non-return this is any
169   // callee-saved register that is not saved in the prolog.
170   const MachineFrameInfo &MFI = MF.getFrameInfo();
171   BitVector Pristine = MFI.getPristineRegs(MF);
172   for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I;
173        ++I) {
174     unsigned Reg = *I;
175     if (!IsReturnBlock && !Pristine.test(Reg))
176       continue;
177     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
178       unsigned AliasReg = *AI;
179       State->UnionGroups(AliasReg, 0);
180       KillIndices[AliasReg] = BB->size();
181       DefIndices[AliasReg] = ~0u;
182     }
183   }
184 }
185 
186 void AggressiveAntiDepBreaker::FinishBlock() {
187   delete State;
188   State = nullptr;
189 }
190 
191 void AggressiveAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count,
192                                        unsigned InsertPosIndex) {
193   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
194 
195   std::set<unsigned> PassthruRegs;
196   GetPassthruRegs(MI, PassthruRegs);
197   PrescanInstruction(MI, Count, PassthruRegs);
198   ScanInstruction(MI, Count);
199 
200   LLVM_DEBUG(dbgs() << "Observe: ");
201   LLVM_DEBUG(MI.dump());
202   LLVM_DEBUG(dbgs() << "\tRegs:");
203 
204   std::vector<unsigned> &DefIndices = State->GetDefIndices();
205   for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
206     // If Reg is current live, then mark that it can't be renamed as
207     // we don't know the extent of its live-range anymore (now that it
208     // has been scheduled). If it is not live but was defined in the
209     // previous schedule region, then set its def index to the most
210     // conservative location (i.e. the beginning of the previous
211     // schedule region).
212     if (State->IsLive(Reg)) {
213       LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs()
214                  << " " << printReg(Reg, TRI) << "=g" << State->GetGroup(Reg)
215                  << "->g0(region live-out)");
216       State->UnionGroups(Reg, 0);
217     } else if ((DefIndices[Reg] < InsertPosIndex)
218                && (DefIndices[Reg] >= Count)) {
219       DefIndices[Reg] = Count;
220     }
221   }
222   LLVM_DEBUG(dbgs() << '\n');
223 }
224 
225 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr &MI,
226                                                 MachineOperand &MO) {
227   if (!MO.isReg() || !MO.isImplicit())
228     return false;
229 
230   Register Reg = MO.getReg();
231   if (Reg == 0)
232     return false;
233 
234   MachineOperand *Op = nullptr;
235   if (MO.isDef())
236     Op = MI.findRegisterUseOperand(Reg, true);
237   else
238     Op = MI.findRegisterDefOperand(Reg);
239 
240   return(Op && Op->isImplicit());
241 }
242 
243 void AggressiveAntiDepBreaker::GetPassthruRegs(
244     MachineInstr &MI, std::set<unsigned> &PassthruRegs) {
245   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
246     MachineOperand &MO = MI.getOperand(i);
247     if (!MO.isReg()) continue;
248     if ((MO.isDef() && MI.isRegTiedToUseOperand(i)) ||
249         IsImplicitDefUse(MI, MO)) {
250       const Register Reg = MO.getReg();
251       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
252            SubRegs.isValid(); ++SubRegs)
253         PassthruRegs.insert(*SubRegs);
254     }
255   }
256 }
257 
258 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
259 /// in SU that we want to consider for breaking.
260 static void AntiDepEdges(const SUnit *SU, std::vector<const SDep *> &Edges) {
261   SmallSet<unsigned, 4> RegSet;
262   for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
263        P != PE; ++P) {
264     if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
265       if (RegSet.insert(P->getReg()).second)
266         Edges.push_back(&*P);
267     }
268   }
269 }
270 
271 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
272 /// critical path.
273 static const SUnit *CriticalPathStep(const SUnit *SU) {
274   const SDep *Next = nullptr;
275   unsigned NextDepth = 0;
276   // Find the predecessor edge with the greatest depth.
277   if (SU) {
278     for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
279          P != PE; ++P) {
280       const SUnit *PredSU = P->getSUnit();
281       unsigned PredLatency = P->getLatency();
282       unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
283       // In the case of a latency tie, prefer an anti-dependency edge over
284       // other types of edges.
285       if (NextDepth < PredTotalLatency ||
286           (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
287         NextDepth = PredTotalLatency;
288         Next = &*P;
289       }
290     }
291   }
292 
293   return (Next) ? Next->getSUnit() : nullptr;
294 }
295 
296 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
297                                              const char *tag,
298                                              const char *header,
299                                              const char *footer) {
300   std::vector<unsigned> &KillIndices = State->GetKillIndices();
301   std::vector<unsigned> &DefIndices = State->GetDefIndices();
302   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
303     RegRefs = State->GetRegRefs();
304 
305   // FIXME: We must leave subregisters of live super registers as live, so that
306   // we don't clear out the register tracking information for subregisters of
307   // super registers we're still tracking (and with which we're unioning
308   // subregister definitions).
309   for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
310     if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI)) {
311       LLVM_DEBUG(if (!header && footer) dbgs() << footer);
312       return;
313     }
314 
315   if (!State->IsLive(Reg)) {
316     KillIndices[Reg] = KillIdx;
317     DefIndices[Reg] = ~0u;
318     RegRefs.erase(Reg);
319     State->LeaveGroup(Reg);
320     LLVM_DEBUG(if (header) {
321       dbgs() << header << printReg(Reg, TRI);
322       header = nullptr;
323     });
324     LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
325     // Repeat for subregisters. Note that we only do this if the superregister
326     // was not live because otherwise, regardless whether we have an explicit
327     // use of the subregister, the subregister's contents are needed for the
328     // uses of the superregister.
329     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
330       unsigned SubregReg = *SubRegs;
331       if (!State->IsLive(SubregReg)) {
332         KillIndices[SubregReg] = KillIdx;
333         DefIndices[SubregReg] = ~0u;
334         RegRefs.erase(SubregReg);
335         State->LeaveGroup(SubregReg);
336         LLVM_DEBUG(if (header) {
337           dbgs() << header << printReg(Reg, TRI);
338           header = nullptr;
339         });
340         LLVM_DEBUG(dbgs() << " " << printReg(SubregReg, TRI) << "->g"
341                           << State->GetGroup(SubregReg) << tag);
342       }
343     }
344   }
345 
346   LLVM_DEBUG(if (!header && footer) dbgs() << footer);
347 }
348 
349 void AggressiveAntiDepBreaker::PrescanInstruction(
350     MachineInstr &MI, unsigned Count, std::set<unsigned> &PassthruRegs) {
351   std::vector<unsigned> &DefIndices = State->GetDefIndices();
352   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
353     RegRefs = State->GetRegRefs();
354 
355   // Handle dead defs by simulating a last-use of the register just
356   // after the def. A dead def can occur because the def is truly
357   // dead, or because only a subregister is live at the def. If we
358   // don't do this the dead def will be incorrectly merged into the
359   // previous def.
360   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
361     MachineOperand &MO = MI.getOperand(i);
362     if (!MO.isReg() || !MO.isDef()) continue;
363     Register Reg = MO.getReg();
364     if (Reg == 0) continue;
365 
366     HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
367   }
368 
369   LLVM_DEBUG(dbgs() << "\tDef Groups:");
370   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
371     MachineOperand &MO = MI.getOperand(i);
372     if (!MO.isReg() || !MO.isDef()) continue;
373     Register Reg = MO.getReg();
374     if (Reg == 0) continue;
375 
376     LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI) << "=g"
377                       << State->GetGroup(Reg));
378 
379     // If MI's defs have a special allocation requirement, don't allow
380     // any def registers to be changed. Also assume all registers
381     // defined in a call must not be changed (ABI). Inline assembly may
382     // reference either system calls or the register directly. Skip it until we
383     // can tell user specified registers from compiler-specified.
384     if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI) ||
385         MI.isInlineAsm()) {
386       LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
387       State->UnionGroups(Reg, 0);
388     }
389 
390     // Any aliased that are live at this point are completely or
391     // partially defined here, so group those aliases with Reg.
392     for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
393       unsigned AliasReg = *AI;
394       if (State->IsLive(AliasReg)) {
395         State->UnionGroups(Reg, AliasReg);
396         LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << "(via "
397                           << printReg(AliasReg, TRI) << ")");
398       }
399     }
400 
401     // Note register reference...
402     const TargetRegisterClass *RC = nullptr;
403     if (i < MI.getDesc().getNumOperands())
404       RC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
405     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
406     RegRefs.insert(std::make_pair(Reg, RR));
407   }
408 
409   LLVM_DEBUG(dbgs() << '\n');
410 
411   // Scan the register defs for this instruction and update
412   // live-ranges.
413   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
414     MachineOperand &MO = MI.getOperand(i);
415     if (!MO.isReg() || !MO.isDef()) continue;
416     Register Reg = MO.getReg();
417     if (Reg == 0) continue;
418     // Ignore KILLs and passthru registers for liveness...
419     if (MI.isKill() || (PassthruRegs.count(Reg) != 0))
420       continue;
421 
422     // Update def for Reg and aliases.
423     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
424       // We need to be careful here not to define already-live super registers.
425       // If the super register is already live, then this definition is not
426       // a definition of the whole super register (just a partial insertion
427       // into it). Earlier subregister definitions (which we've not yet visited
428       // because we're iterating bottom-up) need to be linked to the same group
429       // as this definition.
430       if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI))
431         continue;
432 
433       DefIndices[*AI] = Count;
434     }
435   }
436 }
437 
438 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr &MI,
439                                                unsigned Count) {
440   LLVM_DEBUG(dbgs() << "\tUse Groups:");
441   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
442     RegRefs = State->GetRegRefs();
443 
444   // If MI's uses have special allocation requirement, don't allow
445   // any use registers to be changed. Also assume all registers
446   // used in a call must not be changed (ABI).
447   // Inline Assembly register uses also cannot be safely changed.
448   // FIXME: The issue with predicated instruction is more complex. We are being
449   // conservatively here because the kill markers cannot be trusted after
450   // if-conversion:
451   // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
452   // ...
453   // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
454   // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
455   // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
456   //
457   // The first R6 kill is not really a kill since it's killed by a predicated
458   // instruction which may not be executed. The second R6 def may or may not
459   // re-define R6 so it's not safe to change it since the last R6 use cannot be
460   // changed.
461   bool Special = MI.isCall() || MI.hasExtraSrcRegAllocReq() ||
462                  TII->isPredicated(MI) || MI.isInlineAsm();
463 
464   // Scan the register uses for this instruction and update
465   // live-ranges, groups and RegRefs.
466   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
467     MachineOperand &MO = MI.getOperand(i);
468     if (!MO.isReg() || !MO.isUse()) continue;
469     Register Reg = MO.getReg();
470     if (Reg == 0) continue;
471 
472     LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI) << "=g"
473                       << State->GetGroup(Reg));
474 
475     // It wasn't previously live but now it is, this is a kill. Forget
476     // the previous live-range information and start a new live-range
477     // for the register.
478     HandleLastUse(Reg, Count, "(last-use)");
479 
480     if (Special) {
481       LLVM_DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
482       State->UnionGroups(Reg, 0);
483     }
484 
485     // Note register reference...
486     const TargetRegisterClass *RC = nullptr;
487     if (i < MI.getDesc().getNumOperands())
488       RC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
489     AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
490     RegRefs.insert(std::make_pair(Reg, RR));
491   }
492 
493   LLVM_DEBUG(dbgs() << '\n');
494 
495   // Form a group of all defs and uses of a KILL instruction to ensure
496   // that all registers are renamed as a group.
497   if (MI.isKill()) {
498     LLVM_DEBUG(dbgs() << "\tKill Group:");
499 
500     unsigned FirstReg = 0;
501     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
502       MachineOperand &MO = MI.getOperand(i);
503       if (!MO.isReg()) continue;
504       Register Reg = MO.getReg();
505       if (Reg == 0) continue;
506 
507       if (FirstReg != 0) {
508         LLVM_DEBUG(dbgs() << "=" << printReg(Reg, TRI));
509         State->UnionGroups(FirstReg, Reg);
510       } else {
511         LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
512         FirstReg = Reg;
513       }
514     }
515 
516     LLVM_DEBUG(dbgs() << "->g" << State->GetGroup(FirstReg) << '\n');
517   }
518 }
519 
520 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
521   BitVector BV(TRI->getNumRegs(), false);
522   bool first = true;
523 
524   // Check all references that need rewriting for Reg. For each, use
525   // the corresponding register class to narrow the set of registers
526   // that are appropriate for renaming.
527   for (const auto &Q : make_range(State->GetRegRefs().equal_range(Reg))) {
528     const TargetRegisterClass *RC = Q.second.RC;
529     if (!RC) continue;
530 
531     BitVector RCBV = TRI->getAllocatableSet(MF, RC);
532     if (first) {
533       BV |= RCBV;
534       first = false;
535     } else {
536       BV &= RCBV;
537     }
538 
539     LLVM_DEBUG(dbgs() << " " << TRI->getRegClassName(RC));
540   }
541 
542   return BV;
543 }
544 
545 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
546                                 unsigned AntiDepGroupIndex,
547                                 RenameOrderType& RenameOrder,
548                                 std::map<unsigned, unsigned> &RenameMap) {
549   std::vector<unsigned> &KillIndices = State->GetKillIndices();
550   std::vector<unsigned> &DefIndices = State->GetDefIndices();
551   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
552     RegRefs = State->GetRegRefs();
553 
554   // Collect all referenced registers in the same group as
555   // AntiDepReg. These all need to be renamed together if we are to
556   // break the anti-dependence.
557   std::vector<unsigned> Regs;
558   State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
559   assert(!Regs.empty() && "Empty register group!");
560   if (Regs.empty())
561     return false;
562 
563   // Find the "superest" register in the group. At the same time,
564   // collect the BitVector of registers that can be used to rename
565   // each register.
566   LLVM_DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
567                     << ":\n");
568   std::map<unsigned, BitVector> RenameRegisterMap;
569   unsigned SuperReg = 0;
570   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
571     unsigned Reg = Regs[i];
572     if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
573       SuperReg = Reg;
574 
575     // If Reg has any references, then collect possible rename regs
576     if (RegRefs.count(Reg) > 0) {
577       LLVM_DEBUG(dbgs() << "\t\t" << printReg(Reg, TRI) << ":");
578 
579       BitVector &BV = RenameRegisterMap[Reg];
580       assert(BV.empty());
581       BV = GetRenameRegisters(Reg);
582 
583       LLVM_DEBUG({
584         dbgs() << " ::";
585         for (unsigned r : BV.set_bits())
586           dbgs() << " " << printReg(r, TRI);
587         dbgs() << "\n";
588       });
589     }
590   }
591 
592   // All group registers should be a subreg of SuperReg.
593   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
594     unsigned Reg = Regs[i];
595     if (Reg == SuperReg) continue;
596     bool IsSub = TRI->isSubRegister(SuperReg, Reg);
597     // FIXME: remove this once PR18663 has been properly fixed. For now,
598     // return a conservative answer:
599     // assert(IsSub && "Expecting group subregister");
600     if (!IsSub)
601       return false;
602   }
603 
604 #ifndef NDEBUG
605   // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
606   if (DebugDiv > 0) {
607     static int renamecnt = 0;
608     if (renamecnt++ % DebugDiv != DebugMod)
609       return false;
610 
611     dbgs() << "*** Performing rename " << printReg(SuperReg, TRI)
612            << " for debug ***\n";
613   }
614 #endif
615 
616   // Check each possible rename register for SuperReg in round-robin
617   // order. If that register is available, and the corresponding
618   // registers are available for the other group subregisters, then we
619   // can use those registers to rename.
620 
621   // FIXME: Using getMinimalPhysRegClass is very conservative. We should
622   // check every use of the register and find the largest register class
623   // that can be used in all of them.
624   const TargetRegisterClass *SuperRC =
625     TRI->getMinimalPhysRegClass(SuperReg, MVT::Other);
626 
627   ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(SuperRC);
628   if (Order.empty()) {
629     LLVM_DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
630     return false;
631   }
632 
633   LLVM_DEBUG(dbgs() << "\tFind Registers:");
634 
635   RenameOrder.insert(RenameOrderType::value_type(SuperRC, Order.size()));
636 
637   unsigned OrigR = RenameOrder[SuperRC];
638   unsigned EndR = ((OrigR == Order.size()) ? 0 : OrigR);
639   unsigned R = OrigR;
640   do {
641     if (R == 0) R = Order.size();
642     --R;
643     const unsigned NewSuperReg = Order[R];
644     // Don't consider non-allocatable registers
645     if (!MRI.isAllocatable(NewSuperReg)) continue;
646     // Don't replace a register with itself.
647     if (NewSuperReg == SuperReg) continue;
648 
649     LLVM_DEBUG(dbgs() << " [" << printReg(NewSuperReg, TRI) << ':');
650     RenameMap.clear();
651 
652     // For each referenced group register (which must be a SuperReg or
653     // a subregister of SuperReg), find the corresponding subregister
654     // of NewSuperReg and make sure it is free to be renamed.
655     for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
656       unsigned Reg = Regs[i];
657       unsigned NewReg = 0;
658       if (Reg == SuperReg) {
659         NewReg = NewSuperReg;
660       } else {
661         unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
662         if (NewSubRegIdx != 0)
663           NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
664       }
665 
666       LLVM_DEBUG(dbgs() << " " << printReg(NewReg, TRI));
667 
668       // Check if Reg can be renamed to NewReg.
669       if (!RenameRegisterMap[Reg].test(NewReg)) {
670         LLVM_DEBUG(dbgs() << "(no rename)");
671         goto next_super_reg;
672       }
673 
674       // If NewReg is dead and NewReg's most recent def is not before
675       // Regs's kill, it's safe to replace Reg with NewReg. We
676       // must also check all aliases of NewReg, because we can't define a
677       // register when any sub or super is already live.
678       if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
679         LLVM_DEBUG(dbgs() << "(live)");
680         goto next_super_reg;
681       } else {
682         bool found = false;
683         for (MCRegAliasIterator AI(NewReg, TRI, false); AI.isValid(); ++AI) {
684           unsigned AliasReg = *AI;
685           if (State->IsLive(AliasReg) ||
686               (KillIndices[Reg] > DefIndices[AliasReg])) {
687             LLVM_DEBUG(dbgs()
688                        << "(alias " << printReg(AliasReg, TRI) << " live)");
689             found = true;
690             break;
691           }
692         }
693         if (found)
694           goto next_super_reg;
695       }
696 
697       // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
698       // defines 'NewReg' via an early-clobber operand.
699       for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
700         MachineInstr *UseMI = Q.second.Operand->getParent();
701         int Idx = UseMI->findRegisterDefOperandIdx(NewReg, false, true, TRI);
702         if (Idx == -1)
703           continue;
704 
705         if (UseMI->getOperand(Idx).isEarlyClobber()) {
706           LLVM_DEBUG(dbgs() << "(ec)");
707           goto next_super_reg;
708         }
709       }
710 
711       // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
712       // 'Reg' is an early-clobber define and that instruction also uses
713       // 'NewReg'.
714       for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
715         if (!Q.second.Operand->isDef() || !Q.second.Operand->isEarlyClobber())
716           continue;
717 
718         MachineInstr *DefMI = Q.second.Operand->getParent();
719         if (DefMI->readsRegister(NewReg, TRI)) {
720           LLVM_DEBUG(dbgs() << "(ec)");
721           goto next_super_reg;
722         }
723       }
724 
725       // Record that 'Reg' can be renamed to 'NewReg'.
726       RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
727     }
728 
729     // If we fall-out here, then every register in the group can be
730     // renamed, as recorded in RenameMap.
731     RenameOrder.erase(SuperRC);
732     RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
733     LLVM_DEBUG(dbgs() << "]\n");
734     return true;
735 
736   next_super_reg:
737     LLVM_DEBUG(dbgs() << ']');
738   } while (R != EndR);
739 
740   LLVM_DEBUG(dbgs() << '\n');
741 
742   // No registers are free and available!
743   return false;
744 }
745 
746 /// BreakAntiDependencies - Identifiy anti-dependencies within the
747 /// ScheduleDAG and break them by renaming registers.
748 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
749                               const std::vector<SUnit> &SUnits,
750                               MachineBasicBlock::iterator Begin,
751                               MachineBasicBlock::iterator End,
752                               unsigned InsertPosIndex,
753                               DbgValueVector &DbgValues) {
754   std::vector<unsigned> &KillIndices = State->GetKillIndices();
755   std::vector<unsigned> &DefIndices = State->GetDefIndices();
756   std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
757     RegRefs = State->GetRegRefs();
758 
759   // The code below assumes that there is at least one instruction,
760   // so just duck out immediately if the block is empty.
761   if (SUnits.empty()) return 0;
762 
763   // For each regclass the next register to use for renaming.
764   RenameOrderType RenameOrder;
765 
766   // ...need a map from MI to SUnit.
767   std::map<MachineInstr *, const SUnit *> MISUnitMap;
768   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
769     const SUnit *SU = &SUnits[i];
770     MISUnitMap.insert(std::pair<MachineInstr *, const SUnit *>(SU->getInstr(),
771                                                                SU));
772   }
773 
774   // Track progress along the critical path through the SUnit graph as
775   // we walk the instructions. This is needed for regclasses that only
776   // break critical-path anti-dependencies.
777   const SUnit *CriticalPathSU = nullptr;
778   MachineInstr *CriticalPathMI = nullptr;
779   if (CriticalPathSet.any()) {
780     for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
781       const SUnit *SU = &SUnits[i];
782       if (!CriticalPathSU ||
783           ((SU->getDepth() + SU->Latency) >
784            (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
785         CriticalPathSU = SU;
786       }
787     }
788     assert(CriticalPathSU && "Failed to find SUnit critical path");
789     CriticalPathMI = CriticalPathSU->getInstr();
790   }
791 
792 #ifndef NDEBUG
793   LLVM_DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
794   LLVM_DEBUG(dbgs() << "Available regs:");
795   for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
796     if (!State->IsLive(Reg))
797       LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI));
798   }
799   LLVM_DEBUG(dbgs() << '\n');
800 #endif
801 
802   BitVector RegAliases(TRI->getNumRegs());
803 
804   // Attempt to break anti-dependence edges. Walk the instructions
805   // from the bottom up, tracking information about liveness as we go
806   // to help determine which registers are available.
807   unsigned Broken = 0;
808   unsigned Count = InsertPosIndex - 1;
809   for (MachineBasicBlock::iterator I = End, E = Begin;
810        I != E; --Count) {
811     MachineInstr &MI = *--I;
812 
813     if (MI.isDebugInstr())
814       continue;
815 
816     LLVM_DEBUG(dbgs() << "Anti: ");
817     LLVM_DEBUG(MI.dump());
818 
819     std::set<unsigned> PassthruRegs;
820     GetPassthruRegs(MI, PassthruRegs);
821 
822     // Process the defs in MI...
823     PrescanInstruction(MI, Count, PassthruRegs);
824 
825     // The dependence edges that represent anti- and output-
826     // dependencies that are candidates for breaking.
827     std::vector<const SDep *> Edges;
828     const SUnit *PathSU = MISUnitMap[&MI];
829     AntiDepEdges(PathSU, Edges);
830 
831     // If MI is not on the critical path, then we don't rename
832     // registers in the CriticalPathSet.
833     BitVector *ExcludeRegs = nullptr;
834     if (&MI == CriticalPathMI) {
835       CriticalPathSU = CriticalPathStep(CriticalPathSU);
836       CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : nullptr;
837     } else if (CriticalPathSet.any()) {
838       ExcludeRegs = &CriticalPathSet;
839     }
840 
841     // Ignore KILL instructions (they form a group in ScanInstruction
842     // but don't cause any anti-dependence breaking themselves)
843     if (!MI.isKill()) {
844       // Attempt to break each anti-dependency...
845       for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
846         const SDep *Edge = Edges[i];
847         SUnit *NextSU = Edge->getSUnit();
848 
849         if ((Edge->getKind() != SDep::Anti) &&
850             (Edge->getKind() != SDep::Output)) continue;
851 
852         unsigned AntiDepReg = Edge->getReg();
853         LLVM_DEBUG(dbgs() << "\tAntidep reg: " << printReg(AntiDepReg, TRI));
854         assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
855 
856         if (!MRI.isAllocatable(AntiDepReg)) {
857           // Don't break anti-dependencies on non-allocatable registers.
858           LLVM_DEBUG(dbgs() << " (non-allocatable)\n");
859           continue;
860         } else if (ExcludeRegs && ExcludeRegs->test(AntiDepReg)) {
861           // Don't break anti-dependencies for critical path registers
862           // if not on the critical path
863           LLVM_DEBUG(dbgs() << " (not critical-path)\n");
864           continue;
865         } else if (PassthruRegs.count(AntiDepReg) != 0) {
866           // If the anti-dep register liveness "passes-thru", then
867           // don't try to change it. It will be changed along with
868           // the use if required to break an earlier antidep.
869           LLVM_DEBUG(dbgs() << " (passthru)\n");
870           continue;
871         } else {
872           // No anti-dep breaking for implicit deps
873           MachineOperand *AntiDepOp = MI.findRegisterDefOperand(AntiDepReg);
874           assert(AntiDepOp && "Can't find index for defined register operand");
875           if (!AntiDepOp || AntiDepOp->isImplicit()) {
876             LLVM_DEBUG(dbgs() << " (implicit)\n");
877             continue;
878           }
879 
880           // If the SUnit has other dependencies on the SUnit that
881           // it anti-depends on, don't bother breaking the
882           // anti-dependency since those edges would prevent such
883           // units from being scheduled past each other
884           // regardless.
885           //
886           // Also, if there are dependencies on other SUnits with the
887           // same register as the anti-dependency, don't attempt to
888           // break it.
889           for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
890                  PE = PathSU->Preds.end(); P != PE; ++P) {
891             if (P->getSUnit() == NextSU ?
892                 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
893                 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
894               AntiDepReg = 0;
895               break;
896             }
897           }
898           for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
899                  PE = PathSU->Preds.end(); P != PE; ++P) {
900             if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
901                 (P->getKind() != SDep::Output)) {
902               LLVM_DEBUG(dbgs() << " (real dependency)\n");
903               AntiDepReg = 0;
904               break;
905             } else if ((P->getSUnit() != NextSU) &&
906                        (P->getKind() == SDep::Data) &&
907                        (P->getReg() == AntiDepReg)) {
908               LLVM_DEBUG(dbgs() << " (other dependency)\n");
909               AntiDepReg = 0;
910               break;
911             }
912           }
913 
914           if (AntiDepReg == 0) continue;
915 
916           // If the definition of the anti-dependency register does not start
917           // a new live range, bail out. This can happen if the anti-dep
918           // register is a sub-register of another register whose live range
919           // spans over PathSU. In such case, PathSU defines only a part of
920           // the larger register.
921           RegAliases.reset();
922           for (MCRegAliasIterator AI(AntiDepReg, TRI, true); AI.isValid(); ++AI)
923             RegAliases.set(*AI);
924           for (SDep S : PathSU->Succs) {
925             SDep::Kind K = S.getKind();
926             if (K != SDep::Data && K != SDep::Output && K != SDep::Anti)
927               continue;
928             unsigned R = S.getReg();
929             if (!RegAliases[R])
930               continue;
931             if (R == AntiDepReg || TRI->isSubRegister(AntiDepReg, R))
932               continue;
933             AntiDepReg = 0;
934             break;
935           }
936 
937           if (AntiDepReg == 0) continue;
938         }
939 
940         assert(AntiDepReg != 0);
941         if (AntiDepReg == 0) continue;
942 
943         // Determine AntiDepReg's register group.
944         const unsigned GroupIndex = State->GetGroup(AntiDepReg);
945         if (GroupIndex == 0) {
946           LLVM_DEBUG(dbgs() << " (zero group)\n");
947           continue;
948         }
949 
950         LLVM_DEBUG(dbgs() << '\n');
951 
952         // Look for a suitable register to use to break the anti-dependence.
953         std::map<unsigned, unsigned> RenameMap;
954         if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
955           LLVM_DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
956                             << printReg(AntiDepReg, TRI) << ":");
957 
958           // Handle each group register...
959           for (std::map<unsigned, unsigned>::iterator
960                  S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
961             unsigned CurrReg = S->first;
962             unsigned NewReg = S->second;
963 
964             LLVM_DEBUG(dbgs() << " " << printReg(CurrReg, TRI) << "->"
965                               << printReg(NewReg, TRI) << "("
966                               << RegRefs.count(CurrReg) << " refs)");
967 
968             // Update the references to the old register CurrReg to
969             // refer to the new register NewReg.
970             for (const auto &Q : make_range(RegRefs.equal_range(CurrReg))) {
971               Q.second.Operand->setReg(NewReg);
972               // If the SU for the instruction being updated has debug
973               // information related to the anti-dependency register, make
974               // sure to update that as well.
975               const SUnit *SU = MISUnitMap[Q.second.Operand->getParent()];
976               if (!SU) continue;
977               UpdateDbgValues(DbgValues, Q.second.Operand->getParent(),
978                               AntiDepReg, NewReg);
979             }
980 
981             // We just went back in time and modified history; the
982             // liveness information for CurrReg is now inconsistent. Set
983             // the state as if it were dead.
984             State->UnionGroups(NewReg, 0);
985             RegRefs.erase(NewReg);
986             DefIndices[NewReg] = DefIndices[CurrReg];
987             KillIndices[NewReg] = KillIndices[CurrReg];
988 
989             State->UnionGroups(CurrReg, 0);
990             RegRefs.erase(CurrReg);
991             DefIndices[CurrReg] = KillIndices[CurrReg];
992             KillIndices[CurrReg] = ~0u;
993             assert(((KillIndices[CurrReg] == ~0u) !=
994                     (DefIndices[CurrReg] == ~0u)) &&
995                    "Kill and Def maps aren't consistent for AntiDepReg!");
996           }
997 
998           ++Broken;
999           LLVM_DEBUG(dbgs() << '\n');
1000         }
1001       }
1002     }
1003 
1004     ScanInstruction(MI, Count);
1005   }
1006 
1007   return Broken;
1008 }
1009 
1010 AntiDepBreaker *llvm::createAggressiveAntiDepBreaker(
1011     MachineFunction &MFi, const RegisterClassInfo &RCI,
1012     TargetSubtargetInfo::RegClassVector &CriticalPathRCs) {
1013   return new AggressiveAntiDepBreaker(MFi, RCI, CriticalPathRCs);
1014 }
1015