LLVM  4.0.0
CriticalAntiDepBreaker.cpp
Go to the documentation of this file.
1 //===----- CriticalAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the CriticalAntiDepBreaker class, which
11 // implements register anti-dependence breaking along a blocks
12 // critical path during post-RA scheduler.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CriticalAntiDepBreaker.h"
19 #include "llvm/Support/Debug.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "post-RA-sched"
29 
31  const RegisterClassInfo &RCI)
32  : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
33  TII(MF.getSubtarget().getInstrInfo()),
34  TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
35  Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
36  DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
37 
39 }
40 
42  const unsigned BBSize = BB->size();
43  for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
44  // Clear out the register class data.
45  Classes[i] = nullptr;
46 
47  // Initialize the indices to indicate that no registers are live.
48  KillIndices[i] = ~0u;
49  DefIndices[i] = BBSize;
50  }
51 
52  // Clear "do not change" set.
53  KeepRegs.reset();
54 
55  bool IsReturnBlock = BB->isReturnBlock();
56 
57  // Examine the live-in regs of all successors.
59  SE = BB->succ_end(); SI != SE; ++SI)
60  for (const auto &LI : (*SI)->liveins()) {
61  for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) {
62  unsigned Reg = *AI;
63  Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
64  KillIndices[Reg] = BBSize;
65  DefIndices[Reg] = ~0u;
66  }
67  }
68 
69  // Mark live-out callee-saved registers. In a return block this is
70  // all callee-saved registers. In non-return this is any
71  // callee-saved register that is not saved in the prolog.
72  const MachineFrameInfo &MFI = MF.getFrameInfo();
73  BitVector Pristine = MFI.getPristineRegs(MF);
74  for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
75  if (!IsReturnBlock && !Pristine.test(*I)) continue;
76  for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
77  unsigned Reg = *AI;
78  Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
79  KillIndices[Reg] = BBSize;
80  DefIndices[Reg] = ~0u;
81  }
82  }
83 }
84 
86  RegRefs.clear();
87  KeepRegs.reset();
88 }
89 
91  unsigned InsertPosIndex) {
92  // Kill instructions can define registers but are really nops, and there might
93  // be a real definition earlier that needs to be paired with uses dominated by
94  // this kill.
95 
96  // FIXME: It may be possible to remove the isKill() restriction once PR18663
97  // has been properly fixed. There can be value in processing kills as seen in
98  // the AggressiveAntiDepBreaker class.
99  if (MI.isDebugValue() || MI.isKill())
100  return;
101  assert(Count < InsertPosIndex && "Instruction index out of expected range!");
102 
103  for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
104  if (KillIndices[Reg] != ~0u) {
105  // If Reg is currently live, then mark that it can't be renamed as
106  // we don't know the extent of its live-range anymore (now that it
107  // has been scheduled).
108  Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
109  KillIndices[Reg] = Count;
110  } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
111  // Any register which was defined within the previous scheduling region
112  // may have been rescheduled and its lifetime may overlap with registers
113  // in ways not reflected in our current liveness state. For each such
114  // register, adjust the liveness state to be conservatively correct.
115  Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
116 
117  // Move the def index to the end of the previous region, to reflect
118  // that the def could theoretically have been scheduled at the end.
119  DefIndices[Reg] = InsertPosIndex;
120  }
121  }
122 
123  PrescanInstruction(MI);
124  ScanInstruction(MI, Count);
125 }
126 
127 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
128 /// critical path.
129 static const SDep *CriticalPathStep(const SUnit *SU) {
130  const SDep *Next = nullptr;
131  unsigned NextDepth = 0;
132  // Find the predecessor edge with the greatest depth.
133  for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
134  P != PE; ++P) {
135  const SUnit *PredSU = P->getSUnit();
136  unsigned PredLatency = P->getLatency();
137  unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
138  // In the case of a latency tie, prefer an anti-dependency edge over
139  // other types of edges.
140  if (NextDepth < PredTotalLatency ||
141  (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
142  NextDepth = PredTotalLatency;
143  Next = &*P;
144  }
145  }
146  return Next;
147 }
148 
149 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) {
150  // It's not safe to change register allocation for source operands of
151  // instructions that have special allocation requirements. Also assume all
152  // registers used in a call must not be changed (ABI).
153  // FIXME: The issue with predicated instruction is more complex. We are being
154  // conservative here because the kill markers cannot be trusted after
155  // if-conversion:
156  // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
157  // ...
158  // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
159  // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
160  // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
161  //
162  // The first R6 kill is not really a kill since it's killed by a predicated
163  // instruction which may not be executed. The second R6 def may or may not
164  // re-define R6 so it's not safe to change it since the last R6 use cannot be
165  // changed.
166  bool Special =
167  MI.isCall() || MI.hasExtraSrcRegAllocReq() || TII->isPredicated(MI);
168 
169  // Scan the register operands for this instruction and update
170  // Classes and RegRefs.
171  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
172  MachineOperand &MO = MI.getOperand(i);
173  if (!MO.isReg()) continue;
174  unsigned Reg = MO.getReg();
175  if (Reg == 0) continue;
176  const TargetRegisterClass *NewRC = nullptr;
177 
178  if (i < MI.getDesc().getNumOperands())
179  NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
180 
181  // For now, only allow the register to be changed if its register
182  // class is consistent across all uses.
183  if (!Classes[Reg] && NewRC)
184  Classes[Reg] = NewRC;
185  else if (!NewRC || Classes[Reg] != NewRC)
186  Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
187 
188  // Now check for aliases.
189  for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
190  // If an alias of the reg is used during the live range, give up.
191  // Note that this allows us to skip checking if AntiDepReg
192  // overlaps with any of the aliases, among other things.
193  unsigned AliasReg = *AI;
194  if (Classes[AliasReg]) {
195  Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
196  Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
197  }
198  }
199 
200  // If we're still willing to consider this register, note the reference.
201  if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
202  RegRefs.insert(std::make_pair(Reg, &MO));
203 
204  // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
205  // it or any of its sub or super regs. We need to use KeepRegs to mark the
206  // reg because not all uses of the same reg within an instruction are
207  // necessarily tagged as tied.
208  // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
209  // def register but not the second (see PR20020 for details).
210  // FIXME: can this check be relaxed to account for undef uses
211  // of a register? In the above 'xor' example, the uses of %eax are undef, so
212  // earlier instructions could still replace %eax even though the 'xor'
213  // itself can't be changed.
214  if (MI.isRegTiedToUseOperand(i) &&
215  Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
216  for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
217  SubRegs.isValid(); ++SubRegs) {
218  KeepRegs.set(*SubRegs);
219  }
220  for (MCSuperRegIterator SuperRegs(Reg, TRI);
221  SuperRegs.isValid(); ++SuperRegs) {
222  KeepRegs.set(*SuperRegs);
223  }
224  }
225 
226  if (MO.isUse() && Special) {
227  if (!KeepRegs.test(Reg)) {
228  for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
229  SubRegs.isValid(); ++SubRegs)
230  KeepRegs.set(*SubRegs);
231  }
232  }
233  }
234 }
235 
236 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) {
237  // Update liveness.
238  // Proceeding upwards, registers that are defed but not used in this
239  // instruction are now dead.
240  assert(!MI.isKill() && "Attempting to scan a kill instruction");
241 
242  if (!TII->isPredicated(MI)) {
243  // Predicated defs are modeled as read + write, i.e. similar to two
244  // address updates.
245  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
246  MachineOperand &MO = MI.getOperand(i);
247 
248  if (MO.isRegMask())
249  for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
250  if (MO.clobbersPhysReg(i)) {
251  DefIndices[i] = Count;
252  KillIndices[i] = ~0u;
253  KeepRegs.reset(i);
254  Classes[i] = nullptr;
255  RegRefs.erase(i);
256  }
257 
258  if (!MO.isReg()) continue;
259  unsigned Reg = MO.getReg();
260  if (Reg == 0) continue;
261  if (!MO.isDef()) continue;
262 
263  // Ignore two-addr defs.
264  if (MI.isRegTiedToUseOperand(i))
265  continue;
266 
267  // If we've already marked this reg as unchangeable, don't remove
268  // it or any of its subregs from KeepRegs.
269  bool Keep = KeepRegs.test(Reg);
270 
271  // For the reg itself and all subregs: update the def to current;
272  // reset the kill state, any restrictions, and references.
273  for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) {
274  unsigned SubregReg = *SRI;
275  DefIndices[SubregReg] = Count;
276  KillIndices[SubregReg] = ~0u;
277  Classes[SubregReg] = nullptr;
278  RegRefs.erase(SubregReg);
279  if (!Keep)
280  KeepRegs.reset(SubregReg);
281  }
282  // Conservatively mark super-registers as unusable.
283  for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
284  Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
285  }
286  }
287  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
288  MachineOperand &MO = MI.getOperand(i);
289  if (!MO.isReg()) continue;
290  unsigned Reg = MO.getReg();
291  if (Reg == 0) continue;
292  if (!MO.isUse()) continue;
293 
294  const TargetRegisterClass *NewRC = nullptr;
295  if (i < MI.getDesc().getNumOperands())
296  NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF);
297 
298  // For now, only allow the register to be changed if its register
299  // class is consistent across all uses.
300  if (!Classes[Reg] && NewRC)
301  Classes[Reg] = NewRC;
302  else if (!NewRC || Classes[Reg] != NewRC)
303  Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
304 
305  RegRefs.insert(std::make_pair(Reg, &MO));
306 
307  // It wasn't previously live but now it is, this is a kill.
308  // Repeat for all aliases.
309  for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
310  unsigned AliasReg = *AI;
311  if (KillIndices[AliasReg] == ~0u) {
312  KillIndices[AliasReg] = Count;
313  DefIndices[AliasReg] = ~0u;
314  }
315  }
316  }
317 }
318 
319 // Check all machine operands that reference the antidependent register and must
320 // be replaced by NewReg. Return true if any of their parent instructions may
321 // clobber the new register.
322 //
323 // Note: AntiDepReg may be referenced by a two-address instruction such that
324 // it's use operand is tied to a def operand. We guard against the case in which
325 // the two-address instruction also defines NewReg, as may happen with
326 // pre/postincrement loads. In this case, both the use and def operands are in
327 // RegRefs because the def is inserted by PrescanInstruction and not erased
328 // during ScanInstruction. So checking for an instruction with definitions of
329 // both NewReg and AntiDepReg covers it.
330 bool
331 CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
332  RegRefIter RegRefEnd,
333  unsigned NewReg)
334 {
335  for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
336  MachineOperand *RefOper = I->second;
337 
338  // Don't allow the instruction defining AntiDepReg to earlyclobber its
339  // operands, in case they may be assigned to NewReg. In this case antidep
340  // breaking must fail, but it's too rare to bother optimizing.
341  if (RefOper->isDef() && RefOper->isEarlyClobber())
342  return true;
343 
344  // Handle cases in which this instruction defines NewReg.
345  MachineInstr *MI = RefOper->getParent();
346  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
347  const MachineOperand &CheckOper = MI->getOperand(i);
348 
349  if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
350  return true;
351 
352  if (!CheckOper.isReg() || !CheckOper.isDef() ||
353  CheckOper.getReg() != NewReg)
354  continue;
355 
356  // Don't allow the instruction to define NewReg and AntiDepReg.
357  // When AntiDepReg is renamed it will be an illegal op.
358  if (RefOper->isDef())
359  return true;
360 
361  // Don't allow an instruction using AntiDepReg to be earlyclobbered by
362  // NewReg.
363  if (CheckOper.isEarlyClobber())
364  return true;
365 
366  // Don't allow inline asm to define NewReg at all. Who knows what it's
367  // doing with it.
368  if (MI->isInlineAsm())
369  return true;
370  }
371  }
372  return false;
373 }
374 
375 unsigned CriticalAntiDepBreaker::
376 findSuitableFreeRegister(RegRefIter RegRefBegin,
377  RegRefIter RegRefEnd,
378  unsigned AntiDepReg,
379  unsigned LastNewReg,
380  const TargetRegisterClass *RC,
382 {
383  ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
384  for (unsigned i = 0; i != Order.size(); ++i) {
385  unsigned NewReg = Order[i];
386  // Don't replace a register with itself.
387  if (NewReg == AntiDepReg) continue;
388  // Don't replace a register with one that was recently used to repair
389  // an anti-dependence with this AntiDepReg, because that would
390  // re-introduce that anti-dependence.
391  if (NewReg == LastNewReg) continue;
392  // If any instructions that define AntiDepReg also define the NewReg, it's
393  // not suitable. For example, Instruction with multiple definitions can
394  // result in this condition.
395  if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
396  // If NewReg is dead and NewReg's most recent def is not before
397  // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
398  assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
399  && "Kill and Def maps aren't consistent for AntiDepReg!");
400  assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
401  && "Kill and Def maps aren't consistent for NewReg!");
402  if (KillIndices[NewReg] != ~0u ||
403  Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
404  KillIndices[AntiDepReg] > DefIndices[NewReg])
405  continue;
406  // If NewReg overlaps any of the forbidden registers, we can't use it.
407  bool Forbidden = false;
408  for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
409  ite = Forbid.end(); it != ite; ++it)
410  if (TRI->regsOverlap(NewReg, *it)) {
411  Forbidden = true;
412  break;
413  }
414  if (Forbidden) continue;
415  return NewReg;
416  }
417 
418  // No registers are free and available!
419  return 0;
420 }
421 
423 BreakAntiDependencies(const std::vector<SUnit>& SUnits,
426  unsigned InsertPosIndex,
427  DbgValueVector &DbgValues) {
428  // The code below assumes that there is at least one instruction,
429  // so just duck out immediately if the block is empty.
430  if (SUnits.empty()) return 0;
431 
432  // Keep a map of the MachineInstr*'s back to the SUnit representing them.
433  // This is used for updating debug information.
434  //
435  // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
437 
438  // Find the node at the bottom of the critical path.
439  const SUnit *Max = nullptr;
440  for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
441  const SUnit *SU = &SUnits[i];
442  MISUnitMap[SU->getInstr()] = SU;
443  if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
444  Max = SU;
445  }
446 
447 #ifndef NDEBUG
448  {
449  DEBUG(dbgs() << "Critical path has total latency "
450  << (Max->getDepth() + Max->Latency) << "\n");
451  DEBUG(dbgs() << "Available regs:");
452  for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
453  if (KillIndices[Reg] == ~0u)
454  DEBUG(dbgs() << " " << TRI->getName(Reg));
455  }
456  DEBUG(dbgs() << '\n');
457  }
458 #endif
459 
460  // Track progress along the critical path through the SUnit graph as we walk
461  // the instructions.
462  const SUnit *CriticalPathSU = Max;
463  MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
464 
465  // Consider this pattern:
466  // A = ...
467  // ... = A
468  // A = ...
469  // ... = A
470  // A = ...
471  // ... = A
472  // A = ...
473  // ... = A
474  // There are three anti-dependencies here, and without special care,
475  // we'd break all of them using the same register:
476  // A = ...
477  // ... = A
478  // B = ...
479  // ... = B
480  // B = ...
481  // ... = B
482  // B = ...
483  // ... = B
484  // because at each anti-dependence, B is the first register that
485  // isn't A which is free. This re-introduces anti-dependencies
486  // at all but one of the original anti-dependencies that we were
487  // trying to break. To avoid this, keep track of the most recent
488  // register that each register was replaced with, avoid
489  // using it to repair an anti-dependence on the same register.
490  // This lets us produce this:
491  // A = ...
492  // ... = A
493  // B = ...
494  // ... = B
495  // C = ...
496  // ... = C
497  // B = ...
498  // ... = B
499  // This still has an anti-dependence on B, but at least it isn't on the
500  // original critical path.
501  //
502  // TODO: If we tracked more than one register here, we could potentially
503  // fix that remaining critical edge too. This is a little more involved,
504  // because unlike the most recent register, less recent registers should
505  // still be considered, though only if no other registers are available.
506  std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
507 
508  // Attempt to break anti-dependence edges on the critical path. Walk the
509  // instructions from the bottom up, tracking information about liveness
510  // as we go to help determine which registers are available.
511  unsigned Broken = 0;
512  unsigned Count = InsertPosIndex - 1;
513  for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
514  MachineInstr &MI = *--I;
515  // Kill instructions can define registers but are really nops, and there
516  // might be a real definition earlier that needs to be paired with uses
517  // dominated by this kill.
518 
519  // FIXME: It may be possible to remove the isKill() restriction once PR18663
520  // has been properly fixed. There can be value in processing kills as seen
521  // in the AggressiveAntiDepBreaker class.
522  if (MI.isDebugValue() || MI.isKill())
523  continue;
524 
525  // Check if this instruction has a dependence on the critical path that
526  // is an anti-dependence that we may be able to break. If it is, set
527  // AntiDepReg to the non-zero register associated with the anti-dependence.
528  //
529  // We limit our attention to the critical path as a heuristic to avoid
530  // breaking anti-dependence edges that aren't going to significantly
531  // impact the overall schedule. There are a limited number of registers
532  // and we want to save them for the important edges.
533  //
534  // TODO: Instructions with multiple defs could have multiple
535  // anti-dependencies. The current code here only knows how to break one
536  // edge per instruction. Note that we'd have to be able to break all of
537  // the anti-dependencies in an instruction in order to be effective.
538  unsigned AntiDepReg = 0;
539  if (&MI == CriticalPathMI) {
540  if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
541  const SUnit *NextSU = Edge->getSUnit();
542 
543  // Only consider anti-dependence edges.
544  if (Edge->getKind() == SDep::Anti) {
545  AntiDepReg = Edge->getReg();
546  assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
547  if (!MRI.isAllocatable(AntiDepReg))
548  // Don't break anti-dependencies on non-allocatable registers.
549  AntiDepReg = 0;
550  else if (KeepRegs.test(AntiDepReg))
551  // Don't break anti-dependencies if a use down below requires
552  // this exact register.
553  AntiDepReg = 0;
554  else {
555  // If the SUnit has other dependencies on the SUnit that it
556  // anti-depends on, don't bother breaking the anti-dependency
557  // since those edges would prevent such units from being
558  // scheduled past each other regardless.
559  //
560  // Also, if there are dependencies on other SUnits with the
561  // same register as the anti-dependency, don't attempt to
562  // break it.
563  for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
564  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
565  if (P->getSUnit() == NextSU ?
566  (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
567  (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
568  AntiDepReg = 0;
569  break;
570  }
571  }
572  }
573  CriticalPathSU = NextSU;
574  CriticalPathMI = CriticalPathSU->getInstr();
575  } else {
576  // We've reached the end of the critical path.
577  CriticalPathSU = nullptr;
578  CriticalPathMI = nullptr;
579  }
580  }
581 
582  PrescanInstruction(MI);
583 
584  SmallVector<unsigned, 2> ForbidRegs;
585 
586  // If MI's defs have a special allocation requirement, don't allow
587  // any def registers to be changed. Also assume all registers
588  // defined in a call must not be changed (ABI).
589  if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI))
590  // If this instruction's defs have special allocation requirement, don't
591  // break this anti-dependency.
592  AntiDepReg = 0;
593  else if (AntiDepReg) {
594  // If this instruction has a use of AntiDepReg, breaking it
595  // is invalid. If the instruction defines other registers,
596  // save a list of them so that we don't pick a new register
597  // that overlaps any of them.
598  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
599  MachineOperand &MO = MI.getOperand(i);
600  if (!MO.isReg()) continue;
601  unsigned Reg = MO.getReg();
602  if (Reg == 0) continue;
603  if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
604  AntiDepReg = 0;
605  break;
606  }
607  if (MO.isDef() && Reg != AntiDepReg)
608  ForbidRegs.push_back(Reg);
609  }
610  }
611 
612  // Determine AntiDepReg's register class, if it is live and is
613  // consistently used within a single class.
614  const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
615  : nullptr;
616  assert((AntiDepReg == 0 || RC != nullptr) &&
617  "Register should be live if it's causing an anti-dependence!");
618  if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
619  AntiDepReg = 0;
620 
621  // Look for a suitable register to use to break the anti-dependence.
622  //
623  // TODO: Instead of picking the first free register, consider which might
624  // be the best.
625  if (AntiDepReg != 0) {
626  std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
627  std::multimap<unsigned, MachineOperand *>::iterator>
628  Range = RegRefs.equal_range(AntiDepReg);
629  if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
630  AntiDepReg,
631  LastNewReg[AntiDepReg],
632  RC, ForbidRegs)) {
633  DEBUG(dbgs() << "Breaking anti-dependence edge on "
634  << TRI->getName(AntiDepReg)
635  << " with " << RegRefs.count(AntiDepReg) << " references"
636  << " using " << TRI->getName(NewReg) << "!\n");
637 
638  // Update the references to the old register to refer to the new
639  // register.
640  for (std::multimap<unsigned, MachineOperand *>::iterator
641  Q = Range.first, QE = Range.second; Q != QE; ++Q) {
642  Q->second->setReg(NewReg);
643  // If the SU for the instruction being updated has debug information
644  // related to the anti-dependency register, make sure to update that
645  // as well.
646  const SUnit *SU = MISUnitMap[Q->second->getParent()];
647  if (!SU) continue;
648  for (DbgValueVector::iterator DVI = DbgValues.begin(),
649  DVE = DbgValues.end(); DVI != DVE; ++DVI)
650  if (DVI->second == Q->second->getParent())
651  UpdateDbgValue(*DVI->first, AntiDepReg, NewReg);
652  }
653 
654  // We just went back in time and modified history; the
655  // liveness information for the anti-dependence reg is now
656  // inconsistent. Set the state as if it were dead.
657  Classes[NewReg] = Classes[AntiDepReg];
658  DefIndices[NewReg] = DefIndices[AntiDepReg];
659  KillIndices[NewReg] = KillIndices[AntiDepReg];
660  assert(((KillIndices[NewReg] == ~0u) !=
661  (DefIndices[NewReg] == ~0u)) &&
662  "Kill and Def maps aren't consistent for NewReg!");
663 
664  Classes[AntiDepReg] = nullptr;
665  DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
666  KillIndices[AntiDepReg] = ~0u;
667  assert(((KillIndices[AntiDepReg] == ~0u) !=
668  (DefIndices[AntiDepReg] == ~0u)) &&
669  "Kill and Def maps aren't consistent for AntiDepReg!");
670 
671  RegRefs.erase(AntiDepReg);
672  LastNewReg[AntiDepReg] = NewReg;
673  ++Broken;
674  }
675  }
676 
677  ScanInstruction(MI, Count);
678  }
679 
680  return Broken;
681 }
void push_back(const T &Elt)
Definition: SmallVector.h:211
BitVector & set()
Definition: BitVector.h:219
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
BitVector getPristineRegs(const MachineFunction &MF) const
Return a set of physical registers that are pristine.
size_t i
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
void FinishBlock() override
Finish anti-dep breaking for a basic block.
MachineInstr * getInstr() const
getInstr - Return the representative MachineInstr for this SUnit.
Definition: ScheduleDAG.h:389
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:270
SmallVector< SDep, 4 > Preds
Definition: ScheduleDAG.h:258
A register anti-dependedence (aka WAR).
Definition: ScheduleDAG.h:50
MCSuperRegIterator enumerates all super-registers of Reg.
const HexagonInstrInfo * TII
This class works in conjunction with the post-RA scheduler to rename registers to break register anti...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Regular data dependence (aka true-dependence).
Definition: ScheduleDAG.h:49
std::vector< MachineBasicBlock * >::iterator succ_iterator
Reg
All possible values of the reg field in the ModR/M byte.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:277
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
bool hasExtraSrcRegAllocReq(QueryType Type=AnyInBundle) const
Returns true if this instruction source operands have special register allocation requirements that a...
Definition: MachineInstr.h:702
Function Alias Analysis false
virtual const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const =0
Return a null-terminated list of all of the callee-saved registers on this target.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:141
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
bool isDebugValue() const
Definition: MachineInstr.h:777
SDep - Scheduling dependency.
Definition: ScheduleDAG.h:45
bool isEarlyClobber() const
#define P(N)
unsigned const MachineRegisterInfo * MRI
unsigned short Latency
Definition: ScheduleDAG.h:275
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:279
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
MCRegAliasIterator enumerates all registers aliasing Reg.
BitVector & reset()
Definition: BitVector.h:260
static const unsigned End
void StartBlock(MachineBasicBlock *BB) override
Initialize anti-dep breaking for a new basic block.
CriticalAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &)
unsigned BreakAntiDependencies(const std::vector< SUnit > &SUnits, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned InsertPosIndex, DbgValueVector &DbgValues) override
Identifiy anti-dependencies along the critical path of the ScheduleDAG and break them by renaming reg...
MCSubRegIterator enumerates all sub-registers of Reg.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction. ...
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineOperand class - Representation of each machine instruction operand.
bool test(unsigned Idx) const
Definition: BitVector.h:323
bool isInlineAsm() const
Definition: MachineInstr.h:789
bool hasExtraDefRegAllocReq(QueryType Type=AnyInBundle) const
Returns true if this instruction def operands have special register allocation requirements that are ...
Definition: MachineInstr.h:712
void UpdateDbgValue(MachineInstr &MI, unsigned OldReg, unsigned NewReg)
Update DBG_VALUE if dependency breaker is updating other machine instruction to use NewReg...
bool isKill() const
Definition: MachineInstr.h:787
bool isAllocatable(unsigned PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
unsigned getDepth() const
getDepth - Return the depth of this node, which is the length of the maximum path up to any node whic...
Definition: ScheduleDAG.h:417
void Observe(MachineInstr &MI, unsigned Count, unsigned InsertPosIndex) override
Update liveness information to account for the current instruction, which will not be scheduled...
Representation of each machine instruction.
Definition: MachineInstr.h:52
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
#define I(x, y, z)
Definition: MD5.cpp:54
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:424
static const SDep * CriticalPathStep(const SUnit *SU)
CriticalPathStep - Return the next SUnit after SU on the bottom-up critical path. ...
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
std::vector< std::pair< MachineInstr *, MachineInstr * > > DbgValueVector
#define DEBUG(X)
Definition: Debug.h:100
IRTranslator LLVM IR MI
const TargetRegisterClass * getRegClass(const MCInstrDesc &TID, unsigned OpNum, const TargetRegisterInfo *TRI, const MachineFunction &MF) const
Given a machine instruction descriptor, returns the register class constraint for OpNum...
SUnit - Scheduling unit. This is a node in the scheduling DAG.
Definition: ScheduleDAG.h:244