1 //===----- AggressiveAntiDepBreaker.cpp - Anti-dep breaker ----------------===//
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 the AggressiveAntiDepBreaker class, which
11 // implements register anti-dependence breaking during post-RA
12 // scheduling. It attempts to break all anti-dependencies within a
15 //===----------------------------------------------------------------------===//
17 #include "AggressiveAntiDepBreaker.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/RegisterClassInfo.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
30 #define DEBUG_TYPE "post-RA-sched"
32 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
34 DebugDiv("agg-antidep-debugdiv",
35 cl::desc("Debug control for aggressive anti-dep breaker"),
36 cl::init(0), cl::Hidden);
38 DebugMod("agg-antidep-debugmod",
39 cl::desc("Debug control for aggressive anti-dep breaker"),
40 cl::init(0), cl::Hidden);
42 AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs,
43 MachineBasicBlock *BB) :
44 NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0),
45 GroupNodeIndices(TargetRegs, 0),
46 KillIndices(TargetRegs, 0),
47 DefIndices(TargetRegs, 0)
49 const unsigned BBSize = BB->size();
50 for (unsigned i = 0; i < NumTargetRegs; ++i) {
51 // Initialize all registers to be in their own group. Initially we
52 // assign the register to the same-indexed GroupNode.
53 GroupNodeIndices[i] = i;
54 // Initialize the indices to indicate that no registers are live.
56 DefIndices[i] = BBSize;
60 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg) {
61 unsigned Node = GroupNodeIndices[Reg];
62 while (GroupNodes[Node] != Node)
63 Node = GroupNodes[Node];
68 void AggressiveAntiDepState::GetGroupRegs(
70 std::vector<unsigned> &Regs,
71 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
73 for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
74 if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
79 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
81 assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
82 assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
84 // find group for each register
85 unsigned Group1 = GetGroup(Reg1);
86 unsigned Group2 = GetGroup(Reg2);
88 // if either group is 0, then that must become the parent
89 unsigned Parent = (Group1 == 0) ? Group1 : Group2;
90 unsigned Other = (Parent == Group1) ? Group2 : Group1;
91 GroupNodes.at(Other) = Parent;
95 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
97 // Create a new GroupNode for Reg. Reg's existing GroupNode must
98 // stay as is because there could be other GroupNodes referring to
100 unsigned idx = GroupNodes.size();
101 GroupNodes.push_back(idx);
102 GroupNodeIndices[Reg] = idx;
106 bool AggressiveAntiDepState::IsLive(unsigned Reg)
108 // KillIndex must be defined and DefIndex not defined for a register
110 return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
113 AggressiveAntiDepBreaker::AggressiveAntiDepBreaker(
114 MachineFunction &MFi, const RegisterClassInfo &RCI,
115 TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
116 : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
117 TII(MF.getSubtarget().getInstrInfo()),
118 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
120 /* Collect a bitset of all registers that are only broken if they
121 are on the critical path. */
122 for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
123 BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
124 if (CriticalPathSet.none())
125 CriticalPathSet = CPSet;
127 CriticalPathSet |= CPSet;
130 DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
131 DEBUG(for (int r = CriticalPathSet.find_first(); r != -1;
132 r = CriticalPathSet.find_next(r))
133 dbgs() << " " << TRI->getName(r));
134 DEBUG(dbgs() << '\n');
137 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
141 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
143 State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
145 bool IsReturnBlock = BB->isReturnBlock();
146 std::vector<unsigned> &KillIndices = State->GetKillIndices();
147 std::vector<unsigned> &DefIndices = State->GetDefIndices();
149 // Examine the live-in regs of all successors.
150 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
151 SE = BB->succ_end(); SI != SE; ++SI)
152 for (const auto &LI : (*SI)->liveins()) {
153 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
155 State->UnionGroups(Reg, 0);
156 KillIndices[Reg] = BB->size();
157 DefIndices[Reg] = ~0u;
161 // Mark live-out callee-saved registers. In a return block this is
162 // all callee-saved registers. In non-return this is any
163 // callee-saved register that is not saved in the prolog.
164 const MachineFrameInfo *MFI = MF.getFrameInfo();
165 BitVector Pristine = MFI->getPristineRegs(MF);
166 for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
168 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
169 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
170 unsigned AliasReg = *AI;
171 State->UnionGroups(AliasReg, 0);
172 KillIndices[AliasReg] = BB->size();
173 DefIndices[AliasReg] = ~0u;
178 void AggressiveAntiDepBreaker::FinishBlock() {
183 void AggressiveAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
184 unsigned InsertPosIndex) {
185 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
187 std::set<unsigned> PassthruRegs;
188 GetPassthruRegs(MI, PassthruRegs);
189 PrescanInstruction(MI, Count, PassthruRegs);
190 ScanInstruction(MI, Count);
192 DEBUG(dbgs() << "Observe: ");
194 DEBUG(dbgs() << "\tRegs:");
196 std::vector<unsigned> &DefIndices = State->GetDefIndices();
197 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
198 // If Reg is current live, then mark that it can't be renamed as
199 // we don't know the extent of its live-range anymore (now that it
200 // has been scheduled). If it is not live but was defined in the
201 // previous schedule region, then set its def index to the most
202 // conservative location (i.e. the beginning of the previous
204 if (State->IsLive(Reg)) {
205 DEBUG(if (State->GetGroup(Reg) != 0)
206 dbgs() << " " << TRI->getName(Reg) << "=g" <<
207 State->GetGroup(Reg) << "->g0(region live-out)");
208 State->UnionGroups(Reg, 0);
209 } else if ((DefIndices[Reg] < InsertPosIndex)
210 && (DefIndices[Reg] >= Count)) {
211 DefIndices[Reg] = Count;
214 DEBUG(dbgs() << '\n');
217 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr *MI,
220 if (!MO.isReg() || !MO.isImplicit())
223 unsigned Reg = MO.getReg();
227 MachineOperand *Op = MI->findRegisterUseOperand(Reg, /*isKill=*/MO.isDef());
228 return(Op && Op->isImplicit());
231 void AggressiveAntiDepBreaker::GetPassthruRegs(MachineInstr *MI,
232 std::set<unsigned>& PassthruRegs) {
233 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
234 MachineOperand &MO = MI->getOperand(i);
235 if (!MO.isReg()) continue;
236 if ((MO.isDef() && MI->isRegTiedToUseOperand(i)) ||
237 IsImplicitDefUse(MI, MO)) {
238 const unsigned Reg = MO.getReg();
239 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
240 SubRegs.isValid(); ++SubRegs)
241 PassthruRegs.insert(*SubRegs);
246 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
247 /// in SU that we want to consider for breaking.
248 static void AntiDepEdges(const SUnit *SU, std::vector<const SDep*>& Edges) {
249 SmallSet<unsigned, 4> RegSet;
250 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
252 if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
253 if (RegSet.insert(P->getReg()).second)
254 Edges.push_back(&*P);
259 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
261 static const SUnit *CriticalPathStep(const SUnit *SU) {
262 const SDep *Next = nullptr;
263 unsigned NextDepth = 0;
264 // Find the predecessor edge with the greatest depth.
266 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
268 const SUnit *PredSU = P->getSUnit();
269 unsigned PredLatency = P->getLatency();
270 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
271 // In the case of a latency tie, prefer an anti-dependency edge over
272 // other types of edges.
273 if (NextDepth < PredTotalLatency ||
274 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
275 NextDepth = PredTotalLatency;
281 return (Next) ? Next->getSUnit() : nullptr;
284 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
287 const char *footer) {
288 std::vector<unsigned> &KillIndices = State->GetKillIndices();
289 std::vector<unsigned> &DefIndices = State->GetDefIndices();
290 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
291 RegRefs = State->GetRegRefs();
293 // FIXME: We must leave subregisters of live super registers as live, so that
294 // we don't clear out the register tracking information for subregisters of
295 // super registers we're still tracking (and with which we're unioning
296 // subregister definitions).
297 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
298 if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI)) {
299 DEBUG(if (!header && footer) dbgs() << footer);
303 if (!State->IsLive(Reg)) {
304 KillIndices[Reg] = KillIdx;
305 DefIndices[Reg] = ~0u;
307 State->LeaveGroup(Reg);
309 dbgs() << header << TRI->getName(Reg); header = nullptr; });
310 DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
312 // Repeat for subregisters.
313 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
314 unsigned SubregReg = *SubRegs;
315 if (!State->IsLive(SubregReg)) {
316 KillIndices[SubregReg] = KillIdx;
317 DefIndices[SubregReg] = ~0u;
318 RegRefs.erase(SubregReg);
319 State->LeaveGroup(SubregReg);
321 dbgs() << header << TRI->getName(Reg); header = nullptr; });
322 DEBUG(dbgs() << " " << TRI->getName(SubregReg) << "->g" <<
323 State->GetGroup(SubregReg) << tag);
327 DEBUG(if (!header && footer) dbgs() << footer);
330 void AggressiveAntiDepBreaker::PrescanInstruction(MachineInstr *MI,
332 std::set<unsigned>& PassthruRegs) {
333 std::vector<unsigned> &DefIndices = State->GetDefIndices();
334 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
335 RegRefs = State->GetRegRefs();
337 // Handle dead defs by simulating a last-use of the register just
338 // after the def. A dead def can occur because the def is truly
339 // dead, or because only a subregister is live at the def. If we
340 // don't do this the dead def will be incorrectly merged into the
342 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
343 MachineOperand &MO = MI->getOperand(i);
344 if (!MO.isReg() || !MO.isDef()) continue;
345 unsigned Reg = MO.getReg();
346 if (Reg == 0) continue;
348 HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
351 DEBUG(dbgs() << "\tDef Groups:");
352 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
353 MachineOperand &MO = MI->getOperand(i);
354 if (!MO.isReg() || !MO.isDef()) continue;
355 unsigned Reg = MO.getReg();
356 if (Reg == 0) continue;
358 DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg));
360 // If MI's defs have a special allocation requirement, don't allow
361 // any def registers to be changed. Also assume all registers
362 // defined in a call must not be changed (ABI).
363 if (MI->isCall() || MI->hasExtraDefRegAllocReq() ||
364 TII->isPredicated(MI)) {
365 DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
366 State->UnionGroups(Reg, 0);
369 // Any aliased that are live at this point are completely or
370 // partially defined here, so group those aliases with Reg.
371 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
372 unsigned AliasReg = *AI;
373 if (State->IsLive(AliasReg)) {
374 State->UnionGroups(Reg, AliasReg);
375 DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << "(via " <<
376 TRI->getName(AliasReg) << ")");
380 // Note register reference...
381 const TargetRegisterClass *RC = nullptr;
382 if (i < MI->getDesc().getNumOperands())
383 RC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
384 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
385 RegRefs.insert(std::make_pair(Reg, RR));
388 DEBUG(dbgs() << '\n');
390 // Scan the register defs for this instruction and update
392 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
393 MachineOperand &MO = MI->getOperand(i);
394 if (!MO.isReg() || !MO.isDef()) continue;
395 unsigned Reg = MO.getReg();
396 if (Reg == 0) continue;
397 // Ignore KILLs and passthru registers for liveness...
398 if (MI->isKill() || (PassthruRegs.count(Reg) != 0))
401 // Update def for Reg and aliases.
402 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
403 // We need to be careful here not to define already-live super registers.
404 // If the super register is already live, then this definition is not
405 // a definition of the whole super register (just a partial insertion
406 // into it). Earlier subregister definitions (which we've not yet visited
407 // because we're iterating bottom-up) need to be linked to the same group
408 // as this definition.
409 if (TRI->isSuperRegister(Reg, *AI) && State->IsLive(*AI))
412 DefIndices[*AI] = Count;
417 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr *MI,
419 DEBUG(dbgs() << "\tUse Groups:");
420 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
421 RegRefs = State->GetRegRefs();
423 // If MI's uses have special allocation requirement, don't allow
424 // any use registers to be changed. Also assume all registers
425 // used in a call must not be changed (ABI).
426 // FIXME: The issue with predicated instruction is more complex. We are being
427 // conservatively here because the kill markers cannot be trusted after
429 // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
431 // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
432 // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
433 // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
435 // The first R6 kill is not really a kill since it's killed by a predicated
436 // instruction which may not be executed. The second R6 def may or may not
437 // re-define R6 so it's not safe to change it since the last R6 use cannot be
439 bool Special = MI->isCall() ||
440 MI->hasExtraSrcRegAllocReq() ||
441 TII->isPredicated(MI);
443 // Scan the register uses for this instruction and update
444 // live-ranges, groups and RegRefs.
445 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
446 MachineOperand &MO = MI->getOperand(i);
447 if (!MO.isReg() || !MO.isUse()) continue;
448 unsigned Reg = MO.getReg();
449 if (Reg == 0) continue;
451 DEBUG(dbgs() << " " << TRI->getName(Reg) << "=g" <<
452 State->GetGroup(Reg));
454 // It wasn't previously live but now it is, this is a kill. Forget
455 // the previous live-range information and start a new live-range
457 HandleLastUse(Reg, Count, "(last-use)");
460 DEBUG(if (State->GetGroup(Reg) != 0) dbgs() << "->g0(alloc-req)");
461 State->UnionGroups(Reg, 0);
464 // Note register reference...
465 const TargetRegisterClass *RC = nullptr;
466 if (i < MI->getDesc().getNumOperands())
467 RC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
468 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
469 RegRefs.insert(std::make_pair(Reg, RR));
472 DEBUG(dbgs() << '\n');
474 // Form a group of all defs and uses of a KILL instruction to ensure
475 // that all registers are renamed as a group.
477 DEBUG(dbgs() << "\tKill Group:");
479 unsigned FirstReg = 0;
480 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
481 MachineOperand &MO = MI->getOperand(i);
482 if (!MO.isReg()) continue;
483 unsigned Reg = MO.getReg();
484 if (Reg == 0) continue;
487 DEBUG(dbgs() << "=" << TRI->getName(Reg));
488 State->UnionGroups(FirstReg, Reg);
490 DEBUG(dbgs() << " " << TRI->getName(Reg));
495 DEBUG(dbgs() << "->g" << State->GetGroup(FirstReg) << '\n');
499 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
500 BitVector BV(TRI->getNumRegs(), false);
503 // Check all references that need rewriting for Reg. For each, use
504 // the corresponding register class to narrow the set of registers
505 // that are appropriate for renaming.
506 for (const auto &Q : make_range(State->GetRegRefs().equal_range(Reg))) {
507 const TargetRegisterClass *RC = Q.second.RC;
510 BitVector RCBV = TRI->getAllocatableSet(MF, RC);
518 DEBUG(dbgs() << " " << TRI->getRegClassName(RC));
524 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
525 unsigned AntiDepGroupIndex,
526 RenameOrderType& RenameOrder,
527 std::map<unsigned, unsigned> &RenameMap) {
528 std::vector<unsigned> &KillIndices = State->GetKillIndices();
529 std::vector<unsigned> &DefIndices = State->GetDefIndices();
530 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
531 RegRefs = State->GetRegRefs();
533 // Collect all referenced registers in the same group as
534 // AntiDepReg. These all need to be renamed together if we are to
535 // break the anti-dependence.
536 std::vector<unsigned> Regs;
537 State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
538 assert(Regs.size() > 0 && "Empty register group!");
539 if (Regs.size() == 0)
542 // Find the "superest" register in the group. At the same time,
543 // collect the BitVector of registers that can be used to rename
545 DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
547 std::map<unsigned, BitVector> RenameRegisterMap;
548 unsigned SuperReg = 0;
549 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
550 unsigned Reg = Regs[i];
551 if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
554 // If Reg has any references, then collect possible rename regs
555 if (RegRefs.count(Reg) > 0) {
556 DEBUG(dbgs() << "\t\t" << TRI->getName(Reg) << ":");
558 BitVector BV = GetRenameRegisters(Reg);
559 RenameRegisterMap.insert(std::pair<unsigned, BitVector>(Reg, BV));
561 DEBUG(dbgs() << " ::");
562 DEBUG(for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
563 dbgs() << " " << TRI->getName(r));
564 DEBUG(dbgs() << "\n");
568 // All group registers should be a subreg of SuperReg.
569 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
570 unsigned Reg = Regs[i];
571 if (Reg == SuperReg) continue;
572 bool IsSub = TRI->isSubRegister(SuperReg, Reg);
573 // FIXME: remove this once PR18663 has been properly fixed. For now,
574 // return a conservative answer:
575 // assert(IsSub && "Expecting group subregister");
581 // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
583 static int renamecnt = 0;
584 if (renamecnt++ % DebugDiv != DebugMod)
587 dbgs() << "*** Performing rename " << TRI->getName(SuperReg) <<
592 // Check each possible rename register for SuperReg in round-robin
593 // order. If that register is available, and the corresponding
594 // registers are available for the other group subregisters, then we
595 // can use those registers to rename.
597 // FIXME: Using getMinimalPhysRegClass is very conservative. We should
598 // check every use of the register and find the largest register class
599 // that can be used in all of them.
600 const TargetRegisterClass *SuperRC =
601 TRI->getMinimalPhysRegClass(SuperReg, MVT::Other);
603 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(SuperRC);
605 DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
609 DEBUG(dbgs() << "\tFind Registers:");
611 RenameOrder.insert(RenameOrderType::value_type(SuperRC, Order.size()));
613 unsigned OrigR = RenameOrder[SuperRC];
614 unsigned EndR = ((OrigR == Order.size()) ? 0 : OrigR);
617 if (R == 0) R = Order.size();
619 const unsigned NewSuperReg = Order[R];
620 // Don't consider non-allocatable registers
621 if (!MRI.isAllocatable(NewSuperReg)) continue;
622 // Don't replace a register with itself.
623 if (NewSuperReg == SuperReg) continue;
625 DEBUG(dbgs() << " [" << TRI->getName(NewSuperReg) << ':');
628 // For each referenced group register (which must be a SuperReg or
629 // a subregister of SuperReg), find the corresponding subregister
630 // of NewSuperReg and make sure it is free to be renamed.
631 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
632 unsigned Reg = Regs[i];
634 if (Reg == SuperReg) {
635 NewReg = NewSuperReg;
637 unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
638 if (NewSubRegIdx != 0)
639 NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
642 DEBUG(dbgs() << " " << TRI->getName(NewReg));
644 // Check if Reg can be renamed to NewReg.
645 BitVector BV = RenameRegisterMap[Reg];
646 if (!BV.test(NewReg)) {
647 DEBUG(dbgs() << "(no rename)");
651 // If NewReg is dead and NewReg's most recent def is not before
652 // Regs's kill, it's safe to replace Reg with NewReg. We
653 // must also check all aliases of NewReg, because we can't define a
654 // register when any sub or super is already live.
655 if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
656 DEBUG(dbgs() << "(live)");
660 for (MCRegAliasIterator AI(NewReg, TRI, false); AI.isValid(); ++AI) {
661 unsigned AliasReg = *AI;
662 if (State->IsLive(AliasReg) ||
663 (KillIndices[Reg] > DefIndices[AliasReg])) {
664 DEBUG(dbgs() << "(alias " << TRI->getName(AliasReg) << " live)");
673 // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
674 // defines 'NewReg' via an early-clobber operand.
675 for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
676 MachineInstr *UseMI = Q.second.Operand->getParent();
677 int Idx = UseMI->findRegisterDefOperandIdx(NewReg, false, true, TRI);
681 if (UseMI->getOperand(Idx).isEarlyClobber()) {
682 DEBUG(dbgs() << "(ec)");
687 // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
688 // 'Reg' is an early-clobber define and that instruction also uses
690 for (const auto &Q : make_range(RegRefs.equal_range(Reg))) {
691 if (!Q.second.Operand->isDef() || !Q.second.Operand->isEarlyClobber())
694 MachineInstr *DefMI = Q.second.Operand->getParent();
695 if (DefMI->readsRegister(NewReg, TRI)) {
696 DEBUG(dbgs() << "(ec)");
701 // Record that 'Reg' can be renamed to 'NewReg'.
702 RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
705 // If we fall-out here, then every register in the group can be
706 // renamed, as recorded in RenameMap.
707 RenameOrder.erase(SuperRC);
708 RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
709 DEBUG(dbgs() << "]\n");
713 DEBUG(dbgs() << ']');
716 DEBUG(dbgs() << '\n');
718 // No registers are free and available!
722 /// BreakAntiDependencies - Identifiy anti-dependencies within the
723 /// ScheduleDAG and break them by renaming registers.
725 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
726 const std::vector<SUnit>& SUnits,
727 MachineBasicBlock::iterator Begin,
728 MachineBasicBlock::iterator End,
729 unsigned InsertPosIndex,
730 DbgValueVector &DbgValues) {
732 std::vector<unsigned> &KillIndices = State->GetKillIndices();
733 std::vector<unsigned> &DefIndices = State->GetDefIndices();
734 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
735 RegRefs = State->GetRegRefs();
737 // The code below assumes that there is at least one instruction,
738 // so just duck out immediately if the block is empty.
739 if (SUnits.empty()) return 0;
741 // For each regclass the next register to use for renaming.
742 RenameOrderType RenameOrder;
744 // ...need a map from MI to SUnit.
745 std::map<MachineInstr *, const SUnit *> MISUnitMap;
746 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
747 const SUnit *SU = &SUnits[i];
748 MISUnitMap.insert(std::pair<MachineInstr *, const SUnit *>(SU->getInstr(),
752 // Track progress along the critical path through the SUnit graph as
753 // we walk the instructions. This is needed for regclasses that only
754 // break critical-path anti-dependencies.
755 const SUnit *CriticalPathSU = nullptr;
756 MachineInstr *CriticalPathMI = nullptr;
757 if (CriticalPathSet.any()) {
758 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
759 const SUnit *SU = &SUnits[i];
760 if (!CriticalPathSU ||
761 ((SU->getDepth() + SU->Latency) >
762 (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
767 CriticalPathMI = CriticalPathSU->getInstr();
771 DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
772 DEBUG(dbgs() << "Available regs:");
773 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
774 if (!State->IsLive(Reg))
775 DEBUG(dbgs() << " " << TRI->getName(Reg));
777 DEBUG(dbgs() << '\n');
780 // Attempt to break anti-dependence edges. Walk the instructions
781 // from the bottom up, tracking information about liveness as we go
782 // to help determine which registers are available.
784 unsigned Count = InsertPosIndex - 1;
785 for (MachineBasicBlock::iterator I = End, E = Begin;
787 MachineInstr *MI = --I;
789 if (MI->isDebugValue())
792 DEBUG(dbgs() << "Anti: ");
795 std::set<unsigned> PassthruRegs;
796 GetPassthruRegs(MI, PassthruRegs);
798 // Process the defs in MI...
799 PrescanInstruction(MI, Count, PassthruRegs);
801 // The dependence edges that represent anti- and output-
802 // dependencies that are candidates for breaking.
803 std::vector<const SDep *> Edges;
804 const SUnit *PathSU = MISUnitMap[MI];
805 AntiDepEdges(PathSU, Edges);
807 // If MI is not on the critical path, then we don't rename
808 // registers in the CriticalPathSet.
809 BitVector *ExcludeRegs = nullptr;
810 if (MI == CriticalPathMI) {
811 CriticalPathSU = CriticalPathStep(CriticalPathSU);
812 CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : nullptr;
813 } else if (CriticalPathSet.any()) {
814 ExcludeRegs = &CriticalPathSet;
817 // Ignore KILL instructions (they form a group in ScanInstruction
818 // but don't cause any anti-dependence breaking themselves)
820 // Attempt to break each anti-dependency...
821 for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
822 const SDep *Edge = Edges[i];
823 SUnit *NextSU = Edge->getSUnit();
825 if ((Edge->getKind() != SDep::Anti) &&
826 (Edge->getKind() != SDep::Output)) continue;
828 unsigned AntiDepReg = Edge->getReg();
829 DEBUG(dbgs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
830 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
832 if (!MRI.isAllocatable(AntiDepReg)) {
833 // Don't break anti-dependencies on non-allocatable registers.
834 DEBUG(dbgs() << " (non-allocatable)\n");
836 } else if (ExcludeRegs && ExcludeRegs->test(AntiDepReg)) {
837 // Don't break anti-dependencies for critical path registers
838 // if not on the critical path
839 DEBUG(dbgs() << " (not critical-path)\n");
841 } else if (PassthruRegs.count(AntiDepReg) != 0) {
842 // If the anti-dep register liveness "passes-thru", then
843 // don't try to change it. It will be changed along with
844 // the use if required to break an earlier antidep.
845 DEBUG(dbgs() << " (passthru)\n");
848 // No anti-dep breaking for implicit deps
849 MachineOperand *AntiDepOp = MI->findRegisterDefOperand(AntiDepReg);
850 assert(AntiDepOp && "Can't find index for defined register operand");
851 if (!AntiDepOp || AntiDepOp->isImplicit()) {
852 DEBUG(dbgs() << " (implicit)\n");
856 // If the SUnit has other dependencies on the SUnit that
857 // it anti-depends on, don't bother breaking the
858 // anti-dependency since those edges would prevent such
859 // units from being scheduled past each other
862 // Also, if there are dependencies on other SUnits with the
863 // same register as the anti-dependency, don't attempt to
865 for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
866 PE = PathSU->Preds.end(); P != PE; ++P) {
867 if (P->getSUnit() == NextSU ?
868 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
869 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
874 for (SUnit::const_pred_iterator P = PathSU->Preds.begin(),
875 PE = PathSU->Preds.end(); P != PE; ++P) {
876 if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
877 (P->getKind() != SDep::Output)) {
878 DEBUG(dbgs() << " (real dependency)\n");
881 } else if ((P->getSUnit() != NextSU) &&
882 (P->getKind() == SDep::Data) &&
883 (P->getReg() == AntiDepReg)) {
884 DEBUG(dbgs() << " (other dependency)\n");
890 if (AntiDepReg == 0) continue;
893 assert(AntiDepReg != 0);
894 if (AntiDepReg == 0) continue;
896 // Determine AntiDepReg's register group.
897 const unsigned GroupIndex = State->GetGroup(AntiDepReg);
898 if (GroupIndex == 0) {
899 DEBUG(dbgs() << " (zero group)\n");
903 DEBUG(dbgs() << '\n');
905 // Look for a suitable register to use to break the anti-dependence.
906 std::map<unsigned, unsigned> RenameMap;
907 if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
908 DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
909 << TRI->getName(AntiDepReg) << ":");
911 // Handle each group register...
912 for (std::map<unsigned, unsigned>::iterator
913 S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
914 unsigned CurrReg = S->first;
915 unsigned NewReg = S->second;
917 DEBUG(dbgs() << " " << TRI->getName(CurrReg) << "->" <<
918 TRI->getName(NewReg) << "(" <<
919 RegRefs.count(CurrReg) << " refs)");
921 // Update the references to the old register CurrReg to
922 // refer to the new register NewReg.
923 for (const auto &Q : make_range(RegRefs.equal_range(CurrReg))) {
924 Q.second.Operand->setReg(NewReg);
925 // If the SU for the instruction being updated has debug
926 // information related to the anti-dependency register, make
927 // sure to update that as well.
928 const SUnit *SU = MISUnitMap[Q.second.Operand->getParent()];
930 for (DbgValueVector::iterator DVI = DbgValues.begin(),
931 DVE = DbgValues.end(); DVI != DVE; ++DVI)
932 if (DVI->second == Q.second.Operand->getParent())
933 UpdateDbgValue(DVI->first, AntiDepReg, NewReg);
936 // We just went back in time and modified history; the
937 // liveness information for CurrReg is now inconsistent. Set
938 // the state as if it were dead.
939 State->UnionGroups(NewReg, 0);
940 RegRefs.erase(NewReg);
941 DefIndices[NewReg] = DefIndices[CurrReg];
942 KillIndices[NewReg] = KillIndices[CurrReg];
944 State->UnionGroups(CurrReg, 0);
945 RegRefs.erase(CurrReg);
946 DefIndices[CurrReg] = KillIndices[CurrReg];
947 KillIndices[CurrReg] = ~0u;
948 assert(((KillIndices[CurrReg] == ~0u) !=
949 (DefIndices[CurrReg] == ~0u)) &&
950 "Kill and Def maps aren't consistent for AntiDepReg!");
954 DEBUG(dbgs() << '\n');
959 ScanInstruction(MI, Count);