CriticalAntiDepBreaker.cpp 27 KB

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