CodeEmitterGen.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // CodeEmitterGen uses the descriptions of instructions and their fields to
  11. // construct an automated code emitter: a function that, given a MachineInstr,
  12. // returns the (currently, 32-bit unsigned) value of the instruction.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CodeGenTarget.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/Support/CommandLine.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/TableGen/Record.h"
  20. #include "llvm/TableGen/TableGenBackend.h"
  21. #include <map>
  22. #include <string>
  23. #include <vector>
  24. using namespace llvm;
  25. namespace {
  26. class CodeEmitterGen {
  27. RecordKeeper &Records;
  28. public:
  29. CodeEmitterGen(RecordKeeper &R) : Records(R) {}
  30. void run(raw_ostream &o);
  31. private:
  32. int getVariableBit(const std::string &VarName, BitsInit *BI, int bit);
  33. std::string getInstructionCase(Record *R, CodeGenTarget &Target);
  34. void AddCodeToMergeInOperand(Record *R, BitsInit *BI,
  35. const std::string &VarName,
  36. unsigned &NumberedOp,
  37. std::set<unsigned> &NamedOpIndices,
  38. std::string &Case, CodeGenTarget &Target);
  39. };
  40. // If the VarBitInit at position 'bit' matches the specified variable then
  41. // return the variable bit position. Otherwise return -1.
  42. int CodeEmitterGen::getVariableBit(const std::string &VarName,
  43. BitsInit *BI, int bit) {
  44. if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) {
  45. if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar()))
  46. if (VI->getName() == VarName)
  47. return VBI->getBitNum();
  48. } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) {
  49. if (VI->getName() == VarName)
  50. return 0;
  51. }
  52. return -1;
  53. }
  54. void CodeEmitterGen::
  55. AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
  56. unsigned &NumberedOp,
  57. std::set<unsigned> &NamedOpIndices,
  58. std::string &Case, CodeGenTarget &Target) {
  59. CodeGenInstruction &CGI = Target.getInstruction(R);
  60. // Determine if VarName actually contributes to the Inst encoding.
  61. int bit = BI->getNumBits()-1;
  62. // Scan for a bit that this contributed to.
  63. for (; bit >= 0; ) {
  64. if (getVariableBit(VarName, BI, bit) != -1)
  65. break;
  66. --bit;
  67. }
  68. // If we found no bits, ignore this value, otherwise emit the call to get the
  69. // operand encoding.
  70. if (bit < 0) return;
  71. // If the operand matches by name, reference according to that
  72. // operand number. Non-matching operands are assumed to be in
  73. // order.
  74. unsigned OpIdx;
  75. if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
  76. // Get the machine operand number for the indicated operand.
  77. OpIdx = CGI.Operands[OpIdx].MIOperandNo;
  78. assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
  79. "Explicitly used operand also marked as not emitted!");
  80. } else {
  81. unsigned NumberOps = CGI.Operands.size();
  82. /// If this operand is not supposed to be emitted by the
  83. /// generated emitter, skip it.
  84. while (NumberedOp < NumberOps &&
  85. (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
  86. (!NamedOpIndices.empty() && NamedOpIndices.count(
  87. CGI.Operands.getSubOperandNumber(NumberedOp).first)))) {
  88. ++NumberedOp;
  89. if (NumberedOp >= CGI.Operands.back().MIOperandNo +
  90. CGI.Operands.back().MINumOperands) {
  91. errs() << "Too few operands in record " << R->getName() <<
  92. " (no match for variable " << VarName << "):\n";
  93. errs() << *R;
  94. errs() << '\n';
  95. return;
  96. }
  97. }
  98. OpIdx = NumberedOp++;
  99. }
  100. std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
  101. std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
  102. // If the source operand has a custom encoder, use it. This will
  103. // get the encoding for all of the suboperands.
  104. if (!EncoderMethodName.empty()) {
  105. // A custom encoder has all of the information for the
  106. // sub-operands, if there are more than one, so only
  107. // query the encoder once per source operand.
  108. if (SO.second == 0) {
  109. Case += " // op: " + VarName + "\n" +
  110. " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
  111. Case += ", Fixups, STI";
  112. Case += ");\n";
  113. }
  114. } else {
  115. Case += " // op: " + VarName + "\n" +
  116. " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
  117. Case += ", Fixups, STI";
  118. Case += ");\n";
  119. }
  120. for (; bit >= 0; ) {
  121. int varBit = getVariableBit(VarName, BI, bit);
  122. // If this bit isn't from a variable, skip it.
  123. if (varBit == -1) {
  124. --bit;
  125. continue;
  126. }
  127. // Figure out the consecutive range of bits covered by this operand, in
  128. // order to generate better encoding code.
  129. int beginInstBit = bit;
  130. int beginVarBit = varBit;
  131. int N = 1;
  132. for (--bit; bit >= 0;) {
  133. varBit = getVariableBit(VarName, BI, bit);
  134. if (varBit == -1 || varBit != (beginVarBit - N)) break;
  135. ++N;
  136. --bit;
  137. }
  138. uint64_t opMask = ~(uint64_t)0 >> (64-N);
  139. int opShift = beginVarBit - N + 1;
  140. opMask <<= opShift;
  141. opShift = beginInstBit - beginVarBit;
  142. if (opShift > 0) {
  143. Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " +
  144. itostr(opShift) + ";\n";
  145. } else if (opShift < 0) {
  146. Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " +
  147. itostr(-opShift) + ";\n";
  148. } else {
  149. Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n";
  150. }
  151. }
  152. }
  153. std::string CodeEmitterGen::getInstructionCase(Record *R,
  154. CodeGenTarget &Target) {
  155. std::string Case;
  156. BitsInit *BI = R->getValueAsBitsInit("Inst");
  157. const std::vector<RecordVal> &Vals = R->getValues();
  158. unsigned NumberedOp = 0;
  159. std::set<unsigned> NamedOpIndices;
  160. // Collect the set of operand indices that might correspond to named
  161. // operand, and skip these when assigning operands based on position.
  162. if (Target.getInstructionSet()->
  163. getValueAsBit("noNamedPositionallyEncodedOperands")) {
  164. CodeGenInstruction &CGI = Target.getInstruction(R);
  165. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  166. unsigned OpIdx;
  167. if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
  168. continue;
  169. NamedOpIndices.insert(OpIdx);
  170. }
  171. }
  172. // Loop over all of the fields in the instruction, determining which are the
  173. // operands to the instruction.
  174. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  175. // Ignore fixed fields in the record, we're looking for values like:
  176. // bits<5> RST = { ?, ?, ?, ?, ? };
  177. if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
  178. continue;
  179. AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp,
  180. NamedOpIndices, Case, Target);
  181. }
  182. std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
  183. if (!PostEmitter.empty()) {
  184. Case += " Value = " + PostEmitter + "(MI, Value";
  185. Case += ", STI";
  186. Case += ");\n";
  187. }
  188. return Case;
  189. }
  190. void CodeEmitterGen::run(raw_ostream &o) {
  191. CodeGenTarget Target(Records);
  192. std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
  193. // For little-endian instruction bit encodings, reverse the bit order
  194. Target.reverseBitsForLittleEndianEncoding();
  195. const std::vector<const CodeGenInstruction*> &NumberedInstructions =
  196. Target.getInstructionsByEnumValue();
  197. // Emit function declaration
  198. o << "uint64_t " << Target.getName();
  199. o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
  200. << " SmallVectorImpl<MCFixup> &Fixups,\n"
  201. << " const MCSubtargetInfo &STI) const {\n";
  202. // Emit instruction base values
  203. o << " static const uint64_t InstBits[] = {\n";
  204. for (std::vector<const CodeGenInstruction*>::const_iterator
  205. IN = NumberedInstructions.begin(),
  206. EN = NumberedInstructions.end();
  207. IN != EN; ++IN) {
  208. const CodeGenInstruction *CGI = *IN;
  209. Record *R = CGI->TheDef;
  210. if (R->getValueAsString("Namespace") == "TargetOpcode" ||
  211. R->getValueAsBit("isPseudo")) {
  212. o << " UINT64_C(0),\n";
  213. continue;
  214. }
  215. BitsInit *BI = R->getValueAsBitsInit("Inst");
  216. // Start by filling in fixed values.
  217. uint64_t Value = 0;
  218. for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
  219. if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1)))
  220. Value |= (uint64_t)B->getValue() << (e-i-1);
  221. }
  222. o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n";
  223. }
  224. o << " UINT64_C(0)\n };\n";
  225. // Map to accumulate all the cases.
  226. std::map<std::string, std::vector<std::string> > CaseMap;
  227. // Construct all cases statement for each opcode
  228. for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
  229. IC != EC; ++IC) {
  230. Record *R = *IC;
  231. if (R->getValueAsString("Namespace") == "TargetOpcode" ||
  232. R->getValueAsBit("isPseudo"))
  233. continue;
  234. const std::string &InstName = R->getValueAsString("Namespace") + "::"
  235. + R->getName();
  236. std::string Case = getInstructionCase(R, Target);
  237. CaseMap[Case].push_back(InstName);
  238. }
  239. // Emit initial function code
  240. o << " const unsigned opcode = MI.getOpcode();\n"
  241. << " uint64_t Value = InstBits[opcode];\n"
  242. << " uint64_t op = 0;\n"
  243. << " (void)op; // suppress warning\n"
  244. << " switch (opcode) {\n";
  245. // Emit each case statement
  246. std::map<std::string, std::vector<std::string> >::iterator IE, EE;
  247. for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
  248. const std::string &Case = IE->first;
  249. std::vector<std::string> &InstList = IE->second;
  250. for (int i = 0, N = InstList.size(); i < N; i++) {
  251. if (i) o << "\n";
  252. o << " case " << InstList[i] << ":";
  253. }
  254. o << " {\n";
  255. o << Case;
  256. o << " break;\n"
  257. << " }\n";
  258. }
  259. // Default case: unhandled opcode
  260. o << " default:\n"
  261. << " std::string msg;\n"
  262. << " raw_string_ostream Msg(msg);\n"
  263. << " Msg << \"Not supported instr: \" << MI;\n"
  264. << " report_fatal_error(Msg.str());\n"
  265. << " }\n"
  266. << " return Value;\n"
  267. << "}\n\n";
  268. }
  269. } // End anonymous namespace
  270. namespace llvm {
  271. void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) {
  272. emitSourceFileHeader("Machine Code Emitter", OS);
  273. CodeEmitterGen(RK).run(OS);
  274. }
  275. } // End llvm namespace