InstructionSelect.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. //===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==//
  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 InstructionSelect class.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
  12. #include "llvm/ADT/PostOrderIterator.h"
  13. #include "llvm/ADT/ScopeExit.h"
  14. #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
  15. #include "llvm/Analysis/ProfileSummaryInfo.h"
  16. #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
  17. #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
  18. #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
  19. #include "llvm/CodeGen/GlobalISel/Utils.h"
  20. #include "llvm/CodeGen/MachineFrameInfo.h"
  21. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/CodeGen/TargetLowering.h"
  24. #include "llvm/CodeGen/TargetPassConfig.h"
  25. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  26. #include "llvm/Config/config.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/MC/TargetRegistry.h"
  29. #include "llvm/Support/CodeGenCoverage.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #define DEBUG_TYPE "instruction-select"
  34. using namespace llvm;
  35. #ifdef LLVM_GISEL_COV_PREFIX
  36. static cl::opt<std::string>
  37. CoveragePrefix("gisel-coverage-prefix", cl::init(LLVM_GISEL_COV_PREFIX),
  38. cl::desc("Record GlobalISel rule coverage files of this "
  39. "prefix if instrumentation was generated"));
  40. #else
  41. static const std::string CoveragePrefix;
  42. #endif
  43. char InstructionSelect::ID = 0;
  44. INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE,
  45. "Select target instructions out of generic instructions",
  46. false, false)
  47. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  48. INITIALIZE_PASS_DEPENDENCY(GISelKnownBitsAnalysis)
  49. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  50. INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
  51. INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE,
  52. "Select target instructions out of generic instructions",
  53. false, false)
  54. InstructionSelect::InstructionSelect(CodeGenOpt::Level OL)
  55. : MachineFunctionPass(ID), OptLevel(OL) {}
  56. // In order not to crash when calling getAnalysis during testing with -run-pass
  57. // we use the default opt level here instead of None, so that the addRequired()
  58. // calls are made in getAnalysisUsage().
  59. InstructionSelect::InstructionSelect()
  60. : MachineFunctionPass(ID), OptLevel(CodeGenOpt::Default) {}
  61. void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const {
  62. AU.addRequired<TargetPassConfig>();
  63. AU.addRequired<GISelKnownBitsAnalysis>();
  64. AU.addPreserved<GISelKnownBitsAnalysis>();
  65. if (OptLevel != CodeGenOpt::None) {
  66. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  67. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  68. }
  69. getSelectionDAGFallbackAnalysisUsage(AU);
  70. MachineFunctionPass::getAnalysisUsage(AU);
  71. }
  72. bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) {
  73. // If the ISel pipeline failed, do not bother running that pass.
  74. if (MF.getProperties().hasProperty(
  75. MachineFunctionProperties::Property::FailedISel))
  76. return false;
  77. LLVM_DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n');
  78. const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
  79. InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector();
  80. CodeGenOpt::Level OldOptLevel = OptLevel;
  81. auto RestoreOptLevel = make_scope_exit([=]() { OptLevel = OldOptLevel; });
  82. OptLevel = MF.getFunction().hasOptNone() ? CodeGenOpt::None
  83. : MF.getTarget().getOptLevel();
  84. GISelKnownBits *KB = &getAnalysis<GISelKnownBitsAnalysis>().get(MF);
  85. if (OptLevel != CodeGenOpt::None) {
  86. PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  87. if (PSI && PSI->hasProfileSummary())
  88. BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
  89. }
  90. CodeGenCoverage CoverageInfo;
  91. assert(ISel && "Cannot work without InstructionSelector");
  92. ISel->setupMF(MF, KB, CoverageInfo, PSI, BFI);
  93. // An optimization remark emitter. Used to report failures.
  94. MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr);
  95. // FIXME: There are many other MF/MFI fields we need to initialize.
  96. MachineRegisterInfo &MRI = MF.getRegInfo();
  97. #ifndef NDEBUG
  98. // Check that our input is fully legal: we require the function to have the
  99. // Legalized property, so it should be.
  100. // FIXME: This should be in the MachineVerifier, as the RegBankSelected
  101. // property check already is.
  102. if (!DisableGISelLegalityCheck)
  103. if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
  104. reportGISelFailure(MF, TPC, MORE, "gisel-select",
  105. "instruction is not legal", *MI);
  106. return false;
  107. }
  108. // FIXME: We could introduce new blocks and will need to fix the outer loop.
  109. // Until then, keep track of the number of blocks to assert that we don't.
  110. const size_t NumBlocks = MF.size();
  111. #endif
  112. // Keep track of selected blocks, so we can delete unreachable ones later.
  113. DenseSet<MachineBasicBlock *> SelectedBlocks;
  114. for (MachineBasicBlock *MBB : post_order(&MF)) {
  115. ISel->CurMBB = MBB;
  116. SelectedBlocks.insert(MBB);
  117. if (MBB->empty())
  118. continue;
  119. // Select instructions in reverse block order. We permit erasing so have
  120. // to resort to manually iterating and recognizing the begin (rend) case.
  121. bool ReachedBegin = false;
  122. for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
  123. !ReachedBegin;) {
  124. #ifndef NDEBUG
  125. // Keep track of the insertion range for debug printing.
  126. const auto AfterIt = std::next(MII);
  127. #endif
  128. // Select this instruction.
  129. MachineInstr &MI = *MII;
  130. // And have our iterator point to the next instruction, if there is one.
  131. if (MII == Begin)
  132. ReachedBegin = true;
  133. else
  134. --MII;
  135. LLVM_DEBUG(dbgs() << "Selecting: \n " << MI);
  136. // We could have folded this instruction away already, making it dead.
  137. // If so, erase it.
  138. if (isTriviallyDead(MI, MRI)) {
  139. LLVM_DEBUG(dbgs() << "Is dead; erasing.\n");
  140. salvageDebugInfo(MRI, MI);
  141. MI.eraseFromParent();
  142. continue;
  143. }
  144. // Eliminate hints.
  145. if (isPreISelGenericOptimizationHint(MI.getOpcode())) {
  146. Register DstReg = MI.getOperand(0).getReg();
  147. Register SrcReg = MI.getOperand(1).getReg();
  148. // At this point, the destination register class of the hint may have
  149. // been decided.
  150. //
  151. // Propagate that through to the source register.
  152. const TargetRegisterClass *DstRC = MRI.getRegClassOrNull(DstReg);
  153. if (DstRC)
  154. MRI.setRegClass(SrcReg, DstRC);
  155. assert(canReplaceReg(DstReg, SrcReg, MRI) &&
  156. "Must be able to replace dst with src!");
  157. MI.eraseFromParent();
  158. MRI.replaceRegWith(DstReg, SrcReg);
  159. continue;
  160. }
  161. if (MI.getOpcode() == TargetOpcode::G_INVOKE_REGION_START) {
  162. MI.eraseFromParent();
  163. continue;
  164. }
  165. if (!ISel->select(MI)) {
  166. // FIXME: It would be nice to dump all inserted instructions. It's
  167. // not obvious how, esp. considering select() can insert after MI.
  168. reportGISelFailure(MF, TPC, MORE, "gisel-select", "cannot select", MI);
  169. return false;
  170. }
  171. // Dump the range of instructions that MI expanded into.
  172. LLVM_DEBUG({
  173. auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII);
  174. dbgs() << "Into:\n";
  175. for (auto &InsertedMI : make_range(InsertedBegin, AfterIt))
  176. dbgs() << " " << InsertedMI;
  177. dbgs() << '\n';
  178. });
  179. }
  180. }
  181. for (MachineBasicBlock &MBB : MF) {
  182. if (MBB.empty())
  183. continue;
  184. if (!SelectedBlocks.contains(&MBB)) {
  185. // This is an unreachable block and therefore hasn't been selected, since
  186. // the main selection loop above uses a postorder block traversal.
  187. // We delete all the instructions in this block since it's unreachable.
  188. MBB.clear();
  189. // Don't delete the block in case the block has it's address taken or is
  190. // still being referenced by a phi somewhere.
  191. continue;
  192. }
  193. // Try to find redundant copies b/w vregs of the same register class.
  194. bool ReachedBegin = false;
  195. for (auto MII = std::prev(MBB.end()), Begin = MBB.begin(); !ReachedBegin;) {
  196. // Select this instruction.
  197. MachineInstr &MI = *MII;
  198. // And have our iterator point to the next instruction, if there is one.
  199. if (MII == Begin)
  200. ReachedBegin = true;
  201. else
  202. --MII;
  203. if (MI.getOpcode() != TargetOpcode::COPY)
  204. continue;
  205. Register SrcReg = MI.getOperand(1).getReg();
  206. Register DstReg = MI.getOperand(0).getReg();
  207. if (SrcReg.isVirtual() && DstReg.isVirtual()) {
  208. auto SrcRC = MRI.getRegClass(SrcReg);
  209. auto DstRC = MRI.getRegClass(DstReg);
  210. if (SrcRC == DstRC) {
  211. MRI.replaceRegWith(DstReg, SrcReg);
  212. MI.eraseFromParent();
  213. }
  214. }
  215. }
  216. }
  217. #ifndef NDEBUG
  218. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  219. // Now that selection is complete, there are no more generic vregs. Verify
  220. // that the size of the now-constrained vreg is unchanged and that it has a
  221. // register class.
  222. for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
  223. Register VReg = Register::index2VirtReg(I);
  224. MachineInstr *MI = nullptr;
  225. if (!MRI.def_empty(VReg))
  226. MI = &*MRI.def_instr_begin(VReg);
  227. else if (!MRI.use_empty(VReg)) {
  228. MI = &*MRI.use_instr_begin(VReg);
  229. // Debug value instruction is permitted to use undefined vregs.
  230. if (MI->isDebugValue())
  231. continue;
  232. }
  233. if (!MI)
  234. continue;
  235. const TargetRegisterClass *RC = MRI.getRegClassOrNull(VReg);
  236. if (!RC) {
  237. reportGISelFailure(MF, TPC, MORE, "gisel-select",
  238. "VReg has no regclass after selection", *MI);
  239. return false;
  240. }
  241. const LLT Ty = MRI.getType(VReg);
  242. if (Ty.isValid() && Ty.getSizeInBits() > TRI.getRegSizeInBits(*RC)) {
  243. reportGISelFailure(
  244. MF, TPC, MORE, "gisel-select",
  245. "VReg's low-level type and register class have different sizes", *MI);
  246. return false;
  247. }
  248. }
  249. if (MF.size() != NumBlocks) {
  250. MachineOptimizationRemarkMissed R("gisel-select", "GISelFailure",
  251. MF.getFunction().getSubprogram(),
  252. /*MBB=*/nullptr);
  253. R << "inserting blocks is not supported yet";
  254. reportGISelFailure(MF, TPC, MORE, R);
  255. return false;
  256. }
  257. #endif
  258. // Determine if there are any calls in this machine function. Ported from
  259. // SelectionDAG.
  260. MachineFrameInfo &MFI = MF.getFrameInfo();
  261. for (const auto &MBB : MF) {
  262. if (MFI.hasCalls() && MF.hasInlineAsm())
  263. break;
  264. for (const auto &MI : MBB) {
  265. if ((MI.isCall() && !MI.isReturn()) || MI.isStackAligningInlineAsm())
  266. MFI.setHasCalls(true);
  267. if (MI.isInlineAsm())
  268. MF.setHasInlineAsm(true);
  269. }
  270. }
  271. // FIXME: FinalizeISel pass calls finalizeLowering, so it's called twice.
  272. auto &TLI = *MF.getSubtarget().getTargetLowering();
  273. TLI.finalizeLowering(MF);
  274. LLVM_DEBUG({
  275. dbgs() << "Rules covered by selecting function: " << MF.getName() << ":";
  276. for (auto RuleID : CoverageInfo.covered())
  277. dbgs() << " id" << RuleID;
  278. dbgs() << "\n\n";
  279. });
  280. CoverageInfo.emit(CoveragePrefix,
  281. TLI.getTargetMachine().getTarget().getBackendName());
  282. // If we successfully selected the function nothing is going to use the vreg
  283. // types after us (otherwise MIRPrinter would need them). Make sure the types
  284. // disappear.
  285. MRI.clearVirtRegTypes();
  286. // FIXME: Should we accurately track changes?
  287. return true;
  288. }