CriticalAntiDepBreaker.cpp 28 KB

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