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
if (MI->isDebugValue())
124
assert(Count < InsertPosIndex && "Instruction index out of expected range!");
126
// Any register which was defined within the previous scheduling region
127
// may have been rescheduled and its lifetime may overlap with registers
128
// in ways not reflected in our current liveness state. For each such
129
// register, adjust the liveness state to be conservatively correct.
130
for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg)
131
if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
132
assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
133
// Mark this register to be non-renamable.
134
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
135
// Move the def index to the end of the previous region, to reflect
136
// that the def could theoretically have been scheduled at the end.
137
DefIndices[Reg] = InsertPosIndex;
140
PrescanInstruction(MI);
141
ScanInstruction(MI, Count);
144
/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
146
static SDep *CriticalPathStep(SUnit *SU) {
148
unsigned NextDepth = 0;
149
// Find the predecessor edge with the greatest depth.
150
for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
152
SUnit *PredSU = P->getSUnit();
153
unsigned PredLatency = P->getLatency();
154
unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
155
// In the case of a latency tie, prefer an anti-dependency edge over
156
// other types of edges.
157
if (NextDepth < PredTotalLatency ||
158
(NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
159
NextDepth = PredTotalLatency;
166
void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
167
// Scan the register operands for this instruction and update
168
// Classes and RegRefs.
169
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170
MachineOperand &MO = MI->getOperand(i);
171
if (!MO.isReg()) continue;
172
unsigned Reg = MO.getReg();
173
if (Reg == 0) continue;
174
const TargetRegisterClass *NewRC = 0;
176
if (i < MI->getDesc().getNumOperands())
177
NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
179
// For now, only allow the register to be changed if its register
180
// class is consistent across all uses.
181
if (!Classes[Reg] && NewRC)
182
Classes[Reg] = NewRC;
183
else if (!NewRC || Classes[Reg] != NewRC)
184
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
186
// Now check for aliases.
187
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
188
// If an alias of the reg is used during the live range, give up.
189
// Note that this allows us to skip checking if AntiDepReg
190
// overlaps with any of the aliases, among other things.
191
unsigned AliasReg = *Alias;
192
if (Classes[AliasReg]) {
193
Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
194
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
198
// If we're still willing to consider this register, note the reference.
199
if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
200
RegRefs.insert(std::make_pair(Reg, &MO));
202
// It's not safe to change register allocation for source operands of
203
// that have special allocation requirements.
204
if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
205
if (KeepRegs.insert(Reg)) {
206
for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
208
KeepRegs.insert(*Subreg);
214
void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
217
// Proceding upwards, registers that are defed but not used in this
218
// instruction are now dead.
219
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
220
MachineOperand &MO = MI->getOperand(i);
221
if (!MO.isReg()) continue;
222
unsigned Reg = MO.getReg();
223
if (Reg == 0) continue;
224
if (!MO.isDef()) continue;
225
// Ignore two-addr defs.
226
if (MI->isRegTiedToUseOperand(i)) continue;
228
DefIndices[Reg] = Count;
229
KillIndices[Reg] = ~0u;
230
assert(((KillIndices[Reg] == ~0u) !=
231
(DefIndices[Reg] == ~0u)) &&
232
"Kill and Def maps aren't consistent for Reg!");
236
// Repeat, for all subregs.
237
for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
239
unsigned SubregReg = *Subreg;
240
DefIndices[SubregReg] = Count;
241
KillIndices[SubregReg] = ~0u;
242
KeepRegs.erase(SubregReg);
243
Classes[SubregReg] = 0;
244
RegRefs.erase(SubregReg);
246
// Conservatively mark super-registers as unusable.
247
for (const unsigned *Super = TRI->getSuperRegisters(Reg);
249
unsigned SuperReg = *Super;
250
Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
253
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
254
MachineOperand &MO = MI->getOperand(i);
255
if (!MO.isReg()) continue;
256
unsigned Reg = MO.getReg();
257
if (Reg == 0) continue;
258
if (!MO.isUse()) continue;
260
const TargetRegisterClass *NewRC = 0;
261
if (i < MI->getDesc().getNumOperands())
262
NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
264
// For now, only allow the register to be changed if its register
265
// class is consistent across all uses.
266
if (!Classes[Reg] && NewRC)
267
Classes[Reg] = NewRC;
268
else if (!NewRC || Classes[Reg] != NewRC)
269
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
271
RegRefs.insert(std::make_pair(Reg, &MO));
273
// It wasn't previously live but now it is, this is a kill.
274
if (KillIndices[Reg] == ~0u) {
275
KillIndices[Reg] = Count;
276
DefIndices[Reg] = ~0u;
277
assert(((KillIndices[Reg] == ~0u) !=
278
(DefIndices[Reg] == ~0u)) &&
279
"Kill and Def maps aren't consistent for Reg!");
281
// Repeat, for all aliases.
282
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
283
unsigned AliasReg = *Alias;
284
if (KillIndices[AliasReg] == ~0u) {
285
KillIndices[AliasReg] = Count;
286
DefIndices[AliasReg] = ~0u;
293
CriticalAntiDepBreaker::findSuitableFreeRegister(MachineInstr *MI,
296
const TargetRegisterClass *RC)
298
for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
299
RE = RC->allocation_order_end(MF); R != RE; ++R) {
300
unsigned NewReg = *R;
301
// Don't replace a register with itself.
302
if (NewReg == AntiDepReg) continue;
303
// Don't replace a register with one that was recently used to repair
304
// an anti-dependence with this AntiDepReg, because that would
305
// re-introduce that anti-dependence.
306
if (NewReg == LastNewReg) continue;
307
// If the instruction already has a def of the NewReg, it's not suitable.
308
// For example, Instruction with multiple definitions can result in this
310
if (MI->modifiesRegister(NewReg, TRI)) continue;
311
// If NewReg is dead and NewReg's most recent def is not before
312
// AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
313
assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
314
&& "Kill and Def maps aren't consistent for AntiDepReg!");
315
assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
316
&& "Kill and Def maps aren't consistent for NewReg!");
317
if (KillIndices[NewReg] != ~0u ||
318
Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
319
KillIndices[AntiDepReg] > DefIndices[NewReg])
324
// No registers are free and available!
328
unsigned CriticalAntiDepBreaker::
329
BreakAntiDependencies(std::vector<SUnit>& SUnits,
330
MachineBasicBlock::iterator& Begin,
331
MachineBasicBlock::iterator& End,
332
unsigned InsertPosIndex) {
333
// The code below assumes that there is at least one instruction,
334
// so just duck out immediately if the block is empty.
335
if (SUnits.empty()) return 0;
337
// Find the node at the bottom of the critical path.
339
for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
340
SUnit *SU = &SUnits[i];
341
if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
347
DEBUG(dbgs() << "Critical path has total latency "
348
<< (Max->getDepth() + Max->Latency) << "\n");
349
DEBUG(dbgs() << "Available regs:");
350
for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
351
if (KillIndices[Reg] == ~0u)
352
DEBUG(dbgs() << " " << TRI->getName(Reg));
354
DEBUG(dbgs() << '\n');
358
// Track progress along the critical path through the SUnit graph as we walk
360
SUnit *CriticalPathSU = Max;
361
MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
363
// Consider this pattern:
372
// There are three anti-dependencies here, and without special care,
373
// we'd break all of them using the same register:
382
// because at each anti-dependence, B is the first register that
383
// isn't A which is free. This re-introduces anti-dependencies
384
// at all but one of the original anti-dependencies that we were
385
// trying to break. To avoid this, keep track of the most recent
386
// register that each register was replaced with, avoid
387
// using it to repair an anti-dependence on the same register.
388
// This lets us produce this:
397
// This still has an anti-dependence on B, but at least it isn't on the
398
// original critical path.
400
// TODO: If we tracked more than one register here, we could potentially
401
// fix that remaining critical edge too. This is a little more involved,
402
// because unlike the most recent register, less recent registers should
403
// still be considered, though only if no other registers are available.
404
unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
406
// Attempt to break anti-dependence edges on the critical path. Walk the
407
// instructions from the bottom up, tracking information about liveness
408
// as we go to help determine which registers are available.
410
unsigned Count = InsertPosIndex - 1;
411
for (MachineBasicBlock::iterator I = End, E = Begin;
413
MachineInstr *MI = --I;
414
if (MI->isDebugValue())
417
// Check if this instruction has a dependence on the critical path that
418
// is an anti-dependence that we may be able to break. If it is, set
419
// AntiDepReg to the non-zero register associated with the anti-dependence.
421
// We limit our attention to the critical path as a heuristic to avoid
422
// breaking anti-dependence edges that aren't going to significantly
423
// impact the overall schedule. There are a limited number of registers
424
// and we want to save them for the important edges.
426
// TODO: Instructions with multiple defs could have multiple
427
// anti-dependencies. The current code here only knows how to break one
428
// edge per instruction. Note that we'd have to be able to break all of
429
// the anti-dependencies in an instruction in order to be effective.
430
unsigned AntiDepReg = 0;
431
if (MI == CriticalPathMI) {
432
if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
433
SUnit *NextSU = Edge->getSUnit();
435
// Only consider anti-dependence edges.
436
if (Edge->getKind() == SDep::Anti) {
437
AntiDepReg = Edge->getReg();
438
assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
439
if (!AllocatableSet.test(AntiDepReg))
440
// Don't break anti-dependencies on non-allocatable registers.
442
else if (KeepRegs.count(AntiDepReg))
443
// Don't break anti-dependencies if an use down below requires
444
// this exact register.
447
// If the SUnit has other dependencies on the SUnit that it
448
// anti-depends on, don't bother breaking the anti-dependency
449
// since those edges would prevent such units from being
450
// scheduled past each other regardless.
452
// Also, if there are dependencies on other SUnits with the
453
// same register as the anti-dependency, don't attempt to
455
for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
456
PE = CriticalPathSU->Preds.end(); P != PE; ++P)
457
if (P->getSUnit() == NextSU ?
458
(P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
459
(P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
465
CriticalPathSU = NextSU;
466
CriticalPathMI = CriticalPathSU->getInstr();
468
// We've reached the end of the critical path.
474
PrescanInstruction(MI);
476
if (MI->getDesc().hasExtraDefRegAllocReq())
477
// If this instruction's defs have special allocation requirement, don't
478
// break this anti-dependency.
480
else if (AntiDepReg) {
481
// If this instruction has a use of AntiDepReg, breaking it
483
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
484
MachineOperand &MO = MI->getOperand(i);
485
if (!MO.isReg()) continue;
486
unsigned Reg = MO.getReg();
487
if (Reg == 0) continue;
488
if (MO.isUse() && AntiDepReg == Reg) {
495
// Determine AntiDepReg's register class, if it is live and is
496
// consistently used within a single class.
497
const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
498
assert((AntiDepReg == 0 || RC != NULL) &&
499
"Register should be live if it's causing an anti-dependence!");
500
if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
503
// Look for a suitable register to use to break the anti-depenence.
505
// TODO: Instead of picking the first free register, consider which might
507
if (AntiDepReg != 0) {
508
if (unsigned NewReg = findSuitableFreeRegister(MI, AntiDepReg,
509
LastNewReg[AntiDepReg],
511
DEBUG(dbgs() << "Breaking anti-dependence edge on "
512
<< TRI->getName(AntiDepReg)
513
<< " with " << RegRefs.count(AntiDepReg) << " references"
514
<< " using " << TRI->getName(NewReg) << "!\n");
516
// Update the references to the old register to refer to the new
518
std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
519
std::multimap<unsigned, MachineOperand *>::iterator>
520
Range = RegRefs.equal_range(AntiDepReg);
521
for (std::multimap<unsigned, MachineOperand *>::iterator
522
Q = Range.first, QE = Range.second; Q != QE; ++Q)
523
Q->second->setReg(NewReg);
525
// We just went back in time and modified history; the
526
// liveness information for the anti-depenence reg is now
527
// inconsistent. Set the state as if it were dead.
528
Classes[NewReg] = Classes[AntiDepReg];
529
DefIndices[NewReg] = DefIndices[AntiDepReg];
530
KillIndices[NewReg] = KillIndices[AntiDepReg];
531
assert(((KillIndices[NewReg] == ~0u) !=
532
(DefIndices[NewReg] == ~0u)) &&
533
"Kill and Def maps aren't consistent for NewReg!");
535
Classes[AntiDepReg] = 0;
536
DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
537
KillIndices[AntiDepReg] = ~0u;
538
assert(((KillIndices[AntiDepReg] == ~0u) !=
539
(DefIndices[AntiDepReg] == ~0u)) &&
540
"Kill and Def maps aren't consistent for AntiDepReg!");
542
RegRefs.erase(AntiDepReg);
543
LastNewReg[AntiDepReg] = NewReg;
548
ScanInstruction(MI, Count);