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(const unsigned TargetRegs,
42 MachineBasicBlock *BB) :
43 NumTargetRegs(TargetRegs), GroupNodes(TargetRegs, 0) {
45 const unsigned BBSize = BB->size();
46 for (unsigned i = 0; i < NumTargetRegs; ++i) {
47 // Initialize all registers to be in their own group. Initially we
48 // assign the register to the same-indexed GroupNode.
49 GroupNodeIndices[i] = i;
50 // Initialize the indices to indicate that no registers are live.
52 DefIndices[i] = BBSize;
56 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg)
58 unsigned Node = GroupNodeIndices[Reg];
59 while (GroupNodes[Node] != Node)
60 Node = GroupNodes[Node];
65 void AggressiveAntiDepState::GetGroupRegs(
67 std::vector<unsigned> &Regs,
68 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference> *RegRefs)
70 for (unsigned Reg = 0; Reg != NumTargetRegs; ++Reg) {
71 if ((GetGroup(Reg) == Group) && (RegRefs->count(Reg) > 0))
76 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1, unsigned Reg2)
78 assert(GroupNodes[0] == 0 && "GroupNode 0 not parent!");
79 assert(GroupNodeIndices[0] == 0 && "Reg 0 not in Group 0!");
81 // find group for each register
82 unsigned Group1 = GetGroup(Reg1);
83 unsigned Group2 = GetGroup(Reg2);
85 // if either group is 0, then that must become the parent
86 unsigned Parent = (Group1 == 0) ? Group1 : Group2;
87 unsigned Other = (Parent == Group1) ? Group2 : Group1;
88 GroupNodes.at(Other) = Parent;
92 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg)
94 // Create a new GroupNode for Reg. Reg's existing GroupNode must
95 // stay as is because there could be other GroupNodes referring to
97 unsigned idx = GroupNodes.size();
98 GroupNodes.push_back(idx);
99 GroupNodeIndices[Reg] = idx;
103 bool AggressiveAntiDepState::IsLive(unsigned Reg)
105 // KillIndex must be defined and DefIndex not defined for a register
107 return((KillIndices[Reg] != ~0u) && (DefIndices[Reg] == ~0u));
112 AggressiveAntiDepBreaker::
113 AggressiveAntiDepBreaker(MachineFunction& MFi,
114 TargetSubtarget::RegClassVector& CriticalPathRCs) :
115 AntiDepBreaker(), MF(MFi),
116 MRI(MF.getRegInfo()),
117 TRI(MF.getTarget().getRegisterInfo()),
118 AllocatableSet(TRI->getAllocatableSet(MF)),
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(errs() << "AntiDep Critical-Path Registers:");
131 DEBUG(for (int r = CriticalPathSet.find_first(); r != -1;
132 r = CriticalPathSet.find_next(r))
133 errs() << " " << TRI->getName(r));
134 DEBUG(errs() << '\n');
137 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
141 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
142 assert(State == NULL);
143 State = new AggressiveAntiDepState(TRI->getNumRegs(), BB);
145 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
146 unsigned *KillIndices = State->GetKillIndices();
147 unsigned *DefIndices = State->GetDefIndices();
149 // Determine the live-out physregs for this block.
151 // In a return block, examine the function live-out regs.
152 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
153 E = MRI.liveout_end(); I != E; ++I) {
155 State->UnionGroups(Reg, 0);
156 KillIndices[Reg] = BB->size();
157 DefIndices[Reg] = ~0u;
158 // Repeat, for all aliases.
159 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
160 unsigned AliasReg = *Alias;
161 State->UnionGroups(AliasReg, 0);
162 KillIndices[AliasReg] = BB->size();
163 DefIndices[AliasReg] = ~0u;
167 // In a non-return block, examine the live-in regs of all successors.
168 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
169 SE = BB->succ_end(); SI != SE; ++SI)
170 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
171 E = (*SI)->livein_end(); I != E; ++I) {
173 State->UnionGroups(Reg, 0);
174 KillIndices[Reg] = BB->size();
175 DefIndices[Reg] = ~0u;
176 // Repeat, for all aliases.
177 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
178 unsigned AliasReg = *Alias;
179 State->UnionGroups(AliasReg, 0);
180 KillIndices[AliasReg] = BB->size();
181 DefIndices[AliasReg] = ~0u;
186 // Mark live-out callee-saved registers. In a return block this is
187 // all callee-saved registers. In non-return this is any
188 // callee-saved register that is not saved in the prolog.
189 const MachineFrameInfo *MFI = MF.getFrameInfo();
190 BitVector Pristine = MFI->getPristineRegs(BB);
191 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
193 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
194 State->UnionGroups(Reg, 0);
195 KillIndices[Reg] = BB->size();
196 DefIndices[Reg] = ~0u;
197 // Repeat, for all aliases.
198 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
199 unsigned AliasReg = *Alias;
200 State->UnionGroups(AliasReg, 0);
201 KillIndices[AliasReg] = BB->size();
202 DefIndices[AliasReg] = ~0u;
207 void AggressiveAntiDepBreaker::FinishBlock() {
212 void AggressiveAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
213 unsigned InsertPosIndex) {
214 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
216 std::set<unsigned> PassthruRegs;
217 GetPassthruRegs(MI, PassthruRegs);
218 PrescanInstruction(MI, Count, PassthruRegs);
219 ScanInstruction(MI, Count);
221 DEBUG(errs() << "Observe: ");
223 DEBUG(errs() << "\tRegs:");
225 unsigned *DefIndices = State->GetDefIndices();
226 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
227 // If Reg is current live, then mark that it can't be renamed as
228 // we don't know the extent of its live-range anymore (now that it
229 // has been scheduled). If it is not live but was defined in the
230 // previous schedule region, then set its def index to the most
231 // conservative location (i.e. the beginning of the previous
233 if (State->IsLive(Reg)) {
234 DEBUG(if (State->GetGroup(Reg) != 0)
235 errs() << " " << TRI->getName(Reg) << "=g" <<
236 State->GetGroup(Reg) << "->g0(region live-out)");
237 State->UnionGroups(Reg, 0);
238 } else if ((DefIndices[Reg] < InsertPosIndex) && (DefIndices[Reg] >= Count)) {
239 DefIndices[Reg] = Count;
242 DEBUG(errs() << '\n');
245 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr *MI,
248 if (!MO.isReg() || !MO.isImplicit())
251 unsigned Reg = MO.getReg();
255 MachineOperand *Op = NULL;
257 Op = MI->findRegisterUseOperand(Reg, true);
259 Op = MI->findRegisterDefOperand(Reg);
261 return((Op != NULL) && Op->isImplicit());
264 void AggressiveAntiDepBreaker::GetPassthruRegs(MachineInstr *MI,
265 std::set<unsigned>& PassthruRegs) {
266 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
267 MachineOperand &MO = MI->getOperand(i);
268 if (!MO.isReg()) continue;
269 if ((MO.isDef() && MI->isRegTiedToUseOperand(i)) ||
270 IsImplicitDefUse(MI, MO)) {
271 const unsigned Reg = MO.getReg();
272 PassthruRegs.insert(Reg);
273 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
275 PassthruRegs.insert(*Subreg);
281 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
282 /// in SU that we want to consider for breaking.
283 static void AntiDepEdges(SUnit *SU, std::vector<SDep*>& Edges) {
284 SmallSet<unsigned, 4> RegSet;
285 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
287 if ((P->getKind() == SDep::Anti) || (P->getKind() == SDep::Output)) {
288 unsigned Reg = P->getReg();
289 if (RegSet.count(Reg) == 0) {
290 Edges.push_back(&*P);
297 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
299 static SUnit *CriticalPathStep(SUnit *SU) {
301 unsigned NextDepth = 0;
302 // Find the predecessor edge with the greatest depth.
304 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
306 SUnit *PredSU = P->getSUnit();
307 unsigned PredLatency = P->getLatency();
308 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
309 // In the case of a latency tie, prefer an anti-dependency edge over
310 // other types of edges.
311 if (NextDepth < PredTotalLatency ||
312 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
313 NextDepth = PredTotalLatency;
319 return (Next) ? Next->getSUnit() : 0;
322 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg, unsigned KillIdx,
323 const char *tag, const char *header,
324 const char *footer) {
325 unsigned *KillIndices = State->GetKillIndices();
326 unsigned *DefIndices = State->GetDefIndices();
327 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
328 RegRefs = State->GetRegRefs();
330 if (!State->IsLive(Reg)) {
331 KillIndices[Reg] = KillIdx;
332 DefIndices[Reg] = ~0u;
334 State->LeaveGroup(Reg);
335 DEBUG(if (header != NULL) {
336 errs() << header << TRI->getName(Reg); header = NULL; });
337 DEBUG(errs() << "->g" << State->GetGroup(Reg) << tag);
339 // Repeat for subregisters.
340 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
342 unsigned SubregReg = *Subreg;
343 if (!State->IsLive(SubregReg)) {
344 KillIndices[SubregReg] = KillIdx;
345 DefIndices[SubregReg] = ~0u;
346 RegRefs.erase(SubregReg);
347 State->LeaveGroup(SubregReg);
348 DEBUG(if (header != NULL) {
349 errs() << header << TRI->getName(Reg); header = NULL; });
350 DEBUG(errs() << " " << TRI->getName(SubregReg) << "->g" <<
351 State->GetGroup(SubregReg) << tag);
355 DEBUG(if ((header == NULL) && (footer != NULL)) errs() << footer);
358 void AggressiveAntiDepBreaker::PrescanInstruction(MachineInstr *MI, unsigned Count,
359 std::set<unsigned>& PassthruRegs) {
360 unsigned *DefIndices = State->GetDefIndices();
361 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
362 RegRefs = State->GetRegRefs();
364 // Handle dead defs by simulating a last-use of the register just
365 // after the def. A dead def can occur because the def is truely
366 // dead, or because only a subregister is live at the def. If we
367 // don't do this the dead def will be incorrectly merged into the
369 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
370 MachineOperand &MO = MI->getOperand(i);
371 if (!MO.isReg() || !MO.isDef()) continue;
372 unsigned Reg = MO.getReg();
373 if (Reg == 0) continue;
375 HandleLastUse(Reg, Count + 1, "", "\tDead Def: ", "\n");
378 DEBUG(errs() << "\tDef Groups:");
379 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
380 MachineOperand &MO = MI->getOperand(i);
381 if (!MO.isReg() || !MO.isDef()) continue;
382 unsigned Reg = MO.getReg();
383 if (Reg == 0) continue;
385 DEBUG(errs() << " " << TRI->getName(Reg) << "=g" << State->GetGroup(Reg));
387 // If MI's defs have a special allocation requirement, don't allow
388 // any def registers to be changed. Also assume all registers
389 // defined in a call must not be changed (ABI).
390 if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq()) {
391 DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
392 State->UnionGroups(Reg, 0);
395 // Any aliased that are live at this point are completely or
396 // partially defined here, so group those aliases with Reg.
397 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
398 unsigned AliasReg = *Alias;
399 if (State->IsLive(AliasReg)) {
400 State->UnionGroups(Reg, AliasReg);
401 DEBUG(errs() << "->g" << State->GetGroup(Reg) << "(via " <<
402 TRI->getName(AliasReg) << ")");
406 // Note register reference...
407 const TargetRegisterClass *RC = NULL;
408 if (i < MI->getDesc().getNumOperands())
409 RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
410 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
411 RegRefs.insert(std::make_pair(Reg, RR));
414 DEBUG(errs() << '\n');
416 // Scan the register defs for this instruction and update
418 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
419 MachineOperand &MO = MI->getOperand(i);
420 if (!MO.isReg() || !MO.isDef()) continue;
421 unsigned Reg = MO.getReg();
422 if (Reg == 0) continue;
423 // Ignore KILLs and passthru registers for liveness...
424 if ((MI->getOpcode() == TargetInstrInfo::KILL) ||
425 (PassthruRegs.count(Reg) != 0))
428 // Update def for Reg and aliases.
429 DefIndices[Reg] = Count;
430 for (const unsigned *Alias = TRI->getAliasSet(Reg);
432 unsigned AliasReg = *Alias;
433 DefIndices[AliasReg] = Count;
438 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr *MI,
440 DEBUG(errs() << "\tUse Groups:");
441 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
442 RegRefs = State->GetRegRefs();
444 // Scan the register uses for this instruction and update
445 // live-ranges, groups and RegRefs.
446 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
447 MachineOperand &MO = MI->getOperand(i);
448 if (!MO.isReg() || !MO.isUse()) continue;
449 unsigned Reg = MO.getReg();
450 if (Reg == 0) continue;
452 DEBUG(errs() << " " << TRI->getName(Reg) << "=g" <<
453 State->GetGroup(Reg));
455 // It wasn't previously live but now it is, this is a kill. Forget
456 // the previous live-range information and start a new live-range
458 HandleLastUse(Reg, Count, "(last-use)");
460 // If MI's uses have special allocation requirement, don't allow
461 // any use registers to be changed. Also assume all registers
462 // used in a call must not be changed (ABI).
463 if (MI->getDesc().isCall() || MI->getDesc().hasExtraSrcRegAllocReq()) {
464 DEBUG(if (State->GetGroup(Reg) != 0) errs() << "->g0(alloc-req)");
465 State->UnionGroups(Reg, 0);
468 // Note register reference...
469 const TargetRegisterClass *RC = NULL;
470 if (i < MI->getDesc().getNumOperands())
471 RC = MI->getDesc().OpInfo[i].getRegClass(TRI);
472 AggressiveAntiDepState::RegisterReference RR = { &MO, RC };
473 RegRefs.insert(std::make_pair(Reg, RR));
476 DEBUG(errs() << '\n');
478 // Form a group of all defs and uses of a KILL instruction to ensure
479 // that all registers are renamed as a group.
480 if (MI->getOpcode() == TargetInstrInfo::KILL) {
481 DEBUG(errs() << "\tKill Group:");
483 unsigned FirstReg = 0;
484 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
485 MachineOperand &MO = MI->getOperand(i);
486 if (!MO.isReg()) continue;
487 unsigned Reg = MO.getReg();
488 if (Reg == 0) continue;
491 DEBUG(errs() << "=" << TRI->getName(Reg));
492 State->UnionGroups(FirstReg, Reg);
494 DEBUG(errs() << " " << TRI->getName(Reg));
499 DEBUG(errs() << "->g" << State->GetGroup(FirstReg) << '\n');
503 BitVector AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg) {
504 BitVector BV(TRI->getNumRegs(), false);
507 // Check all references that need rewriting for Reg. For each, use
508 // the corresponding register class to narrow the set of registers
509 // that are appropriate for renaming.
510 std::pair<std::multimap<unsigned,
511 AggressiveAntiDepState::RegisterReference>::iterator,
512 std::multimap<unsigned,
513 AggressiveAntiDepState::RegisterReference>::iterator>
514 Range = State->GetRegRefs().equal_range(Reg);
515 for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
516 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
517 const TargetRegisterClass *RC = Q->second.RC;
518 if (RC == NULL) continue;
520 BitVector RCBV = TRI->getAllocatableSet(MF, RC);
528 DEBUG(errs() << " " << RC->getName());
534 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
535 unsigned AntiDepGroupIndex,
536 RenameOrderType& RenameOrder,
537 std::map<unsigned, unsigned> &RenameMap) {
538 unsigned *KillIndices = State->GetKillIndices();
539 unsigned *DefIndices = State->GetDefIndices();
540 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
541 RegRefs = State->GetRegRefs();
543 // Collect all referenced registers in the same group as
544 // AntiDepReg. These all need to be renamed together if we are to
545 // break the anti-dependence.
546 std::vector<unsigned> Regs;
547 State->GetGroupRegs(AntiDepGroupIndex, Regs, &RegRefs);
548 assert(Regs.size() > 0 && "Empty register group!");
549 if (Regs.size() == 0)
552 // Find the "superest" register in the group. At the same time,
553 // collect the BitVector of registers that can be used to rename
555 DEBUG(errs() << "\tRename Candidates for Group g" << AntiDepGroupIndex << ":\n");
556 std::map<unsigned, BitVector> RenameRegisterMap;
557 unsigned SuperReg = 0;
558 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
559 unsigned Reg = Regs[i];
560 if ((SuperReg == 0) || TRI->isSuperRegister(SuperReg, Reg))
563 // If Reg has any references, then collect possible rename regs
564 if (RegRefs.count(Reg) > 0) {
565 DEBUG(errs() << "\t\t" << TRI->getName(Reg) << ":");
567 BitVector BV = GetRenameRegisters(Reg);
568 RenameRegisterMap.insert(std::pair<unsigned, BitVector>(Reg, BV));
570 DEBUG(errs() << " ::");
571 DEBUG(for (int r = BV.find_first(); r != -1; r = BV.find_next(r))
572 errs() << " " << TRI->getName(r));
573 DEBUG(errs() << "\n");
577 // All group registers should be a subreg of SuperReg.
578 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
579 unsigned Reg = Regs[i];
580 if (Reg == SuperReg) continue;
581 bool IsSub = TRI->isSubRegister(SuperReg, Reg);
582 assert(IsSub && "Expecting group subregister");
588 // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
590 static int renamecnt = 0;
591 if (renamecnt++ % DebugDiv != DebugMod)
594 errs() << "*** Performing rename " << TRI->getName(SuperReg) <<
599 // Check each possible rename register for SuperReg in round-robin
600 // order. If that register is available, and the corresponding
601 // registers are available for the other group subregisters, then we
602 // can use those registers to rename.
603 const TargetRegisterClass *SuperRC =
604 TRI->getPhysicalRegisterRegClass(SuperReg, MVT::Other);
606 const TargetRegisterClass::iterator RB = SuperRC->allocation_order_begin(MF);
607 const TargetRegisterClass::iterator RE = SuperRC->allocation_order_end(MF);
609 DEBUG(errs() << "\tEmpty Super Regclass!!\n");
613 DEBUG(errs() << "\tFind Registers:");
615 if (RenameOrder.count(SuperRC) == 0)
616 RenameOrder.insert(RenameOrderType::value_type(SuperRC, RE));
618 const TargetRegisterClass::iterator OrigR = RenameOrder[SuperRC];
619 const TargetRegisterClass::iterator EndR = ((OrigR == RE) ? RB : OrigR);
620 TargetRegisterClass::iterator R = OrigR;
624 const unsigned NewSuperReg = *R;
625 // Don't replace a register with itself.
626 if (NewSuperReg == SuperReg) continue;
628 DEBUG(errs() << " [" << TRI->getName(NewSuperReg) << ':');
631 // For each referenced group register (which must be a SuperReg or
632 // a subregister of SuperReg), find the corresponding subregister
633 // of NewSuperReg and make sure it is free to be renamed.
634 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
635 unsigned Reg = Regs[i];
637 if (Reg == SuperReg) {
638 NewReg = NewSuperReg;
640 unsigned NewSubRegIdx = TRI->getSubRegIndex(SuperReg, Reg);
641 if (NewSubRegIdx != 0)
642 NewReg = TRI->getSubReg(NewSuperReg, NewSubRegIdx);
645 DEBUG(errs() << " " << TRI->getName(NewReg));
647 // Check if Reg can be renamed to NewReg.
648 BitVector BV = RenameRegisterMap[Reg];
649 if (!BV.test(NewReg)) {
650 DEBUG(errs() << "(no rename)");
654 // If NewReg is dead and NewReg's most recent def is not before
655 // Regs's kill, it's safe to replace Reg with NewReg. We
656 // must also check all aliases of NewReg, because we can't define a
657 // register when any sub or super is already live.
658 if (State->IsLive(NewReg) || (KillIndices[Reg] > DefIndices[NewReg])) {
659 DEBUG(errs() << "(live)");
663 for (const unsigned *Alias = TRI->getAliasSet(NewReg);
665 unsigned AliasReg = *Alias;
666 if (State->IsLive(AliasReg) || (KillIndices[Reg] > DefIndices[AliasReg])) {
667 DEBUG(errs() << "(alias " << TRI->getName(AliasReg) << " live)");
676 // Record that 'Reg' can be renamed to 'NewReg'.
677 RenameMap.insert(std::pair<unsigned, unsigned>(Reg, NewReg));
680 // If we fall-out here, then every register in the group can be
681 // renamed, as recorded in RenameMap.
682 RenameOrder.erase(SuperRC);
683 RenameOrder.insert(RenameOrderType::value_type(SuperRC, R));
684 DEBUG(errs() << "]\n");
688 DEBUG(errs() << ']');
691 DEBUG(errs() << '\n');
693 // No registers are free and available!
697 /// BreakAntiDependencies - Identifiy anti-dependencies within the
698 /// ScheduleDAG and break them by renaming registers.
700 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
701 std::vector<SUnit>& SUnits,
702 MachineBasicBlock::iterator& Begin,
703 MachineBasicBlock::iterator& End,
704 unsigned InsertPosIndex) {
705 unsigned *KillIndices = State->GetKillIndices();
706 unsigned *DefIndices = State->GetDefIndices();
707 std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>&
708 RegRefs = State->GetRegRefs();
710 // The code below assumes that there is at least one instruction,
711 // so just duck out immediately if the block is empty.
712 if (SUnits.empty()) return 0;
714 // For each regclass the next register to use for renaming.
715 RenameOrderType RenameOrder;
717 // ...need a map from MI to SUnit.
718 std::map<MachineInstr *, SUnit *> MISUnitMap;
719 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
720 SUnit *SU = &SUnits[i];
721 MISUnitMap.insert(std::pair<MachineInstr *, SUnit *>(SU->getInstr(), SU));
724 // Track progress along the critical path through the SUnit graph as
725 // we walk the instructions. This is needed for regclasses that only
726 // break critical-path anti-dependencies.
727 SUnit *CriticalPathSU = 0;
728 MachineInstr *CriticalPathMI = 0;
729 if (CriticalPathSet.any()) {
730 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
731 SUnit *SU = &SUnits[i];
732 if (!CriticalPathSU ||
733 ((SU->getDepth() + SU->Latency) >
734 (CriticalPathSU->getDepth() + CriticalPathSU->Latency))) {
739 CriticalPathMI = CriticalPathSU->getInstr();
743 DEBUG(errs() << "\n===== Aggressive anti-dependency breaking\n");
744 DEBUG(errs() << "Available regs:");
745 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
746 if (!State->IsLive(Reg))
747 DEBUG(errs() << " " << TRI->getName(Reg));
749 DEBUG(errs() << '\n');
752 // Attempt to break anti-dependence edges. Walk the instructions
753 // from the bottom up, tracking information about liveness as we go
754 // to help determine which registers are available.
756 unsigned Count = InsertPosIndex - 1;
757 for (MachineBasicBlock::iterator I = End, E = Begin;
759 MachineInstr *MI = --I;
761 DEBUG(errs() << "Anti: ");
764 std::set<unsigned> PassthruRegs;
765 GetPassthruRegs(MI, PassthruRegs);
767 // Process the defs in MI...
768 PrescanInstruction(MI, Count, PassthruRegs);
770 // The dependence edges that represent anti- and output-
771 // dependencies that are candidates for breaking.
772 std::vector<SDep*> Edges;
773 SUnit *PathSU = MISUnitMap[MI];
774 AntiDepEdges(PathSU, Edges);
776 // If MI is not on the critical path, then we don't rename
777 // registers in the CriticalPathSet.
778 BitVector *ExcludeRegs = NULL;
779 if (MI == CriticalPathMI) {
780 CriticalPathSU = CriticalPathStep(CriticalPathSU);
781 CriticalPathMI = (CriticalPathSU) ? CriticalPathSU->getInstr() : 0;
783 ExcludeRegs = &CriticalPathSet;
786 // Ignore KILL instructions (they form a group in ScanInstruction
787 // but don't cause any anti-dependence breaking themselves)
788 if (MI->getOpcode() != TargetInstrInfo::KILL) {
789 // Attempt to break each anti-dependency...
790 for (unsigned i = 0, e = Edges.size(); i != e; ++i) {
791 SDep *Edge = Edges[i];
792 SUnit *NextSU = Edge->getSUnit();
794 if ((Edge->getKind() != SDep::Anti) &&
795 (Edge->getKind() != SDep::Output)) continue;
797 unsigned AntiDepReg = Edge->getReg();
798 DEBUG(errs() << "\tAntidep reg: " << TRI->getName(AntiDepReg));
799 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
801 if (!AllocatableSet.test(AntiDepReg)) {
802 // Don't break anti-dependencies on non-allocatable registers.
803 DEBUG(errs() << " (non-allocatable)\n");
805 } else if ((ExcludeRegs != NULL) && ExcludeRegs->test(AntiDepReg)) {
806 // Don't break anti-dependencies for critical path registers
807 // if not on the critical path
808 DEBUG(errs() << " (not critical-path)\n");
810 } else if (PassthruRegs.count(AntiDepReg) != 0) {
811 // If the anti-dep register liveness "passes-thru", then
812 // don't try to change it. It will be changed along with
813 // the use if required to break an earlier antidep.
814 DEBUG(errs() << " (passthru)\n");
817 // No anti-dep breaking for implicit deps
818 MachineOperand *AntiDepOp = MI->findRegisterDefOperand(AntiDepReg);
819 assert(AntiDepOp != NULL && "Can't find index for defined register operand");
820 if ((AntiDepOp == NULL) || AntiDepOp->isImplicit()) {
821 DEBUG(errs() << " (implicit)\n");
825 // If the SUnit has other dependencies on the SUnit that
826 // it anti-depends on, don't bother breaking the
827 // anti-dependency since those edges would prevent such
828 // units from being scheduled past each other
831 // Also, if there are dependencies on other SUnits with the
832 // same register as the anti-dependency, don't attempt to
834 for (SUnit::pred_iterator P = PathSU->Preds.begin(),
835 PE = PathSU->Preds.end(); P != PE; ++P) {
836 if (P->getSUnit() == NextSU ?
837 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
838 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
843 for (SUnit::pred_iterator P = PathSU->Preds.begin(),
844 PE = PathSU->Preds.end(); P != PE; ++P) {
845 if ((P->getSUnit() == NextSU) && (P->getKind() != SDep::Anti) &&
846 (P->getKind() != SDep::Output)) {
847 DEBUG(errs() << " (real dependency)\n");
850 } else if ((P->getSUnit() != NextSU) &&
851 (P->getKind() == SDep::Data) &&
852 (P->getReg() == AntiDepReg)) {
853 DEBUG(errs() << " (other dependency)\n");
859 if (AntiDepReg == 0) continue;
862 assert(AntiDepReg != 0);
863 if (AntiDepReg == 0) continue;
865 // Determine AntiDepReg's register group.
866 const unsigned GroupIndex = State->GetGroup(AntiDepReg);
867 if (GroupIndex == 0) {
868 DEBUG(errs() << " (zero group)\n");
872 DEBUG(errs() << '\n');
874 // Look for a suitable register to use to break the anti-dependence.
875 std::map<unsigned, unsigned> RenameMap;
876 if (FindSuitableFreeRegisters(GroupIndex, RenameOrder, RenameMap)) {
877 DEBUG(errs() << "\tBreaking anti-dependence edge on "
878 << TRI->getName(AntiDepReg) << ":");
880 // Handle each group register...
881 for (std::map<unsigned, unsigned>::iterator
882 S = RenameMap.begin(), E = RenameMap.end(); S != E; ++S) {
883 unsigned CurrReg = S->first;
884 unsigned NewReg = S->second;
886 DEBUG(errs() << " " << TRI->getName(CurrReg) << "->" <<
887 TRI->getName(NewReg) << "(" <<
888 RegRefs.count(CurrReg) << " refs)");
890 // Update the references to the old register CurrReg to
891 // refer to the new register NewReg.
892 std::pair<std::multimap<unsigned,
893 AggressiveAntiDepState::RegisterReference>::iterator,
894 std::multimap<unsigned,
895 AggressiveAntiDepState::RegisterReference>::iterator>
896 Range = RegRefs.equal_range(CurrReg);
897 for (std::multimap<unsigned, AggressiveAntiDepState::RegisterReference>::iterator
898 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
899 Q->second.Operand->setReg(NewReg);
902 // We just went back in time and modified history; the
903 // liveness information for CurrReg is now inconsistent. Set
904 // the state as if it were dead.
905 State->UnionGroups(NewReg, 0);
906 RegRefs.erase(NewReg);
907 DefIndices[NewReg] = DefIndices[CurrReg];
908 KillIndices[NewReg] = KillIndices[CurrReg];
910 State->UnionGroups(CurrReg, 0);
911 RegRefs.erase(CurrReg);
912 DefIndices[CurrReg] = KillIndices[CurrReg];
913 KillIndices[CurrReg] = ~0u;
914 assert(((KillIndices[CurrReg] == ~0u) !=
915 (DefIndices[CurrReg] == ~0u)) &&
916 "Kill and Def maps aren't consistent for AntiDepReg!");
920 DEBUG(errs() << '\n');
925 ScanInstruction(MI, Count);