CSEMIRBuilder.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //===-- llvm/CodeGen/GlobalISel/CSEMIRBuilder.cpp - MIBuilder--*- 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 CSEMIRBuilder class which CSEs as it builds
  10. /// instructions.
  11. //===----------------------------------------------------------------------===//
  12. //
  13. #include "llvm/CodeGen/GlobalISel/CSEMIRBuilder.h"
  14. #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
  15. #include "llvm/CodeGen/GlobalISel/Utils.h"
  16. #include "llvm/CodeGen/MachineInstrBuilder.h"
  17. #include "llvm/IR/DebugInfoMetadata.h"
  18. using namespace llvm;
  19. bool CSEMIRBuilder::dominates(MachineBasicBlock::const_iterator A,
  20. MachineBasicBlock::const_iterator B) const {
  21. auto MBBEnd = getMBB().end();
  22. if (B == MBBEnd)
  23. return true;
  24. assert(A->getParent() == B->getParent() &&
  25. "Iterators should be in same block");
  26. const MachineBasicBlock *BBA = A->getParent();
  27. MachineBasicBlock::const_iterator I = BBA->begin();
  28. for (; &*I != A && &*I != B; ++I)
  29. ;
  30. return &*I == A;
  31. }
  32. MachineInstrBuilder
  33. CSEMIRBuilder::getDominatingInstrForID(FoldingSetNodeID &ID,
  34. void *&NodeInsertPos) {
  35. GISelCSEInfo *CSEInfo = getCSEInfo();
  36. assert(CSEInfo && "Can't get here without setting CSEInfo");
  37. MachineBasicBlock *CurMBB = &getMBB();
  38. MachineInstr *MI =
  39. CSEInfo->getMachineInstrIfExists(ID, CurMBB, NodeInsertPos);
  40. if (MI) {
  41. CSEInfo->countOpcodeHit(MI->getOpcode());
  42. auto CurrPos = getInsertPt();
  43. auto MII = MachineBasicBlock::iterator(MI);
  44. if (MII == CurrPos) {
  45. // Move the insert point ahead of the instruction so any future uses of
  46. // this builder will have the def ready.
  47. setInsertPt(*CurMBB, std::next(MII));
  48. } else if (!dominates(MI, CurrPos)) {
  49. CurMBB->splice(CurrPos, CurMBB, MI);
  50. }
  51. return MachineInstrBuilder(getMF(), MI);
  52. }
  53. return MachineInstrBuilder();
  54. }
  55. bool CSEMIRBuilder::canPerformCSEForOpc(unsigned Opc) const {
  56. const GISelCSEInfo *CSEInfo = getCSEInfo();
  57. if (!CSEInfo || !CSEInfo->shouldCSE(Opc))
  58. return false;
  59. return true;
  60. }
  61. void CSEMIRBuilder::profileDstOp(const DstOp &Op,
  62. GISelInstProfileBuilder &B) const {
  63. switch (Op.getDstOpKind()) {
  64. case DstOp::DstType::Ty_RC:
  65. B.addNodeIDRegType(Op.getRegClass());
  66. break;
  67. case DstOp::DstType::Ty_Reg: {
  68. // Regs can have LLT&(RB|RC). If those exist, profile them as well.
  69. B.addNodeIDReg(Op.getReg());
  70. break;
  71. }
  72. default:
  73. B.addNodeIDRegType(Op.getLLTTy(*getMRI()));
  74. break;
  75. }
  76. }
  77. void CSEMIRBuilder::profileSrcOp(const SrcOp &Op,
  78. GISelInstProfileBuilder &B) const {
  79. switch (Op.getSrcOpKind()) {
  80. case SrcOp::SrcType::Ty_Imm:
  81. B.addNodeIDImmediate(static_cast<int64_t>(Op.getImm()));
  82. break;
  83. case SrcOp::SrcType::Ty_Predicate:
  84. B.addNodeIDImmediate(static_cast<int64_t>(Op.getPredicate()));
  85. break;
  86. default:
  87. B.addNodeIDRegType(Op.getReg());
  88. break;
  89. }
  90. }
  91. void CSEMIRBuilder::profileMBBOpcode(GISelInstProfileBuilder &B,
  92. unsigned Opc) const {
  93. // First add the MBB (Local CSE).
  94. B.addNodeIDMBB(&getMBB());
  95. // Then add the opcode.
  96. B.addNodeIDOpcode(Opc);
  97. }
  98. void CSEMIRBuilder::profileEverything(unsigned Opc, ArrayRef<DstOp> DstOps,
  99. ArrayRef<SrcOp> SrcOps,
  100. Optional<unsigned> Flags,
  101. GISelInstProfileBuilder &B) const {
  102. profileMBBOpcode(B, Opc);
  103. // Then add the DstOps.
  104. profileDstOps(DstOps, B);
  105. // Then add the SrcOps.
  106. profileSrcOps(SrcOps, B);
  107. // Add Flags if passed in.
  108. if (Flags)
  109. B.addNodeIDFlag(*Flags);
  110. }
  111. MachineInstrBuilder CSEMIRBuilder::memoizeMI(MachineInstrBuilder MIB,
  112. void *NodeInsertPos) {
  113. assert(canPerformCSEForOpc(MIB->getOpcode()) &&
  114. "Attempting to CSE illegal op");
  115. MachineInstr *MIBInstr = MIB;
  116. getCSEInfo()->insertInstr(MIBInstr, NodeInsertPos);
  117. return MIB;
  118. }
  119. bool CSEMIRBuilder::checkCopyToDefsPossible(ArrayRef<DstOp> DstOps) {
  120. if (DstOps.size() == 1)
  121. return true; // always possible to emit copy to just 1 vreg.
  122. return llvm::all_of(DstOps, [](const DstOp &Op) {
  123. DstOp::DstType DT = Op.getDstOpKind();
  124. return DT == DstOp::DstType::Ty_LLT || DT == DstOp::DstType::Ty_RC;
  125. });
  126. }
  127. MachineInstrBuilder
  128. CSEMIRBuilder::generateCopiesIfRequired(ArrayRef<DstOp> DstOps,
  129. MachineInstrBuilder &MIB) {
  130. assert(checkCopyToDefsPossible(DstOps) &&
  131. "Impossible return a single MIB with copies to multiple defs");
  132. if (DstOps.size() == 1) {
  133. const DstOp &Op = DstOps[0];
  134. if (Op.getDstOpKind() == DstOp::DstType::Ty_Reg)
  135. return buildCopy(Op.getReg(), MIB.getReg(0));
  136. }
  137. // If we didn't generate a copy then we're re-using an existing node directly
  138. // instead of emitting any code. Merge the debug location we wanted to emit
  139. // into the instruction we're CSE'ing with. Debug locations arent part of the
  140. // profile so we don't need to recompute it.
  141. if (getDebugLoc()) {
  142. GISelChangeObserver *Observer = getState().Observer;
  143. if (Observer)
  144. Observer->changingInstr(*MIB);
  145. MIB->setDebugLoc(
  146. DILocation::getMergedLocation(MIB->getDebugLoc(), getDebugLoc()));
  147. if (Observer)
  148. Observer->changedInstr(*MIB);
  149. }
  150. return MIB;
  151. }
  152. MachineInstrBuilder CSEMIRBuilder::buildInstr(unsigned Opc,
  153. ArrayRef<DstOp> DstOps,
  154. ArrayRef<SrcOp> SrcOps,
  155. Optional<unsigned> Flag) {
  156. switch (Opc) {
  157. default:
  158. break;
  159. case TargetOpcode::G_ADD:
  160. case TargetOpcode::G_AND:
  161. case TargetOpcode::G_ASHR:
  162. case TargetOpcode::G_LSHR:
  163. case TargetOpcode::G_MUL:
  164. case TargetOpcode::G_OR:
  165. case TargetOpcode::G_SHL:
  166. case TargetOpcode::G_SUB:
  167. case TargetOpcode::G_XOR:
  168. case TargetOpcode::G_UDIV:
  169. case TargetOpcode::G_SDIV:
  170. case TargetOpcode::G_UREM:
  171. case TargetOpcode::G_SREM: {
  172. // Try to constant fold these.
  173. assert(SrcOps.size() == 2 && "Invalid sources");
  174. assert(DstOps.size() == 1 && "Invalid dsts");
  175. if (SrcOps[0].getLLTTy(*getMRI()).isVector()) {
  176. // Try to constant fold vector constants.
  177. Register VecCst = ConstantFoldVectorBinop(
  178. Opc, SrcOps[0].getReg(), SrcOps[1].getReg(), *getMRI(), *this);
  179. if (VecCst)
  180. return buildCopy(DstOps[0], VecCst);
  181. break;
  182. }
  183. if (Optional<APInt> Cst = ConstantFoldBinOp(Opc, SrcOps[0].getReg(),
  184. SrcOps[1].getReg(), *getMRI()))
  185. return buildConstant(DstOps[0], *Cst);
  186. break;
  187. }
  188. case TargetOpcode::G_SEXT_INREG: {
  189. assert(DstOps.size() == 1 && "Invalid dst ops");
  190. assert(SrcOps.size() == 2 && "Invalid src ops");
  191. const DstOp &Dst = DstOps[0];
  192. const SrcOp &Src0 = SrcOps[0];
  193. const SrcOp &Src1 = SrcOps[1];
  194. if (auto MaybeCst =
  195. ConstantFoldExtOp(Opc, Src0.getReg(), Src1.getImm(), *getMRI()))
  196. return buildConstant(Dst, *MaybeCst);
  197. break;
  198. }
  199. case TargetOpcode::G_SITOFP:
  200. case TargetOpcode::G_UITOFP: {
  201. // Try to constant fold these.
  202. assert(SrcOps.size() == 1 && "Invalid sources");
  203. assert(DstOps.size() == 1 && "Invalid dsts");
  204. if (Optional<APFloat> Cst = ConstantFoldIntToFloat(
  205. Opc, DstOps[0].getLLTTy(*getMRI()), SrcOps[0].getReg(), *getMRI()))
  206. return buildFConstant(DstOps[0], *Cst);
  207. break;
  208. }
  209. case TargetOpcode::G_CTLZ: {
  210. assert(SrcOps.size() == 1 && "Expected one source");
  211. assert(DstOps.size() == 1 && "Expected one dest");
  212. auto MaybeCsts = ConstantFoldCTLZ(SrcOps[0].getReg(), *getMRI());
  213. if (!MaybeCsts)
  214. break;
  215. if (MaybeCsts->size() == 1)
  216. return buildConstant(DstOps[0], (*MaybeCsts)[0]);
  217. // This was a vector constant. Build a G_BUILD_VECTOR for them.
  218. SmallVector<Register> ConstantRegs;
  219. LLT VecTy = DstOps[0].getLLTTy(*getMRI());
  220. for (unsigned Cst : *MaybeCsts)
  221. ConstantRegs.emplace_back(
  222. buildConstant(VecTy.getScalarType(), Cst).getReg(0));
  223. return buildBuildVector(DstOps[0], ConstantRegs);
  224. }
  225. }
  226. bool CanCopy = checkCopyToDefsPossible(DstOps);
  227. if (!canPerformCSEForOpc(Opc))
  228. return MachineIRBuilder::buildInstr(Opc, DstOps, SrcOps, Flag);
  229. // If we can CSE this instruction, but involves generating copies to multiple
  230. // regs, give up. This frequently happens to UNMERGEs.
  231. if (!CanCopy) {
  232. auto MIB = MachineIRBuilder::buildInstr(Opc, DstOps, SrcOps, Flag);
  233. // CSEInfo would have tracked this instruction. Remove it from the temporary
  234. // insts.
  235. getCSEInfo()->handleRemoveInst(&*MIB);
  236. return MIB;
  237. }
  238. FoldingSetNodeID ID;
  239. GISelInstProfileBuilder ProfBuilder(ID, *getMRI());
  240. void *InsertPos = nullptr;
  241. profileEverything(Opc, DstOps, SrcOps, Flag, ProfBuilder);
  242. MachineInstrBuilder MIB = getDominatingInstrForID(ID, InsertPos);
  243. if (MIB) {
  244. // Handle generating copies here.
  245. return generateCopiesIfRequired(DstOps, MIB);
  246. }
  247. // This instruction does not exist in the CSEInfo. Build it and CSE it.
  248. MachineInstrBuilder NewMIB =
  249. MachineIRBuilder::buildInstr(Opc, DstOps, SrcOps, Flag);
  250. return memoizeMI(NewMIB, InsertPos);
  251. }
  252. MachineInstrBuilder CSEMIRBuilder::buildConstant(const DstOp &Res,
  253. const ConstantInt &Val) {
  254. constexpr unsigned Opc = TargetOpcode::G_CONSTANT;
  255. if (!canPerformCSEForOpc(Opc))
  256. return MachineIRBuilder::buildConstant(Res, Val);
  257. // For vectors, CSE the element only for now.
  258. LLT Ty = Res.getLLTTy(*getMRI());
  259. if (Ty.isVector())
  260. return buildSplatVector(Res, buildConstant(Ty.getElementType(), Val));
  261. FoldingSetNodeID ID;
  262. GISelInstProfileBuilder ProfBuilder(ID, *getMRI());
  263. void *InsertPos = nullptr;
  264. profileMBBOpcode(ProfBuilder, Opc);
  265. profileDstOp(Res, ProfBuilder);
  266. ProfBuilder.addNodeIDMachineOperand(MachineOperand::CreateCImm(&Val));
  267. MachineInstrBuilder MIB = getDominatingInstrForID(ID, InsertPos);
  268. if (MIB) {
  269. // Handle generating copies here.
  270. return generateCopiesIfRequired({Res}, MIB);
  271. }
  272. MachineInstrBuilder NewMIB = MachineIRBuilder::buildConstant(Res, Val);
  273. return memoizeMI(NewMIB, InsertPos);
  274. }
  275. MachineInstrBuilder CSEMIRBuilder::buildFConstant(const DstOp &Res,
  276. const ConstantFP &Val) {
  277. constexpr unsigned Opc = TargetOpcode::G_FCONSTANT;
  278. if (!canPerformCSEForOpc(Opc))
  279. return MachineIRBuilder::buildFConstant(Res, Val);
  280. // For vectors, CSE the element only for now.
  281. LLT Ty = Res.getLLTTy(*getMRI());
  282. if (Ty.isVector())
  283. return buildSplatVector(Res, buildFConstant(Ty.getElementType(), Val));
  284. FoldingSetNodeID ID;
  285. GISelInstProfileBuilder ProfBuilder(ID, *getMRI());
  286. void *InsertPos = nullptr;
  287. profileMBBOpcode(ProfBuilder, Opc);
  288. profileDstOp(Res, ProfBuilder);
  289. ProfBuilder.addNodeIDMachineOperand(MachineOperand::CreateFPImm(&Val));
  290. MachineInstrBuilder MIB = getDominatingInstrForID(ID, InsertPos);
  291. if (MIB) {
  292. // Handle generating copies here.
  293. return generateCopiesIfRequired({Res}, MIB);
  294. }
  295. MachineInstrBuilder NewMIB = MachineIRBuilder::buildFConstant(Res, Val);
  296. return memoizeMI(NewMIB, InsertPos);
  297. }