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 #define DEBUG_TYPE "post-RA-sched"
18 #include "AggressiveAntiDepBreaker.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
31 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
33 DebugDiv("agg-antidep-debugdiv",
34 cl::desc("Debug control for aggressive anti-dep breaker"),
35 cl::init(0), cl::Hidden);
37 DebugMod("agg-antidep-debugmod",
38 cl::desc("Debug control for aggressive anti-dep breaker"),
39 cl::init(0), cl::Hidden);
41 AggressiveAntiDepState::AggressiveAntiDepState(MachineBasicBlock *BB) :
42 GroupNodes(TargetRegisterInfo::FirstVirtualRegister, 0) {
43 // Initialize all registers to be in their own group. Initially we
44 // assign the register to the same-indexed GroupNode.
45 for (unsigned i = 0; i < TargetRegisterInfo::FirstVirtualRegister; ++i)
46 GroupNodeIndices[i] = i;
48 // Initialize the indices to indicate that no registers are live.
49 std::fill(KillIndices, array_endof(KillIndices), ~0u);
50 std::fill(DefIndices, array_endof(DefIndices), BB->size());
53 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg)
55 unsigned Node = GroupNodeIndices[Reg];
56 while (GroupNodes[Node] != Node)
57 Node = GroupNodes[Node];
62 void AggressiveAntiDepState::GetGroupRegs(
64 std::vector<unsigned> &Regs,
65 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
67 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg) {
68 if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
73 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
75 assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
76 assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
78 // find group for each register
79 unsigned Group1 = GetGroup(Reg1);
80 unsigned Group2 = GetGroup(Reg2);
82 // if either group is 0, then that must become the parent
83 unsigned Parent = (Group1 == 0) ? Group1 : Group2;
84 unsigned Other = (Parent == Group1) ? Group2 : Group1;
85 GroupNodes.at(Other) = Parent;
89 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
91 // Create a new GroupNode for Reg. Reg's existing GroupNode must
92 // stay as is because there could be other GroupNodes referring to
94 unsigned idx = GroupNodes.size();
95 GroupNodes.push_back(idx);
96 GroupNodeIndices[Reg] = idx;
100 bool AggressiveAntiDepState::IsLive(unsigned Reg)
102 // KillIndex must be defined and DefIndex not defined for a register
104 return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
109 AggressiveAntiDepBreaker::
110 AggressiveAntiDepBreaker(MachineFunction& MFi,
111 TargetSubtarget::RegClassVector& CriticalPathRCs) :
112 AntiDepBreaker(), MF(MFi),
113 MRI(MF.getRegInfo()),
114 TRI(MF.getTarget().getRegisterInfo()),
115 AllocatableSet(TRI->getAllocatableSet(MF)),
117 /* Collect a bitset of all registers that are only broken if they
118 are on the critical path. */
119 for (unsigned i = 0, e = CriticalPathRCs.size(); i < e; ++i) {
120 BitVector CPSet = TRI->getAllocatableSet(MF, CriticalPathRCs[i]);
121 if (CriticalPathSet.none())
122 CriticalPathSet = CPSet;
124 CriticalPathSet |= CPSet;
127 DEBUG(errs() << "AntiDep Critical-Path Registers:");
128 DEBUG(for (int r = CriticalPathSet.find_first(); r != -1;
129 r = CriticalPathSet.find_next(r))
130 errs() << " " << TRI->getName(r));
131 DEBUG(errs() << '\n');
134 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
138 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
139 assert(State == NULL);
140 State = new AggressiveAntiDepState(BB);
142 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
143 unsigned *KillIndices = State->GetKillIndices();
144 unsigned *DefIndices = State->GetDefIndices();
146 // Determine the live-out physregs for this block.
148 // In a return block, examine the function live-out regs.
149 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
150 E = MRI.liveout_end(); I != E; ++I) {
152 State->UnionGroups(Reg, 0);
153 KillIndices[Reg] = BB->size();
154 DefIndices[Reg] = ~0u;
155 // Repeat, for all aliases.
156 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
157 unsigned AliasReg = *Alias;
158 State->UnionGroups(AliasReg, 0);
159 KillIndices[AliasReg] = BB->size();
160 DefIndices[AliasReg] = ~0u;
164 // In a non-return block, examine the live-in regs of all successors.
165 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
166 SE = BB->succ_end(); SI != SE; ++SI)
167 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
168 E = (*SI)->livein_end(); I != E; ++I) {
170 State->UnionGroups(Reg, 0);
171 KillIndices[Reg] = BB->size();
172 DefIndices[Reg] = ~0u;
173 // Repeat, for all aliases.
174 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
175 unsigned AliasReg = *Alias;
176 State->UnionGroups(AliasReg, 0);
177 KillIndices[AliasReg] = BB->size();
178 DefIndices[AliasReg] = ~0u;
183 // Mark live-out callee-saved registers. In a return block this is
184 // all callee-saved registers. In non-return this is any
185 // callee-saved register that is not saved in the prolog.
186 const MachineFrameInfo *MFI = MF.getFrameInfo();
187 BitVector Pristine = MFI->getPristineRegs(BB);
188 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
190 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
191 State->UnionGroups(Reg, 0);
192 KillIndices[Reg] = BB->size();
193 DefIndices[Reg] = ~0u;
194 // Repeat, for all aliases.
195 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
196 unsigned AliasReg = *Alias;
197 State->UnionGroups(AliasReg, 0);
198 KillIndices[AliasReg] = BB->size();
199 DefIndices[AliasReg] = ~0u;
204 void AggressiveAntiDepBreaker::FinishBlock() {
209 void AggressiveAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
210 unsigned InsertPosIndex) {
211 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
213 std::set<unsigned> PassthruRegs;
214 GetPassthruRegs(MI, PassthruRegs);
215 PrescanInstruction(MI, Count, PassthruRegs);
216 ScanInstruction(MI, Count);
218 DEBUG(errs() << "Observe: ");
220 DEBUG(errs() << "\tRegs:");
222 unsigned *DefIndices = State->GetDefIndices();
223 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg) {
224 // If Reg is current live, then mark that it can't be renamed as
225 // we don't know the extent of its live-range anymore (now that it
226 // has been scheduled). If it is not live but was defined in the
227 // previous schedule region, then set its def index to the most
228 // conservative location (i.e. the beginning of the previous
230 if (State->IsLive(Reg)) {
231 DEBUG(if (State->GetGroup(Reg) != 0)
232 errs() << " " << TRI->getName(Reg) << "=g" <<
233 State->GetGroup(Reg) << "->g0(region live-out)");
234 State->UnionGroups(Reg, 0);
235 } else if ((DefIndices[Reg] < InsertPosIndex) && (DefIndices[Reg] >= Count)) {
236 DefIndices[Reg] = Count;
239 DEBUG(errs() << '\n');
242 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr *MI,
245 if (!MO.isReg() || !MO.isImplicit())
248 unsigned Reg = MO.getReg();
252 MachineOperand *Op = NULL;
254 Op = MI->findRegisterUseOperand(Reg, true);
256 Op = MI->findRegisterDefOperand(Reg);
258 return((Op != NULL) && Op->isImplicit());
261 void AggressiveAntiDepBreaker::GetPassthruRegs(MachineInstr *MI,
262 std::set<unsigned>& PassthruRegs) {
263 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
264 MachineOperand &MO = MI->getOperand(i);
265 if (!MO.isReg()) continue;
266 if ((MO.isDef() && MI->isRegTiedToUseOperand(i)) ||
267 IsImplicitDefUse(MI, MO)) {
268 const unsigned Reg = MO.getReg();
269 PassthruRegs.insert(Reg);
270 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
272 PassthruRegs.insert(*Subreg);
278 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
279 /// in SU that we want to consider for breaking.
280 static void AntiDepEdges(SUnit *SU, std::vector<SDep*>& Edges) {
281 SmallSet<unsigned, 4> RegSet;
282 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
284 if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
285 unsigned Reg = P->getReg();
286 if (RegSet.count(Reg) == 0) {
287 Edges.push_back(&*P);
294 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
296 static SUnit *CriticalPathStep(SUnit *SU) {
298 unsigned NextDepth = 0;
299 // Find the predecessor edge with the greatest depth.
301 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
303 SUnit *PredSU = P->getSUnit();
304 unsigned PredLatency = P->getLatency();
305 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
306 // In the case of a latency tie, prefer an anti-dependency edge over
307 // other types of edges.
308 if (NextDepth < PredTotalLatency ||
309 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
310 NextDepth = PredTotalLatency;
316 return (Next) ? Next->getSUnit() : 0;
319 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
320 const char *tag, const char *header,
321 const char *footer) {
322 unsigned *KillIndices = State->GetKillIndices();
323 unsigned *DefIndices = State->GetDefIndices();
324 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
325 RegRefs = State->GetRegRefs();
327 if (!State->IsLive(Reg)) {
328 KillIndices[Reg] = KillIdx;
329 DefIndices[Reg] = ~0u;
331 State->LeaveGroup(Reg);
332 DEBUG(if (header != NULL) {
333 errs() << header << TRI->getName(Reg); header = NULL; });
334 DEBUG(errs() << "->g" << State->GetGroup(Reg) << tag);
336 // Repeat for subregisters.
337 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
339 unsigned SubregReg = *Subreg;
340 if (!State->IsLive(SubregReg)) {
341 KillIndices[SubregReg] = KillIdx;
342 DefIndices[SubregReg] = ~0u;
343 RegRefs.erase(SubregReg);
344 State->LeaveGroup(SubregReg);
345 DEBUG(if (header != NULL) {
346 errs() << header << TRI->getName(Reg); header = NULL; });
347 DEBUG(errs() << " " << TRI->getName(SubregReg) << "->g" <<
348 State->GetGroup(SubregReg) << tag);
352 DEBUG(if ((header == NULL) && (footer != NULL)) errs() << footer);
355 void AggressiveAntiDepBreaker::PrescanInstruction(MachineInstr *MI, unsigned Count,
356 std::set<unsigned>& PassthruRegs) {
357 unsigned *DefIndices = State->GetDefIndices();
358 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
359 RegRefs = State->GetRegRefs();
361 // Handle dead defs by simulating a last-use of the register just
362 // after the def. A dead def can occur because the def is truely
363 // dead, or because only a subregister is live at the def. If we
364 // don't do this the dead def will be incorrectly merged into the
366 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
367 MachineOperand &MO = MI->getOperand(i);
368 if (!MO.isReg() || !MO.isDef()) continue;
369 unsigned Reg = MO.getReg();
370 if (Reg == 0) continue;
372 HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
375 DEBUG(errs() << "\tDef Groups:");
376 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
377 MachineOperand &MO = MI->getOperand(i);
378 if (!MO.isReg() || !MO.isDef()) continue;
379 unsigned Reg = MO.getReg();
380 if (Reg == 0) continue;
382 DEBUG(errs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg));
384 // If MI's defs have a special allocation requirement, don't allow
385 // any def registers to be changed. Also assume all registers
386 // defined in a call must not be changed (ABI).
387 if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq()) {
388 DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
389 State->UnionGroups(Reg, 0);
392 // Any aliased that are live at this point are completely or
393 // partially defined here, so group those aliases with Reg.
394 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
395 unsigned AliasReg = *Alias;
396 if (State->IsLive(AliasReg)) {
397 State->UnionGroups(Reg, AliasReg);
398 DEBUG(errs() << "->g" << State->GetGroup(Reg) << "(via " <<
399 TRI->getName(AliasReg) << ")");
403 // Note register reference...
404 const TargetRegisterClass *RC = NULL;
405 if (i < MI->getDesc().getNumOperands())
406 RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
407 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
408 RegRefs.insert(std::make_pair(Reg, RR));
411 DEBUG(errs() << '\n');
413 // Scan the register defs for this instruction and update
415 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
416 MachineOperand &MO = MI->getOperand(i);
417 if (!MO.isReg() || !MO.isDef()) continue;
418 unsigned Reg = MO.getReg();
419 if (Reg == 0) continue;
420 // Ignore KILLs and passthru registers for liveness...
421 if ((MI->getOpcode() == TargetInstrInfo::KILL) ||
422 (PassthruRegs.count(Reg) != 0))
425 // Update def for Reg and aliases.
426 DefIndices[Reg] = Count;
427 for (const unsigned *Alias = TRI->getAliasSet(Reg);
429 unsigned AliasReg = *Alias;
430 DefIndices[AliasReg] = Count;
435 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr *MI,
437 DEBUG(errs() << "\tUse Groups:");
438 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
439 RegRefs = State->GetRegRefs();
441 // Scan the register uses for this instruction and update
442 // live-ranges, groups and RegRefs.
443 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
444 MachineOperand &MO = MI->getOperand(i);
445 if (!MO.isReg() || !MO.isUse()) continue;
446 unsigned Reg = MO.getReg();
447 if (Reg == 0) continue;
449 DEBUG(errs() << " " << TRI->getName(Reg) << "=g" <<
450 State->GetGroup(Reg));
452 // It wasn't previously live but now it is, this is a kill. Forget
453 // the previous live-range information and start a new live-range
455 HandleLastUse(Reg, Count, "(last-use)");
457 // If MI's uses have special allocation requirement, don't allow
458 // any use registers to be changed. Also assume all registers
459 // used in a call must not be changed (ABI).
460 if (MI->getDesc().isCall() || MI->getDesc().hasExtraSrcRegAllocReq()) {
461 DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
462 State->UnionGroups(Reg, 0);
465 // Note register reference...
466 const TargetRegisterClass *RC = NULL;
467 if (i < MI->getDesc().getNumOperands())
468 RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
469 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
470 RegRefs.insert(std::make_pair(Reg, RR));
473 DEBUG(errs() << '\n');
475 // Form a group of all defs and uses of a KILL instruction to ensure
476 // that all registers are renamed as a group.
477 if (MI->getOpcode() == TargetInstrInfo::KILL) {
478 DEBUG(errs() << "\tKill Group:");
480 unsigned FirstReg = 0;
481 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
482 MachineOperand &MO = MI->getOperand(i);
483 if (!MO.isReg()) continue;
484 unsigned Reg = MO.getReg();
485 if (Reg == 0) continue;
488 DEBUG(errs() << "=" << TRI->getName(Reg));
489 State->UnionGroups(FirstReg, Reg);
491 DEBUG(errs() << " " << TRI->getName(Reg));
496 DEBUG(errs() << "->g" << State->GetGroup(FirstReg) << '\n');
500 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
501 BitVector BV(TRI->getNumRegs(), false);
504 // Check all references that need rewriting for Reg. For each, use
505 // the corresponding register class to narrow the set of registers
506 // that are appropriate for renaming.
507 std::pair<std::multimap<unsigned,
508 AggressiveAntiDepState::RegisterReference>::iterator,
509 std::multimap<unsigned,
510 AggressiveAntiDepState::RegisterReference>::iterator>
511 Range = State->GetRegRefs().equal_range(Reg);
512 for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
513 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
514 const TargetRegisterClass *RC = Q->second.RC;
515 if (RC == NULL) continue;
517 BitVector RCBV = TRI->getAllocatableSet(MF, RC);
525 DEBUG(errs() << " " << RC->getName());
531 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
532 unsigned AntiDepGroupIndex,
533 RenameOrderType& RenameOrder,
534 std::map<unsigned, unsigned> &RenameMap) {
535 unsigned *KillIndices = State->GetKillIndices();
536 unsigned *DefIndices = State->GetDefIndices();
537 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
538 RegRefs = State->GetRegRefs();
540 // Collect all referenced registers in the same group as
541 // AntiDepReg. These all need to be renamed together if we are to
542 // break the anti-dependence.
543 std::vector<unsigned> Regs;
544 State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
545 assert(Regs.size() > 0 && "Empty register group!");
546 if (Regs.size() == 0)
549 // Find the "superest" register in the group. At the same time,
550 // collect the BitVector of registers that can be used to rename
552 DEBUG(errs() << "\tRename Candidates for Group g" << AntiDepGroupIndex << ":\n");
553 std::map<unsigned, BitVector> RenameRegisterMap;
554 unsigned SuperReg = 0;
555 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
556 unsigned Reg = Regs[i];
557 if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
560 // If Reg has any references, then collect possible rename regs
561 if (RegRefs.count(Reg) > 0) {
562 DEBUG(errs() << "\t\t" << TRI->getName(Reg) << ":");
564 BitVector BV = GetRenameRegisters(Reg);
565 RenameRegisterMap.insert(std::pair<unsigned, BitVector>(Reg, BV));
567 DEBUG(errs() << " ::");
568 DEBUG(for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
569 errs() << " " << TRI->getName(r));
570 DEBUG(errs() << "\n");
574 // All group registers should be a subreg of SuperReg.
575 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
576 unsigned Reg = Regs[i];
577 if (Reg == SuperReg) continue;
578 bool IsSub = TRI->isSubRegister(SuperReg, Reg);
579 assert(IsSub && "Expecting group subregister");
584 // FIXME: for now just handle single register in group case...
585 if (Regs.size() > 1) {
586 DEBUG(errs() << "\tMultiple rename registers in group\n");
591 // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
593 static int renamecnt = 0;
594 if (renamecnt++ % DebugDiv != DebugMod)
597 errs() << "*** Performing rename " << TRI->getName(SuperReg) <<
602 // Check each possible rename register for SuperReg in round-robin
603 // order. If that register is available, and the corresponding
604 // registers are available for the other group subregisters, then we
605 // can use those registers to rename.
606 const TargetRegisterClass *SuperRC =
607 TRI->getPhysicalRegisterRegClass(SuperReg, MVT::Other);
609 const TargetRegisterClass::iterator RB = SuperRC->allocation_order_begin(MF);
610 const TargetRegisterClass::iterator RE = SuperRC->allocation_order_end(MF);
612 DEBUG(errs() << "\tEmpty Super Regclass!!\n");
616 DEBUG(errs() << "\tFind Registers:");
618 if (RenameOrder.count(SuperRC) == 0)
619 RenameOrder.insert(RenameOrderType::value_type(SuperRC, RE));
621 const TargetRegisterClass::iterator OrigR = RenameOrder[SuperRC];
622 const TargetRegisterClass::iterator EndR = ((OrigR == RE) ? RB : OrigR);
623 TargetRegisterClass::iterator R = OrigR;
627 const unsigned NewSuperReg = *R;
628 // Don't replace a register with itself.
629 if (NewSuperReg == SuperReg) continue;
631 DEBUG(errs() << " [" << TRI->getName(NewSuperReg) << ':');
634 // For each referenced group register (which must be a SuperReg or
635 // a subregister of SuperReg), find the corresponding subregister
636 // of NewSuperReg and make sure it is free to be renamed.
637 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
638 unsigned Reg = Regs[i];
640 if (Reg == SuperReg) {
641 NewReg = NewSuperReg;
643 unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
644 if (NewSubRegIdx != 0)
645 NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
648 DEBUG(errs() << " " << TRI->getName(NewReg));
650 // Check if Reg can be renamed to NewReg.
651 BitVector BV = RenameRegisterMap[Reg];
652 if (!BV.test(NewReg)) {
653 DEBUG(errs() << "(no rename)");
657 // If NewReg is dead and NewReg's most recent def is not before
658 // Regs's kill, it's safe to replace Reg with NewReg. We
659 // must also check all aliases of NewReg, because we can't define a
660 // register when any sub or super is already live.
661 if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
662 DEBUG(errs() << "(live)");
666 for (const unsigned *Alias = TRI->getAliasSet(NewReg);
668 unsigned AliasReg = *Alias;
669 if (State->IsLive(AliasReg) || (KillIndices[Reg] > DefIndices[AliasReg])) {
670 DEBUG(errs() << "(alias " << TRI->getName(AliasReg) << " live)");
679 // Record that 'Reg' can be renamed to 'NewReg'.
680 RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
683 // If we fall-out here, then every register in the group can be
684 // renamed, as recorded in RenameMap.
685 RenameOrder.erase(SuperRC);
686 RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
687 DEBUG(errs() << "]\n");
691 DEBUG(errs() << ']');
694 DEBUG(errs() << '\n');
696 // No registers are free and available!
700 /// BreakAntiDependencies - Identifiy anti-dependencies within the
701 /// ScheduleDAG and break them by renaming registers.
703 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
704 std::vector<SUnit>& SUnits,
705 MachineBasicBlock::iterator& Begin,
706 MachineBasicBlock::iterator& End,
707 unsigned InsertPosIndex) {
708 unsigned *KillIndices = State->GetKillIndices();
709 unsigned *DefIndices = State->GetDefIndices();
710 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
711 RegRefs = State->GetRegRefs();
713 // The code below assumes that there is at least one instruction,
714 // so just duck out immediately if the block is empty.
715 if (SUnits.empty()) return 0;
717 // For each regclass the next register to use for renaming.
718 RenameOrderType RenameOrder;
720 // ...need a map from MI to SUnit.
721 std::map<MachineInstr *, SUnit *> MISUnitMap;
722 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
723 SUnit *SU = &SUnits[i];
724 MISUnitMap.insert(std::pair<MachineInstr *, SUnit *>(SU->getInstr(), SU));
727 // Track progress along the critical path through the SUnit graph as
728 // we walk the instructions. This is needed for regclasses that only
729 // break critical-path anti-dependencies.
730 SUnit *CriticalPathSU = 0;
731 MachineInstr *CriticalPathMI = 0;
732 if (CriticalPathSet.any()) {
733 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
734 SUnit *SU = &SUnits[i];
735 if (!CriticalPathSU ||
736 ((SU->getDepth() + SU->Latency) >
737 (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
742 CriticalPathMI = CriticalPathSU->getInstr();
746 DEBUG(errs() << "\n===== Aggressive anti-dependency breaking\n");
747 DEBUG(errs() << "Available regs:");
748 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
749 if (!State->IsLive(Reg))
750 DEBUG(errs() << " " << TRI->getName(Reg));
752 DEBUG(errs() << '\n');
755 // Attempt to break anti-dependence edges. Walk the instructions
756 // from the bottom up, tracking information about liveness as we go
757 // to help determine which registers are available.
759 unsigned Count = InsertPosIndex - 1;
760 for (MachineBasicBlock::iterator I = End, E = Begin;
762 MachineInstr *MI = --I;
764 DEBUG(errs() << "Anti: ");
767 std::set<unsigned> PassthruRegs;
768 GetPassthruRegs(MI, PassthruRegs);
770 // Process the defs in MI...
771 PrescanInstruction(MI, Count, PassthruRegs);
773 // The dependence edges that represent anti- and output-
774 // dependencies that are candidates for breaking.
775 std::vector<SDep*> Edges;
776 SUnit *PathSU = MISUnitMap[MI];
777 AntiDepEdges(PathSU, Edges);
779 // If MI is not on the critical path, then we don't rename
780 // registers in the CriticalPathSet.
781 BitVector *ExcludeRegs = NULL;
782 if (MI == CriticalPathMI) {
783 CriticalPathSU = CriticalPathStep(CriticalPathSU);
784 CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : 0;
786 ExcludeRegs = &CriticalPathSet;
789 // Ignore KILL instructions (they form a group in ScanInstruction
790 // but don't cause any anti-dependence breaking themselves)
791 if (MI->getOpcode() != TargetInstrInfo::KILL) {
792 // Attempt to break each anti-dependency...
793 for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
794 SDep *Edge = Edges[i];
795 SUnit *NextSU = Edge->getSUnit();
797 if ((Edge->getKind() != SDep::Anti) &&
798 (Edge->getKind() != SDep::Output)) continue;
800 unsigned AntiDepReg = Edge->getReg();
801 DEBUG(errs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
802 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
804 if (!AllocatableSet.test(AntiDepReg)) {
805 // Don't break anti-dependencies on non-allocatable registers.
806 DEBUG(errs() << " (non-allocatable)\n");
808 } else if ((ExcludeRegs != NULL) && ExcludeRegs->test(AntiDepReg)) {
809 // Don't break anti-dependencies for critical path registers
810 // if not on the critical path
811 DEBUG(errs() << " (not critical-path)\n");
813 } else if (PassthruRegs.count(AntiDepReg) != 0) {
814 // If the anti-dep register liveness "passes-thru", then
815 // don't try to change it. It will be changed along with
816 // the use if required to break an earlier antidep.
817 DEBUG(errs() << " (passthru)\n");
820 // No anti-dep breaking for implicit deps
821 MachineOperand *AntiDepOp = MI->findRegisterDefOperand(AntiDepReg);
822 assert(AntiDepOp != NULL && "Can't find index for defined register operand");
823 if ((AntiDepOp == NULL) || AntiDepOp->isImplicit()) {
824 DEBUG(errs() << " (implicit)\n");
828 // If the SUnit has other dependencies on the SUnit that
829 // it anti-depends on, don't bother breaking the
830 // anti-dependency since those edges would prevent such
831 // units from being scheduled past each other
834 // Also, if there are dependencies on other SUnits with the
835 // same register as the anti-dependency, don't attempt to
837 for (SUnit::pred_iterator P = PathSU->Preds.begin(),
838 PE = PathSU->Preds.end(); P != PE; ++P) {
839 if (P->getSUnit() == NextSU ?
840 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
841 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
846 for (SUnit::pred_iterator P = PathSU->Preds.begin(),
847 PE = PathSU->Preds.end(); P != PE; ++P) {
848 if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
849 (P->getKind() != SDep::Output)) {
850 DEBUG(errs() << " (real dependency)\n");
853 } else if ((P->getSUnit() != NextSU) &&
854 (P->getKind() == SDep::Data) &&
855 (P->getReg() == AntiDepReg)) {
856 DEBUG(errs() << " (other dependency)\n");
862 if (AntiDepReg == 0) continue;
865 assert(AntiDepReg != 0);
866 if (AntiDepReg == 0) continue;
868 // Determine AntiDepReg's register group.
869 const unsigned GroupIndex = State->GetGroup(AntiDepReg);
870 if (GroupIndex == 0) {
871 DEBUG(errs() << " (zero group)\n");
875 DEBUG(errs() << '\n');
877 // Look for a suitable register to use to break the anti-dependence.
878 std::map<unsigned, unsigned> RenameMap;
879 if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
880 DEBUG(errs() << "\tBreaking anti-dependence edge on "
881 << TRI->getName(AntiDepReg) << ":");
883 // Handle each group register...
884 for (std::map<unsigned, unsigned>::iterator
885 S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
886 unsigned CurrReg = S->first;
887 unsigned NewReg = S->second;
889 DEBUG(errs() << " " << TRI->getName(CurrReg) << "->" <<
890 TRI->getName(NewReg) << "(" <<
891 RegRefs.count(CurrReg) << " refs)");
893 // Update the references to the old register CurrReg to
894 // refer to the new register NewReg.
895 std::pair<std::multimap<unsigned,
896 AggressiveAntiDepState::RegisterReference>::iterator,
897 std::multimap<unsigned,
898 AggressiveAntiDepState::RegisterReference>::iterator>
899 Range = RegRefs.equal_range(CurrReg);
900 for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
901 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
902 Q->second.Operand->setReg(NewReg);
905 // We just went back in time and modified history; the
906 // liveness information for CurrReg is now inconsistent. Set
907 // the state as if it were dead.
908 State->UnionGroups(NewReg, 0);
909 RegRefs.erase(NewReg);
910 DefIndices[NewReg] = DefIndices[CurrReg];
911 KillIndices[NewReg] = KillIndices[CurrReg];
913 State->UnionGroups(CurrReg, 0);
914 RegRefs.erase(CurrReg);
915 DefIndices[CurrReg] = KillIndices[CurrReg];
916 KillIndices[CurrReg] = ~0u;
917 assert(((KillIndices[CurrReg] == ~0u) !=
918 (DefIndices[CurrReg] == ~0u)) &&
919 "Kill and Def maps aren't consistent for AntiDepReg!");
923 DEBUG(errs() << '\n');
928 ScanInstruction(MI, Count);