DFAPacketizerEmitter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //===- DFAPacketizerEmitter.cpp - Packetization DFA for a VLIW machine ----===//
  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 class parses the Schedule.td file and produces an API that can be used
  10. // to reason about whether an instruction can be added to a packet on a VLIW
  11. // architecture. The class internally generates a deterministic finite
  12. // automaton (DFA) that models all possible mappings of machine instructions
  13. // to functional units as instructions are added to a packet.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "CodeGenSchedule.h"
  17. #include "CodeGenTarget.h"
  18. #include "DFAEmitter.h"
  19. #include "llvm/ADT/DenseSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/TableGen/Record.h"
  25. #include "llvm/TableGen/TableGenBackend.h"
  26. #include <cassert>
  27. #include <cstdint>
  28. #include <map>
  29. #include <set>
  30. #include <string>
  31. #include <unordered_map>
  32. #include <vector>
  33. #define DEBUG_TYPE "dfa-emitter"
  34. using namespace llvm;
  35. // We use a uint64_t to represent a resource bitmask.
  36. #define DFA_MAX_RESOURCES 64
  37. namespace {
  38. using ResourceVector = SmallVector<uint64_t, 4>;
  39. struct ScheduleClass {
  40. /// The parent itinerary index (processor model ID).
  41. unsigned ItineraryID;
  42. /// Index within this itinerary of the schedule class.
  43. unsigned Idx;
  44. /// The index within the uniqued set of required resources of Resources.
  45. unsigned ResourcesIdx;
  46. /// Conjunctive list of resource requirements:
  47. /// {a|b, b|c} => (a OR b) AND (b or c).
  48. /// Resources are unique across all itineraries.
  49. ResourceVector Resources;
  50. };
  51. // Generates and prints out the DFA for resource tracking.
  52. class DFAPacketizerEmitter {
  53. private:
  54. std::string TargetName;
  55. RecordKeeper &Records;
  56. UniqueVector<ResourceVector> UniqueResources;
  57. std::vector<ScheduleClass> ScheduleClasses;
  58. std::map<std::string, uint64_t> FUNameToBitsMap;
  59. std::map<unsigned, uint64_t> ComboBitToBitsMap;
  60. public:
  61. DFAPacketizerEmitter(RecordKeeper &R);
  62. // Construct a map of function unit names to bits.
  63. int collectAllFuncUnits(
  64. ArrayRef<const CodeGenProcModel *> ProcModels);
  65. // Construct a map from a combo function unit bit to the bits of all included
  66. // functional units.
  67. int collectAllComboFuncs(ArrayRef<Record *> ComboFuncList);
  68. ResourceVector getResourcesForItinerary(Record *Itinerary);
  69. void createScheduleClasses(unsigned ItineraryIdx, const RecVec &Itineraries);
  70. // Emit code for a subset of itineraries.
  71. void emitForItineraries(raw_ostream &OS,
  72. std::vector<const CodeGenProcModel *> &ProcItinList,
  73. std::string DFAName);
  74. void run(raw_ostream &OS);
  75. };
  76. } // end anonymous namespace
  77. DFAPacketizerEmitter::DFAPacketizerEmitter(RecordKeeper &R)
  78. : TargetName(std::string(CodeGenTarget(R).getName())), Records(R) {}
  79. int DFAPacketizerEmitter::collectAllFuncUnits(
  80. ArrayRef<const CodeGenProcModel *> ProcModels) {
  81. LLVM_DEBUG(dbgs() << "-------------------------------------------------------"
  82. "----------------------\n");
  83. LLVM_DEBUG(dbgs() << "collectAllFuncUnits");
  84. LLVM_DEBUG(dbgs() << " (" << ProcModels.size() << " itineraries)\n");
  85. std::set<Record *> ProcItinList;
  86. for (const CodeGenProcModel *Model : ProcModels)
  87. ProcItinList.insert(Model->ItinsDef);
  88. int totalFUs = 0;
  89. // Parse functional units for all the itineraries.
  90. for (Record *Proc : ProcItinList) {
  91. std::vector<Record *> FUs = Proc->getValueAsListOfDefs("FU");
  92. LLVM_DEBUG(dbgs() << " FU:"
  93. << " (" << FUs.size() << " FUs) " << Proc->getName());
  94. // Convert macros to bits for each stage.
  95. unsigned numFUs = FUs.size();
  96. for (unsigned j = 0; j < numFUs; ++j) {
  97. assert((j < DFA_MAX_RESOURCES) &&
  98. "Exceeded maximum number of representable resources");
  99. uint64_t FuncResources = 1ULL << j;
  100. FUNameToBitsMap[std::string(FUs[j]->getName())] = FuncResources;
  101. LLVM_DEBUG(dbgs() << " " << FUs[j]->getName() << ":0x"
  102. << Twine::utohexstr(FuncResources));
  103. }
  104. totalFUs += numFUs;
  105. LLVM_DEBUG(dbgs() << "\n");
  106. }
  107. return totalFUs;
  108. }
  109. int DFAPacketizerEmitter::collectAllComboFuncs(ArrayRef<Record *> ComboFuncList) {
  110. LLVM_DEBUG(dbgs() << "-------------------------------------------------------"
  111. "----------------------\n");
  112. LLVM_DEBUG(dbgs() << "collectAllComboFuncs");
  113. LLVM_DEBUG(dbgs() << " (" << ComboFuncList.size() << " sets)\n");
  114. int numCombos = 0;
  115. for (unsigned i = 0, N = ComboFuncList.size(); i < N; ++i) {
  116. Record *Func = ComboFuncList[i];
  117. std::vector<Record *> FUs = Func->getValueAsListOfDefs("CFD");
  118. LLVM_DEBUG(dbgs() << " CFD:" << i << " (" << FUs.size() << " combo FUs) "
  119. << Func->getName() << "\n");
  120. // Convert macros to bits for each stage.
  121. for (unsigned j = 0, N = FUs.size(); j < N; ++j) {
  122. assert((j < DFA_MAX_RESOURCES) &&
  123. "Exceeded maximum number of DFA resources");
  124. Record *FuncData = FUs[j];
  125. Record *ComboFunc = FuncData->getValueAsDef("TheComboFunc");
  126. const std::vector<Record *> &FuncList =
  127. FuncData->getValueAsListOfDefs("FuncList");
  128. const std::string &ComboFuncName = std::string(ComboFunc->getName());
  129. uint64_t ComboBit = FUNameToBitsMap[ComboFuncName];
  130. uint64_t ComboResources = ComboBit;
  131. LLVM_DEBUG(dbgs() << " combo: " << ComboFuncName << ":0x"
  132. << Twine::utohexstr(ComboResources) << "\n");
  133. for (auto *K : FuncList) {
  134. std::string FuncName = std::string(K->getName());
  135. uint64_t FuncResources = FUNameToBitsMap[FuncName];
  136. LLVM_DEBUG(dbgs() << " " << FuncName << ":0x"
  137. << Twine::utohexstr(FuncResources) << "\n");
  138. ComboResources |= FuncResources;
  139. }
  140. ComboBitToBitsMap[ComboBit] = ComboResources;
  141. numCombos++;
  142. LLVM_DEBUG(dbgs() << " => combo bits: " << ComboFuncName << ":0x"
  143. << Twine::utohexstr(ComboBit) << " = 0x"
  144. << Twine::utohexstr(ComboResources) << "\n");
  145. }
  146. }
  147. return numCombos;
  148. }
  149. ResourceVector
  150. DFAPacketizerEmitter::getResourcesForItinerary(Record *Itinerary) {
  151. ResourceVector Resources;
  152. assert(Itinerary);
  153. for (Record *StageDef : Itinerary->getValueAsListOfDefs("Stages")) {
  154. uint64_t StageResources = 0;
  155. for (Record *Unit : StageDef->getValueAsListOfDefs("Units")) {
  156. StageResources |= FUNameToBitsMap[std::string(Unit->getName())];
  157. }
  158. if (StageResources != 0)
  159. Resources.push_back(StageResources);
  160. }
  161. return Resources;
  162. }
  163. void DFAPacketizerEmitter::createScheduleClasses(unsigned ItineraryIdx,
  164. const RecVec &Itineraries) {
  165. unsigned Idx = 0;
  166. for (Record *Itinerary : Itineraries) {
  167. if (!Itinerary) {
  168. ScheduleClasses.push_back({ItineraryIdx, Idx++, 0, ResourceVector{}});
  169. continue;
  170. }
  171. ResourceVector Resources = getResourcesForItinerary(Itinerary);
  172. ScheduleClasses.push_back(
  173. {ItineraryIdx, Idx++, UniqueResources.insert(Resources), Resources});
  174. }
  175. }
  176. //
  177. // Run the worklist algorithm to generate the DFA.
  178. //
  179. void DFAPacketizerEmitter::run(raw_ostream &OS) {
  180. OS << "\n"
  181. << "#include \"llvm/CodeGen/DFAPacketizer.h\"\n";
  182. OS << "namespace llvm {\n";
  183. CodeGenTarget CGT(Records);
  184. CodeGenSchedModels CGS(Records, CGT);
  185. std::unordered_map<std::string, std::vector<const CodeGenProcModel *>>
  186. ItinsByNamespace;
  187. for (const CodeGenProcModel &ProcModel : CGS.procModels()) {
  188. if (ProcModel.hasItineraries()) {
  189. auto NS = ProcModel.ItinsDef->getValueAsString("PacketizerNamespace");
  190. ItinsByNamespace[std::string(NS)].push_back(&ProcModel);
  191. }
  192. }
  193. for (auto &KV : ItinsByNamespace)
  194. emitForItineraries(OS, KV.second, KV.first);
  195. OS << "} // end namespace llvm\n";
  196. }
  197. void DFAPacketizerEmitter::emitForItineraries(
  198. raw_ostream &OS, std::vector<const CodeGenProcModel *> &ProcModels,
  199. std::string DFAName) {
  200. OS << "} // end namespace llvm\n\n";
  201. OS << "namespace {\n";
  202. collectAllFuncUnits(ProcModels);
  203. collectAllComboFuncs(Records.getAllDerivedDefinitions("ComboFuncUnits"));
  204. // Collect the itineraries.
  205. DenseMap<const CodeGenProcModel *, unsigned> ProcModelStartIdx;
  206. for (const CodeGenProcModel *Model : ProcModels) {
  207. assert(Model->hasItineraries());
  208. ProcModelStartIdx[Model] = ScheduleClasses.size();
  209. createScheduleClasses(Model->Index, Model->ItinDefList);
  210. }
  211. // Output the mapping from ScheduleClass to ResourcesIdx.
  212. unsigned Idx = 0;
  213. OS << "constexpr unsigned " << TargetName << DFAName
  214. << "ResourceIndices[] = {";
  215. for (const ScheduleClass &SC : ScheduleClasses) {
  216. if (Idx++ % 32 == 0)
  217. OS << "\n ";
  218. OS << SC.ResourcesIdx << ", ";
  219. }
  220. OS << "\n};\n\n";
  221. // And the mapping from Itinerary index into the previous table.
  222. OS << "constexpr unsigned " << TargetName << DFAName
  223. << "ProcResourceIndexStart[] = {\n";
  224. OS << " 0, // NoSchedModel\n";
  225. for (const CodeGenProcModel *Model : ProcModels) {
  226. OS << " " << ProcModelStartIdx[Model] << ", // " << Model->ModelName
  227. << "\n";
  228. }
  229. OS << " " << ScheduleClasses.size() << "\n};\n\n";
  230. // The type of a state in the nondeterministic automaton we're defining.
  231. using NfaStateTy = uint64_t;
  232. // Given a resource state, return all resource states by applying
  233. // InsnClass.
  234. auto applyInsnClass = [&](const ResourceVector &InsnClass,
  235. NfaStateTy State) -> std::deque<NfaStateTy> {
  236. std::deque<NfaStateTy> V(1, State);
  237. // Apply every stage in the class individually.
  238. for (NfaStateTy Stage : InsnClass) {
  239. // Apply this stage to every existing member of V in turn.
  240. size_t Sz = V.size();
  241. for (unsigned I = 0; I < Sz; ++I) {
  242. NfaStateTy S = V.front();
  243. V.pop_front();
  244. // For this stage, state combination, try all possible resources.
  245. for (unsigned J = 0; J < DFA_MAX_RESOURCES; ++J) {
  246. NfaStateTy ResourceMask = 1ULL << J;
  247. if ((ResourceMask & Stage) == 0)
  248. // This resource isn't required by this stage.
  249. continue;
  250. NfaStateTy Combo = ComboBitToBitsMap[ResourceMask];
  251. if (Combo && ((~S & Combo) != Combo))
  252. // This combo units bits are not available.
  253. continue;
  254. NfaStateTy ResultingResourceState = S | ResourceMask | Combo;
  255. if (ResultingResourceState == S)
  256. continue;
  257. V.push_back(ResultingResourceState);
  258. }
  259. }
  260. }
  261. return V;
  262. };
  263. // Given a resource state, return a quick (conservative) guess as to whether
  264. // InsnClass can be applied. This is a filter for the more heavyweight
  265. // applyInsnClass.
  266. auto canApplyInsnClass = [](const ResourceVector &InsnClass,
  267. NfaStateTy State) -> bool {
  268. for (NfaStateTy Resources : InsnClass) {
  269. if ((State | Resources) == State)
  270. return false;
  271. }
  272. return true;
  273. };
  274. DfaEmitter Emitter;
  275. std::deque<NfaStateTy> Worklist(1, 0);
  276. std::set<NfaStateTy> SeenStates;
  277. SeenStates.insert(Worklist.front());
  278. while (!Worklist.empty()) {
  279. NfaStateTy State = Worklist.front();
  280. Worklist.pop_front();
  281. for (const ResourceVector &Resources : UniqueResources) {
  282. if (!canApplyInsnClass(Resources, State))
  283. continue;
  284. unsigned ResourcesID = UniqueResources.idFor(Resources);
  285. for (uint64_t NewState : applyInsnClass(Resources, State)) {
  286. if (SeenStates.emplace(NewState).second)
  287. Worklist.emplace_back(NewState);
  288. Emitter.addTransition(State, NewState, ResourcesID);
  289. }
  290. }
  291. }
  292. std::string TargetAndDFAName = TargetName + DFAName;
  293. Emitter.emit(TargetAndDFAName, OS);
  294. OS << "} // end anonymous namespace\n\n";
  295. std::string SubTargetClassName = TargetName + "GenSubtargetInfo";
  296. OS << "namespace llvm {\n";
  297. OS << "DFAPacketizer *" << SubTargetClassName << "::"
  298. << "create" << DFAName
  299. << "DFAPacketizer(const InstrItineraryData *IID) const {\n"
  300. << " static Automaton<uint64_t> A(ArrayRef<" << TargetAndDFAName
  301. << "Transition>(" << TargetAndDFAName << "Transitions), "
  302. << TargetAndDFAName << "TransitionInfo);\n"
  303. << " unsigned ProcResIdxStart = " << TargetAndDFAName
  304. << "ProcResourceIndexStart[IID->SchedModel.ProcID];\n"
  305. << " unsigned ProcResIdxNum = " << TargetAndDFAName
  306. << "ProcResourceIndexStart[IID->SchedModel.ProcID + 1] - "
  307. "ProcResIdxStart;\n"
  308. << " return new DFAPacketizer(IID, A, {&" << TargetAndDFAName
  309. << "ResourceIndices[ProcResIdxStart], ProcResIdxNum});\n"
  310. << "\n}\n\n";
  311. }
  312. namespace llvm {
  313. void EmitDFAPacketizer(RecordKeeper &RK, raw_ostream &OS) {
  314. emitSourceFileHeader("Target DFA Packetizer Tables", OS);
  315. DFAPacketizerEmitter(RK).run(OS);
  316. }
  317. } // end namespace llvm