RenameIndependentSubregs.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. //===-- RenameIndependentSubregs.cpp - Live Interval Analysis -------------===//
  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. /// Rename independent subregisters looks for virtual registers with
  10. /// independently used subregisters and renames them to new virtual registers.
  11. /// Example: In the following:
  12. /// %0:sub0<read-undef> = ...
  13. /// %0:sub1 = ...
  14. /// use %0:sub0
  15. /// %0:sub0 = ...
  16. /// use %0:sub0
  17. /// use %0:sub1
  18. /// sub0 and sub1 are never used together, and we have two independent sub0
  19. /// definitions. This pass will rename to:
  20. /// %0:sub0<read-undef> = ...
  21. /// %1:sub1<read-undef> = ...
  22. /// use %1:sub1
  23. /// %2:sub1<read-undef> = ...
  24. /// use %2:sub1
  25. /// use %0:sub0
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #include "LiveRangeUtils.h"
  29. #include "PHIEliminationUtils.h"
  30. #include "llvm/CodeGen/LiveInterval.h"
  31. #include "llvm/CodeGen/LiveIntervals.h"
  32. #include "llvm/CodeGen/MachineFunctionPass.h"
  33. #include "llvm/CodeGen/MachineInstrBuilder.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/Passes.h"
  36. #include "llvm/CodeGen/TargetInstrInfo.h"
  37. using namespace llvm;
  38. #define DEBUG_TYPE "rename-independent-subregs"
  39. namespace {
  40. class RenameIndependentSubregs : public MachineFunctionPass {
  41. public:
  42. static char ID;
  43. RenameIndependentSubregs() : MachineFunctionPass(ID) {}
  44. StringRef getPassName() const override {
  45. return "Rename Disconnected Subregister Components";
  46. }
  47. void getAnalysisUsage(AnalysisUsage &AU) const override {
  48. AU.setPreservesCFG();
  49. AU.addRequired<LiveIntervals>();
  50. AU.addPreserved<LiveIntervals>();
  51. AU.addRequired<SlotIndexes>();
  52. AU.addPreserved<SlotIndexes>();
  53. MachineFunctionPass::getAnalysisUsage(AU);
  54. }
  55. bool runOnMachineFunction(MachineFunction &MF) override;
  56. private:
  57. struct SubRangeInfo {
  58. ConnectedVNInfoEqClasses ConEQ;
  59. LiveInterval::SubRange *SR;
  60. unsigned Index;
  61. SubRangeInfo(LiveIntervals &LIS, LiveInterval::SubRange &SR,
  62. unsigned Index)
  63. : ConEQ(LIS), SR(&SR), Index(Index) {}
  64. };
  65. /// Split unrelated subregister components and rename them to new vregs.
  66. bool renameComponents(LiveInterval &LI) const;
  67. /// Build a vector of SubRange infos and a union find set of
  68. /// equivalence classes.
  69. /// Returns true if more than 1 equivalence class was found.
  70. bool findComponents(IntEqClasses &Classes,
  71. SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
  72. LiveInterval &LI) const;
  73. /// Distribute the LiveInterval segments into the new LiveIntervals
  74. /// belonging to their class.
  75. void distribute(const IntEqClasses &Classes,
  76. const SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
  77. const SmallVectorImpl<LiveInterval*> &Intervals) const;
  78. /// Constructs main liverange and add missing undef+dead flags.
  79. void computeMainRangesFixFlags(const IntEqClasses &Classes,
  80. const SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
  81. const SmallVectorImpl<LiveInterval*> &Intervals) const;
  82. /// Rewrite Machine Operands to use the new vreg belonging to their class.
  83. void rewriteOperands(const IntEqClasses &Classes,
  84. const SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
  85. const SmallVectorImpl<LiveInterval*> &Intervals) const;
  86. LiveIntervals *LIS;
  87. MachineRegisterInfo *MRI;
  88. const TargetInstrInfo *TII;
  89. };
  90. } // end anonymous namespace
  91. char RenameIndependentSubregs::ID;
  92. char &llvm::RenameIndependentSubregsID = RenameIndependentSubregs::ID;
  93. INITIALIZE_PASS_BEGIN(RenameIndependentSubregs, DEBUG_TYPE,
  94. "Rename Independent Subregisters", false, false)
  95. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  96. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  97. INITIALIZE_PASS_END(RenameIndependentSubregs, DEBUG_TYPE,
  98. "Rename Independent Subregisters", false, false)
  99. bool RenameIndependentSubregs::renameComponents(LiveInterval &LI) const {
  100. // Shortcut: We cannot have split components with a single definition.
  101. if (LI.valnos.size() < 2)
  102. return false;
  103. SmallVector<SubRangeInfo, 4> SubRangeInfos;
  104. IntEqClasses Classes;
  105. if (!findComponents(Classes, SubRangeInfos, LI))
  106. return false;
  107. // Create a new VReg for each class.
  108. unsigned Reg = LI.reg;
  109. const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
  110. SmallVector<LiveInterval*, 4> Intervals;
  111. Intervals.push_back(&LI);
  112. LLVM_DEBUG(dbgs() << printReg(Reg) << ": Found " << Classes.getNumClasses()
  113. << " equivalence classes.\n");
  114. LLVM_DEBUG(dbgs() << printReg(Reg) << ": Splitting into newly created:");
  115. for (unsigned I = 1, NumClasses = Classes.getNumClasses(); I < NumClasses;
  116. ++I) {
  117. Register NewVReg = MRI->createVirtualRegister(RegClass);
  118. LiveInterval &NewLI = LIS->createEmptyInterval(NewVReg);
  119. Intervals.push_back(&NewLI);
  120. LLVM_DEBUG(dbgs() << ' ' << printReg(NewVReg));
  121. }
  122. LLVM_DEBUG(dbgs() << '\n');
  123. rewriteOperands(Classes, SubRangeInfos, Intervals);
  124. distribute(Classes, SubRangeInfos, Intervals);
  125. computeMainRangesFixFlags(Classes, SubRangeInfos, Intervals);
  126. return true;
  127. }
  128. bool RenameIndependentSubregs::findComponents(IntEqClasses &Classes,
  129. SmallVectorImpl<RenameIndependentSubregs::SubRangeInfo> &SubRangeInfos,
  130. LiveInterval &LI) const {
  131. // First step: Create connected components for the VNInfos inside the
  132. // subranges and count the global number of such components.
  133. unsigned NumComponents = 0;
  134. for (LiveInterval::SubRange &SR : LI.subranges()) {
  135. SubRangeInfos.push_back(SubRangeInfo(*LIS, SR, NumComponents));
  136. ConnectedVNInfoEqClasses &ConEQ = SubRangeInfos.back().ConEQ;
  137. unsigned NumSubComponents = ConEQ.Classify(SR);
  138. NumComponents += NumSubComponents;
  139. }
  140. // Shortcut: With only 1 subrange, the normal separate component tests are
  141. // enough and we do not need to perform the union-find on the subregister
  142. // segments.
  143. if (SubRangeInfos.size() < 2)
  144. return false;
  145. // Next step: Build union-find structure over all subranges and merge classes
  146. // across subranges when they are affected by the same MachineOperand.
  147. const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
  148. Classes.grow(NumComponents);
  149. unsigned Reg = LI.reg;
  150. for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
  151. if (!MO.isDef() && !MO.readsReg())
  152. continue;
  153. unsigned SubRegIdx = MO.getSubReg();
  154. LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubRegIdx);
  155. unsigned MergedID = ~0u;
  156. for (RenameIndependentSubregs::SubRangeInfo &SRInfo : SubRangeInfos) {
  157. const LiveInterval::SubRange &SR = *SRInfo.SR;
  158. if ((SR.LaneMask & LaneMask).none())
  159. continue;
  160. SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
  161. Pos = MO.isDef() ? Pos.getRegSlot(MO.isEarlyClobber())
  162. : Pos.getBaseIndex();
  163. const VNInfo *VNI = SR.getVNInfoAt(Pos);
  164. if (VNI == nullptr)
  165. continue;
  166. // Map to local representant ID.
  167. unsigned LocalID = SRInfo.ConEQ.getEqClass(VNI);
  168. // Global ID
  169. unsigned ID = LocalID + SRInfo.Index;
  170. // Merge other sets
  171. MergedID = MergedID == ~0u ? ID : Classes.join(MergedID, ID);
  172. }
  173. }
  174. // Early exit if we ended up with a single equivalence class.
  175. Classes.compress();
  176. unsigned NumClasses = Classes.getNumClasses();
  177. return NumClasses > 1;
  178. }
  179. void RenameIndependentSubregs::rewriteOperands(const IntEqClasses &Classes,
  180. const SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
  181. const SmallVectorImpl<LiveInterval*> &Intervals) const {
  182. const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
  183. unsigned Reg = Intervals[0]->reg;
  184. for (MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(Reg),
  185. E = MRI->reg_nodbg_end(); I != E; ) {
  186. MachineOperand &MO = *I++;
  187. if (!MO.isDef() && !MO.readsReg())
  188. continue;
  189. auto *MI = MO.getParent();
  190. SlotIndex Pos = LIS->getInstructionIndex(*MI);
  191. Pos = MO.isDef() ? Pos.getRegSlot(MO.isEarlyClobber())
  192. : Pos.getBaseIndex();
  193. unsigned SubRegIdx = MO.getSubReg();
  194. LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubRegIdx);
  195. unsigned ID = ~0u;
  196. for (const SubRangeInfo &SRInfo : SubRangeInfos) {
  197. const LiveInterval::SubRange &SR = *SRInfo.SR;
  198. if ((SR.LaneMask & LaneMask).none())
  199. continue;
  200. const VNInfo *VNI = SR.getVNInfoAt(Pos);
  201. if (VNI == nullptr)
  202. continue;
  203. // Map to local representant ID.
  204. unsigned LocalID = SRInfo.ConEQ.getEqClass(VNI);
  205. // Global ID
  206. ID = Classes[LocalID + SRInfo.Index];
  207. break;
  208. }
  209. unsigned VReg = Intervals[ID]->reg;
  210. MO.setReg(VReg);
  211. if (MO.isTied() && Reg != VReg) {
  212. /// Undef use operands are not tracked in the equivalence class,
  213. /// but need to be updated if they are tied; take care to only
  214. /// update the tied operand.
  215. unsigned OperandNo = MI->getOperandNo(&MO);
  216. unsigned TiedIdx = MI->findTiedOperandIdx(OperandNo);
  217. MI->getOperand(TiedIdx).setReg(VReg);
  218. // above substitution breaks the iterator, so restart.
  219. I = MRI->reg_nodbg_begin(Reg);
  220. }
  221. }
  222. // TODO: We could attempt to recompute new register classes while visiting
  223. // the operands: Some of the split register may be fine with less constraint
  224. // classes than the original vreg.
  225. }
  226. void RenameIndependentSubregs::distribute(const IntEqClasses &Classes,
  227. const SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
  228. const SmallVectorImpl<LiveInterval*> &Intervals) const {
  229. unsigned NumClasses = Classes.getNumClasses();
  230. SmallVector<unsigned, 8> VNIMapping;
  231. SmallVector<LiveInterval::SubRange*, 8> SubRanges;
  232. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  233. for (const SubRangeInfo &SRInfo : SubRangeInfos) {
  234. LiveInterval::SubRange &SR = *SRInfo.SR;
  235. unsigned NumValNos = SR.valnos.size();
  236. VNIMapping.clear();
  237. VNIMapping.reserve(NumValNos);
  238. SubRanges.clear();
  239. SubRanges.resize(NumClasses-1, nullptr);
  240. for (unsigned I = 0; I < NumValNos; ++I) {
  241. const VNInfo &VNI = *SR.valnos[I];
  242. unsigned LocalID = SRInfo.ConEQ.getEqClass(&VNI);
  243. unsigned ID = Classes[LocalID + SRInfo.Index];
  244. VNIMapping.push_back(ID);
  245. if (ID > 0 && SubRanges[ID-1] == nullptr)
  246. SubRanges[ID-1] = Intervals[ID]->createSubRange(Allocator, SR.LaneMask);
  247. }
  248. DistributeRange(SR, SubRanges.data(), VNIMapping);
  249. }
  250. }
  251. static bool subRangeLiveAt(const LiveInterval &LI, SlotIndex Pos) {
  252. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  253. if (SR.liveAt(Pos))
  254. return true;
  255. }
  256. return false;
  257. }
  258. void RenameIndependentSubregs::computeMainRangesFixFlags(
  259. const IntEqClasses &Classes,
  260. const SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
  261. const SmallVectorImpl<LiveInterval*> &Intervals) const {
  262. BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  263. const SlotIndexes &Indexes = *LIS->getSlotIndexes();
  264. for (size_t I = 0, E = Intervals.size(); I < E; ++I) {
  265. LiveInterval &LI = *Intervals[I];
  266. unsigned Reg = LI.reg;
  267. LI.removeEmptySubRanges();
  268. // There must be a def (or live-in) before every use. Splitting vregs may
  269. // violate this principle as the splitted vreg may not have a definition on
  270. // every path. Fix this by creating IMPLICIT_DEF instruction as necessary.
  271. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  272. // Search for "PHI" value numbers in the subranges. We must find a live
  273. // value in each predecessor block, add an IMPLICIT_DEF where it is
  274. // missing.
  275. for (unsigned I = 0; I < SR.valnos.size(); ++I) {
  276. const VNInfo &VNI = *SR.valnos[I];
  277. if (VNI.isUnused() || !VNI.isPHIDef())
  278. continue;
  279. SlotIndex Def = VNI.def;
  280. MachineBasicBlock &MBB = *Indexes.getMBBFromIndex(Def);
  281. for (MachineBasicBlock *PredMBB : MBB.predecessors()) {
  282. SlotIndex PredEnd = Indexes.getMBBEndIdx(PredMBB);
  283. if (subRangeLiveAt(LI, PredEnd.getPrevSlot()))
  284. continue;
  285. MachineBasicBlock::iterator InsertPos =
  286. llvm::findPHICopyInsertPoint(PredMBB, &MBB, Reg);
  287. const MCInstrDesc &MCDesc = TII->get(TargetOpcode::IMPLICIT_DEF);
  288. MachineInstrBuilder ImpDef = BuildMI(*PredMBB, InsertPos,
  289. DebugLoc(), MCDesc, Reg);
  290. SlotIndex DefIdx = LIS->InsertMachineInstrInMaps(*ImpDef);
  291. SlotIndex RegDefIdx = DefIdx.getRegSlot();
  292. for (LiveInterval::SubRange &SR : LI.subranges()) {
  293. VNInfo *SRVNI = SR.getNextValue(RegDefIdx, Allocator);
  294. SR.addSegment(LiveRange::Segment(RegDefIdx, PredEnd, SRVNI));
  295. }
  296. }
  297. }
  298. }
  299. for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
  300. if (!MO.isDef())
  301. continue;
  302. unsigned SubRegIdx = MO.getSubReg();
  303. if (SubRegIdx == 0)
  304. continue;
  305. // After assigning the new vreg we may not have any other sublanes living
  306. // in and out of the instruction anymore. We need to add new dead and
  307. // undef flags in these cases.
  308. if (!MO.isUndef()) {
  309. SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
  310. if (!subRangeLiveAt(LI, Pos))
  311. MO.setIsUndef();
  312. }
  313. if (!MO.isDead()) {
  314. SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent()).getDeadSlot();
  315. if (!subRangeLiveAt(LI, Pos))
  316. MO.setIsDead();
  317. }
  318. }
  319. if (I == 0)
  320. LI.clear();
  321. LIS->constructMainRangeFromSubranges(LI);
  322. // A def of a subregister may be a use of other register lanes. Replacing
  323. // such a def with a def of a different register will eliminate the use,
  324. // and may cause the recorded live range to be larger than the actual
  325. // liveness in the program IR.
  326. LIS->shrinkToUses(&LI);
  327. }
  328. }
  329. bool RenameIndependentSubregs::runOnMachineFunction(MachineFunction &MF) {
  330. // Skip renaming if liveness of subregister is not tracked.
  331. MRI = &MF.getRegInfo();
  332. if (!MRI->subRegLivenessEnabled())
  333. return false;
  334. LLVM_DEBUG(dbgs() << "Renaming independent subregister live ranges in "
  335. << MF.getName() << '\n');
  336. LIS = &getAnalysis<LiveIntervals>();
  337. TII = MF.getSubtarget().getInstrInfo();
  338. // Iterate over all vregs. Note that we query getNumVirtRegs() the newly
  339. // created vregs end up with higher numbers but do not need to be visited as
  340. // there can't be any further splitting.
  341. bool Changed = false;
  342. for (size_t I = 0, E = MRI->getNumVirtRegs(); I < E; ++I) {
  343. unsigned Reg = Register::index2VirtReg(I);
  344. if (!LIS->hasInterval(Reg))
  345. continue;
  346. LiveInterval &LI = LIS->getInterval(Reg);
  347. if (!LI.hasSubRanges())
  348. continue;
  349. Changed |= renameComponents(LI);
  350. }
  351. return Changed;
  352. }