1 //===- DFAPacketizerEmitter.cpp - Packetization DFA for a VLIW machine-----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class parses the Schedule.td file and produces an API that can be used
11 // to reason about whether an instruction can be added to a packet on a VLIW
12 // architecture. The class internally generates a deterministic finite
13 // automaton (DFA) that models all possible mappings of machine instructions
14 // to functional units as instructions are added to a packet.
16 //===----------------------------------------------------------------------===//
18 #include "CodeGenTarget.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/TableGen/Record.h"
22 #include "llvm/TableGen/TableGenBackend.h"
29 // class DFAPacketizerEmitter: class that generates and prints out the DFA
30 // for resource tracking.
33 class DFAPacketizerEmitter {
35 std::string TargetName;
37 // allInsnClasses is the set of all possible resources consumed by an
40 DenseSet<unsigned> allInsnClasses;
41 RecordKeeper &Records;
44 DFAPacketizerEmitter(RecordKeeper &R);
47 // collectAllInsnClasses: Populate allInsnClasses which is a set of units
48 // used in each stage.
50 void collectAllInsnClasses(const std::string &Name,
55 void run(raw_ostream &OS);
57 } // End anonymous namespace.
61 // State represents the usage of machine resources if the packet contains
62 // a set of instruction classes.
64 // Specifically, currentState is a set of bit-masks.
65 // The nth bit in a bit-mask indicates whether the nth resource is being used
66 // by this state. The set of bit-masks in a state represent the different
67 // possible outcomes of transitioning to this state.
68 // For example: consider a two resource architecture: resource L and resource M
69 // with three instruction classes: L, M, and L_or_M.
70 // From the initial state (currentState = 0x00), if we add instruction class
71 // L_or_M we will transition to a state with currentState = [0x01, 0x10]. This
72 // represents the possible resource states that can result from adding a L_or_M
75 // Another way of thinking about this transition is we are mapping a NDFA with
76 // two states [0x01] and [0x10] into a DFA with a single state [0x01, 0x10].
78 // A State instance also contains a collection of transitions from that state:
79 // a map from inputs to new states.
84 static int currentStateNum;
85 // stateNum is the only member used for equality/ordering, all other members
86 // can be mutated even in const State objects.
88 mutable bool isInitial;
89 mutable std::set<unsigned> stateInfo;
90 typedef std::map<unsigned, const State *> TransitionMap;
91 mutable TransitionMap Transitions;
95 bool operator<(const State &s) const {
96 return stateNum < s.stateNum;
100 // canAddInsnClass - Returns true if an instruction of type InsnClass is a
101 // valid transition from this state, i.e., can an instruction of type InsnClass
102 // be added to the packet represented by this state.
104 // PossibleStates is the set of valid resource states that ensue from valid
107 bool canAddInsnClass(unsigned InsnClass) const;
109 // AddInsnClass - Return all combinations of resource reservation
110 // which are possible from this state (PossibleStates).
112 void AddInsnClass(unsigned InsnClass, std::set<unsigned> &PossibleStates) const;
114 // addTransition - Add a transition from this state given the input InsnClass
116 void addTransition(unsigned InsnClass, const State *To) const;
118 // hasTransition - Returns true if there is a transition from this state
119 // given the input InsnClass
121 bool hasTransition(unsigned InsnClass) const;
123 } // End anonymous namespace.
126 // class DFA: deterministic finite automaton for processor resource tracking.
133 // Set of states. Need to keep this sorted to emit the transition table.
134 typedef std::set<State> StateSet;
142 const State &newState();
145 // writeTable: Print out a table representing the DFA.
147 void writeTableAndAPI(raw_ostream &OS, const std::string &ClassName);
149 } // End anonymous namespace.
153 // Constructors and destructors for State and DFA
156 stateNum(currentStateNum++), isInitial(false) {}
158 DFA::DFA(): currentState(nullptr) {}
161 // addTransition - Add a transition from this state given the input InsnClass
163 void State::addTransition(unsigned InsnClass, const State *To) const {
164 assert(!Transitions.count(InsnClass) &&
165 "Cannot have multiple transitions for the same input");
166 Transitions[InsnClass] = To;
170 // hasTransition - Returns true if there is a transition from this state
171 // given the input InsnClass
173 bool State::hasTransition(unsigned InsnClass) const {
174 return Transitions.count(InsnClass) > 0;
178 // AddInsnClass - Return all combinations of resource reservation
179 // which are possible from this state (PossibleStates).
181 void State::AddInsnClass(unsigned InsnClass,
182 std::set<unsigned> &PossibleStates) const {
184 // Iterate over all resource states in currentState.
187 for (std::set<unsigned>::iterator SI = stateInfo.begin();
188 SI != stateInfo.end(); ++SI) {
189 unsigned thisState = *SI;
192 // Iterate over all possible resources used in InsnClass.
193 // For ex: for InsnClass = 0x11, all resources = {0x01, 0x10}.
196 DenseSet<unsigned> VisitedResourceStates;
197 for (unsigned int j = 0; j < sizeof(InsnClass) * 8; ++j) {
198 if ((0x1 << j) & InsnClass) {
200 // For each possible resource used in InsnClass, generate the
201 // resource state if that resource was used.
203 unsigned ResultingResourceState = thisState | (0x1 << j);
205 // Check if the resulting resource state can be accommodated in this
207 // We compute ResultingResourceState OR thisState.
208 // If the result of the OR is different than thisState, it implies
209 // that there is at least one resource that can be used to schedule
210 // InsnClass in the current packet.
211 // Insert ResultingResourceState into PossibleStates only if we haven't
212 // processed ResultingResourceState before.
214 if ((ResultingResourceState != thisState) &&
215 (VisitedResourceStates.count(ResultingResourceState) == 0)) {
216 VisitedResourceStates.insert(ResultingResourceState);
217 PossibleStates.insert(ResultingResourceState);
227 // canAddInsnClass - Quickly verifies if an instruction of type InsnClass is a
228 // valid transition from this state i.e., can an instruction of type InsnClass
229 // be added to the packet represented by this state.
231 bool State::canAddInsnClass(unsigned InsnClass) const {
232 for (std::set<unsigned>::const_iterator SI = stateInfo.begin();
233 SI != stateInfo.end(); ++SI) {
234 if (~*SI & InsnClass)
241 const State &DFA::newState() {
242 auto IterPair = states.insert(State());
243 assert(IterPair.second && "State already exists");
244 return *IterPair.first;
248 int State::currentStateNum = 0;
250 DFAPacketizerEmitter::DFAPacketizerEmitter(RecordKeeper &R):
251 TargetName(CodeGenTarget(R).getName()),
252 allInsnClasses(), Records(R) {}
256 // writeTableAndAPI - Print out a table representing the DFA and the
257 // associated API to create a DFA packetizer.
260 // DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid
262 // DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable for
266 void DFA::writeTableAndAPI(raw_ostream &OS, const std::string &TargetName) {
267 static const std::string SentinelEntry = "{-1, -1}";
268 DFA::StateSet::iterator SI = states.begin();
269 // This table provides a map to the beginning of the transitions for State s
270 // in DFAStateInputTable.
271 std::vector<int> StateEntry(states.size());
273 OS << "namespace llvm {\n\n";
274 OS << "const int " << TargetName << "DFAStateInputTable[][2] = {\n";
276 // Tracks the total valid transitions encountered so far. It is used
277 // to construct the StateEntry table.
278 int ValidTransitions = 0;
279 for (unsigned i = 0; i < states.size(); ++i, ++SI) {
280 assert ((SI->stateNum == (int) i) && "Mismatch in state numbers");
281 StateEntry[i] = ValidTransitions;
282 for (State::TransitionMap::iterator
283 II = SI->Transitions.begin(), IE = SI->Transitions.end();
285 OS << "{" << II->first << ", "
286 << II->second->stateNum
289 ValidTransitions += SI->Transitions.size();
291 // If there are no valid transitions from this stage, we need a sentinel
293 if (ValidTransitions == StateEntry[i]) {
294 OS << SentinelEntry << ",";
301 // Print out a sentinel entry at the end of the StateInputTable. This is
302 // needed to iterate over StateInputTable in DFAPacketizer::ReadTable()
303 OS << SentinelEntry << "\n";
306 OS << "const unsigned int " << TargetName << "DFAStateEntryTable[] = {\n";
308 // Multiply i by 2 since each entry in DFAStateInputTable is a set of
310 for (unsigned i = 0; i < states.size(); ++i)
311 OS << StateEntry[i] << ", ";
313 // Print out the index to the sentinel entry in StateInputTable
314 OS << ValidTransitions << ", ";
317 OS << "} // namespace\n";
321 // Emit DFA Packetizer tables if the target is a VLIW machine.
323 std::string SubTargetClassName = TargetName + "GenSubtargetInfo";
324 OS << "\n" << "#include \"llvm/CodeGen/DFAPacketizer.h\"\n";
325 OS << "namespace llvm {\n";
326 OS << "DFAPacketizer *" << SubTargetClassName << "::"
327 << "createDFAPacketizer(const InstrItineraryData *IID) const {\n"
328 << " return new DFAPacketizer(IID, " << TargetName
329 << "DFAStateInputTable, " << TargetName << "DFAStateEntryTable);\n}\n\n";
330 OS << "} // End llvm namespace \n";
335 // collectAllInsnClasses - Populate allInsnClasses which is a set of units
336 // used in each stage.
338 void DFAPacketizerEmitter::collectAllInsnClasses(const std::string &Name,
342 // Collect processor itineraries.
343 std::vector<Record*> ProcItinList =
344 Records.getAllDerivedDefinitions("ProcessorItineraries");
346 // If just no itinerary then don't bother.
347 if (ProcItinList.size() < 2)
349 std::map<std::string, unsigned> NameToBitsMap;
351 // Parse functional units for all the itineraries.
352 for (unsigned i = 0, N = ProcItinList.size(); i < N; ++i) {
353 Record *Proc = ProcItinList[i];
354 std::vector<Record*> FUs = Proc->getValueAsListOfDefs("FU");
356 // Convert macros to bits for each stage.
357 for (unsigned i = 0, N = FUs.size(); i < N; ++i)
358 NameToBitsMap[FUs[i]->getName()] = (unsigned) (1U << i);
361 const std::vector<Record*> &StageList =
362 ItinData->getValueAsListOfDefs("Stages");
364 // The number of stages.
365 NStages = StageList.size();
368 unsigned UnitBitValue = 0;
370 // Compute the bitwise or of each unit used in this stage.
371 for (unsigned i = 0; i < NStages; ++i) {
372 const Record *Stage = StageList[i];
375 const std::vector<Record*> &UnitList =
376 Stage->getValueAsListOfDefs("Units");
378 for (unsigned j = 0, M = UnitList.size(); j < M; ++j) {
379 // Conduct bitwise or.
380 std::string UnitName = UnitList[j]->getName();
381 assert(NameToBitsMap.count(UnitName));
382 UnitBitValue |= NameToBitsMap[UnitName];
385 if (UnitBitValue != 0)
386 allInsnClasses.insert(UnitBitValue);
392 // Run the worklist algorithm to generate the DFA.
394 void DFAPacketizerEmitter::run(raw_ostream &OS) {
396 // Collect processor iteraries.
397 std::vector<Record*> ProcItinList =
398 Records.getAllDerivedDefinitions("ProcessorItineraries");
401 // Collect the instruction classes.
403 for (unsigned i = 0, N = ProcItinList.size(); i < N; i++) {
404 Record *Proc = ProcItinList[i];
406 // Get processor itinerary name.
407 const std::string &Name = Proc->getName();
410 if (Name == "NoItineraries")
413 // Sanity check for at least one instruction itinerary class.
414 unsigned NItinClasses =
415 Records.getAllDerivedDefinitions("InstrItinClass").size();
416 if (NItinClasses == 0)
419 // Get itinerary data list.
420 std::vector<Record*> ItinDataList = Proc->getValueAsListOfDefs("IID");
422 // Collect instruction classes for all itinerary data.
423 for (unsigned j = 0, M = ItinDataList.size(); j < M; j++) {
424 Record *ItinData = ItinDataList[j];
426 collectAllInsnClasses(Name, ItinData, NStages, OS);
432 // Run a worklist algorithm to generate the DFA.
435 const State *Initial = &D.newState();
436 Initial->isInitial = true;
437 Initial->stateInfo.insert(0x0);
438 SmallVector<const State*, 32> WorkList;
439 std::map<std::set<unsigned>, const State*> Visited;
441 WorkList.push_back(Initial);
444 // Worklist algorithm to create a DFA for processor resource tracking.
445 // C = {set of InsnClasses}
446 // Begin with initial node in worklist. Initial node does not have
447 // any consumed resources,
448 // ResourceState = 0x0
450 // While worklist != empty
451 // S = first element of worklist
452 // For every instruction class C
453 // if we can accommodate C in S:
454 // S' = state with resource states = {S Union C}
455 // Add a new transition: S x C -> S'
456 // If S' is not in Visited:
457 // Add S' to worklist
460 while (!WorkList.empty()) {
461 const State *current = WorkList.pop_back_val();
462 for (DenseSet<unsigned>::iterator CI = allInsnClasses.begin(),
463 CE = allInsnClasses.end(); CI != CE; ++CI) {
464 unsigned InsnClass = *CI;
466 std::set<unsigned> NewStateResources;
468 // If we haven't already created a transition for this input
469 // and the state can accommodate this InsnClass, create a transition.
471 if (!current->hasTransition(InsnClass) &&
472 current->canAddInsnClass(InsnClass)) {
473 const State *NewState;
474 current->AddInsnClass(InsnClass, NewStateResources);
475 assert(!NewStateResources.empty() && "New states must be generated");
478 // If we have seen this state before, then do not create a new state.
481 auto VI = Visited.find(NewStateResources);
482 if (VI != Visited.end())
483 NewState = VI->second;
485 NewState = &D.newState();
486 NewState->stateInfo = NewStateResources;
487 Visited[NewStateResources] = NewState;
488 WorkList.push_back(NewState);
491 current->addTransition(InsnClass, NewState);
496 // Print out the table.
497 D.writeTableAndAPI(OS, TargetName);
502 void EmitDFAPacketizer(RecordKeeper &RK, raw_ostream &OS) {
503 emitSourceFileHeader("Target DFA Packetizer Tables", OS);
504 DFAPacketizerEmitter(RK).run(OS);
507 } // End llvm namespace