X86DomainReassignment.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. //===--- X86DomainReassignment.cpp - Selectively switch register classes---===//
  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 attempts to find instruction chains (closures) in one domain,
  10. // and convert them to equivalent instructions in a different domain,
  11. // if profitable.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "X86.h"
  15. #include "X86InstrInfo.h"
  16. #include "X86Subtarget.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/DenseMapInfo.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/CodeGen/MachineFunctionPass.h"
  23. #include "llvm/CodeGen/MachineInstrBuilder.h"
  24. #include "llvm/CodeGen/MachineRegisterInfo.h"
  25. #include "llvm/CodeGen/TargetRegisterInfo.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/Printable.h"
  28. #include <bitset>
  29. using namespace llvm;
  30. #define DEBUG_TYPE "x86-domain-reassignment"
  31. STATISTIC(NumClosuresConverted, "Number of closures converted by the pass");
  32. static cl::opt<bool> DisableX86DomainReassignment(
  33. "disable-x86-domain-reassignment", cl::Hidden,
  34. cl::desc("X86: Disable Virtual Register Reassignment."), cl::init(false));
  35. namespace {
  36. enum RegDomain { NoDomain = -1, GPRDomain, MaskDomain, OtherDomain, NumDomains };
  37. static bool isGPR(const TargetRegisterClass *RC) {
  38. return X86::GR64RegClass.hasSubClassEq(RC) ||
  39. X86::GR32RegClass.hasSubClassEq(RC) ||
  40. X86::GR16RegClass.hasSubClassEq(RC) ||
  41. X86::GR8RegClass.hasSubClassEq(RC);
  42. }
  43. static bool isMask(const TargetRegisterClass *RC,
  44. const TargetRegisterInfo *TRI) {
  45. return X86::VK16RegClass.hasSubClassEq(RC);
  46. }
  47. static RegDomain getDomain(const TargetRegisterClass *RC,
  48. const TargetRegisterInfo *TRI) {
  49. if (isGPR(RC))
  50. return GPRDomain;
  51. if (isMask(RC, TRI))
  52. return MaskDomain;
  53. return OtherDomain;
  54. }
  55. /// Return a register class equivalent to \p SrcRC, in \p Domain.
  56. static const TargetRegisterClass *getDstRC(const TargetRegisterClass *SrcRC,
  57. RegDomain Domain) {
  58. assert(Domain == MaskDomain && "add domain");
  59. if (X86::GR8RegClass.hasSubClassEq(SrcRC))
  60. return &X86::VK8RegClass;
  61. if (X86::GR16RegClass.hasSubClassEq(SrcRC))
  62. return &X86::VK16RegClass;
  63. if (X86::GR32RegClass.hasSubClassEq(SrcRC))
  64. return &X86::VK32RegClass;
  65. if (X86::GR64RegClass.hasSubClassEq(SrcRC))
  66. return &X86::VK64RegClass;
  67. llvm_unreachable("add register class");
  68. return nullptr;
  69. }
  70. /// Abstract Instruction Converter class.
  71. class InstrConverterBase {
  72. protected:
  73. unsigned SrcOpcode;
  74. public:
  75. InstrConverterBase(unsigned SrcOpcode) : SrcOpcode(SrcOpcode) {}
  76. virtual ~InstrConverterBase() {}
  77. /// \returns true if \p MI is legal to convert.
  78. virtual bool isLegal(const MachineInstr *MI,
  79. const TargetInstrInfo *TII) const {
  80. assert(MI->getOpcode() == SrcOpcode &&
  81. "Wrong instruction passed to converter");
  82. return true;
  83. }
  84. /// Applies conversion to \p MI.
  85. ///
  86. /// \returns true if \p MI is no longer need, and can be deleted.
  87. virtual bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
  88. MachineRegisterInfo *MRI) const = 0;
  89. /// \returns the cost increment incurred by converting \p MI.
  90. virtual double getExtraCost(const MachineInstr *MI,
  91. MachineRegisterInfo *MRI) const = 0;
  92. };
  93. /// An Instruction Converter which ignores the given instruction.
  94. /// For example, PHI instructions can be safely ignored since only the registers
  95. /// need to change.
  96. class InstrIgnore : public InstrConverterBase {
  97. public:
  98. InstrIgnore(unsigned SrcOpcode) : InstrConverterBase(SrcOpcode) {}
  99. bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
  100. MachineRegisterInfo *MRI) const override {
  101. assert(isLegal(MI, TII) && "Cannot convert instruction");
  102. return false;
  103. }
  104. double getExtraCost(const MachineInstr *MI,
  105. MachineRegisterInfo *MRI) const override {
  106. return 0;
  107. }
  108. };
  109. /// An Instruction Converter which replaces an instruction with another.
  110. class InstrReplacer : public InstrConverterBase {
  111. public:
  112. /// Opcode of the destination instruction.
  113. unsigned DstOpcode;
  114. InstrReplacer(unsigned SrcOpcode, unsigned DstOpcode)
  115. : InstrConverterBase(SrcOpcode), DstOpcode(DstOpcode) {}
  116. bool isLegal(const MachineInstr *MI,
  117. const TargetInstrInfo *TII) const override {
  118. if (!InstrConverterBase::isLegal(MI, TII))
  119. return false;
  120. // It's illegal to replace an instruction that implicitly defines a register
  121. // with an instruction that doesn't, unless that register dead.
  122. for (const auto &MO : MI->implicit_operands())
  123. if (MO.isReg() && MO.isDef() && !MO.isDead() &&
  124. !TII->get(DstOpcode).hasImplicitDefOfPhysReg(MO.getReg()))
  125. return false;
  126. return true;
  127. }
  128. bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
  129. MachineRegisterInfo *MRI) const override {
  130. assert(isLegal(MI, TII) && "Cannot convert instruction");
  131. MachineInstrBuilder Bld =
  132. BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(DstOpcode));
  133. // Transfer explicit operands from original instruction. Implicit operands
  134. // are handled by BuildMI.
  135. for (auto &Op : MI->explicit_operands())
  136. Bld.add(Op);
  137. return true;
  138. }
  139. double getExtraCost(const MachineInstr *MI,
  140. MachineRegisterInfo *MRI) const override {
  141. // Assuming instructions have the same cost.
  142. return 0;
  143. }
  144. };
  145. /// An Instruction Converter which replaces an instruction with another, and
  146. /// adds a COPY from the new instruction's destination to the old one's.
  147. class InstrReplacerDstCOPY : public InstrConverterBase {
  148. public:
  149. unsigned DstOpcode;
  150. InstrReplacerDstCOPY(unsigned SrcOpcode, unsigned DstOpcode)
  151. : InstrConverterBase(SrcOpcode), DstOpcode(DstOpcode) {}
  152. bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
  153. MachineRegisterInfo *MRI) const override {
  154. assert(isLegal(MI, TII) && "Cannot convert instruction");
  155. MachineBasicBlock *MBB = MI->getParent();
  156. const DebugLoc &DL = MI->getDebugLoc();
  157. Register Reg = MRI->createVirtualRegister(
  158. TII->getRegClass(TII->get(DstOpcode), 0, MRI->getTargetRegisterInfo(),
  159. *MBB->getParent()));
  160. MachineInstrBuilder Bld = BuildMI(*MBB, MI, DL, TII->get(DstOpcode), Reg);
  161. for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
  162. Bld.add(MO);
  163. BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::COPY))
  164. .add(MI->getOperand(0))
  165. .addReg(Reg);
  166. return true;
  167. }
  168. double getExtraCost(const MachineInstr *MI,
  169. MachineRegisterInfo *MRI) const override {
  170. // Assuming instructions have the same cost, and that COPY is in the same
  171. // domain so it will be eliminated.
  172. return 0;
  173. }
  174. };
  175. /// An Instruction Converter for replacing COPY instructions.
  176. class InstrCOPYReplacer : public InstrReplacer {
  177. public:
  178. RegDomain DstDomain;
  179. InstrCOPYReplacer(unsigned SrcOpcode, RegDomain DstDomain, unsigned DstOpcode)
  180. : InstrReplacer(SrcOpcode, DstOpcode), DstDomain(DstDomain) {}
  181. bool isLegal(const MachineInstr *MI,
  182. const TargetInstrInfo *TII) const override {
  183. if (!InstrConverterBase::isLegal(MI, TII))
  184. return false;
  185. // Don't allow copies to/flow GR8/GR16 physical registers.
  186. // FIXME: Is there some better way to support this?
  187. Register DstReg = MI->getOperand(0).getReg();
  188. if (DstReg.isPhysical() && (X86::GR8RegClass.contains(DstReg) ||
  189. X86::GR16RegClass.contains(DstReg)))
  190. return false;
  191. Register SrcReg = MI->getOperand(1).getReg();
  192. if (SrcReg.isPhysical() && (X86::GR8RegClass.contains(SrcReg) ||
  193. X86::GR16RegClass.contains(SrcReg)))
  194. return false;
  195. return true;
  196. }
  197. double getExtraCost(const MachineInstr *MI,
  198. MachineRegisterInfo *MRI) const override {
  199. assert(MI->getOpcode() == TargetOpcode::COPY && "Expected a COPY");
  200. for (const auto &MO : MI->operands()) {
  201. // Physical registers will not be converted. Assume that converting the
  202. // COPY to the destination domain will eventually result in a actual
  203. // instruction.
  204. if (Register::isPhysicalRegister(MO.getReg()))
  205. return 1;
  206. RegDomain OpDomain = getDomain(MRI->getRegClass(MO.getReg()),
  207. MRI->getTargetRegisterInfo());
  208. // Converting a cross domain COPY to a same domain COPY should eliminate
  209. // an insturction
  210. if (OpDomain == DstDomain)
  211. return -1;
  212. }
  213. return 0;
  214. }
  215. };
  216. /// An Instruction Converter which replaces an instruction with a COPY.
  217. class InstrReplaceWithCopy : public InstrConverterBase {
  218. public:
  219. // Source instruction operand Index, to be used as the COPY source.
  220. unsigned SrcOpIdx;
  221. InstrReplaceWithCopy(unsigned SrcOpcode, unsigned SrcOpIdx)
  222. : InstrConverterBase(SrcOpcode), SrcOpIdx(SrcOpIdx) {}
  223. bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
  224. MachineRegisterInfo *MRI) const override {
  225. assert(isLegal(MI, TII) && "Cannot convert instruction");
  226. BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
  227. TII->get(TargetOpcode::COPY))
  228. .add({MI->getOperand(0), MI->getOperand(SrcOpIdx)});
  229. return true;
  230. }
  231. double getExtraCost(const MachineInstr *MI,
  232. MachineRegisterInfo *MRI) const override {
  233. return 0;
  234. }
  235. };
  236. // Key type to be used by the Instruction Converters map.
  237. // A converter is identified by <destination domain, source opcode>
  238. typedef std::pair<int, unsigned> InstrConverterBaseKeyTy;
  239. typedef DenseMap<InstrConverterBaseKeyTy, std::unique_ptr<InstrConverterBase>>
  240. InstrConverterBaseMap;
  241. /// A closure is a set of virtual register representing all of the edges in
  242. /// the closure, as well as all of the instructions connected by those edges.
  243. ///
  244. /// A closure may encompass virtual registers in the same register bank that
  245. /// have different widths. For example, it may contain 32-bit GPRs as well as
  246. /// 64-bit GPRs.
  247. ///
  248. /// A closure that computes an address (i.e. defines a virtual register that is
  249. /// used in a memory operand) excludes the instructions that contain memory
  250. /// operands using the address. Such an instruction will be included in a
  251. /// different closure that manipulates the loaded or stored value.
  252. class Closure {
  253. private:
  254. /// Virtual registers in the closure.
  255. DenseSet<Register> Edges;
  256. /// Instructions in the closure.
  257. SmallVector<MachineInstr *, 8> Instrs;
  258. /// Domains which this closure can legally be reassigned to.
  259. std::bitset<NumDomains> LegalDstDomains;
  260. /// An ID to uniquely identify this closure, even when it gets
  261. /// moved around
  262. unsigned ID;
  263. public:
  264. Closure(unsigned ID, std::initializer_list<RegDomain> LegalDstDomainList) : ID(ID) {
  265. for (RegDomain D : LegalDstDomainList)
  266. LegalDstDomains.set(D);
  267. }
  268. /// Mark this closure as illegal for reassignment to all domains.
  269. void setAllIllegal() { LegalDstDomains.reset(); }
  270. /// \returns true if this closure has domains which are legal to reassign to.
  271. bool hasLegalDstDomain() const { return LegalDstDomains.any(); }
  272. /// \returns true if is legal to reassign this closure to domain \p RD.
  273. bool isLegal(RegDomain RD) const { return LegalDstDomains[RD]; }
  274. /// Mark this closure as illegal for reassignment to domain \p RD.
  275. void setIllegal(RegDomain RD) { LegalDstDomains[RD] = false; }
  276. bool empty() const { return Edges.empty(); }
  277. bool insertEdge(Register Reg) { return Edges.insert(Reg).second; }
  278. using const_edge_iterator = DenseSet<Register>::const_iterator;
  279. iterator_range<const_edge_iterator> edges() const {
  280. return iterator_range<const_edge_iterator>(Edges.begin(), Edges.end());
  281. }
  282. void addInstruction(MachineInstr *I) {
  283. Instrs.push_back(I);
  284. }
  285. ArrayRef<MachineInstr *> instructions() const {
  286. return Instrs;
  287. }
  288. LLVM_DUMP_METHOD void dump(const MachineRegisterInfo *MRI) const {
  289. dbgs() << "Registers: ";
  290. bool First = true;
  291. for (Register Reg : Edges) {
  292. if (!First)
  293. dbgs() << ", ";
  294. First = false;
  295. dbgs() << printReg(Reg, MRI->getTargetRegisterInfo(), 0, MRI);
  296. }
  297. dbgs() << "\n" << "Instructions:";
  298. for (MachineInstr *MI : Instrs) {
  299. dbgs() << "\n ";
  300. MI->print(dbgs());
  301. }
  302. dbgs() << "\n";
  303. }
  304. unsigned getID() const {
  305. return ID;
  306. }
  307. };
  308. class X86DomainReassignment : public MachineFunctionPass {
  309. const X86Subtarget *STI = nullptr;
  310. MachineRegisterInfo *MRI = nullptr;
  311. const X86InstrInfo *TII = nullptr;
  312. /// All edges that are included in some closure
  313. DenseSet<unsigned> EnclosedEdges;
  314. /// All instructions that are included in some closure.
  315. DenseMap<MachineInstr *, unsigned> EnclosedInstrs;
  316. public:
  317. static char ID;
  318. X86DomainReassignment() : MachineFunctionPass(ID) { }
  319. bool runOnMachineFunction(MachineFunction &MF) override;
  320. void getAnalysisUsage(AnalysisUsage &AU) const override {
  321. AU.setPreservesCFG();
  322. MachineFunctionPass::getAnalysisUsage(AU);
  323. }
  324. StringRef getPassName() const override {
  325. return "X86 Domain Reassignment Pass";
  326. }
  327. private:
  328. /// A map of available Instruction Converters.
  329. InstrConverterBaseMap Converters;
  330. /// Initialize Converters map.
  331. void initConverters();
  332. /// Starting from \Reg, expand the closure as much as possible.
  333. void buildClosure(Closure &, Register Reg);
  334. /// Enqueue \p Reg to be considered for addition to the closure.
  335. void visitRegister(Closure &, Register Reg, RegDomain &Domain,
  336. SmallVectorImpl<unsigned> &Worklist);
  337. /// Reassign the closure to \p Domain.
  338. void reassign(const Closure &C, RegDomain Domain) const;
  339. /// Add \p MI to the closure.
  340. void encloseInstr(Closure &C, MachineInstr *MI);
  341. /// /returns true if it is profitable to reassign the closure to \p Domain.
  342. bool isReassignmentProfitable(const Closure &C, RegDomain Domain) const;
  343. /// Calculate the total cost of reassigning the closure to \p Domain.
  344. double calculateCost(const Closure &C, RegDomain Domain) const;
  345. };
  346. char X86DomainReassignment::ID = 0;
  347. } // End anonymous namespace.
  348. void X86DomainReassignment::visitRegister(Closure &C, Register Reg,
  349. RegDomain &Domain,
  350. SmallVectorImpl<unsigned> &Worklist) {
  351. if (EnclosedEdges.count(Reg))
  352. return;
  353. if (!Reg.isVirtual())
  354. return;
  355. if (!MRI->hasOneDef(Reg))
  356. return;
  357. RegDomain RD = getDomain(MRI->getRegClass(Reg), MRI->getTargetRegisterInfo());
  358. // First edge in closure sets the domain.
  359. if (Domain == NoDomain)
  360. Domain = RD;
  361. if (Domain != RD)
  362. return;
  363. Worklist.push_back(Reg);
  364. }
  365. void X86DomainReassignment::encloseInstr(Closure &C, MachineInstr *MI) {
  366. auto I = EnclosedInstrs.find(MI);
  367. if (I != EnclosedInstrs.end()) {
  368. if (I->second != C.getID())
  369. // Instruction already belongs to another closure, avoid conflicts between
  370. // closure and mark this closure as illegal.
  371. C.setAllIllegal();
  372. return;
  373. }
  374. EnclosedInstrs[MI] = C.getID();
  375. C.addInstruction(MI);
  376. // Mark closure as illegal for reassignment to domains, if there is no
  377. // converter for the instruction or if the converter cannot convert the
  378. // instruction.
  379. for (int i = 0; i != NumDomains; ++i) {
  380. if (C.isLegal((RegDomain)i)) {
  381. auto I = Converters.find({i, MI->getOpcode()});
  382. if (I == Converters.end() || !I->second->isLegal(MI, TII))
  383. C.setIllegal((RegDomain)i);
  384. }
  385. }
  386. }
  387. double X86DomainReassignment::calculateCost(const Closure &C,
  388. RegDomain DstDomain) const {
  389. assert(C.isLegal(DstDomain) && "Cannot calculate cost for illegal closure");
  390. double Cost = 0.0;
  391. for (auto *MI : C.instructions())
  392. Cost += Converters.find({DstDomain, MI->getOpcode()})
  393. ->second->getExtraCost(MI, MRI);
  394. return Cost;
  395. }
  396. bool X86DomainReassignment::isReassignmentProfitable(const Closure &C,
  397. RegDomain Domain) const {
  398. return calculateCost(C, Domain) < 0.0;
  399. }
  400. void X86DomainReassignment::reassign(const Closure &C, RegDomain Domain) const {
  401. assert(C.isLegal(Domain) && "Cannot convert illegal closure");
  402. // Iterate all instructions in the closure, convert each one using the
  403. // appropriate converter.
  404. SmallVector<MachineInstr *, 8> ToErase;
  405. for (auto *MI : C.instructions())
  406. if (Converters.find({Domain, MI->getOpcode()})
  407. ->second->convertInstr(MI, TII, MRI))
  408. ToErase.push_back(MI);
  409. // Iterate all registers in the closure, replace them with registers in the
  410. // destination domain.
  411. for (Register Reg : C.edges()) {
  412. MRI->setRegClass(Reg, getDstRC(MRI->getRegClass(Reg), Domain));
  413. for (auto &MO : MRI->use_operands(Reg)) {
  414. if (MO.isReg())
  415. // Remove all subregister references as they are not valid in the
  416. // destination domain.
  417. MO.setSubReg(0);
  418. }
  419. }
  420. for (auto *MI : ToErase)
  421. MI->eraseFromParent();
  422. }
  423. /// \returns true when \p Reg is used as part of an address calculation in \p
  424. /// MI.
  425. static bool usedAsAddr(const MachineInstr &MI, Register Reg,
  426. const TargetInstrInfo *TII) {
  427. if (!MI.mayLoadOrStore())
  428. return false;
  429. const MCInstrDesc &Desc = TII->get(MI.getOpcode());
  430. int MemOpStart = X86II::getMemoryOperandNo(Desc.TSFlags);
  431. if (MemOpStart == -1)
  432. return false;
  433. MemOpStart += X86II::getOperandBias(Desc);
  434. for (unsigned MemOpIdx = MemOpStart,
  435. MemOpEnd = MemOpStart + X86::AddrNumOperands;
  436. MemOpIdx < MemOpEnd; ++MemOpIdx) {
  437. const MachineOperand &Op = MI.getOperand(MemOpIdx);
  438. if (Op.isReg() && Op.getReg() == Reg)
  439. return true;
  440. }
  441. return false;
  442. }
  443. void X86DomainReassignment::buildClosure(Closure &C, Register Reg) {
  444. SmallVector<unsigned, 4> Worklist;
  445. RegDomain Domain = NoDomain;
  446. visitRegister(C, Reg, Domain, Worklist);
  447. while (!Worklist.empty()) {
  448. unsigned CurReg = Worklist.pop_back_val();
  449. // Register already in this closure.
  450. if (!C.insertEdge(CurReg))
  451. continue;
  452. EnclosedEdges.insert(Reg);
  453. MachineInstr *DefMI = MRI->getVRegDef(CurReg);
  454. encloseInstr(C, DefMI);
  455. // Add register used by the defining MI to the worklist.
  456. // Do not add registers which are used in address calculation, they will be
  457. // added to a different closure.
  458. int OpEnd = DefMI->getNumOperands();
  459. const MCInstrDesc &Desc = DefMI->getDesc();
  460. int MemOp = X86II::getMemoryOperandNo(Desc.TSFlags);
  461. if (MemOp != -1)
  462. MemOp += X86II::getOperandBias(Desc);
  463. for (int OpIdx = 0; OpIdx < OpEnd; ++OpIdx) {
  464. if (OpIdx == MemOp) {
  465. // skip address calculation.
  466. OpIdx += (X86::AddrNumOperands - 1);
  467. continue;
  468. }
  469. auto &Op = DefMI->getOperand(OpIdx);
  470. if (!Op.isReg() || !Op.isUse())
  471. continue;
  472. visitRegister(C, Op.getReg(), Domain, Worklist);
  473. }
  474. // Expand closure through register uses.
  475. for (auto &UseMI : MRI->use_nodbg_instructions(CurReg)) {
  476. // We would like to avoid converting closures which calculare addresses,
  477. // as this should remain in GPRs.
  478. if (usedAsAddr(UseMI, CurReg, TII)) {
  479. C.setAllIllegal();
  480. continue;
  481. }
  482. encloseInstr(C, &UseMI);
  483. for (auto &DefOp : UseMI.defs()) {
  484. if (!DefOp.isReg())
  485. continue;
  486. Register DefReg = DefOp.getReg();
  487. if (!DefReg.isVirtual()) {
  488. C.setAllIllegal();
  489. continue;
  490. }
  491. visitRegister(C, DefReg, Domain, Worklist);
  492. }
  493. }
  494. }
  495. }
  496. void X86DomainReassignment::initConverters() {
  497. Converters[{MaskDomain, TargetOpcode::PHI}] =
  498. std::make_unique<InstrIgnore>(TargetOpcode::PHI);
  499. Converters[{MaskDomain, TargetOpcode::IMPLICIT_DEF}] =
  500. std::make_unique<InstrIgnore>(TargetOpcode::IMPLICIT_DEF);
  501. Converters[{MaskDomain, TargetOpcode::INSERT_SUBREG}] =
  502. std::make_unique<InstrReplaceWithCopy>(TargetOpcode::INSERT_SUBREG, 2);
  503. Converters[{MaskDomain, TargetOpcode::COPY}] =
  504. std::make_unique<InstrCOPYReplacer>(TargetOpcode::COPY, MaskDomain,
  505. TargetOpcode::COPY);
  506. auto createReplacerDstCOPY = [&](unsigned From, unsigned To) {
  507. Converters[{MaskDomain, From}] =
  508. std::make_unique<InstrReplacerDstCOPY>(From, To);
  509. };
  510. createReplacerDstCOPY(X86::MOVZX32rm16, X86::KMOVWkm);
  511. createReplacerDstCOPY(X86::MOVZX64rm16, X86::KMOVWkm);
  512. createReplacerDstCOPY(X86::MOVZX32rr16, X86::KMOVWkk);
  513. createReplacerDstCOPY(X86::MOVZX64rr16, X86::KMOVWkk);
  514. if (STI->hasDQI()) {
  515. createReplacerDstCOPY(X86::MOVZX16rm8, X86::KMOVBkm);
  516. createReplacerDstCOPY(X86::MOVZX32rm8, X86::KMOVBkm);
  517. createReplacerDstCOPY(X86::MOVZX64rm8, X86::KMOVBkm);
  518. createReplacerDstCOPY(X86::MOVZX16rr8, X86::KMOVBkk);
  519. createReplacerDstCOPY(X86::MOVZX32rr8, X86::KMOVBkk);
  520. createReplacerDstCOPY(X86::MOVZX64rr8, X86::KMOVBkk);
  521. }
  522. auto createReplacer = [&](unsigned From, unsigned To) {
  523. Converters[{MaskDomain, From}] = std::make_unique<InstrReplacer>(From, To);
  524. };
  525. createReplacer(X86::MOV16rm, X86::KMOVWkm);
  526. createReplacer(X86::MOV16mr, X86::KMOVWmk);
  527. createReplacer(X86::MOV16rr, X86::KMOVWkk);
  528. createReplacer(X86::SHR16ri, X86::KSHIFTRWri);
  529. createReplacer(X86::SHL16ri, X86::KSHIFTLWri);
  530. createReplacer(X86::NOT16r, X86::KNOTWrr);
  531. createReplacer(X86::OR16rr, X86::KORWrr);
  532. createReplacer(X86::AND16rr, X86::KANDWrr);
  533. createReplacer(X86::XOR16rr, X86::KXORWrr);
  534. if (STI->hasBWI()) {
  535. createReplacer(X86::MOV32rm, X86::KMOVDkm);
  536. createReplacer(X86::MOV64rm, X86::KMOVQkm);
  537. createReplacer(X86::MOV32mr, X86::KMOVDmk);
  538. createReplacer(X86::MOV64mr, X86::KMOVQmk);
  539. createReplacer(X86::MOV32rr, X86::KMOVDkk);
  540. createReplacer(X86::MOV64rr, X86::KMOVQkk);
  541. createReplacer(X86::SHR32ri, X86::KSHIFTRDri);
  542. createReplacer(X86::SHR64ri, X86::KSHIFTRQri);
  543. createReplacer(X86::SHL32ri, X86::KSHIFTLDri);
  544. createReplacer(X86::SHL64ri, X86::KSHIFTLQri);
  545. createReplacer(X86::ADD32rr, X86::KADDDrr);
  546. createReplacer(X86::ADD64rr, X86::KADDQrr);
  547. createReplacer(X86::NOT32r, X86::KNOTDrr);
  548. createReplacer(X86::NOT64r, X86::KNOTQrr);
  549. createReplacer(X86::OR32rr, X86::KORDrr);
  550. createReplacer(X86::OR64rr, X86::KORQrr);
  551. createReplacer(X86::AND32rr, X86::KANDDrr);
  552. createReplacer(X86::AND64rr, X86::KANDQrr);
  553. createReplacer(X86::ANDN32rr, X86::KANDNDrr);
  554. createReplacer(X86::ANDN64rr, X86::KANDNQrr);
  555. createReplacer(X86::XOR32rr, X86::KXORDrr);
  556. createReplacer(X86::XOR64rr, X86::KXORQrr);
  557. // TODO: KTEST is not a replacement for TEST due to flag differences. Need
  558. // to prove only Z flag is used.
  559. //createReplacer(X86::TEST32rr, X86::KTESTDrr);
  560. //createReplacer(X86::TEST64rr, X86::KTESTQrr);
  561. }
  562. if (STI->hasDQI()) {
  563. createReplacer(X86::ADD8rr, X86::KADDBrr);
  564. createReplacer(X86::ADD16rr, X86::KADDWrr);
  565. createReplacer(X86::AND8rr, X86::KANDBrr);
  566. createReplacer(X86::MOV8rm, X86::KMOVBkm);
  567. createReplacer(X86::MOV8mr, X86::KMOVBmk);
  568. createReplacer(X86::MOV8rr, X86::KMOVBkk);
  569. createReplacer(X86::NOT8r, X86::KNOTBrr);
  570. createReplacer(X86::OR8rr, X86::KORBrr);
  571. createReplacer(X86::SHR8ri, X86::KSHIFTRBri);
  572. createReplacer(X86::SHL8ri, X86::KSHIFTLBri);
  573. // TODO: KTEST is not a replacement for TEST due to flag differences. Need
  574. // to prove only Z flag is used.
  575. //createReplacer(X86::TEST8rr, X86::KTESTBrr);
  576. //createReplacer(X86::TEST16rr, X86::KTESTWrr);
  577. createReplacer(X86::XOR8rr, X86::KXORBrr);
  578. }
  579. }
  580. bool X86DomainReassignment::runOnMachineFunction(MachineFunction &MF) {
  581. if (skipFunction(MF.getFunction()))
  582. return false;
  583. if (DisableX86DomainReassignment)
  584. return false;
  585. LLVM_DEBUG(
  586. dbgs() << "***** Machine Function before Domain Reassignment *****\n");
  587. LLVM_DEBUG(MF.print(dbgs()));
  588. STI = &MF.getSubtarget<X86Subtarget>();
  589. // GPR->K is the only transformation currently supported, bail out early if no
  590. // AVX512.
  591. // TODO: We're also bailing of AVX512BW isn't supported since we use VK32 and
  592. // VK64 for GR32/GR64, but those aren't legal classes on KNL. If the register
  593. // coalescer doesn't clean it up and we generate a spill we will crash.
  594. if (!STI->hasAVX512() || !STI->hasBWI())
  595. return false;
  596. MRI = &MF.getRegInfo();
  597. assert(MRI->isSSA() && "Expected MIR to be in SSA form");
  598. TII = STI->getInstrInfo();
  599. initConverters();
  600. bool Changed = false;
  601. EnclosedEdges.clear();
  602. EnclosedInstrs.clear();
  603. std::vector<Closure> Closures;
  604. // Go over all virtual registers and calculate a closure.
  605. unsigned ClosureID = 0;
  606. for (unsigned Idx = 0; Idx < MRI->getNumVirtRegs(); ++Idx) {
  607. Register Reg = Register::index2VirtReg(Idx);
  608. // GPR only current source domain supported.
  609. if (!isGPR(MRI->getRegClass(Reg)))
  610. continue;
  611. // Register already in closure.
  612. if (EnclosedEdges.count(Reg))
  613. continue;
  614. // Calculate closure starting with Reg.
  615. Closure C(ClosureID++, {MaskDomain});
  616. buildClosure(C, Reg);
  617. // Collect all closures that can potentially be converted.
  618. if (!C.empty() && C.isLegal(MaskDomain))
  619. Closures.push_back(std::move(C));
  620. }
  621. for (Closure &C : Closures) {
  622. LLVM_DEBUG(C.dump(MRI));
  623. if (isReassignmentProfitable(C, MaskDomain)) {
  624. reassign(C, MaskDomain);
  625. ++NumClosuresConverted;
  626. Changed = true;
  627. }
  628. }
  629. LLVM_DEBUG(
  630. dbgs() << "***** Machine Function after Domain Reassignment *****\n");
  631. LLVM_DEBUG(MF.print(dbgs()));
  632. return Changed;
  633. }
  634. INITIALIZE_PASS(X86DomainReassignment, "x86-domain-reassignment",
  635. "X86 Domain Reassignment Pass", false, false)
  636. /// Returns an instance of the Domain Reassignment pass.
  637. FunctionPass *llvm::createX86DomainReassignmentPass() {
  638. return new X86DomainReassignment();
  639. }