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/TargetInstrInfo.h"
22
#include "llvm/Target/TargetRegisterInfo.h"
23
#include "llvm/Support/Debug.h"
24
#include "llvm/Support/ErrorHandling.h"
25
#include "llvm/Support/raw_ostream.h"
29
CriticalAntiDepBreaker::
30
CriticalAntiDepBreaker(MachineFunction& MFi) :
31
AntiDepBreaker(), MF(MFi),
33
TII(MF.getTarget().getInstrInfo()),
34
TRI(MF.getTarget().getRegisterInfo()),
35
AllocatableSet(TRI->getAllocatableSet(MF)),
36
Classes(TRI->getNumRegs(), static_cast<const TargetRegisterClass *>(0)),
37
KillIndices(TRI->getNumRegs(), 0),
38
DefIndices(TRI->getNumRegs(), 0) {}
40
CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
43
void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
44
const unsigned BBSize = BB->size();
45
for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
46
// Clear out the register class data.
47
Classes[i] = static_cast<const TargetRegisterClass *>(0);
49
// Initialize the indices to indicate that no registers are live.
51
DefIndices[i] = BBSize;
54
// Clear "do not change" set.
57
bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
59
// Determine the live-out physregs for this block.
61
// In a return block, examine the function live-out regs.
62
for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
63
E = MRI.liveout_end(); I != E; ++I) {
65
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
66
KillIndices[Reg] = BB->size();
67
DefIndices[Reg] = ~0u;
69
// Repeat, for all aliases.
70
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
71
unsigned AliasReg = *Alias;
72
Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
73
KillIndices[AliasReg] = BB->size();
74
DefIndices[AliasReg] = ~0u;
79
// In a non-return block, examine the live-in regs of all successors.
80
// Note a return block can have successors if the return instruction is
82
for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
83
SE = BB->succ_end(); SI != SE; ++SI)
84
for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
85
E = (*SI)->livein_end(); I != E; ++I) {
87
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
88
KillIndices[Reg] = BB->size();
89
DefIndices[Reg] = ~0u;
91
// Repeat, for all aliases.
92
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
93
unsigned AliasReg = *Alias;
94
Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
95
KillIndices[AliasReg] = BB->size();
96
DefIndices[AliasReg] = ~0u;
100
// Mark live-out callee-saved registers. In a return block this is
101
// all callee-saved registers. In non-return this is any
102
// callee-saved register that is not saved in the prolog.
103
const MachineFrameInfo *MFI = MF.getFrameInfo();
104
BitVector Pristine = MFI->getPristineRegs(BB);
105
for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
107
if (!IsReturnBlock && !Pristine.test(Reg)) continue;
108
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
109
KillIndices[Reg] = BB->size();
110
DefIndices[Reg] = ~0u;
112
// Repeat, for all aliases.
113
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
114
unsigned AliasReg = *Alias;
115
Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
116
KillIndices[AliasReg] = BB->size();
117
DefIndices[AliasReg] = ~0u;
122
void CriticalAntiDepBreaker::FinishBlock() {
127
void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
128
unsigned InsertPosIndex) {
129
if (MI->isDebugValue())
131
assert(Count < InsertPosIndex && "Instruction index out of expected range!");
133
// Any register which was defined within the previous scheduling region
134
// may have been rescheduled and its lifetime may overlap with registers
135
// in ways not reflected in our current liveness state. For each such
136
// register, adjust the liveness state to be conservatively correct.
137
for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg)
138
if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
139
assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
141
// Mark this register to be non-renamable.
142
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
144
// Move the def index to the end of the previous region, to reflect
145
// that the def could theoretically have been scheduled at the end.
146
DefIndices[Reg] = InsertPosIndex;
149
PrescanInstruction(MI);
150
ScanInstruction(MI, Count);
153
/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
155
static const SDep *CriticalPathStep(const SUnit *SU) {
156
const SDep *Next = 0;
157
unsigned NextDepth = 0;
158
// Find the predecessor edge with the greatest depth.
159
for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
161
const SUnit *PredSU = P->getSUnit();
162
unsigned PredLatency = P->getLatency();
163
unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
164
// In the case of a latency tie, prefer an anti-dependency edge over
165
// other types of edges.
166
if (NextDepth < PredTotalLatency ||
167
(NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
168
NextDepth = PredTotalLatency;
175
void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
176
// It's not safe to change register allocation for source operands of
177
// that have special allocation requirements. Also assume all registers
178
// used in a call must not be changed (ABI).
179
// FIXME: The issue with predicated instruction is more complex. We are being
180
// conservatively here because the kill markers cannot be trusted after
182
// %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
184
// STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
185
// %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
186
// STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
188
// The first R6 kill is not really a kill since it's killed by a predicated
189
// instruction which may not be executed. The second R6 def may or may not
190
// re-define R6 so it's not safe to change it since the last R6 use cannot be
192
bool Special = MI->getDesc().isCall() ||
193
MI->getDesc().hasExtraSrcRegAllocReq() ||
194
TII->isPredicated(MI);
196
// Scan the register operands for this instruction and update
197
// Classes and RegRefs.
198
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
199
MachineOperand &MO = MI->getOperand(i);
200
if (!MO.isReg()) continue;
201
unsigned Reg = MO.getReg();
202
if (Reg == 0) continue;
203
const TargetRegisterClass *NewRC = 0;
205
if (i < MI->getDesc().getNumOperands())
206
NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
208
// For now, only allow the register to be changed if its register
209
// class is consistent across all uses.
210
if (!Classes[Reg] && NewRC)
211
Classes[Reg] = NewRC;
212
else if (!NewRC || Classes[Reg] != NewRC)
213
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
215
// Now check for aliases.
216
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
217
// If an alias of the reg is used during the live range, give up.
218
// Note that this allows us to skip checking if AntiDepReg
219
// overlaps with any of the aliases, among other things.
220
unsigned AliasReg = *Alias;
221
if (Classes[AliasReg]) {
222
Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
223
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
227
// If we're still willing to consider this register, note the reference.
228
if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
229
RegRefs.insert(std::make_pair(Reg, &MO));
231
if (MO.isUse() && Special) {
232
if (KeepRegs.insert(Reg)) {
233
for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
235
KeepRegs.insert(*Subreg);
241
void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
244
// Proceding upwards, registers that are defed but not used in this
245
// instruction are now dead.
247
if (!TII->isPredicated(MI)) {
248
// Predicated defs are modeled as read + write, i.e. similar to two
250
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
251
MachineOperand &MO = MI->getOperand(i);
252
if (!MO.isReg()) continue;
253
unsigned Reg = MO.getReg();
254
if (Reg == 0) continue;
255
if (!MO.isDef()) continue;
256
// Ignore two-addr defs.
257
if (MI->isRegTiedToUseOperand(i)) continue;
259
DefIndices[Reg] = Count;
260
KillIndices[Reg] = ~0u;
261
assert(((KillIndices[Reg] == ~0u) !=
262
(DefIndices[Reg] == ~0u)) &&
263
"Kill and Def maps aren't consistent for Reg!");
267
// Repeat, for all subregs.
268
for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
270
unsigned SubregReg = *Subreg;
271
DefIndices[SubregReg] = Count;
272
KillIndices[SubregReg] = ~0u;
273
KeepRegs.erase(SubregReg);
274
Classes[SubregReg] = 0;
275
RegRefs.erase(SubregReg);
277
// Conservatively mark super-registers as unusable.
278
for (const unsigned *Super = TRI->getSuperRegisters(Reg);
280
unsigned SuperReg = *Super;
281
Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
285
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
286
MachineOperand &MO = MI->getOperand(i);
287
if (!MO.isReg()) continue;
288
unsigned Reg = MO.getReg();
289
if (Reg == 0) continue;
290
if (!MO.isUse()) continue;
292
const TargetRegisterClass *NewRC = 0;
293
if (i < MI->getDesc().getNumOperands())
294
NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
296
// For now, only allow the register to be changed if its register
297
// class is consistent across all uses.
298
if (!Classes[Reg] && NewRC)
299
Classes[Reg] = NewRC;
300
else if (!NewRC || Classes[Reg] != NewRC)
301
Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
303
RegRefs.insert(std::make_pair(Reg, &MO));
305
// It wasn't previously live but now it is, this is a kill.
306
if (KillIndices[Reg] == ~0u) {
307
KillIndices[Reg] = Count;
308
DefIndices[Reg] = ~0u;
309
assert(((KillIndices[Reg] == ~0u) !=
310
(DefIndices[Reg] == ~0u)) &&
311
"Kill and Def maps aren't consistent for Reg!");
313
// Repeat, for all aliases.
314
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
315
unsigned AliasReg = *Alias;
316
if (KillIndices[AliasReg] == ~0u) {
317
KillIndices[AliasReg] = Count;
318
DefIndices[AliasReg] = ~0u;
325
CriticalAntiDepBreaker::findSuitableFreeRegister(MachineInstr *MI,
328
const TargetRegisterClass *RC)
330
for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
331
RE = RC->allocation_order_end(MF); R != RE; ++R) {
332
unsigned NewReg = *R;
333
// Don't consider non-allocatable registers
334
if (!AllocatableSet.test(NewReg)) continue;
335
// Don't replace a register with itself.
336
if (NewReg == AntiDepReg) continue;
337
// Don't replace a register with one that was recently used to repair
338
// an anti-dependence with this AntiDepReg, because that would
339
// re-introduce that anti-dependence.
340
if (NewReg == LastNewReg) continue;
341
// If the instruction already has a def of the NewReg, it's not suitable.
342
// For example, Instruction with multiple definitions can result in this
344
if (MI->modifiesRegister(NewReg, TRI)) continue;
345
// If NewReg is dead and NewReg's most recent def is not before
346
// AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
347
assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
348
&& "Kill and Def maps aren't consistent for AntiDepReg!");
349
assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
350
&& "Kill and Def maps aren't consistent for NewReg!");
351
if (KillIndices[NewReg] != ~0u ||
352
Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
353
KillIndices[AntiDepReg] > DefIndices[NewReg])
358
// No registers are free and available!
362
unsigned CriticalAntiDepBreaker::
363
BreakAntiDependencies(const std::vector<SUnit>& SUnits,
364
MachineBasicBlock::iterator Begin,
365
MachineBasicBlock::iterator End,
366
unsigned InsertPosIndex) {
367
// The code below assumes that there is at least one instruction,
368
// so just duck out immediately if the block is empty.
369
if (SUnits.empty()) return 0;
371
// Keep a map of the MachineInstr*'s back to the SUnit representing them.
372
// This is used for updating debug information.
373
DenseMap<MachineInstr*,const SUnit*> MISUnitMap;
375
// Find the node at the bottom of the critical path.
376
const SUnit *Max = 0;
377
for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
378
const SUnit *SU = &SUnits[i];
379
MISUnitMap[SU->getInstr()] = SU;
380
if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
386
DEBUG(dbgs() << "Critical path has total latency "
387
<< (Max->getDepth() + Max->Latency) << "\n");
388
DEBUG(dbgs() << "Available regs:");
389
for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
390
if (KillIndices[Reg] == ~0u)
391
DEBUG(dbgs() << " " << TRI->getName(Reg));
393
DEBUG(dbgs() << '\n');
397
// Track progress along the critical path through the SUnit graph as we walk
399
const SUnit *CriticalPathSU = Max;
400
MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
402
// Consider this pattern:
411
// There are three anti-dependencies here, and without special care,
412
// we'd break all of them using the same register:
421
// because at each anti-dependence, B is the first register that
422
// isn't A which is free. This re-introduces anti-dependencies
423
// at all but one of the original anti-dependencies that we were
424
// trying to break. To avoid this, keep track of the most recent
425
// register that each register was replaced with, avoid
426
// using it to repair an anti-dependence on the same register.
427
// This lets us produce this:
436
// This still has an anti-dependence on B, but at least it isn't on the
437
// original critical path.
439
// TODO: If we tracked more than one register here, we could potentially
440
// fix that remaining critical edge too. This is a little more involved,
441
// because unlike the most recent register, less recent registers should
442
// still be considered, though only if no other registers are available.
443
std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
445
// Attempt to break anti-dependence edges on the critical path. Walk the
446
// instructions from the bottom up, tracking information about liveness
447
// as we go to help determine which registers are available.
449
unsigned Count = InsertPosIndex - 1;
450
for (MachineBasicBlock::iterator I = End, E = Begin;
452
MachineInstr *MI = --I;
453
if (MI->isDebugValue())
456
// Check if this instruction has a dependence on the critical path that
457
// is an anti-dependence that we may be able to break. If it is, set
458
// AntiDepReg to the non-zero register associated with the anti-dependence.
460
// We limit our attention to the critical path as a heuristic to avoid
461
// breaking anti-dependence edges that aren't going to significantly
462
// impact the overall schedule. There are a limited number of registers
463
// and we want to save them for the important edges.
465
// TODO: Instructions with multiple defs could have multiple
466
// anti-dependencies. The current code here only knows how to break one
467
// edge per instruction. Note that we'd have to be able to break all of
468
// the anti-dependencies in an instruction in order to be effective.
469
unsigned AntiDepReg = 0;
470
if (MI == CriticalPathMI) {
471
if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
472
const SUnit *NextSU = Edge->getSUnit();
474
// Only consider anti-dependence edges.
475
if (Edge->getKind() == SDep::Anti) {
476
AntiDepReg = Edge->getReg();
477
assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
478
if (!AllocatableSet.test(AntiDepReg))
479
// Don't break anti-dependencies on non-allocatable registers.
481
else if (KeepRegs.count(AntiDepReg))
482
// Don't break anti-dependencies if an use down below requires
483
// this exact register.
486
// If the SUnit has other dependencies on the SUnit that it
487
// anti-depends on, don't bother breaking the anti-dependency
488
// since those edges would prevent such units from being
489
// scheduled past each other regardless.
491
// Also, if there are dependencies on other SUnits with the
492
// same register as the anti-dependency, don't attempt to
494
for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
495
PE = CriticalPathSU->Preds.end(); P != PE; ++P)
496
if (P->getSUnit() == NextSU ?
497
(P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
498
(P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
504
CriticalPathSU = NextSU;
505
CriticalPathMI = CriticalPathSU->getInstr();
507
// We've reached the end of the critical path.
513
PrescanInstruction(MI);
515
// If MI's defs have a special allocation requirement, don't allow
516
// any def registers to be changed. Also assume all registers
517
// defined in a call must not be changed (ABI).
518
if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq() ||
519
TII->isPredicated(MI))
520
// If this instruction's defs have special allocation requirement, don't
521
// break this anti-dependency.
523
else if (AntiDepReg) {
524
// If this instruction has a use of AntiDepReg, breaking it
526
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
527
MachineOperand &MO = MI->getOperand(i);
528
if (!MO.isReg()) continue;
529
unsigned Reg = MO.getReg();
530
if (Reg == 0) continue;
531
if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
538
// Determine AntiDepReg's register class, if it is live and is
539
// consistently used within a single class.
540
const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
541
assert((AntiDepReg == 0 || RC != NULL) &&
542
"Register should be live if it's causing an anti-dependence!");
543
if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
546
// Look for a suitable register to use to break the anti-depenence.
548
// TODO: Instead of picking the first free register, consider which might
550
if (AntiDepReg != 0) {
551
if (unsigned NewReg = findSuitableFreeRegister(MI, AntiDepReg,
552
LastNewReg[AntiDepReg],
554
DEBUG(dbgs() << "Breaking anti-dependence edge on "
555
<< TRI->getName(AntiDepReg)
556
<< " with " << RegRefs.count(AntiDepReg) << " references"
557
<< " using " << TRI->getName(NewReg) << "!\n");
559
// Update the references to the old register to refer to the new
561
std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
562
std::multimap<unsigned, MachineOperand *>::iterator>
563
Range = RegRefs.equal_range(AntiDepReg);
564
for (std::multimap<unsigned, MachineOperand *>::iterator
565
Q = Range.first, QE = Range.second; Q != QE; ++Q) {
566
Q->second->setReg(NewReg);
567
// If the SU for the instruction being updated has debug information
568
// related to the anti-dependency register, make sure to update that
570
const SUnit *SU = MISUnitMap[Q->second->getParent()];
572
for (unsigned i = 0, e = SU->DbgInstrList.size() ; i < e ; ++i) {
573
MachineInstr *DI = SU->DbgInstrList[i];
574
assert (DI->getNumOperands()==3 && DI->getOperand(0).isReg() &&
575
DI->getOperand(0).getReg()
576
&& "Non register dbg_value attached to SUnit!");
577
if (DI->getOperand(0).getReg() == AntiDepReg)
578
DI->getOperand(0).setReg(NewReg);
582
// We just went back in time and modified history; the
583
// liveness information for the anti-depenence reg is now
584
// inconsistent. Set the state as if it were dead.
585
Classes[NewReg] = Classes[AntiDepReg];
586
DefIndices[NewReg] = DefIndices[AntiDepReg];
587
KillIndices[NewReg] = KillIndices[AntiDepReg];
588
assert(((KillIndices[NewReg] == ~0u) !=
589
(DefIndices[NewReg] == ~0u)) &&
590
"Kill and Def maps aren't consistent for NewReg!");
592
Classes[AntiDepReg] = 0;
593
DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
594
KillIndices[AntiDepReg] = ~0u;
595
assert(((KillIndices[AntiDepReg] == ~0u) !=
596
(DefIndices[AntiDepReg] == ~0u)) &&
597
"Kill and Def maps aren't consistent for AntiDepReg!");
599
RegRefs.erase(AntiDepReg);
600
LastNewReg[AntiDepReg] = NewReg;
605
ScanInstruction(MI, Count);