X86InsertPrefetch.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //===------- X86InsertPrefetch.cpp - Insert cache prefetch hints ----------===//
  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 pass applies cache prefetch instructions based on a profile. The pass
  10. // assumes DiscriminateMemOps ran immediately before, to ensure debug info
  11. // matches the one used at profile generation time. The profile is encoded in
  12. // afdo format (text or binary). It contains prefetch hints recommendations.
  13. // Each recommendation is made in terms of debug info locations, a type (i.e.
  14. // nta, t{0|1|2}) and a delta. The debug info identifies an instruction with a
  15. // memory operand (see X86DiscriminateMemOps). The prefetch will be made for
  16. // a location at that memory operand + the delta specified in the
  17. // recommendation.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "X86.h"
  21. #include "X86InstrBuilder.h"
  22. #include "X86InstrInfo.h"
  23. #include "X86MachineFunctionInfo.h"
  24. #include "X86Subtarget.h"
  25. #include "llvm/CodeGen/MachineModuleInfo.h"
  26. #include "llvm/IR/DebugInfoMetadata.h"
  27. #include "llvm/ProfileData/SampleProf.h"
  28. #include "llvm/ProfileData/SampleProfReader.h"
  29. #include "llvm/Transforms/IPO/SampleProfile.h"
  30. using namespace llvm;
  31. using namespace sampleprof;
  32. static cl::opt<std::string>
  33. PrefetchHintsFile("prefetch-hints-file",
  34. cl::desc("Path to the prefetch hints profile. See also "
  35. "-x86-discriminate-memops"),
  36. cl::Hidden);
  37. namespace {
  38. class X86InsertPrefetch : public MachineFunctionPass {
  39. void getAnalysisUsage(AnalysisUsage &AU) const override;
  40. bool doInitialization(Module &) override;
  41. bool runOnMachineFunction(MachineFunction &MF) override;
  42. struct PrefetchInfo {
  43. unsigned InstructionID;
  44. int64_t Delta;
  45. };
  46. typedef SmallVectorImpl<PrefetchInfo> Prefetches;
  47. bool findPrefetchInfo(const FunctionSamples *Samples, const MachineInstr &MI,
  48. Prefetches &prefetches) const;
  49. public:
  50. static char ID;
  51. X86InsertPrefetch(const std::string &PrefetchHintsFilename);
  52. StringRef getPassName() const override {
  53. return "X86 Insert Cache Prefetches";
  54. }
  55. private:
  56. std::string Filename;
  57. std::unique_ptr<SampleProfileReader> Reader;
  58. };
  59. using PrefetchHints = SampleRecord::CallTargetMap;
  60. // Return any prefetching hints for the specified MachineInstruction. The hints
  61. // are returned as pairs (name, delta).
  62. ErrorOr<PrefetchHints> getPrefetchHints(const FunctionSamples *TopSamples,
  63. const MachineInstr &MI) {
  64. if (const auto &Loc = MI.getDebugLoc())
  65. if (const auto *Samples = TopSamples->findFunctionSamples(Loc))
  66. return Samples->findCallTargetMapAt(FunctionSamples::getOffset(Loc),
  67. Loc->getBaseDiscriminator());
  68. return std::error_code();
  69. }
  70. // The prefetch instruction can't take memory operands involving vector
  71. // registers.
  72. bool IsMemOpCompatibleWithPrefetch(const MachineInstr &MI, int Op) {
  73. Register BaseReg = MI.getOperand(Op + X86::AddrBaseReg).getReg();
  74. Register IndexReg = MI.getOperand(Op + X86::AddrIndexReg).getReg();
  75. return (BaseReg == 0 ||
  76. X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) ||
  77. X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg)) &&
  78. (IndexReg == 0 ||
  79. X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg) ||
  80. X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg));
  81. }
  82. } // end anonymous namespace
  83. //===----------------------------------------------------------------------===//
  84. // Implementation
  85. //===----------------------------------------------------------------------===//
  86. char X86InsertPrefetch::ID = 0;
  87. X86InsertPrefetch::X86InsertPrefetch(const std::string &PrefetchHintsFilename)
  88. : MachineFunctionPass(ID), Filename(PrefetchHintsFilename) {}
  89. /// Return true if the provided MachineInstruction has cache prefetch hints. In
  90. /// that case, the prefetch hints are stored, in order, in the Prefetches
  91. /// vector.
  92. bool X86InsertPrefetch::findPrefetchInfo(const FunctionSamples *TopSamples,
  93. const MachineInstr &MI,
  94. Prefetches &Prefetches) const {
  95. assert(Prefetches.empty() &&
  96. "Expected caller passed empty PrefetchInfo vector.");
  97. static constexpr std::pair<StringLiteral, unsigned> HintTypes[] = {
  98. {"_nta_", X86::PREFETCHNTA},
  99. {"_t0_", X86::PREFETCHT0},
  100. {"_t1_", X86::PREFETCHT1},
  101. {"_t2_", X86::PREFETCHT2},
  102. };
  103. static const char *SerializedPrefetchPrefix = "__prefetch";
  104. const ErrorOr<PrefetchHints> T = getPrefetchHints(TopSamples, MI);
  105. if (!T)
  106. return false;
  107. int16_t max_index = -1;
  108. // Convert serialized prefetch hints into PrefetchInfo objects, and populate
  109. // the Prefetches vector.
  110. for (const auto &S_V : *T) {
  111. StringRef Name = S_V.getKey();
  112. if (Name.consume_front(SerializedPrefetchPrefix)) {
  113. int64_t D = static_cast<int64_t>(S_V.second);
  114. unsigned IID = 0;
  115. for (const auto &HintType : HintTypes) {
  116. if (Name.startswith(HintType.first)) {
  117. Name = Name.drop_front(HintType.first.size());
  118. IID = HintType.second;
  119. break;
  120. }
  121. }
  122. if (IID == 0)
  123. return false;
  124. uint8_t index = 0;
  125. Name.consumeInteger(10, index);
  126. if (index >= Prefetches.size())
  127. Prefetches.resize(index + 1);
  128. Prefetches[index] = {IID, D};
  129. max_index = std::max(max_index, static_cast<int16_t>(index));
  130. }
  131. }
  132. assert(max_index + 1 >= 0 &&
  133. "Possible overflow: max_index + 1 should be positive.");
  134. assert(static_cast<size_t>(max_index + 1) == Prefetches.size() &&
  135. "The number of prefetch hints received should match the number of "
  136. "PrefetchInfo objects returned");
  137. return !Prefetches.empty();
  138. }
  139. bool X86InsertPrefetch::doInitialization(Module &M) {
  140. if (Filename.empty())
  141. return false;
  142. LLVMContext &Ctx = M.getContext();
  143. ErrorOr<std::unique_ptr<SampleProfileReader>> ReaderOrErr =
  144. SampleProfileReader::create(Filename, Ctx);
  145. if (std::error_code EC = ReaderOrErr.getError()) {
  146. std::string Msg = "Could not open profile: " + EC.message();
  147. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg,
  148. DiagnosticSeverity::DS_Warning));
  149. return false;
  150. }
  151. Reader = std::move(ReaderOrErr.get());
  152. Reader->read();
  153. return true;
  154. }
  155. void X86InsertPrefetch::getAnalysisUsage(AnalysisUsage &AU) const {
  156. AU.setPreservesAll();
  157. MachineFunctionPass::getAnalysisUsage(AU);
  158. }
  159. bool X86InsertPrefetch::runOnMachineFunction(MachineFunction &MF) {
  160. if (!Reader)
  161. return false;
  162. const FunctionSamples *Samples = Reader->getSamplesFor(MF.getFunction());
  163. if (!Samples)
  164. return false;
  165. bool Changed = false;
  166. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  167. SmallVector<PrefetchInfo, 4> Prefetches;
  168. for (auto &MBB : MF) {
  169. for (auto MI = MBB.instr_begin(); MI != MBB.instr_end();) {
  170. auto Current = MI;
  171. ++MI;
  172. int Offset = X86II::getMemoryOperandNo(Current->getDesc().TSFlags);
  173. if (Offset < 0)
  174. continue;
  175. unsigned Bias = X86II::getOperandBias(Current->getDesc());
  176. int MemOpOffset = Offset + Bias;
  177. // FIXME(mtrofin): ORE message when the recommendation cannot be taken.
  178. if (!IsMemOpCompatibleWithPrefetch(*Current, MemOpOffset))
  179. continue;
  180. Prefetches.clear();
  181. if (!findPrefetchInfo(Samples, *Current, Prefetches))
  182. continue;
  183. assert(!Prefetches.empty() &&
  184. "The Prefetches vector should contain at least a value if "
  185. "findPrefetchInfo returned true.");
  186. for (auto &PrefInfo : Prefetches) {
  187. unsigned PFetchInstrID = PrefInfo.InstructionID;
  188. int64_t Delta = PrefInfo.Delta;
  189. const MCInstrDesc &Desc = TII->get(PFetchInstrID);
  190. MachineInstr *PFetch =
  191. MF.CreateMachineInstr(Desc, Current->getDebugLoc(), true);
  192. MachineInstrBuilder MIB(MF, PFetch);
  193. static_assert(X86::AddrBaseReg == 0 && X86::AddrScaleAmt == 1 &&
  194. X86::AddrIndexReg == 2 && X86::AddrDisp == 3 &&
  195. X86::AddrSegmentReg == 4,
  196. "Unexpected change in X86 operand offset order.");
  197. // This assumes X86::AddBaseReg = 0, {...}ScaleAmt = 1, etc.
  198. // FIXME(mtrofin): consider adding a:
  199. // MachineInstrBuilder::set(unsigned offset, op).
  200. MIB.addReg(Current->getOperand(MemOpOffset + X86::AddrBaseReg).getReg())
  201. .addImm(
  202. Current->getOperand(MemOpOffset + X86::AddrScaleAmt).getImm())
  203. .addReg(
  204. Current->getOperand(MemOpOffset + X86::AddrIndexReg).getReg())
  205. .addImm(Current->getOperand(MemOpOffset + X86::AddrDisp).getImm() +
  206. Delta)
  207. .addReg(Current->getOperand(MemOpOffset + X86::AddrSegmentReg)
  208. .getReg());
  209. if (!Current->memoperands_empty()) {
  210. MachineMemOperand *CurrentOp = *(Current->memoperands_begin());
  211. MIB.addMemOperand(MF.getMachineMemOperand(
  212. CurrentOp, CurrentOp->getOffset() + Delta, CurrentOp->getSize()));
  213. }
  214. // Insert before Current. This is because Current may clobber some of
  215. // the registers used to describe the input memory operand.
  216. MBB.insert(Current, PFetch);
  217. Changed = true;
  218. }
  219. }
  220. }
  221. return Changed;
  222. }
  223. FunctionPass *llvm::createX86InsertPrefetchPass() {
  224. return new X86InsertPrefetch(PrefetchHintsFile);
  225. }