X86PreTileConfig.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. //===-- X86PreTileConfig.cpp - Tile Register Pre-configure-----------------===//
  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. /// \file Pass to pre-config the shapes of AMX registers
  10. /// AMX register needs to be configured before use. The shapes of AMX register
  11. /// are encoded in the 1st and 2nd machine operand of AMX pseudo instructions.
  12. ///
  13. /// The instruction ldtilecfg is used to config the shapes. It must be reachable
  14. /// for all variable shapes. ldtilecfg will be inserted more than once if we
  15. /// cannot find a dominating point for all AMX instructions.
  16. ///
  17. /// The configure register is caller saved according to ABI. We need to insert
  18. /// ldtilecfg again after the call instruction if callee clobbers any AMX
  19. /// registers.
  20. ///
  21. /// This pass calculates all points that ldtilecfg need to be inserted to and
  22. /// insert them. It reports error if the reachability conditions aren't met.
  23. //
  24. //===----------------------------------------------------------------------===//
  25. #include "X86.h"
  26. #include "X86InstrBuilder.h"
  27. #include "X86MachineFunctionInfo.h"
  28. #include "X86RegisterInfo.h"
  29. #include "X86Subtarget.h"
  30. #include "llvm/CodeGen/MachineFunctionPass.h"
  31. #include "llvm/CodeGen/MachineInstr.h"
  32. #include "llvm/CodeGen/MachineLoopInfo.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/Passes.h"
  35. #include "llvm/CodeGen/TargetInstrInfo.h"
  36. #include "llvm/CodeGen/TargetRegisterInfo.h"
  37. #include "llvm/InitializePasses.h"
  38. using namespace llvm;
  39. #define DEBUG_TYPE "tile-pre-config"
  40. #define REPORT_CONFIG_FAIL \
  41. report_fatal_error( \
  42. MF.getName() + \
  43. ": Failed to config tile register, please define the shape earlier");
  44. namespace {
  45. struct MIRef {
  46. MachineInstr *MI = nullptr;
  47. MachineBasicBlock *MBB = nullptr;
  48. // A virtual position for instruction that will be inserted after MI.
  49. size_t Pos = 0;
  50. MIRef() = default;
  51. MIRef(MachineBasicBlock *MBB) : MBB(MBB) {
  52. for (auto I = MBB->begin(), E = MBB->end(); I != E && I->isPHI();
  53. ++I, ++Pos)
  54. MI = &*I;
  55. }
  56. MIRef(MachineInstr *MI)
  57. : MI(MI), MBB(MI->getParent()),
  58. Pos(std::distance(MBB->instr_begin(), ++MI->getIterator())) {}
  59. MIRef(MachineInstr *MI, MachineBasicBlock *MBB)
  60. : MI(MI), MBB(MBB),
  61. Pos(std::distance(MBB->instr_begin(), ++MI->getIterator())) {}
  62. MIRef(MachineInstr *MI, MachineBasicBlock *MBB, size_t Pos)
  63. : MI(MI), MBB(MBB), Pos(Pos) {}
  64. operator bool() const { return MBB != nullptr; }
  65. bool operator==(const MIRef &RHS) const {
  66. return MI == RHS.MI && MBB == RHS.MBB;
  67. }
  68. bool operator!=(const MIRef &RHS) const { return !(*this == RHS); }
  69. bool operator<(const MIRef &RHS) const {
  70. // Comparison between different BBs happens when inserting a MIRef into set.
  71. // So we compare MBB first to make the insertion happy.
  72. return MBB < RHS.MBB || (MBB == RHS.MBB && Pos < RHS.Pos);
  73. }
  74. bool operator>(const MIRef &RHS) const {
  75. // Comparison between different BBs happens when inserting a MIRef into set.
  76. // So we compare MBB first to make the insertion happy.
  77. return MBB > RHS.MBB || (MBB == RHS.MBB && Pos > RHS.Pos);
  78. }
  79. };
  80. struct BBInfo {
  81. MIRef FirstAMX;
  82. MIRef LastCall;
  83. bool HasAMXRegLiveIn = false;
  84. bool TileCfgForbidden = false;
  85. bool NeedTileCfgLiveIn = false;
  86. };
  87. class X86PreTileConfig : public MachineFunctionPass {
  88. MachineRegisterInfo *MRI;
  89. const MachineLoopInfo *MLI;
  90. SmallSet<MachineInstr *, 8> DefVisited;
  91. DenseMap<MachineBasicBlock *, BBInfo> BBVisitedInfo;
  92. DenseMap<MachineBasicBlock *, SmallVector<MIRef, 8>> ShapeBBs;
  93. /// Check if the callee will clobber AMX registers.
  94. bool isDestructiveCall(MachineInstr &MI, BitVector UsableRegs) {
  95. auto Iter = llvm::find_if(
  96. MI.operands(), [](MachineOperand &MO) { return MO.isRegMask(); });
  97. if (Iter == MI.operands_end())
  98. return false;
  99. UsableRegs.clearBitsInMask(Iter->getRegMask());
  100. return !UsableRegs.none();
  101. }
  102. /// Check if MI is AMX pseudo instruction.
  103. bool isAMXInstruction(MachineInstr &MI) {
  104. if (MI.isPHI() || MI.isDebugInstr() || MI.getNumOperands() < 3)
  105. return false;
  106. MachineOperand &MO = MI.getOperand(0);
  107. // We can simply check if it is AMX instruction by its def.
  108. // But we should exclude old API which uses physical registers.
  109. if (MO.isReg() && MO.getReg().isVirtual() &&
  110. MRI->getRegClass(MO.getReg())->getID() == X86::TILERegClassID) {
  111. collectShapeInfo(MI);
  112. return true;
  113. }
  114. // PTILESTOREDV is the only exception that doesn't def a AMX register.
  115. return MI.getOpcode() == X86::PTILESTOREDV;
  116. }
  117. /// Check if it is an edge from loop bottom to loop head.
  118. bool isLoopBackEdge(MachineBasicBlock *Header, MachineBasicBlock *Bottom) {
  119. if (!MLI->isLoopHeader(Header))
  120. return false;
  121. auto *ML = MLI->getLoopFor(Header);
  122. if (ML->contains(Bottom) && ML->isLoopLatch(Bottom))
  123. return true;
  124. return false;
  125. }
  126. /// Collect the shape def information for later use.
  127. void collectShapeInfo(MachineInstr &MI);
  128. /// Try to hoist shapes definded below AMX instructions.
  129. bool hoistShapesInBB(MachineBasicBlock *MBB, SmallVectorImpl<MIRef> &Shapes) {
  130. MIRef &FirstAMX = BBVisitedInfo[MBB].FirstAMX;
  131. auto FirstShapeBelowAMX = llvm::lower_bound(Shapes, FirstAMX);
  132. auto InsertPoint = FirstAMX.MI->getIterator();
  133. for (auto I = FirstShapeBelowAMX, E = Shapes.end(); I != E; ++I) {
  134. // Do not hoist instructions that access memory.
  135. if (I->MI->mayLoadOrStore())
  136. return false;
  137. for (auto &MO : I->MI->operands()) {
  138. if (MO.isDef())
  139. continue;
  140. // Do not hoist instructions if the sources' def under AMX instruction.
  141. // TODO: We can handle isMoveImmediate MI here.
  142. if (MO.isReg() && MIRef(MRI->getVRegDef(MO.getReg())) > FirstAMX)
  143. return false;
  144. // TODO: Maybe need more checks here.
  145. }
  146. MBB->insert(InsertPoint, I->MI->removeFromParent());
  147. }
  148. // We only need to mark the last shape in the BB now.
  149. Shapes.clear();
  150. Shapes.push_back(MIRef(&*--InsertPoint, MBB));
  151. return true;
  152. }
  153. public:
  154. X86PreTileConfig() : MachineFunctionPass(ID) {}
  155. /// Return the pass name.
  156. StringRef getPassName() const override {
  157. return "Tile Register Pre-configure";
  158. }
  159. /// X86PreTileConfig analysis usage.
  160. void getAnalysisUsage(AnalysisUsage &AU) const override {
  161. AU.setPreservesAll();
  162. AU.addRequired<MachineLoopInfo>();
  163. MachineFunctionPass::getAnalysisUsage(AU);
  164. }
  165. /// Clear MF related structures.
  166. void releaseMemory() override {
  167. ShapeBBs.clear();
  168. DefVisited.clear();
  169. BBVisitedInfo.clear();
  170. }
  171. /// Perform ldtilecfg instructions inserting.
  172. bool runOnMachineFunction(MachineFunction &MF) override;
  173. static char ID;
  174. };
  175. } // end anonymous namespace
  176. char X86PreTileConfig::ID = 0;
  177. INITIALIZE_PASS_BEGIN(X86PreTileConfig, "tilepreconfig",
  178. "Tile Register Pre-configure", false, false)
  179. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  180. INITIALIZE_PASS_END(X86PreTileConfig, "tilepreconfig",
  181. "Tile Register Pre-configure", false, false)
  182. void X86PreTileConfig::collectShapeInfo(MachineInstr &MI) {
  183. auto RecordShape = [&](MachineInstr *MI, MachineBasicBlock *MBB) {
  184. MIRef MIR(MI, MBB);
  185. auto I = llvm::lower_bound(ShapeBBs[MBB], MIR);
  186. if (I == ShapeBBs[MBB].end() || *I != MIR)
  187. ShapeBBs[MBB].insert(I, MIR);
  188. };
  189. SmallVector<Register, 8> WorkList(
  190. {MI.getOperand(1).getReg(), MI.getOperand(2).getReg()});
  191. while (!WorkList.empty()) {
  192. Register R = WorkList.pop_back_val();
  193. MachineInstr *DefMI = MRI->getVRegDef(R);
  194. assert(DefMI && "R must has one define instruction");
  195. MachineBasicBlock *DefMBB = DefMI->getParent();
  196. if (DefMI->isMoveImmediate() || !DefVisited.insert(DefMI).second)
  197. continue;
  198. if (DefMI->isPHI()) {
  199. for (unsigned I = 1; I < DefMI->getNumOperands(); I += 2)
  200. if (isLoopBackEdge(DefMBB, DefMI->getOperand(I + 1).getMBB()))
  201. RecordShape(DefMI, DefMBB); // In this case, PHI is also a shape def.
  202. else
  203. WorkList.push_back(DefMI->getOperand(I).getReg());
  204. } else {
  205. RecordShape(DefMI, DefMBB);
  206. }
  207. }
  208. }
  209. bool X86PreTileConfig::runOnMachineFunction(MachineFunction &MF) {
  210. const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
  211. const TargetInstrInfo *TII = ST.getInstrInfo();
  212. const TargetRegisterInfo *TRI = ST.getRegisterInfo();
  213. const TargetRegisterClass *RC = TRI->getRegClass(X86::TILERegClassID);
  214. X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
  215. BitVector AMXRegs(TRI->getNumRegs());
  216. for (unsigned I = 0; I < RC->getNumRegs(); I++)
  217. AMXRegs.set(X86::TMM0 + I);
  218. // Iterate MF to collect information.
  219. MRI = &MF.getRegInfo();
  220. MLI = &getAnalysis<MachineLoopInfo>();
  221. SmallSet<MIRef, 8> CfgNeedInsert;
  222. SmallVector<MachineBasicBlock *, 8> CfgLiveInBBs;
  223. for (auto &MBB : MF) {
  224. size_t Pos = 0;
  225. for (auto &MI : MBB) {
  226. ++Pos;
  227. if (isAMXInstruction(MI)) {
  228. // If there's call before the AMX, we need to reload tile config.
  229. if (BBVisitedInfo[&MBB].LastCall)
  230. CfgNeedInsert.insert(BBVisitedInfo[&MBB].LastCall);
  231. else // Otherwise, we need tile config to live in this BB.
  232. BBVisitedInfo[&MBB].NeedTileCfgLiveIn = true;
  233. // Always record the first AMX in case there's shape def after it.
  234. if (!BBVisitedInfo[&MBB].FirstAMX)
  235. BBVisitedInfo[&MBB].FirstAMX = MIRef(&MI, &MBB, Pos);
  236. } else if (MI.isCall() && isDestructiveCall(MI, AMXRegs)) {
  237. // Record the call only if the callee clobbers all AMX registers.
  238. BBVisitedInfo[&MBB].LastCall = MIRef(&MI, &MBB, Pos);
  239. }
  240. }
  241. if (BBVisitedInfo[&MBB].NeedTileCfgLiveIn) {
  242. if (&MBB == &MF.front())
  243. CfgNeedInsert.insert(MIRef(&MBB));
  244. else
  245. CfgLiveInBBs.push_back(&MBB);
  246. }
  247. if (BBVisitedInfo[&MBB].FirstAMX || BBVisitedInfo[&MBB].HasAMXRegLiveIn)
  248. for (auto *Succ : MBB.successors())
  249. if (!isLoopBackEdge(Succ, &MBB))
  250. BBVisitedInfo[Succ].HasAMXRegLiveIn = true;
  251. }
  252. // Update NeedTileCfgLiveIn for predecessors.
  253. while (!CfgLiveInBBs.empty()) {
  254. MachineBasicBlock *MBB = CfgLiveInBBs.pop_back_val();
  255. for (auto *Pred : MBB->predecessors()) {
  256. if (BBVisitedInfo[Pred].LastCall) {
  257. CfgNeedInsert.insert(BBVisitedInfo[Pred].LastCall);
  258. } else if (!BBVisitedInfo[Pred].NeedTileCfgLiveIn) {
  259. BBVisitedInfo[Pred].NeedTileCfgLiveIn = true;
  260. if (Pred == &MF.front())
  261. CfgNeedInsert.insert(MIRef(Pred));
  262. else
  263. CfgLiveInBBs.push_back(Pred);
  264. }
  265. }
  266. }
  267. // There's no AMX instruction if we didn't find a tile config live in point.
  268. if (CfgNeedInsert.empty())
  269. return false;
  270. X86FI->setHasVirtualTileReg(true);
  271. // Avoid to insert ldtilecfg before any shape defs.
  272. SmallVector<MachineBasicBlock *, 8> WorkList;
  273. for (auto &I : ShapeBBs) {
  274. // TODO: We can hoist shapes across BBs here.
  275. if (BBVisitedInfo[I.first].HasAMXRegLiveIn)
  276. REPORT_CONFIG_FAIL
  277. if (BBVisitedInfo[I.first].FirstAMX &&
  278. BBVisitedInfo[I.first].FirstAMX < I.second.back() &&
  279. !hoistShapesInBB(I.first, I.second))
  280. REPORT_CONFIG_FAIL
  281. WorkList.push_back(I.first);
  282. }
  283. while (!WorkList.empty()) {
  284. MachineBasicBlock *MBB = WorkList.pop_back_val();
  285. for (auto *Pred : MBB->predecessors()) {
  286. if (!BBVisitedInfo[Pred].TileCfgForbidden && !isLoopBackEdge(MBB, Pred)) {
  287. BBVisitedInfo[Pred].TileCfgForbidden = true;
  288. WorkList.push_back(Pred);
  289. }
  290. }
  291. }
  292. DebugLoc DL;
  293. SmallSet<MIRef, 8> VisitedOrInserted;
  294. int SS = MF.getFrameInfo().CreateStackObject(
  295. ST.getTileConfigSize(), ST.getTileConfigAlignment(), false);
  296. // Try to insert for the tile config live in points.
  297. for (const auto &I : CfgNeedInsert) {
  298. SmallSet<MIRef, 8> InsertPoints;
  299. SmallVector<MIRef, 8> WorkList({I});
  300. while (!WorkList.empty()) {
  301. MIRef I = WorkList.pop_back_val();
  302. if (!VisitedOrInserted.count(I)) {
  303. if (!BBVisitedInfo[I.MBB].TileCfgForbidden) {
  304. // If the BB is all shapes reachable, stop sink and try to insert.
  305. InsertPoints.insert(I);
  306. } else {
  307. // Avoid the BB to be multi visited.
  308. VisitedOrInserted.insert(I);
  309. // Sink the inserting point along the chain with NeedTileCfgLiveIn =
  310. // true when MBB isn't all shapes reachable.
  311. for (auto *Succ : I.MBB->successors())
  312. if (BBVisitedInfo[Succ].NeedTileCfgLiveIn)
  313. WorkList.push_back(MIRef(Succ));
  314. }
  315. }
  316. }
  317. // A given point might be forked due to shape conditions are not met.
  318. for (MIRef I : InsertPoints) {
  319. // Make sure we insert ldtilecfg after the last shape def in MBB.
  320. if (ShapeBBs.count(I.MBB) && I < ShapeBBs[I.MBB].back())
  321. I = ShapeBBs[I.MBB].back();
  322. // There're chances the MBB is sunk more than once. Record it to avoid
  323. // multi insert.
  324. if (VisitedOrInserted.insert(I).second) {
  325. auto II = I.MI ? I.MI->getIterator() : I.MBB->instr_begin();
  326. addFrameReference(BuildMI(*I.MBB, ++II, DL, TII->get(X86::LDTILECFG)),
  327. SS);
  328. }
  329. }
  330. }
  331. // Zero stack slot.
  332. MachineBasicBlock &MBB = MF.front();
  333. MachineInstr *MI = &*MBB.begin();
  334. if (ST.hasAVX512()) {
  335. Register Zmm = MRI->createVirtualRegister(&X86::VR512RegClass);
  336. BuildMI(MBB, MI, DL, TII->get(X86::VPXORDZrr), Zmm)
  337. .addReg(Zmm, RegState::Undef)
  338. .addReg(Zmm, RegState::Undef);
  339. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSZmr)), SS)
  340. .addReg(Zmm);
  341. } else if (ST.hasAVX2()) {
  342. Register Ymm = MRI->createVirtualRegister(&X86::VR256RegClass);
  343. BuildMI(MBB, MI, DL, TII->get(X86::VPXORYrr), Ymm)
  344. .addReg(Ymm, RegState::Undef)
  345. .addReg(Ymm, RegState::Undef);
  346. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSYmr)), SS)
  347. .addReg(Ymm);
  348. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::VMOVUPSYmr)), SS, 32)
  349. .addReg(Ymm);
  350. } else {
  351. assert(ST.hasSSE2() && "AMX should assume SSE2 enabled");
  352. Register Xmm = MRI->createVirtualRegister(&X86::VR128RegClass);
  353. BuildMI(MBB, MI, DL, TII->get(X86::PXORrr), Xmm)
  354. .addReg(Xmm, RegState::Undef)
  355. .addReg(Xmm, RegState::Undef);
  356. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOVUPSmr)), SS)
  357. .addReg(Xmm);
  358. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOVUPSmr)), SS, 16)
  359. .addReg(Xmm);
  360. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOVUPSmr)), SS, 32)
  361. .addReg(Xmm);
  362. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOVUPSmr)), SS, 48)
  363. .addReg(Xmm);
  364. }
  365. // Fill in the palette first.
  366. addFrameReference(BuildMI(MBB, MI, DL, TII->get(X86::MOV8mi)), SS).addImm(1);
  367. return true;
  368. }
  369. FunctionPass *llvm::createX86PreTileConfigPass() {
  370. return new X86PreTileConfig();
  371. }