PseudoLoweringEmitter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. //===- PseudoLoweringEmitter.cpp - PseudoLowering Generator -----*- 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. #include "CodeGenInstruction.h"
  9. #include "CodeGenTarget.h"
  10. #include "llvm/ADT/IndexedMap.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StringMap.h"
  13. #include "llvm/Support/Debug.h"
  14. #include "llvm/Support/ErrorHandling.h"
  15. #include "llvm/TableGen/Error.h"
  16. #include "llvm/TableGen/Record.h"
  17. #include "llvm/TableGen/TableGenBackend.h"
  18. #include <vector>
  19. using namespace llvm;
  20. #define DEBUG_TYPE "pseudo-lowering"
  21. namespace {
  22. class PseudoLoweringEmitter {
  23. struct OpData {
  24. enum MapKind { Operand, Imm, Reg };
  25. MapKind Kind;
  26. union {
  27. unsigned Operand; // Operand number mapped to.
  28. uint64_t Imm; // Integer immedate value.
  29. Record *Reg; // Physical register.
  30. } Data;
  31. };
  32. struct PseudoExpansion {
  33. CodeGenInstruction Source; // The source pseudo instruction definition.
  34. CodeGenInstruction Dest; // The destination instruction to lower to.
  35. IndexedMap<OpData> OperandMap;
  36. PseudoExpansion(CodeGenInstruction &s, CodeGenInstruction &d,
  37. IndexedMap<OpData> &m) :
  38. Source(s), Dest(d), OperandMap(m) {}
  39. };
  40. RecordKeeper &Records;
  41. // It's overkill to have an instance of the full CodeGenTarget object,
  42. // but it loads everything on demand, not in the constructor, so it's
  43. // lightweight in performance, so it works out OK.
  44. CodeGenTarget Target;
  45. SmallVector<PseudoExpansion, 64> Expansions;
  46. unsigned addDagOperandMapping(Record *Rec, DagInit *Dag,
  47. CodeGenInstruction &Insn,
  48. IndexedMap<OpData> &OperandMap,
  49. unsigned BaseIdx);
  50. void evaluateExpansion(Record *Pseudo);
  51. void emitLoweringEmitter(raw_ostream &o);
  52. public:
  53. PseudoLoweringEmitter(RecordKeeper &R) : Records(R), Target(R) {}
  54. /// run - Output the pseudo-lowerings.
  55. void run(raw_ostream &o);
  56. };
  57. } // End anonymous namespace
  58. // FIXME: This pass currently can only expand a pseudo to a single instruction.
  59. // The pseudo expansion really should take a list of dags, not just
  60. // a single dag, so we can do fancier things.
  61. unsigned PseudoLoweringEmitter::
  62. addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Insn,
  63. IndexedMap<OpData> &OperandMap, unsigned BaseIdx) {
  64. unsigned OpsAdded = 0;
  65. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
  66. if (DefInit *DI = dyn_cast<DefInit>(Dag->getArg(i))) {
  67. // Physical register reference. Explicit check for the special case
  68. // "zero_reg" definition.
  69. if (DI->getDef()->isSubClassOf("Register") ||
  70. DI->getDef()->getName() == "zero_reg") {
  71. OperandMap[BaseIdx + i].Kind = OpData::Reg;
  72. OperandMap[BaseIdx + i].Data.Reg = DI->getDef();
  73. ++OpsAdded;
  74. continue;
  75. }
  76. // Normal operands should always have the same type, or we have a
  77. // problem.
  78. // FIXME: We probably shouldn't ever get a non-zero BaseIdx here.
  79. assert(BaseIdx == 0 && "Named subargument in pseudo expansion?!");
  80. // FIXME: Are the message operand types backward?
  81. if (DI->getDef() != Insn.Operands[BaseIdx + i].Rec) {
  82. PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
  83. "', operand type '" + DI->getDef()->getName() +
  84. "' does not match expansion operand type '" +
  85. Insn.Operands[BaseIdx + i].Rec->getName() + "'");
  86. PrintFatalNote(DI->getDef(),
  87. "Value was assigned at the following location:");
  88. }
  89. // Source operand maps to destination operand. The Data element
  90. // will be filled in later, just set the Kind for now. Do it
  91. // for each corresponding MachineInstr operand, not just the first.
  92. for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
  93. OperandMap[BaseIdx + i + I].Kind = OpData::Operand;
  94. OpsAdded += Insn.Operands[i].MINumOperands;
  95. } else if (IntInit *II = dyn_cast<IntInit>(Dag->getArg(i))) {
  96. OperandMap[BaseIdx + i].Kind = OpData::Imm;
  97. OperandMap[BaseIdx + i].Data.Imm = II->getValue();
  98. ++OpsAdded;
  99. } else if (DagInit *SubDag = dyn_cast<DagInit>(Dag->getArg(i))) {
  100. // Just add the operands recursively. This is almost certainly
  101. // a constant value for a complex operand (> 1 MI operand).
  102. unsigned NewOps =
  103. addDagOperandMapping(Rec, SubDag, Insn, OperandMap, BaseIdx + i);
  104. OpsAdded += NewOps;
  105. // Since we added more than one, we also need to adjust the base.
  106. BaseIdx += NewOps - 1;
  107. } else
  108. llvm_unreachable("Unhandled pseudo-expansion argument type!");
  109. }
  110. return OpsAdded;
  111. }
  112. void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) {
  113. LLVM_DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n");
  114. // Validate that the result pattern has the corrent number and types
  115. // of arguments for the instruction it references.
  116. DagInit *Dag = Rec->getValueAsDag("ResultInst");
  117. assert(Dag && "Missing result instruction in pseudo expansion!");
  118. LLVM_DEBUG(dbgs() << " Result: " << *Dag << "\n");
  119. DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
  120. if (!OpDef) {
  121. PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
  122. "', result operator is not a record");
  123. PrintFatalNote(Rec->getValue("ResultInst"),
  124. "Result was assigned at the following location:");
  125. }
  126. Record *Operator = OpDef->getDef();
  127. if (!Operator->isSubClassOf("Instruction")) {
  128. PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
  129. "', result operator '" + Operator->getName() +
  130. "' is not an instruction");
  131. PrintFatalNote(Rec->getValue("ResultInst"),
  132. "Result was assigned at the following location:");
  133. }
  134. CodeGenInstruction Insn(Operator);
  135. if (Insn.isCodeGenOnly || Insn.isPseudo) {
  136. PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
  137. "', result operator '" + Operator->getName() +
  138. "' cannot be a pseudo instruction");
  139. PrintFatalNote(Rec->getValue("ResultInst"),
  140. "Result was assigned at the following location:");
  141. }
  142. if (Insn.Operands.size() != Dag->getNumArgs()) {
  143. PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
  144. "', result operator '" + Operator->getName() +
  145. "' has the wrong number of operands");
  146. PrintFatalNote(Rec->getValue("ResultInst"),
  147. "Result was assigned at the following location:");
  148. }
  149. unsigned NumMIOperands = 0;
  150. for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i)
  151. NumMIOperands += Insn.Operands[i].MINumOperands;
  152. IndexedMap<OpData> OperandMap;
  153. OperandMap.grow(NumMIOperands);
  154. addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0);
  155. // If there are more operands that weren't in the DAG, they have to
  156. // be operands that have default values, or we have an error. Currently,
  157. // Operands that are a subclass of OperandWithDefaultOp have default values.
  158. // Validate that each result pattern argument has a matching (by name)
  159. // argument in the source instruction, in either the (outs) or (ins) list.
  160. // Also check that the type of the arguments match.
  161. //
  162. // Record the mapping of the source to result arguments for use by
  163. // the lowering emitter.
  164. CodeGenInstruction SourceInsn(Rec);
  165. StringMap<unsigned> SourceOperands;
  166. for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i)
  167. SourceOperands[SourceInsn.Operands[i].Name] = i;
  168. LLVM_DEBUG(dbgs() << " Operand mapping:\n");
  169. for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) {
  170. // We've already handled constant values. Just map instruction operands
  171. // here.
  172. if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand)
  173. continue;
  174. StringMap<unsigned>::iterator SourceOp =
  175. SourceOperands.find(Dag->getArgNameStr(i));
  176. if (SourceOp == SourceOperands.end()) {
  177. PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
  178. "', output operand '" + Dag->getArgNameStr(i) +
  179. "' has no matching source operand");
  180. PrintFatalNote(Rec->getValue("ResultInst"),
  181. "Value was assigned at the following location:");
  182. }
  183. // Map the source operand to the destination operand index for each
  184. // MachineInstr operand.
  185. for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
  186. OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand =
  187. SourceOp->getValue();
  188. LLVM_DEBUG(dbgs() << " " << SourceOp->getValue() << " ==> " << i
  189. << "\n");
  190. }
  191. Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap));
  192. }
  193. void PseudoLoweringEmitter::emitLoweringEmitter(raw_ostream &o) {
  194. // Emit file header.
  195. emitSourceFileHeader("Pseudo-instruction MC lowering Source Fragment", o);
  196. o << "bool " << Target.getName() + "AsmPrinter" << "::\n"
  197. << "emitPseudoExpansionLowering(MCStreamer &OutStreamer,\n"
  198. << " const MachineInstr *MI) {\n";
  199. if (!Expansions.empty()) {
  200. o << " switch (MI->getOpcode()) {\n"
  201. << " default: return false;\n";
  202. for (auto &Expansion : Expansions) {
  203. CodeGenInstruction &Source = Expansion.Source;
  204. CodeGenInstruction &Dest = Expansion.Dest;
  205. o << " case " << Source.Namespace << "::"
  206. << Source.TheDef->getName() << ": {\n"
  207. << " MCInst TmpInst;\n"
  208. << " MCOperand MCOp;\n"
  209. << " TmpInst.setOpcode(" << Dest.Namespace << "::"
  210. << Dest.TheDef->getName() << ");\n";
  211. // Copy the operands from the source instruction.
  212. // FIXME: Instruction operands with defaults values (predicates and cc_out
  213. // in ARM, for example shouldn't need explicit values in the
  214. // expansion DAG.
  215. unsigned MIOpNo = 0;
  216. for (const auto &DestOperand : Dest.Operands) {
  217. o << " // Operand: " << DestOperand.Name << "\n";
  218. for (unsigned i = 0, e = DestOperand.MINumOperands; i != e; ++i) {
  219. switch (Expansion.OperandMap[MIOpNo + i].Kind) {
  220. case OpData::Operand:
  221. o << " lowerOperand(MI->getOperand("
  222. << Source.Operands[Expansion.OperandMap[MIOpNo].Data
  223. .Operand].MIOperandNo + i
  224. << "), MCOp);\n"
  225. << " TmpInst.addOperand(MCOp);\n";
  226. break;
  227. case OpData::Imm:
  228. o << " TmpInst.addOperand(MCOperand::createImm("
  229. << Expansion.OperandMap[MIOpNo + i].Data.Imm << "));\n";
  230. break;
  231. case OpData::Reg: {
  232. Record *Reg = Expansion.OperandMap[MIOpNo + i].Data.Reg;
  233. o << " TmpInst.addOperand(MCOperand::createReg(";
  234. // "zero_reg" is special.
  235. if (Reg->getName() == "zero_reg")
  236. o << "0";
  237. else
  238. o << Reg->getValueAsString("Namespace") << "::"
  239. << Reg->getName();
  240. o << "));\n";
  241. break;
  242. }
  243. }
  244. }
  245. MIOpNo += DestOperand.MINumOperands;
  246. }
  247. if (Dest.Operands.isVariadic) {
  248. MIOpNo = Source.Operands.size() + 1;
  249. o << " // variable_ops\n";
  250. o << " for (unsigned i = " << MIOpNo
  251. << ", e = MI->getNumOperands(); i != e; ++i)\n"
  252. << " if (lowerOperand(MI->getOperand(i), MCOp))\n"
  253. << " TmpInst.addOperand(MCOp);\n";
  254. }
  255. o << " EmitToStreamer(OutStreamer, TmpInst);\n"
  256. << " break;\n"
  257. << " }\n";
  258. }
  259. o << " }\n return true;";
  260. } else
  261. o << " return false;";
  262. o << "\n}\n\n";
  263. }
  264. void PseudoLoweringEmitter::run(raw_ostream &o) {
  265. StringRef Classes[] = {"PseudoInstExpansion", "Instruction"};
  266. std::vector<Record *> Insts =
  267. Records.getAllDerivedDefinitions(makeArrayRef(Classes));
  268. // Process the pseudo expansion definitions, validating them as we do so.
  269. Records.startTimer("Process definitions");
  270. for (unsigned i = 0, e = Insts.size(); i != e; ++i)
  271. evaluateExpansion(Insts[i]);
  272. // Generate expansion code to lower the pseudo to an MCInst of the real
  273. // instruction.
  274. Records.startTimer("Emit expansion code");
  275. emitLoweringEmitter(o);
  276. }
  277. namespace llvm {
  278. void EmitPseudoLowering(RecordKeeper &RK, raw_ostream &OS) {
  279. PseudoLoweringEmitter(RK).run(OS);
  280. }
  281. } // End llvm namespace