CriticalAntiDepBreaker.cpp 27 KB

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