Localizer.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. //===- Localizer.cpp ---------------------- Localize some instrs -*- C++ -*-==//
  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. /// \file
  9. /// This file implements the Localizer class.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/CodeGen/GlobalISel/Localizer.h"
  12. #include "llvm/ADT/DenseMap.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/Analysis/TargetTransformInfo.h"
  15. #include "llvm/CodeGen/MachineRegisterInfo.h"
  16. #include "llvm/CodeGen/TargetLowering.h"
  17. #include "llvm/InitializePasses.h"
  18. #include "llvm/Support/Debug.h"
  19. #define DEBUG_TYPE "localizer"
  20. using namespace llvm;
  21. char Localizer::ID = 0;
  22. INITIALIZE_PASS_BEGIN(Localizer, DEBUG_TYPE,
  23. "Move/duplicate certain instructions close to their use",
  24. false, false)
  25. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  26. INITIALIZE_PASS_END(Localizer, DEBUG_TYPE,
  27. "Move/duplicate certain instructions close to their use",
  28. false, false)
  29. Localizer::Localizer(std::function<bool(const MachineFunction &)> F)
  30. : MachineFunctionPass(ID), DoNotRunPass(F) {}
  31. Localizer::Localizer()
  32. : Localizer([](const MachineFunction &) { return false; }) {}
  33. void Localizer::init(MachineFunction &MF) {
  34. MRI = &MF.getRegInfo();
  35. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(MF.getFunction());
  36. }
  37. void Localizer::getAnalysisUsage(AnalysisUsage &AU) const {
  38. AU.addRequired<TargetTransformInfoWrapperPass>();
  39. getSelectionDAGFallbackAnalysisUsage(AU);
  40. MachineFunctionPass::getAnalysisUsage(AU);
  41. }
  42. bool Localizer::isLocalUse(MachineOperand &MOUse, const MachineInstr &Def,
  43. MachineBasicBlock *&InsertMBB) {
  44. MachineInstr &MIUse = *MOUse.getParent();
  45. InsertMBB = MIUse.getParent();
  46. if (MIUse.isPHI())
  47. InsertMBB = MIUse.getOperand(MIUse.getOperandNo(&MOUse) + 1).getMBB();
  48. return InsertMBB == Def.getParent();
  49. }
  50. bool Localizer::isNonUniquePhiValue(MachineOperand &Op) const {
  51. MachineInstr *MI = Op.getParent();
  52. if (!MI->isPHI())
  53. return false;
  54. Register SrcReg = Op.getReg();
  55. for (unsigned Idx = 1; Idx < MI->getNumOperands(); Idx += 2) {
  56. auto &MO = MI->getOperand(Idx);
  57. if (&MO != &Op && MO.isReg() && MO.getReg() == SrcReg)
  58. return true;
  59. }
  60. return false;
  61. }
  62. bool Localizer::localizeInterBlock(MachineFunction &MF,
  63. LocalizedSetVecT &LocalizedInstrs) {
  64. bool Changed = false;
  65. DenseMap<std::pair<MachineBasicBlock *, unsigned>, unsigned> MBBWithLocalDef;
  66. // Since the IRTranslator only emits constants into the entry block, and the
  67. // rest of the GISel pipeline generally emits constants close to their users,
  68. // we only localize instructions in the entry block here. This might change if
  69. // we start doing CSE across blocks.
  70. auto &MBB = MF.front();
  71. auto &TL = *MF.getSubtarget().getTargetLowering();
  72. for (MachineInstr &MI : llvm::reverse(MBB)) {
  73. if (!TL.shouldLocalize(MI, TTI))
  74. continue;
  75. LLVM_DEBUG(dbgs() << "Should localize: " << MI);
  76. assert(MI.getDesc().getNumDefs() == 1 &&
  77. "More than one definition not supported yet");
  78. Register Reg = MI.getOperand(0).getReg();
  79. // Check if all the users of MI are local.
  80. // We are going to invalidation the list of use operands, so we
  81. // can't use range iterator.
  82. for (MachineOperand &MOUse :
  83. llvm::make_early_inc_range(MRI->use_operands(Reg))) {
  84. // Check if the use is already local.
  85. MachineBasicBlock *InsertMBB;
  86. LLVM_DEBUG(MachineInstr &MIUse = *MOUse.getParent();
  87. dbgs() << "Checking use: " << MIUse
  88. << " #Opd: " << MIUse.getOperandNo(&MOUse) << '\n');
  89. if (isLocalUse(MOUse, MI, InsertMBB)) {
  90. // Even if we're in the same block, if the block is very large we could
  91. // still have many long live ranges. Try to do intra-block localization
  92. // too.
  93. LocalizedInstrs.insert(&MI);
  94. continue;
  95. }
  96. // If the use is a phi operand that's not unique, don't try to localize.
  97. // If we do, we can cause unnecessary instruction bloat by duplicating
  98. // into each predecessor block, when the existing one is sufficient and
  99. // allows for easier optimization later.
  100. if (isNonUniquePhiValue(MOUse))
  101. continue;
  102. LLVM_DEBUG(dbgs() << "Fixing non-local use\n");
  103. Changed = true;
  104. auto MBBAndReg = std::make_pair(InsertMBB, Reg);
  105. auto NewVRegIt = MBBWithLocalDef.find(MBBAndReg);
  106. if (NewVRegIt == MBBWithLocalDef.end()) {
  107. // Create the localized instruction.
  108. MachineInstr *LocalizedMI = MF.CloneMachineInstr(&MI);
  109. LocalizedInstrs.insert(LocalizedMI);
  110. MachineInstr &UseMI = *MOUse.getParent();
  111. if (MRI->hasOneUse(Reg) && !UseMI.isPHI())
  112. InsertMBB->insert(UseMI, LocalizedMI);
  113. else
  114. InsertMBB->insert(InsertMBB->SkipPHIsAndLabels(InsertMBB->begin()),
  115. LocalizedMI);
  116. // Set a new register for the definition.
  117. Register NewReg = MRI->cloneVirtualRegister(Reg);
  118. LocalizedMI->getOperand(0).setReg(NewReg);
  119. NewVRegIt =
  120. MBBWithLocalDef.insert(std::make_pair(MBBAndReg, NewReg)).first;
  121. LLVM_DEBUG(dbgs() << "Inserted: " << *LocalizedMI);
  122. }
  123. LLVM_DEBUG(dbgs() << "Update use with: " << printReg(NewVRegIt->second)
  124. << '\n');
  125. // Update the user reg.
  126. MOUse.setReg(NewVRegIt->second);
  127. }
  128. }
  129. return Changed;
  130. }
  131. bool Localizer::localizeIntraBlock(LocalizedSetVecT &LocalizedInstrs) {
  132. bool Changed = false;
  133. // For each already-localized instruction which has multiple users, then we
  134. // scan the block top down from the current position until we hit one of them.
  135. // FIXME: Consider doing inst duplication if live ranges are very long due to
  136. // many users, but this case may be better served by regalloc improvements.
  137. for (MachineInstr *MI : LocalizedInstrs) {
  138. Register Reg = MI->getOperand(0).getReg();
  139. MachineBasicBlock &MBB = *MI->getParent();
  140. // All of the user MIs of this reg.
  141. SmallPtrSet<MachineInstr *, 32> Users;
  142. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
  143. if (!UseMI.isPHI())
  144. Users.insert(&UseMI);
  145. }
  146. // If all the users were PHIs then they're not going to be in our block,
  147. // don't try to move this instruction.
  148. if (Users.empty())
  149. continue;
  150. MachineBasicBlock::iterator II(MI);
  151. ++II;
  152. while (II != MBB.end() && !Users.count(&*II))
  153. ++II;
  154. assert(II != MBB.end() && "Didn't find the user in the MBB");
  155. LLVM_DEBUG(dbgs() << "Intra-block: moving " << *MI << " before " << *II
  156. << '\n');
  157. MI->removeFromParent();
  158. MBB.insert(II, MI);
  159. Changed = true;
  160. }
  161. return Changed;
  162. }
  163. bool Localizer::runOnMachineFunction(MachineFunction &MF) {
  164. // If the ISel pipeline failed, do not bother running that pass.
  165. if (MF.getProperties().hasProperty(
  166. MachineFunctionProperties::Property::FailedISel))
  167. return false;
  168. // Don't run the pass if the target asked so.
  169. if (DoNotRunPass(MF))
  170. return false;
  171. LLVM_DEBUG(dbgs() << "Localize instructions for: " << MF.getName() << '\n');
  172. init(MF);
  173. // Keep track of the instructions we localized. We'll do a second pass of
  174. // intra-block localization to further reduce live ranges.
  175. LocalizedSetVecT LocalizedInstrs;
  176. bool Changed = localizeInterBlock(MF, LocalizedInstrs);
  177. Changed |= localizeIntraBlock(LocalizedInstrs);
  178. return Changed;
  179. }