InstrInfoEmitter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. --*- 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. //
  9. // This tablegen backend is responsible for emitting a description of the target
  10. // instruction set for the code generator.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenDAGPatterns.h"
  14. #include "CodeGenInstruction.h"
  15. #include "CodeGenSchedule.h"
  16. #include "CodeGenTarget.h"
  17. #include "PredicateExpander.h"
  18. #include "SequenceToOffsetTable.h"
  19. #include "TableGenBackends.h"
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/Support/Casting.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/TableGen/Error.h"
  25. #include "llvm/TableGen/Record.h"
  26. #include "llvm/TableGen/TableGenBackend.h"
  27. #include <cassert>
  28. #include <cstdint>
  29. #include <map>
  30. #include <string>
  31. #include <utility>
  32. #include <vector>
  33. using namespace llvm;
  34. namespace {
  35. class InstrInfoEmitter {
  36. RecordKeeper &Records;
  37. CodeGenDAGPatterns CDP;
  38. const CodeGenSchedModels &SchedModels;
  39. public:
  40. InstrInfoEmitter(RecordKeeper &R):
  41. Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
  42. // run - Output the instruction set description.
  43. void run(raw_ostream &OS);
  44. private:
  45. void emitEnums(raw_ostream &OS);
  46. typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
  47. /// The keys of this map are maps which have OpName enum values as their keys
  48. /// and instruction operand indices as their values. The values of this map
  49. /// are lists of instruction names.
  50. typedef std::map<std::map<unsigned, unsigned>,
  51. std::vector<std::string>> OpNameMapTy;
  52. typedef std::map<std::string, unsigned>::iterator StrUintMapIter;
  53. /// Generate member functions in the target-specific GenInstrInfo class.
  54. ///
  55. /// This method is used to custom expand TIIPredicate definitions.
  56. /// See file llvm/Target/TargetInstPredicates.td for a description of what is
  57. /// a TIIPredicate and how to use it.
  58. void emitTIIHelperMethods(raw_ostream &OS, StringRef TargetName,
  59. bool ExpandDefinition = true);
  60. /// Expand TIIPredicate definitions to functions that accept a const MCInst
  61. /// reference.
  62. void emitMCIIHelperMethods(raw_ostream &OS, StringRef TargetName);
  63. void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
  64. Record *InstrInfo,
  65. std::map<std::vector<Record*>, unsigned> &EL,
  66. const OperandInfoMapTy &OpInfo,
  67. raw_ostream &OS);
  68. void emitOperandTypeMappings(
  69. raw_ostream &OS, const CodeGenTarget &Target,
  70. ArrayRef<const CodeGenInstruction *> NumberedInstructions);
  71. void initOperandMapData(
  72. ArrayRef<const CodeGenInstruction *> NumberedInstructions,
  73. StringRef Namespace,
  74. std::map<std::string, unsigned> &Operands,
  75. OpNameMapTy &OperandMap);
  76. void emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target,
  77. ArrayRef<const CodeGenInstruction*> NumberedInstructions);
  78. // Operand information.
  79. void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
  80. std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
  81. };
  82. } // end anonymous namespace
  83. static void PrintDefList(const std::vector<Record*> &Uses,
  84. unsigned Num, raw_ostream &OS) {
  85. OS << "static const MCPhysReg ImplicitList" << Num << "[] = { ";
  86. for (Record *U : Uses)
  87. OS << getQualifiedName(U) << ", ";
  88. OS << "0 };\n";
  89. }
  90. //===----------------------------------------------------------------------===//
  91. // Operand Info Emission.
  92. //===----------------------------------------------------------------------===//
  93. std::vector<std::string>
  94. InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
  95. std::vector<std::string> Result;
  96. for (auto &Op : Inst.Operands) {
  97. // Handle aggregate operands and normal operands the same way by expanding
  98. // either case into a list of operands for this op.
  99. std::vector<CGIOperandList::OperandInfo> OperandList;
  100. // This might be a multiple operand thing. Targets like X86 have
  101. // registers in their multi-operand operands. It may also be an anonymous
  102. // operand, which has a single operand, but no declared class for the
  103. // operand.
  104. DagInit *MIOI = Op.MIOperandInfo;
  105. if (!MIOI || MIOI->getNumArgs() == 0) {
  106. // Single, anonymous, operand.
  107. OperandList.push_back(Op);
  108. } else {
  109. for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) {
  110. OperandList.push_back(Op);
  111. auto *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
  112. OperandList.back().Rec = OpR;
  113. }
  114. }
  115. for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
  116. Record *OpR = OperandList[j].Rec;
  117. std::string Res;
  118. if (OpR->isSubClassOf("RegisterOperand"))
  119. OpR = OpR->getValueAsDef("RegClass");
  120. if (OpR->isSubClassOf("RegisterClass"))
  121. Res += getQualifiedName(OpR) + "RegClassID, ";
  122. else if (OpR->isSubClassOf("PointerLikeRegClass"))
  123. Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
  124. else
  125. // -1 means the operand does not have a fixed register class.
  126. Res += "-1, ";
  127. // Fill in applicable flags.
  128. Res += "0";
  129. // Ptr value whose register class is resolved via callback.
  130. if (OpR->isSubClassOf("PointerLikeRegClass"))
  131. Res += "|(1<<MCOI::LookupPtrRegClass)";
  132. // Predicate operands. Check to see if the original unexpanded operand
  133. // was of type PredicateOp.
  134. if (Op.Rec->isSubClassOf("PredicateOp"))
  135. Res += "|(1<<MCOI::Predicate)";
  136. // Optional def operands. Check to see if the original unexpanded operand
  137. // was of type OptionalDefOperand.
  138. if (Op.Rec->isSubClassOf("OptionalDefOperand"))
  139. Res += "|(1<<MCOI::OptionalDef)";
  140. // Branch target operands. Check to see if the original unexpanded
  141. // operand was of type BranchTargetOperand.
  142. if (Op.Rec->isSubClassOf("BranchTargetOperand"))
  143. Res += "|(1<<MCOI::BranchTarget)";
  144. // Fill in operand type.
  145. Res += ", ";
  146. assert(!Op.OperandType.empty() && "Invalid operand type.");
  147. Res += Op.OperandType;
  148. // Fill in constraint info.
  149. Res += ", ";
  150. const CGIOperandList::ConstraintInfo &Constraint =
  151. Op.Constraints[j];
  152. if (Constraint.isNone())
  153. Res += "0";
  154. else if (Constraint.isEarlyClobber())
  155. Res += "MCOI_EARLY_CLOBBER";
  156. else {
  157. assert(Constraint.isTied());
  158. Res += "MCOI_TIED_TO(" + utostr(Constraint.getTiedOperand()) + ")";
  159. }
  160. Result.push_back(Res);
  161. }
  162. }
  163. return Result;
  164. }
  165. void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
  166. OperandInfoMapTy &OperandInfoIDs) {
  167. // ID #0 is for no operand info.
  168. unsigned OperandListNum = 0;
  169. OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
  170. OS << "\n";
  171. const CodeGenTarget &Target = CDP.getTargetInfo();
  172. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  173. std::vector<std::string> OperandInfo = GetOperandInfo(*Inst);
  174. unsigned &N = OperandInfoIDs[OperandInfo];
  175. if (N != 0) continue;
  176. N = ++OperandListNum;
  177. OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
  178. for (const std::string &Info : OperandInfo)
  179. OS << "{ " << Info << " }, ";
  180. OS << "};\n";
  181. }
  182. }
  183. /// Initialize data structures for generating operand name mappings.
  184. ///
  185. /// \param Operands [out] A map used to generate the OpName enum with operand
  186. /// names as its keys and operand enum values as its values.
  187. /// \param OperandMap [out] A map for representing the operand name mappings for
  188. /// each instructions. This is used to generate the OperandMap table as
  189. /// well as the getNamedOperandIdx() function.
  190. void InstrInfoEmitter::initOperandMapData(
  191. ArrayRef<const CodeGenInstruction *> NumberedInstructions,
  192. StringRef Namespace,
  193. std::map<std::string, unsigned> &Operands,
  194. OpNameMapTy &OperandMap) {
  195. unsigned NumOperands = 0;
  196. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  197. if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable"))
  198. continue;
  199. std::map<unsigned, unsigned> OpList;
  200. for (const auto &Info : Inst->Operands) {
  201. StrUintMapIter I = Operands.find(Info.Name);
  202. if (I == Operands.end()) {
  203. I = Operands.insert(Operands.begin(),
  204. std::pair<std::string, unsigned>(Info.Name, NumOperands++));
  205. }
  206. OpList[I->second] = Info.MIOperandNo;
  207. }
  208. OperandMap[OpList].push_back(Namespace.str() + "::" +
  209. Inst->TheDef->getName().str());
  210. }
  211. }
  212. /// Generate a table and function for looking up the indices of operands by
  213. /// name.
  214. ///
  215. /// This code generates:
  216. /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
  217. /// for each operand name.
  218. /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
  219. /// operand indices.
  220. /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
  221. /// for looking up the operand index for an instruction, given a value from
  222. /// OpName enum
  223. void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
  224. const CodeGenTarget &Target,
  225. ArrayRef<const CodeGenInstruction*> NumberedInstructions) {
  226. StringRef Namespace = Target.getInstNamespace();
  227. std::string OpNameNS = "OpName";
  228. // Map of operand names to their enumeration value. This will be used to
  229. // generate the OpName enum.
  230. std::map<std::string, unsigned> Operands;
  231. OpNameMapTy OperandMap;
  232. initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
  233. OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
  234. OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
  235. OS << "namespace llvm {\n";
  236. OS << "namespace " << Namespace << " {\n";
  237. OS << "namespace " << OpNameNS << " {\n";
  238. OS << "enum {\n";
  239. for (const auto &Op : Operands)
  240. OS << " " << Op.first << " = " << Op.second << ",\n";
  241. OS << " OPERAND_LAST";
  242. OS << "\n};\n";
  243. OS << "} // end namespace OpName\n";
  244. OS << "} // end namespace " << Namespace << "\n";
  245. OS << "} // end namespace llvm\n";
  246. OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n\n";
  247. OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
  248. OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
  249. OS << "namespace llvm {\n";
  250. OS << "namespace " << Namespace << " {\n";
  251. OS << "LLVM_READONLY\n";
  252. OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
  253. if (!Operands.empty()) {
  254. OS << " static const int16_t OperandMap [][" << Operands.size()
  255. << "] = {\n";
  256. for (const auto &Entry : OperandMap) {
  257. const std::map<unsigned, unsigned> &OpList = Entry.first;
  258. OS << "{";
  259. // Emit a row of the OperandMap table
  260. for (unsigned i = 0, e = Operands.size(); i != e; ++i)
  261. OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";
  262. OS << "},\n";
  263. }
  264. OS << "};\n";
  265. OS << " switch(Opcode) {\n";
  266. unsigned TableIndex = 0;
  267. for (const auto &Entry : OperandMap) {
  268. for (const std::string &Name : Entry.second)
  269. OS << " case " << Name << ":\n";
  270. OS << " return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
  271. }
  272. OS << " default: return -1;\n";
  273. OS << " }\n";
  274. } else {
  275. // There are no operands, so no need to emit anything
  276. OS << " return -1;\n";
  277. }
  278. OS << "}\n";
  279. OS << "} // end namespace " << Namespace << "\n";
  280. OS << "} // end namespace llvm\n";
  281. OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n";
  282. }
  283. /// Generate an enum for all the operand types for this target, under the
  284. /// llvm::TargetNamespace::OpTypes namespace.
  285. /// Operand types are all definitions derived of the Operand Target.td class.
  286. void InstrInfoEmitter::emitOperandTypeMappings(
  287. raw_ostream &OS, const CodeGenTarget &Target,
  288. ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
  289. StringRef Namespace = Target.getInstNamespace();
  290. std::vector<Record *> Operands = Records.getAllDerivedDefinitions("Operand");
  291. std::vector<Record *> RegisterOperands =
  292. Records.getAllDerivedDefinitions("RegisterOperand");
  293. std::vector<Record *> RegisterClasses =
  294. Records.getAllDerivedDefinitions("RegisterClass");
  295. OS << "#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
  296. OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
  297. OS << "namespace llvm {\n";
  298. OS << "namespace " << Namespace << " {\n";
  299. OS << "namespace OpTypes {\n";
  300. OS << "enum OperandType {\n";
  301. unsigned EnumVal = 0;
  302. for (const std::vector<Record *> *RecordsToAdd :
  303. {&Operands, &RegisterOperands, &RegisterClasses}) {
  304. for (const Record *Op : *RecordsToAdd) {
  305. if (!Op->isAnonymous())
  306. OS << " " << Op->getName() << " = " << EnumVal << ",\n";
  307. ++EnumVal;
  308. }
  309. }
  310. OS << " OPERAND_TYPE_LIST_END" << "\n};\n";
  311. OS << "} // end namespace OpTypes\n";
  312. OS << "} // end namespace " << Namespace << "\n";
  313. OS << "} // end namespace llvm\n";
  314. OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n\n";
  315. OS << "#ifdef GET_INSTRINFO_OPERAND_TYPE\n";
  316. OS << "#undef GET_INSTRINFO_OPERAND_TYPE\n";
  317. OS << "namespace llvm {\n";
  318. OS << "namespace " << Namespace << " {\n";
  319. OS << "LLVM_READONLY\n";
  320. OS << "static int getOperandType(uint16_t Opcode, uint16_t OpIdx) {\n";
  321. // TODO: Factor out duplicate operand lists to compress the tables.
  322. if (!NumberedInstructions.empty()) {
  323. std::vector<int> OperandOffsets;
  324. std::vector<Record *> OperandRecords;
  325. int CurrentOffset = 0;
  326. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  327. OperandOffsets.push_back(CurrentOffset);
  328. for (const auto &Op : Inst->Operands) {
  329. const DagInit *MIOI = Op.MIOperandInfo;
  330. if (!MIOI || MIOI->getNumArgs() == 0) {
  331. // Single, anonymous, operand.
  332. OperandRecords.push_back(Op.Rec);
  333. ++CurrentOffset;
  334. } else {
  335. for (Init *Arg : MIOI->getArgs()) {
  336. OperandRecords.push_back(cast<DefInit>(Arg)->getDef());
  337. ++CurrentOffset;
  338. }
  339. }
  340. }
  341. }
  342. // Emit the table of offsets (indexes) into the operand type table.
  343. // Size the unsigned integer offset to save space.
  344. assert(OperandRecords.size() <= UINT32_MAX &&
  345. "Too many operands for offset table");
  346. OS << ((OperandRecords.size() <= UINT16_MAX) ? " const uint16_t"
  347. : " const uint32_t");
  348. OS << " Offsets[] = {\n";
  349. for (int I = 0, E = OperandOffsets.size(); I != E; ++I)
  350. OS << " " << OperandOffsets[I] << ",\n";
  351. OS << " };\n";
  352. // Add an entry for the end so that we don't need to special case it below.
  353. OperandOffsets.push_back(OperandRecords.size());
  354. // Emit the actual operand types in a flat table.
  355. // Size the signed integer operand type to save space.
  356. assert(EnumVal <= INT16_MAX &&
  357. "Too many operand types for operand types table");
  358. OS << ((EnumVal <= INT8_MAX) ? " const int8_t" : " const int16_t");
  359. OS << " OpcodeOperandTypes[] = {\n ";
  360. for (int I = 0, E = OperandRecords.size(), CurOffset = 1; I != E; ++I) {
  361. // We print each Opcode's operands in its own row.
  362. if (I == OperandOffsets[CurOffset]) {
  363. OS << "\n ";
  364. // If there are empty rows, mark them with an empty comment.
  365. while (OperandOffsets[++CurOffset] == I)
  366. OS << "/**/\n ";
  367. }
  368. Record *OpR = OperandRecords[I];
  369. if ((OpR->isSubClassOf("Operand") ||
  370. OpR->isSubClassOf("RegisterOperand") ||
  371. OpR->isSubClassOf("RegisterClass")) &&
  372. !OpR->isAnonymous())
  373. OS << "OpTypes::" << OpR->getName();
  374. else
  375. OS << -1;
  376. OS << ", ";
  377. }
  378. OS << "\n };\n";
  379. OS << " return OpcodeOperandTypes[Offsets[Opcode] + OpIdx];\n";
  380. } else {
  381. OS << " llvm_unreachable(\"No instructions defined\");\n";
  382. }
  383. OS << "}\n";
  384. OS << "} // end namespace " << Namespace << "\n";
  385. OS << "} // end namespace llvm\n";
  386. OS << "#endif // GET_INSTRINFO_OPERAND_TYPE\n\n";
  387. }
  388. void InstrInfoEmitter::emitMCIIHelperMethods(raw_ostream &OS,
  389. StringRef TargetName) {
  390. RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
  391. if (TIIPredicates.empty())
  392. return;
  393. OS << "#ifdef GET_INSTRINFO_MC_HELPER_DECLS\n";
  394. OS << "#undef GET_INSTRINFO_MC_HELPER_DECLS\n\n";
  395. OS << "namespace llvm {\n";
  396. OS << "class MCInst;\n\n";
  397. OS << "namespace " << TargetName << "_MC {\n\n";
  398. for (const Record *Rec : TIIPredicates) {
  399. OS << "bool " << Rec->getValueAsString("FunctionName")
  400. << "(const MCInst &MI);\n";
  401. }
  402. OS << "\n} // end namespace " << TargetName << "_MC\n";
  403. OS << "} // end namespace llvm\n\n";
  404. OS << "#endif // GET_INSTRINFO_MC_HELPER_DECLS\n\n";
  405. OS << "#ifdef GET_INSTRINFO_MC_HELPERS\n";
  406. OS << "#undef GET_INSTRINFO_MC_HELPERS\n\n";
  407. OS << "namespace llvm {\n";
  408. OS << "namespace " << TargetName << "_MC {\n\n";
  409. PredicateExpander PE(TargetName);
  410. PE.setExpandForMC(true);
  411. for (const Record *Rec : TIIPredicates) {
  412. OS << "bool " << Rec->getValueAsString("FunctionName");
  413. OS << "(const MCInst &MI) {\n";
  414. OS.indent(PE.getIndentLevel() * 2);
  415. PE.expandStatement(OS, Rec->getValueAsDef("Body"));
  416. OS << "\n}\n\n";
  417. }
  418. OS << "} // end namespace " << TargetName << "_MC\n";
  419. OS << "} // end namespace llvm\n\n";
  420. OS << "#endif // GET_GENISTRINFO_MC_HELPERS\n";
  421. }
  422. void InstrInfoEmitter::emitTIIHelperMethods(raw_ostream &OS,
  423. StringRef TargetName,
  424. bool ExpandDefinition) {
  425. RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
  426. if (TIIPredicates.empty())
  427. return;
  428. PredicateExpander PE(TargetName);
  429. PE.setExpandForMC(false);
  430. for (const Record *Rec : TIIPredicates) {
  431. OS << (ExpandDefinition ? "" : "static ") << "bool ";
  432. if (ExpandDefinition)
  433. OS << TargetName << "InstrInfo::";
  434. OS << Rec->getValueAsString("FunctionName");
  435. OS << "(const MachineInstr &MI)";
  436. if (!ExpandDefinition) {
  437. OS << ";\n";
  438. continue;
  439. }
  440. OS << " {\n";
  441. OS.indent(PE.getIndentLevel() * 2);
  442. PE.expandStatement(OS, Rec->getValueAsDef("Body"));
  443. OS << "\n}\n\n";
  444. }
  445. }
  446. //===----------------------------------------------------------------------===//
  447. // Main Output.
  448. //===----------------------------------------------------------------------===//
  449. // run - Emit the main instruction description records for the target...
  450. void InstrInfoEmitter::run(raw_ostream &OS) {
  451. emitSourceFileHeader("Target Instruction Enum Values and Descriptors", OS);
  452. emitEnums(OS);
  453. OS << "#ifdef GET_INSTRINFO_MC_DESC\n";
  454. OS << "#undef GET_INSTRINFO_MC_DESC\n";
  455. OS << "namespace llvm {\n\n";
  456. CodeGenTarget &Target = CDP.getTargetInfo();
  457. const std::string &TargetName = std::string(Target.getName());
  458. Record *InstrInfo = Target.getInstructionSet();
  459. // Keep track of all of the def lists we have emitted already.
  460. std::map<std::vector<Record*>, unsigned> EmittedLists;
  461. unsigned ListNumber = 0;
  462. // Emit all of the instruction's implicit uses and defs.
  463. Records.startTimer("Emit uses/defs");
  464. for (const CodeGenInstruction *II : Target.getInstructionsByEnumValue()) {
  465. Record *Inst = II->TheDef;
  466. std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
  467. if (!Uses.empty()) {
  468. unsigned &IL = EmittedLists[Uses];
  469. if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
  470. }
  471. std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
  472. if (!Defs.empty()) {
  473. unsigned &IL = EmittedLists[Defs];
  474. if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
  475. }
  476. }
  477. OperandInfoMapTy OperandInfoIDs;
  478. // Emit all of the operand info records.
  479. Records.startTimer("Emit operand info");
  480. EmitOperandInfo(OS, OperandInfoIDs);
  481. // Emit all of the MCInstrDesc records in their ENUM ordering.
  482. //
  483. Records.startTimer("Emit InstrDesc records");
  484. OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
  485. ArrayRef<const CodeGenInstruction*> NumberedInstructions =
  486. Target.getInstructionsByEnumValue();
  487. SequenceToOffsetTable<std::string> InstrNames;
  488. unsigned Num = 0;
  489. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  490. // Keep a list of the instruction names.
  491. InstrNames.add(std::string(Inst->TheDef->getName()));
  492. // Emit the record into the table.
  493. emitRecord(*Inst, Num++, InstrInfo, EmittedLists, OperandInfoIDs, OS);
  494. }
  495. OS << "};\n\n";
  496. // Emit the array of instruction names.
  497. Records.startTimer("Emit instruction names");
  498. InstrNames.layout();
  499. InstrNames.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
  500. "InstrNameData[]");
  501. OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
  502. Num = 0;
  503. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  504. // Newline every eight entries.
  505. if (Num % 8 == 0)
  506. OS << "\n ";
  507. OS << InstrNames.get(std::string(Inst->TheDef->getName())) << "U, ";
  508. ++Num;
  509. }
  510. OS << "\n};\n\n";
  511. bool HasDeprecationFeatures =
  512. llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
  513. return !Inst->HasComplexDeprecationPredicate &&
  514. !Inst->DeprecatedReason.empty();
  515. });
  516. if (HasDeprecationFeatures) {
  517. OS << "extern const uint8_t " << TargetName
  518. << "InstrDeprecationFeatures[] = {";
  519. Num = 0;
  520. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  521. if (Num % 8 == 0)
  522. OS << "\n ";
  523. if (!Inst->HasComplexDeprecationPredicate &&
  524. !Inst->DeprecatedReason.empty())
  525. OS << Target.getInstNamespace() << "::" << Inst->DeprecatedReason
  526. << ", ";
  527. else
  528. OS << "uint8_t(-1), ";
  529. ++Num;
  530. }
  531. OS << "\n};\n\n";
  532. }
  533. bool HasComplexDeprecationInfos =
  534. llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
  535. return Inst->HasComplexDeprecationPredicate;
  536. });
  537. if (HasComplexDeprecationInfos) {
  538. OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
  539. << "InstrComplexDeprecationInfos[] = {";
  540. Num = 0;
  541. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  542. if (Num % 8 == 0)
  543. OS << "\n ";
  544. if (Inst->HasComplexDeprecationPredicate)
  545. // Emit a function pointer to the complex predicate method.
  546. OS << "&get" << Inst->DeprecatedReason << "DeprecationInfo, ";
  547. else
  548. OS << "nullptr, ";
  549. ++Num;
  550. }
  551. OS << "\n};\n\n";
  552. }
  553. // MCInstrInfo initialization routine.
  554. Records.startTimer("Emit initialization routine");
  555. OS << "static inline void Init" << TargetName
  556. << "MCInstrInfo(MCInstrInfo *II) {\n";
  557. OS << " II->InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
  558. << "InstrNameIndices, " << TargetName << "InstrNameData, ";
  559. if (HasDeprecationFeatures)
  560. OS << TargetName << "InstrDeprecationFeatures, ";
  561. else
  562. OS << "nullptr, ";
  563. if (HasComplexDeprecationInfos)
  564. OS << TargetName << "InstrComplexDeprecationInfos, ";
  565. else
  566. OS << "nullptr, ";
  567. OS << NumberedInstructions.size() << ");\n}\n\n";
  568. OS << "} // end namespace llvm\n";
  569. OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
  570. // Create a TargetInstrInfo subclass to hide the MC layer initialization.
  571. OS << "#ifdef GET_INSTRINFO_HEADER\n";
  572. OS << "#undef GET_INSTRINFO_HEADER\n";
  573. std::string ClassName = TargetName + "GenInstrInfo";
  574. OS << "namespace llvm {\n";
  575. OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
  576. << " explicit " << ClassName
  577. << "(int CFSetupOpcode = -1, int CFDestroyOpcode = -1, int CatchRetOpcode = -1, int ReturnOpcode = -1);\n"
  578. << " ~" << ClassName << "() override = default;\n";
  579. OS << "\n};\n} // end namespace llvm\n";
  580. OS << "#endif // GET_INSTRINFO_HEADER\n\n";
  581. OS << "#ifdef GET_INSTRINFO_HELPER_DECLS\n";
  582. OS << "#undef GET_INSTRINFO_HELPER_DECLS\n\n";
  583. emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */false);
  584. OS << "\n";
  585. OS << "#endif // GET_INSTRINFO_HELPER_DECLS\n\n";
  586. OS << "#ifdef GET_INSTRINFO_HELPERS\n";
  587. OS << "#undef GET_INSTRINFO_HELPERS\n\n";
  588. emitTIIHelperMethods(OS, TargetName, /* ExpandDefintion = */true);
  589. OS << "#endif // GET_INSTRINFO_HELPERS\n\n";
  590. OS << "#ifdef GET_INSTRINFO_CTOR_DTOR\n";
  591. OS << "#undef GET_INSTRINFO_CTOR_DTOR\n";
  592. OS << "namespace llvm {\n";
  593. OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
  594. OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
  595. OS << "extern const char " << TargetName << "InstrNameData[];\n";
  596. if (HasDeprecationFeatures)
  597. OS << "extern const uint8_t " << TargetName
  598. << "InstrDeprecationFeatures[];\n";
  599. if (HasComplexDeprecationInfos)
  600. OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
  601. << "InstrComplexDeprecationInfos[];\n";
  602. OS << ClassName << "::" << ClassName
  603. << "(int CFSetupOpcode, int CFDestroyOpcode, int CatchRetOpcode, int "
  604. "ReturnOpcode)\n"
  605. << " : TargetInstrInfo(CFSetupOpcode, CFDestroyOpcode, CatchRetOpcode, "
  606. "ReturnOpcode) {\n"
  607. << " InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
  608. << "InstrNameIndices, " << TargetName << "InstrNameData, ";
  609. if (HasDeprecationFeatures)
  610. OS << TargetName << "InstrDeprecationFeatures, ";
  611. else
  612. OS << "nullptr, ";
  613. if (HasComplexDeprecationInfos)
  614. OS << TargetName << "InstrComplexDeprecationInfos, ";
  615. else
  616. OS << "nullptr, ";
  617. OS << NumberedInstructions.size() << ");\n}\n";
  618. OS << "} // end namespace llvm\n";
  619. OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n";
  620. Records.startTimer("Emit operand name mappings");
  621. emitOperandNameMappings(OS, Target, NumberedInstructions);
  622. Records.startTimer("Emit operand type mappings");
  623. emitOperandTypeMappings(OS, Target, NumberedInstructions);
  624. Records.startTimer("Emit helper methods");
  625. emitMCIIHelperMethods(OS, TargetName);
  626. }
  627. void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
  628. Record *InstrInfo,
  629. std::map<std::vector<Record*>, unsigned> &EmittedLists,
  630. const OperandInfoMapTy &OpInfo,
  631. raw_ostream &OS) {
  632. int MinOperands = 0;
  633. if (!Inst.Operands.empty())
  634. // Each logical operand can be multiple MI operands.
  635. MinOperands = Inst.Operands.back().MIOperandNo +
  636. Inst.Operands.back().MINumOperands;
  637. OS << " { ";
  638. OS << Num << ",\t" << MinOperands << ",\t"
  639. << Inst.Operands.NumDefs << ",\t"
  640. << Inst.TheDef->getValueAsInt("Size") << ",\t"
  641. << SchedModels.getSchedClassIdx(Inst) << ",\t0";
  642. CodeGenTarget &Target = CDP.getTargetInfo();
  643. // Emit all of the target independent flags...
  644. if (Inst.isPreISelOpcode) OS << "|(1ULL<<MCID::PreISelOpcode)";
  645. if (Inst.isPseudo) OS << "|(1ULL<<MCID::Pseudo)";
  646. if (Inst.isReturn) OS << "|(1ULL<<MCID::Return)";
  647. if (Inst.isEHScopeReturn) OS << "|(1ULL<<MCID::EHScopeReturn)";
  648. if (Inst.isBranch) OS << "|(1ULL<<MCID::Branch)";
  649. if (Inst.isIndirectBranch) OS << "|(1ULL<<MCID::IndirectBranch)";
  650. if (Inst.isCompare) OS << "|(1ULL<<MCID::Compare)";
  651. if (Inst.isMoveImm) OS << "|(1ULL<<MCID::MoveImm)";
  652. if (Inst.isMoveReg) OS << "|(1ULL<<MCID::MoveReg)";
  653. if (Inst.isBitcast) OS << "|(1ULL<<MCID::Bitcast)";
  654. if (Inst.isAdd) OS << "|(1ULL<<MCID::Add)";
  655. if (Inst.isTrap) OS << "|(1ULL<<MCID::Trap)";
  656. if (Inst.isSelect) OS << "|(1ULL<<MCID::Select)";
  657. if (Inst.isBarrier) OS << "|(1ULL<<MCID::Barrier)";
  658. if (Inst.hasDelaySlot) OS << "|(1ULL<<MCID::DelaySlot)";
  659. if (Inst.isCall) OS << "|(1ULL<<MCID::Call)";
  660. if (Inst.canFoldAsLoad) OS << "|(1ULL<<MCID::FoldableAsLoad)";
  661. if (Inst.mayLoad) OS << "|(1ULL<<MCID::MayLoad)";
  662. if (Inst.mayStore) OS << "|(1ULL<<MCID::MayStore)";
  663. if (Inst.mayRaiseFPException) OS << "|(1ULL<<MCID::MayRaiseFPException)";
  664. if (Inst.isPredicable) OS << "|(1ULL<<MCID::Predicable)";
  665. if (Inst.isConvertibleToThreeAddress) OS << "|(1ULL<<MCID::ConvertibleTo3Addr)";
  666. if (Inst.isCommutable) OS << "|(1ULL<<MCID::Commutable)";
  667. if (Inst.isTerminator) OS << "|(1ULL<<MCID::Terminator)";
  668. if (Inst.isReMaterializable) OS << "|(1ULL<<MCID::Rematerializable)";
  669. if (Inst.isNotDuplicable) OS << "|(1ULL<<MCID::NotDuplicable)";
  670. if (Inst.Operands.hasOptionalDef) OS << "|(1ULL<<MCID::HasOptionalDef)";
  671. if (Inst.usesCustomInserter) OS << "|(1ULL<<MCID::UsesCustomInserter)";
  672. if (Inst.hasPostISelHook) OS << "|(1ULL<<MCID::HasPostISelHook)";
  673. if (Inst.Operands.isVariadic)OS << "|(1ULL<<MCID::Variadic)";
  674. if (Inst.hasSideEffects) OS << "|(1ULL<<MCID::UnmodeledSideEffects)";
  675. if (Inst.isAsCheapAsAMove) OS << "|(1ULL<<MCID::CheapAsAMove)";
  676. if (!Target.getAllowRegisterRenaming() || Inst.hasExtraSrcRegAllocReq)
  677. OS << "|(1ULL<<MCID::ExtraSrcRegAllocReq)";
  678. if (!Target.getAllowRegisterRenaming() || Inst.hasExtraDefRegAllocReq)
  679. OS << "|(1ULL<<MCID::ExtraDefRegAllocReq)";
  680. if (Inst.isRegSequence) OS << "|(1ULL<<MCID::RegSequence)";
  681. if (Inst.isExtractSubreg) OS << "|(1ULL<<MCID::ExtractSubreg)";
  682. if (Inst.isInsertSubreg) OS << "|(1ULL<<MCID::InsertSubreg)";
  683. if (Inst.isConvergent) OS << "|(1ULL<<MCID::Convergent)";
  684. if (Inst.variadicOpsAreDefs) OS << "|(1ULL<<MCID::VariadicOpsAreDefs)";
  685. if (Inst.isAuthenticated) OS << "|(1ULL<<MCID::Authenticated)";
  686. // Emit all of the target-specific flags...
  687. BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
  688. if (!TSF)
  689. PrintFatalError(Inst.TheDef->getLoc(), "no TSFlags?");
  690. uint64_t Value = 0;
  691. for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
  692. if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
  693. Value |= uint64_t(Bit->getValue()) << i;
  694. else
  695. PrintFatalError(Inst.TheDef->getLoc(),
  696. "Invalid TSFlags bit in " + Inst.TheDef->getName());
  697. }
  698. OS << ", 0x";
  699. OS.write_hex(Value);
  700. OS << "ULL, ";
  701. // Emit the implicit uses and defs lists...
  702. std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
  703. if (UseList.empty())
  704. OS << "nullptr, ";
  705. else
  706. OS << "ImplicitList" << EmittedLists[UseList] << ", ";
  707. std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
  708. if (DefList.empty())
  709. OS << "nullptr, ";
  710. else
  711. OS << "ImplicitList" << EmittedLists[DefList] << ", ";
  712. // Emit the operand info.
  713. std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
  714. if (OperandInfo.empty())
  715. OS << "nullptr";
  716. else
  717. OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
  718. OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
  719. }
  720. // emitEnums - Print out enum values for all of the instructions.
  721. void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
  722. OS << "#ifdef GET_INSTRINFO_ENUM\n";
  723. OS << "#undef GET_INSTRINFO_ENUM\n";
  724. OS << "namespace llvm {\n\n";
  725. const CodeGenTarget &Target = CDP.getTargetInfo();
  726. // We must emit the PHI opcode first...
  727. StringRef Namespace = Target.getInstNamespace();
  728. if (Namespace.empty())
  729. PrintFatalError("No instructions defined!");
  730. OS << "namespace " << Namespace << " {\n";
  731. OS << " enum {\n";
  732. unsigned Num = 0;
  733. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue())
  734. OS << " " << Inst->TheDef->getName() << "\t= " << Num++ << ",\n";
  735. OS << " INSTRUCTION_LIST_END = " << Num << "\n";
  736. OS << " };\n\n";
  737. OS << "} // end namespace " << Namespace << "\n";
  738. OS << "} // end namespace llvm\n";
  739. OS << "#endif // GET_INSTRINFO_ENUM\n\n";
  740. OS << "#ifdef GET_INSTRINFO_SCHED_ENUM\n";
  741. OS << "#undef GET_INSTRINFO_SCHED_ENUM\n";
  742. OS << "namespace llvm {\n\n";
  743. OS << "namespace " << Namespace << " {\n";
  744. OS << "namespace Sched {\n";
  745. OS << " enum {\n";
  746. Num = 0;
  747. for (const auto &Class : SchedModels.explicit_classes())
  748. OS << " " << Class.Name << "\t= " << Num++ << ",\n";
  749. OS << " SCHED_LIST_END = " << Num << "\n";
  750. OS << " };\n";
  751. OS << "} // end namespace Sched\n";
  752. OS << "} // end namespace " << Namespace << "\n";
  753. OS << "} // end namespace llvm\n";
  754. OS << "#endif // GET_INSTRINFO_SCHED_ENUM\n\n";
  755. }
  756. namespace llvm {
  757. void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
  758. RK.startTimer("Analyze DAG patterns");
  759. InstrInfoEmitter(RK).run(OS);
  760. RK.startTimer("Emit map table");
  761. EmitMapTable(RK, OS);
  762. }
  763. } // end namespace llvm