1 //===----- CriticalAntiDepBreaker.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 CriticalAntiDepBreaker class, which
11 // implements register anti-dependence breaking along a blocks
12 // critical path during post-RA scheduler.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "post-RA-sched"
17 #include "CriticalAntiDepBreaker.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
28 CriticalAntiDepBreaker::
29 CriticalAntiDepBreaker(MachineFunction& MFi) :
30 AntiDepBreaker(), MF(MFi),
32 TRI(MF.getTarget().getRegisterInfo()),
33 AllocatableSet(TRI->getAllocatableSet(MF))
37 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
40 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
41 // Clear out the register class data.
42 std::fill(Classes, array_endof(Classes),
43 static_cast<const TargetRegisterClass *>(0));
45 // Initialize the indices to indicate that no registers are live.
46 const unsigned BBSize = BB->size();
47 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
49 DefIndices[i] = BBSize;
52 // Clear "do not change" set.
55 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
57 // Determine the live-out physregs for this block.
59 // In a return block, examine the function live-out regs.
60 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
61 E = MRI.liveout_end(); I != E; ++I) {
63 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
64 KillIndices[Reg] = BB->size();
65 DefIndices[Reg] = ~0u;
66 // Repeat, for all aliases.
67 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
68 unsigned AliasReg = *Alias;
69 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
70 KillIndices[AliasReg] = BB->size();
71 DefIndices[AliasReg] = ~0u;
75 // In a non-return block, examine the live-in regs of all successors.
76 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
77 SE = BB->succ_end(); SI != SE; ++SI)
78 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
79 E = (*SI)->livein_end(); I != E; ++I) {
81 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
82 KillIndices[Reg] = BB->size();
83 DefIndices[Reg] = ~0u;
84 // Repeat, for all aliases.
85 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
86 unsigned AliasReg = *Alias;
87 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
88 KillIndices[AliasReg] = BB->size();
89 DefIndices[AliasReg] = ~0u;
94 // Mark live-out callee-saved registers. In a return block this is
95 // all callee-saved registers. In non-return this is any
96 // callee-saved register that is not saved in the prolog.
97 const MachineFrameInfo *MFI = MF.getFrameInfo();
98 BitVector Pristine = MFI->getPristineRegs(BB);
99 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
101 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
102 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
103 KillIndices[Reg] = BB->size();
104 DefIndices[Reg] = ~0u;
105 // Repeat, for all aliases.
106 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
107 unsigned AliasReg = *Alias;
108 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
109 KillIndices[AliasReg] = BB->size();
110 DefIndices[AliasReg] = ~0u;
115 void CriticalAntiDepBreaker::FinishBlock() {
120 void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
121 unsigned InsertPosIndex) {
122 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
124 // Any register which was defined within the previous scheduling region
125 // may have been rescheduled and its lifetime may overlap with registers
126 // in ways not reflected in our current liveness state. For each such
127 // register, adjust the liveness state to be conservatively correct.
128 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg)
129 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
130 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
131 // Mark this register to be non-renamable.
132 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
133 // Move the def index to the end of the previous region, to reflect
134 // that the def could theoretically have been scheduled at the end.
135 DefIndices[Reg] = InsertPosIndex;
138 PrescanInstruction(MI);
139 ScanInstruction(MI, Count);
142 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
144 static SDep *CriticalPathStep(SUnit *SU) {
146 unsigned NextDepth = 0;
147 // Find the predecessor edge with the greatest depth.
148 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
150 SUnit *PredSU = P->getSUnit();
151 unsigned PredLatency = P->getLatency();
152 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
153 // In the case of a latency tie, prefer an anti-dependency edge over
154 // other types of edges.
155 if (NextDepth < PredTotalLatency ||
156 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
157 NextDepth = PredTotalLatency;
164 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
165 // Scan the register operands for this instruction and update
166 // Classes and RegRefs.
167 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
168 MachineOperand &MO = MI->getOperand(i);
169 if (!MO.isReg()) continue;
170 unsigned Reg = MO.getReg();
171 if (Reg == 0) continue;
172 const TargetRegisterClass *NewRC = 0;
174 if (i < MI->getDesc().getNumOperands())
175 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
177 // For now, only allow the register to be changed if its register
178 // class is consistent across all uses.
179 if (!Classes[Reg] && NewRC)
180 Classes[Reg] = NewRC;
181 else if (!NewRC || Classes[Reg] != NewRC)
182 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
184 // Now check for aliases.
185 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
186 // If an alias of the reg is used during the live range, give up.
187 // Note that this allows us to skip checking if AntiDepReg
188 // overlaps with any of the aliases, among other things.
189 unsigned AliasReg = *Alias;
190 if (Classes[AliasReg]) {
191 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
192 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
196 // If we're still willing to consider this register, note the reference.
197 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
198 RegRefs.insert(std::make_pair(Reg, &MO));
200 // It's not safe to change register allocation for source operands of
201 // that have special allocation requirements.
202 if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
203 if (KeepRegs.insert(Reg)) {
204 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
206 KeepRegs.insert(*Subreg);
212 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
215 // Proceding upwards, registers that are defed but not used in this
216 // instruction are now dead.
217 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
218 MachineOperand &MO = MI->getOperand(i);
219 if (!MO.isReg()) continue;
220 unsigned Reg = MO.getReg();
221 if (Reg == 0) continue;
222 if (!MO.isDef()) continue;
223 // Ignore two-addr defs.
224 if (MI->isRegTiedToUseOperand(i)) continue;
226 DefIndices[Reg] = Count;
227 KillIndices[Reg] = ~0u;
228 assert(((KillIndices[Reg] == ~0u) !=
229 (DefIndices[Reg] == ~0u)) &&
230 "Kill and Def maps aren't consistent for Reg!");
234 // Repeat, for all subregs.
235 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
237 unsigned SubregReg = *Subreg;
238 DefIndices[SubregReg] = Count;
239 KillIndices[SubregReg] = ~0u;
240 KeepRegs.erase(SubregReg);
241 Classes[SubregReg] = 0;
242 RegRefs.erase(SubregReg);
244 // Conservatively mark super-registers as unusable.
245 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
247 unsigned SuperReg = *Super;
248 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
251 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
252 MachineOperand &MO = MI->getOperand(i);
253 if (!MO.isReg()) continue;
254 unsigned Reg = MO.getReg();
255 if (Reg == 0) continue;
256 if (!MO.isUse()) continue;
258 const TargetRegisterClass *NewRC = 0;
259 if (i < MI->getDesc().getNumOperands())
260 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
262 // For now, only allow the register to be changed if its register
263 // class is consistent across all uses.
264 if (!Classes[Reg] && NewRC)
265 Classes[Reg] = NewRC;
266 else if (!NewRC || Classes[Reg] != NewRC)
267 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
269 RegRefs.insert(std::make_pair(Reg, &MO));
271 // It wasn't previously live but now it is, this is a kill.
272 if (KillIndices[Reg] == ~0u) {
273 KillIndices[Reg] = Count;
274 DefIndices[Reg] = ~0u;
275 assert(((KillIndices[Reg] == ~0u) !=
276 (DefIndices[Reg] == ~0u)) &&
277 "Kill and Def maps aren't consistent for Reg!");
279 // Repeat, for all aliases.
280 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
281 unsigned AliasReg = *Alias;
282 if (KillIndices[AliasReg] == ~0u) {
283 KillIndices[AliasReg] = Count;
284 DefIndices[AliasReg] = ~0u;
291 CriticalAntiDepBreaker::findSuitableFreeRegister(unsigned AntiDepReg,
293 const TargetRegisterClass *RC) {
294 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
295 RE = RC->allocation_order_end(MF); R != RE; ++R) {
296 unsigned NewReg = *R;
297 // Don't replace a register with itself.
298 if (NewReg == AntiDepReg) continue;
299 // Don't replace a register with one that was recently used to repair
300 // an anti-dependence with this AntiDepReg, because that would
301 // re-introduce that anti-dependence.
302 if (NewReg == LastNewReg) continue;
303 // If NewReg is dead and NewReg's most recent def is not before
304 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
305 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
306 "Kill and Def maps aren't consistent for AntiDepReg!");
307 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
308 "Kill and Def maps aren't consistent for NewReg!");
309 if (KillIndices[NewReg] != ~0u ||
310 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
311 KillIndices[AntiDepReg] > DefIndices[NewReg])
316 // No registers are free and available!
320 unsigned CriticalAntiDepBreaker::
321 BreakAntiDependencies(std::vector<SUnit>& SUnits,
322 MachineBasicBlock::iterator& Begin,
323 MachineBasicBlock::iterator& End,
324 unsigned InsertPosIndex) {
325 // The code below assumes that there is at least one instruction,
326 // so just duck out immediately if the block is empty.
327 if (SUnits.empty()) return 0;
329 // Find the node at the bottom of the critical path.
331 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
332 SUnit *SU = &SUnits[i];
333 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
339 DEBUG(errs() << "Critical path has total latency "
340 << (Max->getDepth() + Max->Latency) << "\n");
341 DEBUG(errs() << "Available regs:");
342 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
343 if (KillIndices[Reg] == ~0u)
344 DEBUG(errs() << " " << TRI->getName(Reg));
346 DEBUG(errs() << '\n');
350 // Track progress along the critical path through the SUnit graph as we walk
352 SUnit *CriticalPathSU = Max;
353 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
355 // Consider this pattern:
364 // There are three anti-dependencies here, and without special care,
365 // we'd break all of them using the same register:
374 // because at each anti-dependence, B is the first register that
375 // isn't A which is free. This re-introduces anti-dependencies
376 // at all but one of the original anti-dependencies that we were
377 // trying to break. To avoid this, keep track of the most recent
378 // register that each register was replaced with, avoid
379 // using it to repair an anti-dependence on the same register.
380 // This lets us produce this:
389 // This still has an anti-dependence on B, but at least it isn't on the
390 // original critical path.
392 // TODO: If we tracked more than one register here, we could potentially
393 // fix that remaining critical edge too. This is a little more involved,
394 // because unlike the most recent register, less recent registers should
395 // still be considered, though only if no other registers are available.
396 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
398 // Attempt to break anti-dependence edges on the critical path. Walk the
399 // instructions from the bottom up, tracking information about liveness
400 // as we go to help determine which registers are available.
402 unsigned Count = InsertPosIndex - 1;
403 for (MachineBasicBlock::iterator I = End, E = Begin;
405 MachineInstr *MI = --I;
407 // Check if this instruction has a dependence on the critical path that
408 // is an anti-dependence that we may be able to break. If it is, set
409 // AntiDepReg to the non-zero register associated with the anti-dependence.
411 // We limit our attention to the critical path as a heuristic to avoid
412 // breaking anti-dependence edges that aren't going to significantly
413 // impact the overall schedule. There are a limited number of registers
414 // and we want to save them for the important edges.
416 // TODO: Instructions with multiple defs could have multiple
417 // anti-dependencies. The current code here only knows how to break one
418 // edge per instruction. Note that we'd have to be able to break all of
419 // the anti-dependencies in an instruction in order to be effective.
420 unsigned AntiDepReg = 0;
421 if (MI == CriticalPathMI) {
422 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
423 SUnit *NextSU = Edge->getSUnit();
425 // Only consider anti-dependence edges.
426 if (Edge->getKind() == SDep::Anti) {
427 AntiDepReg = Edge->getReg();
428 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
429 if (!AllocatableSet.test(AntiDepReg))
430 // Don't break anti-dependencies on non-allocatable registers.
432 else if (KeepRegs.count(AntiDepReg))
433 // Don't break anti-dependencies if an use down below requires
434 // this exact register.
437 // If the SUnit has other dependencies on the SUnit that it
438 // anti-depends on, don't bother breaking the anti-dependency
439 // since those edges would prevent such units from being
440 // scheduled past each other regardless.
442 // Also, if there are dependencies on other SUnits with the
443 // same register as the anti-dependency, don't attempt to
445 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
446 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
447 if (P->getSUnit() == NextSU ?
448 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
449 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
455 CriticalPathSU = NextSU;
456 CriticalPathMI = CriticalPathSU->getInstr();
458 // We've reached the end of the critical path.
464 PrescanInstruction(MI);
466 if (MI->getDesc().hasExtraDefRegAllocReq())
467 // If this instruction's defs have special allocation requirement, don't
468 // break this anti-dependency.
470 else if (AntiDepReg) {
471 // If this instruction has a use of AntiDepReg, breaking it
473 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
474 MachineOperand &MO = MI->getOperand(i);
475 if (!MO.isReg()) continue;
476 unsigned Reg = MO.getReg();
477 if (Reg == 0) continue;
478 if (MO.isUse() && AntiDepReg == Reg) {
485 // Determine AntiDepReg's register class, if it is live and is
486 // consistently used within a single class.
487 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
488 assert((AntiDepReg == 0 || RC != NULL) &&
489 "Register should be live if it's causing an anti-dependence!");
490 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
493 // Look for a suitable register to use to break the anti-depenence.
495 // TODO: Instead of picking the first free register, consider which might
497 if (AntiDepReg != 0) {
498 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
499 LastNewReg[AntiDepReg],
501 DEBUG(errs() << "Breaking anti-dependence edge on "
502 << TRI->getName(AntiDepReg)
503 << " with " << RegRefs.count(AntiDepReg) << " references"
504 << " using " << TRI->getName(NewReg) << "!\n");
506 // Update the references to the old register to refer to the new
508 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
509 std::multimap<unsigned, MachineOperand *>::iterator>
510 Range = RegRefs.equal_range(AntiDepReg);
511 for (std::multimap<unsigned, MachineOperand *>::iterator
512 Q = Range.first, QE = Range.second; Q != QE; ++Q)
513 Q->second->setReg(NewReg);
515 // We just went back in time and modified history; the
516 // liveness information for the anti-depenence reg is now
517 // inconsistent. Set the state as if it were dead.
518 Classes[NewReg] = Classes[AntiDepReg];
519 DefIndices[NewReg] = DefIndices[AntiDepReg];
520 KillIndices[NewReg] = KillIndices[AntiDepReg];
521 assert(((KillIndices[NewReg] == ~0u) !=
522 (DefIndices[NewReg] == ~0u)) &&
523 "Kill and Def maps aren't consistent for NewReg!");
525 Classes[AntiDepReg] = 0;
526 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
527 KillIndices[AntiDepReg] = ~0u;
528 assert(((KillIndices[AntiDepReg] == ~0u) !=
529 (DefIndices[AntiDepReg] == ~0u)) &&
530 "Kill and Def maps aren't consistent for AntiDepReg!");
532 RegRefs.erase(AntiDepReg);
533 LastNewReg[AntiDepReg] = NewReg;
538 ScanInstruction(MI, Count);