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;
94 State(const State &S);
96 bool operator<(const State &s) const {
97 return stateNum < s.stateNum;
101 // canAddInsnClass - Returns true if an instruction of type InsnClass is a
102 // valid transition from this state, i.e., can an instruction of type InsnClass
103 // be added to the packet represented by this state.
105 // PossibleStates is the set of valid resource states that ensue from valid
108 bool canAddInsnClass(unsigned InsnClass) const;
110 // AddInsnClass - Return all combinations of resource reservation
111 // which are possible from this state (PossibleStates).
113 void AddInsnClass(unsigned InsnClass, std::set<unsigned> &PossibleStates) const;
115 // addTransition - Add a transition from this state given the input InsnClass
117 void addTransition(unsigned InsnClass, const State *To) const;
119 // hasTransition - Returns true if there is a transition from this state
120 // given the input InsnClass
122 bool hasTransition(unsigned InsnClass) const;
124 } // End anonymous namespace.
127 // class DFA: deterministic finite automaton for processor resource tracking.
134 // Set of states. Need to keep this sorted to emit the transition table.
135 typedef std::set<State> StateSet;
143 const State &newState();
146 // writeTable: Print out a table representing the DFA.
148 void writeTableAndAPI(raw_ostream &OS, const std::string &ClassName);
150 } // End anonymous namespace.
154 // Constructors and destructors for State and DFA
157 stateNum(currentStateNum++), isInitial(false) {}
160 State::State(const State &S) :
161 stateNum(currentStateNum++), isInitial(S.isInitial),
162 stateInfo(S.stateInfo) {}
164 DFA::DFA(): currentState(nullptr) {}
167 // addTransition - Add a transition from this state given the input InsnClass
169 void State::addTransition(unsigned InsnClass, const State *To) const {
170 assert(!Transitions.count(InsnClass) &&
171 "Cannot have multiple transitions for the same input");
172 Transitions[InsnClass] = To;
176 // hasTransition - Returns true if there is a transition from this state
177 // given the input InsnClass
179 bool State::hasTransition(unsigned InsnClass) const {
180 return Transitions.count(InsnClass) > 0;
184 // AddInsnClass - Return all combinations of resource reservation
185 // which are possible from this state (PossibleStates).
187 void State::AddInsnClass(unsigned InsnClass,
188 std::set<unsigned> &PossibleStates) const {
190 // Iterate over all resource states in currentState.
193 for (std::set<unsigned>::iterator SI = stateInfo.begin();
194 SI != stateInfo.end(); ++SI) {
195 unsigned thisState = *SI;
198 // Iterate over all possible resources used in InsnClass.
199 // For ex: for InsnClass = 0x11, all resources = {0x01, 0x10}.
202 DenseSet<unsigned> VisitedResourceStates;
203 for (unsigned int j = 0; j < sizeof(InsnClass) * 8; ++j) {
204 if ((0x1 << j) & InsnClass) {
206 // For each possible resource used in InsnClass, generate the
207 // resource state if that resource was used.
209 unsigned ResultingResourceState = thisState | (0x1 << j);
211 // Check if the resulting resource state can be accommodated in this
213 // We compute ResultingResourceState OR thisState.
214 // If the result of the OR is different than thisState, it implies
215 // that there is at least one resource that can be used to schedule
216 // InsnClass in the current packet.
217 // Insert ResultingResourceState into PossibleStates only if we haven't
218 // processed ResultingResourceState before.
220 if ((ResultingResourceState != thisState) &&
221 (VisitedResourceStates.count(ResultingResourceState) == 0)) {
222 VisitedResourceStates.insert(ResultingResourceState);
223 PossibleStates.insert(ResultingResourceState);
233 // canAddInsnClass - Quickly verifies if an instruction of type InsnClass is a
234 // valid transition from this state i.e., can an instruction of type InsnClass
235 // be added to the packet represented by this state.
237 bool State::canAddInsnClass(unsigned InsnClass) const {
238 for (std::set<unsigned>::const_iterator SI = stateInfo.begin();
239 SI != stateInfo.end(); ++SI) {
240 if (~*SI & InsnClass)
247 const State &DFA::newState() {
248 auto IterPair = states.insert(State());
249 assert(IterPair.second && "State already exists");
250 return *IterPair.first;
254 int State::currentStateNum = 0;
256 DFAPacketizerEmitter::DFAPacketizerEmitter(RecordKeeper &R):
257 TargetName(CodeGenTarget(R).getName()),
258 allInsnClasses(), Records(R) {}
262 // writeTableAndAPI - Print out a table representing the DFA and the
263 // associated API to create a DFA packetizer.
266 // DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid
268 // DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable for
272 void DFA::writeTableAndAPI(raw_ostream &OS, const std::string &TargetName) {
273 static const std::string SentinelEntry = "{-1, -1}";
274 DFA::StateSet::iterator SI = states.begin();
275 // This table provides a map to the beginning of the transitions for State s
276 // in DFAStateInputTable.
277 std::vector<int> StateEntry(states.size());
279 OS << "namespace llvm {\n\n";
280 OS << "const int " << TargetName << "DFAStateInputTable[][2] = {\n";
282 // Tracks the total valid transitions encountered so far. It is used
283 // to construct the StateEntry table.
284 int ValidTransitions = 0;
285 for (unsigned i = 0; i < states.size(); ++i, ++SI) {
286 assert ((SI->stateNum == (int) i) && "Mismatch in state numbers");
287 StateEntry[i] = ValidTransitions;
288 for (State::TransitionMap::iterator
289 II = SI->Transitions.begin(), IE = SI->Transitions.end();
291 OS << "{" << II->first << ", "
292 << II->second->stateNum
295 ValidTransitions += SI->Transitions.size();
297 // If there are no valid transitions from this stage, we need a sentinel
299 if (ValidTransitions == StateEntry[i]) {
300 OS << SentinelEntry << ",";
307 // Print out a sentinel entry at the end of the StateInputTable. This is
308 // needed to iterate over StateInputTable in DFAPacketizer::ReadTable()
309 OS << SentinelEntry << "\n";
312 OS << "const unsigned int " << TargetName << "DFAStateEntryTable[] = {\n";
314 // Multiply i by 2 since each entry in DFAStateInputTable is a set of
316 for (unsigned i = 0; i < states.size(); ++i)
317 OS << StateEntry[i] << ", ";
319 // Print out the index to the sentinel entry in StateInputTable
320 OS << ValidTransitions << ", ";
323 OS << "} // namespace\n";
327 // Emit DFA Packetizer tables if the target is a VLIW machine.
329 std::string SubTargetClassName = TargetName + "GenSubtargetInfo";
330 OS << "\n" << "#include \"llvm/CodeGen/DFAPacketizer.h\"\n";
331 OS << "namespace llvm {\n";
332 OS << "DFAPacketizer *" << SubTargetClassName << "::"
333 << "createDFAPacketizer(const InstrItineraryData *IID) const {\n"
334 << " return new DFAPacketizer(IID, " << TargetName
335 << "DFAStateInputTable, " << TargetName << "DFAStateEntryTable);\n}\n\n";
336 OS << "} // End llvm namespace \n";
341 // collectAllInsnClasses - Populate allInsnClasses which is a set of units
342 // used in each stage.
344 void DFAPacketizerEmitter::collectAllInsnClasses(const std::string &Name,
348 // Collect processor itineraries.
349 std::vector<Record*> ProcItinList =
350 Records.getAllDerivedDefinitions("ProcessorItineraries");
352 // If just no itinerary then don't bother.
353 if (ProcItinList.size() < 2)
355 std::map<std::string, unsigned> NameToBitsMap;
357 // Parse functional units for all the itineraries.
358 for (unsigned i = 0, N = ProcItinList.size(); i < N; ++i) {
359 Record *Proc = ProcItinList[i];
360 std::vector<Record*> FUs = Proc->getValueAsListOfDefs("FU");
362 // Convert macros to bits for each stage.
363 for (unsigned i = 0, N = FUs.size(); i < N; ++i)
364 NameToBitsMap[FUs[i]->getName()] = (unsigned) (1U << i);
367 const std::vector<Record*> &StageList =
368 ItinData->getValueAsListOfDefs("Stages");
370 // The number of stages.
371 NStages = StageList.size();
374 unsigned UnitBitValue = 0;
376 // Compute the bitwise or of each unit used in this stage.
377 for (unsigned i = 0; i < NStages; ++i) {
378 const Record *Stage = StageList[i];
381 const std::vector<Record*> &UnitList =
382 Stage->getValueAsListOfDefs("Units");
384 for (unsigned j = 0, M = UnitList.size(); j < M; ++j) {
385 // Conduct bitwise or.
386 std::string UnitName = UnitList[j]->getName();
387 assert(NameToBitsMap.count(UnitName));
388 UnitBitValue |= NameToBitsMap[UnitName];
391 if (UnitBitValue != 0)
392 allInsnClasses.insert(UnitBitValue);
398 // Run the worklist algorithm to generate the DFA.
400 void DFAPacketizerEmitter::run(raw_ostream &OS) {
402 // Collect processor iteraries.
403 std::vector<Record*> ProcItinList =
404 Records.getAllDerivedDefinitions("ProcessorItineraries");
407 // Collect the instruction classes.
409 for (unsigned i = 0, N = ProcItinList.size(); i < N; i++) {
410 Record *Proc = ProcItinList[i];
412 // Get processor itinerary name.
413 const std::string &Name = Proc->getName();
416 if (Name == "NoItineraries")
419 // Sanity check for at least one instruction itinerary class.
420 unsigned NItinClasses =
421 Records.getAllDerivedDefinitions("InstrItinClass").size();
422 if (NItinClasses == 0)
425 // Get itinerary data list.
426 std::vector<Record*> ItinDataList = Proc->getValueAsListOfDefs("IID");
428 // Collect instruction classes for all itinerary data.
429 for (unsigned j = 0, M = ItinDataList.size(); j < M; j++) {
430 Record *ItinData = ItinDataList[j];
432 collectAllInsnClasses(Name, ItinData, NStages, OS);
438 // Run a worklist algorithm to generate the DFA.
441 const State *Initial = &D.newState();
442 Initial->isInitial = true;
443 Initial->stateInfo.insert(0x0);
444 SmallVector<const State*, 32> WorkList;
445 std::map<std::set<unsigned>, const State*> Visited;
447 WorkList.push_back(Initial);
450 // Worklist algorithm to create a DFA for processor resource tracking.
451 // C = {set of InsnClasses}
452 // Begin with initial node in worklist. Initial node does not have
453 // any consumed resources,
454 // ResourceState = 0x0
456 // While worklist != empty
457 // S = first element of worklist
458 // For every instruction class C
459 // if we can accommodate C in S:
460 // S' = state with resource states = {S Union C}
461 // Add a new transition: S x C -> S'
462 // If S' is not in Visited:
463 // Add S' to worklist
466 while (!WorkList.empty()) {
467 const State *current = WorkList.pop_back_val();
468 for (DenseSet<unsigned>::iterator CI = allInsnClasses.begin(),
469 CE = allInsnClasses.end(); CI != CE; ++CI) {
470 unsigned InsnClass = *CI;
472 std::set<unsigned> NewStateResources;
474 // If we haven't already created a transition for this input
475 // and the state can accommodate this InsnClass, create a transition.
477 if (!current->hasTransition(InsnClass) &&
478 current->canAddInsnClass(InsnClass)) {
479 const State *NewState;
480 current->AddInsnClass(InsnClass, NewStateResources);
481 assert(NewStateResources.size() && "New states must be generated");
484 // If we have seen this state before, then do not create a new state.
487 auto VI = Visited.find(NewStateResources);
488 if (VI != Visited.end())
489 NewState = VI->second;
491 NewState = &D.newState();
492 NewState->stateInfo = NewStateResources;
493 Visited[NewStateResources] = NewState;
494 WorkList.push_back(NewState);
497 current->addTransition(InsnClass, NewState);
502 // Print out the table.
503 D.writeTableAndAPI(OS, TargetName);
508 void EmitDFAPacketizer(RecordKeeper &RK, raw_ostream &OS) {
509 emitSourceFileHeader("Target DFA Packetizer Tables", OS);
510 DFAPacketizerEmitter(RK).run(OS);
513 } // End llvm namespace