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/TableGen/Record.h"
21 #include "llvm/TableGen/TableGenBackend.h"
28 // class DFAPacketizerEmitter: class that generates and prints out the DFA
29 // for resource tracking.
32 class DFAPacketizerEmitter {
34 std::string TargetName;
36 // allInsnClasses is the set of all possible resources consumed by an
39 DenseSet<unsigned> allInsnClasses;
40 RecordKeeper &Records;
43 DFAPacketizerEmitter(RecordKeeper &R);
46 // collectAllInsnClasses: Populate allInsnClasses which is a set of units
47 // used in each stage.
49 void collectAllInsnClasses(const std::string &Name,
54 void run(raw_ostream &OS);
56 } // End anonymous namespace.
60 // State represents the usage of machine resources if the packet contains
61 // a set of instruction classes.
63 // Specifically, currentState is a set of bit-masks.
64 // The nth bit in a bit-mask indicates whether the nth resource is being used
65 // by this state. The set of bit-masks in a state represent the different
66 // possible outcomes of transitioning to this state.
67 // For example: consider a two resource architecture: resource L and resource M
68 // with three instruction classes: L, M, and L_or_M.
69 // From the initial state (currentState = 0x00), if we add instruction class
70 // L_or_M we will transition to a state with currentState = [0x01, 0x10]. This
71 // represents the possible resource states that can result from adding a L_or_M
74 // Another way of thinking about this transition is we are mapping a NDFA with
75 // two states [0x01] and [0x10] into a DFA with a single state [0x01, 0x10].
81 static int currentStateNum;
84 std::set<unsigned> stateInfo;
87 State(const State &S);
90 // canAddInsnClass - Returns true if an instruction of type InsnClass is a
91 // valid transition from this state, i.e., can an instruction of type InsnClass
92 // be added to the packet represented by this state.
94 // PossibleStates is the set of valid resource states that ensue from valid
97 bool canAddInsnClass(unsigned InsnClass) const;
99 // AddInsnClass - Return all combinations of resource reservation
100 // which are possible from this state (PossibleStates).
102 void AddInsnClass(unsigned InsnClass, std::set<unsigned> &PossibleStates);
104 } // End anonymous namespace.
110 static int currentTransitionNum;
116 Transition(State *from_, unsigned input_, State *to_);
118 } // End anonymous namespace.
122 // Comparators to keep set of states sorted.
126 bool operator()(const State *s1, const State *s2) const;
129 struct ltTransition {
130 bool operator()(const Transition *s1, const Transition *s2) const;
132 } // End anonymous namespace.
136 // class DFA: deterministic finite automaton for processor resource tracking.
143 // Set of states. Need to keep this sorted to emit the transition table.
144 std::set<State*, ltState> states;
146 // Map from a state to the list of transitions with that state as source.
147 std::map<State*, std::set<Transition*, ltTransition>, ltState>
151 // Highest valued Input seen.
152 unsigned LargestInput;
158 void addState(State *);
159 void addTransition(Transition *);
162 // getTransition - Return the state when a transition is made from
163 // State From with Input I. If a transition is not found, return NULL.
165 State *getTransition(State *, unsigned);
168 // isValidTransition: Predicate that checks if there is a valid transition
169 // from state From on input InsnClass.
171 bool isValidTransition(State *From, unsigned InsnClass);
174 // writeTable: Print out a table representing the DFA.
176 void writeTableAndAPI(raw_ostream &OS, const std::string &ClassName);
178 } // End anonymous namespace.
182 // Constructors for State, Transition, and DFA
185 stateNum(currentStateNum++), isInitial(false) {}
188 State::State(const State &S) :
189 stateNum(currentStateNum++), isInitial(S.isInitial),
190 stateInfo(S.stateInfo) {}
193 Transition::Transition(State *from_, unsigned input_, State *to_) :
194 transitionNum(currentTransitionNum++), from(from_), input(input_),
202 bool ltState::operator()(const State *s1, const State *s2) const {
203 return (s1->stateNum < s2->stateNum);
206 bool ltTransition::operator()(const Transition *s1, const Transition *s2) const {
207 return (s1->input < s2->input);
211 // AddInsnClass - Return all combinations of resource reservation
212 // which are possible from this state (PossibleStates).
214 void State::AddInsnClass(unsigned InsnClass,
215 std::set<unsigned> &PossibleStates) {
217 // Iterate over all resource states in currentState.
220 for (std::set<unsigned>::iterator SI = stateInfo.begin();
221 SI != stateInfo.end(); ++SI) {
222 unsigned thisState = *SI;
225 // Iterate over all possible resources used in InsnClass.
226 // For ex: for InsnClass = 0x11, all resources = {0x01, 0x10}.
229 DenseSet<unsigned> VisitedResourceStates;
230 for (unsigned int j = 0; j < sizeof(InsnClass) * 8; ++j) {
231 if ((0x1 << j) & InsnClass) {
233 // For each possible resource used in InsnClass, generate the
234 // resource state if that resource was used.
236 unsigned ResultingResourceState = thisState | (0x1 << j);
238 // Check if the resulting resource state can be accommodated in this
240 // We compute ResultingResourceState OR thisState.
241 // If the result of the OR is different than thisState, it implies
242 // that there is at least one resource that can be used to schedule
243 // InsnClass in the current packet.
244 // Insert ResultingResourceState into PossibleStates only if we haven't
245 // processed ResultingResourceState before.
247 if ((ResultingResourceState != thisState) &&
248 (VisitedResourceStates.count(ResultingResourceState) == 0)) {
249 VisitedResourceStates.insert(ResultingResourceState);
250 PossibleStates.insert(ResultingResourceState);
260 // canAddInsnClass - Quickly verifies if an instruction of type InsnClass is a
261 // valid transition from this state i.e., can an instruction of type InsnClass
262 // be added to the packet represented by this state.
264 bool State::canAddInsnClass(unsigned InsnClass) const {
265 for (std::set<unsigned>::iterator SI = stateInfo.begin();
266 SI != stateInfo.end(); ++SI) {
267 if (~*SI & InsnClass)
274 void DFA::initialize() {
275 currentState->isInitial = true;
279 void DFA::addState(State *S) {
280 assert(!states.count(S) && "State already exists");
285 void DFA::addTransition(Transition *T) {
286 // Update LargestInput.
287 if (T->input > LargestInput)
288 LargestInput = T->input;
290 // Add the new transition.
291 bool Added = stateTransitions[T->from].insert(T).second;
292 assert(Added && "Cannot have multiple states for the same input");
297 // getTransition - Return the state when a transition is made from
298 // State From with Input I. If a transition is not found, return NULL.
300 State *DFA::getTransition(State *From, unsigned I) {
301 // Do we have a transition from state From?
302 if (!stateTransitions.count(From))
305 // Do we have a transition from state From with Input I?
306 Transition TVal(NULL, I, NULL);
307 // Do not count this temporal instance
308 Transition::currentTransitionNum--;
309 std::set<Transition*, ltTransition>::iterator T =
310 stateTransitions[From].find(&TVal);
311 if (T != stateTransitions[From].end())
318 bool DFA::isValidTransition(State *From, unsigned InsnClass) {
319 return (getTransition(From, InsnClass) != NULL);
323 int State::currentStateNum = 0;
324 int Transition::currentTransitionNum = 0;
326 DFAPacketizerEmitter::DFAPacketizerEmitter(RecordKeeper &R):
327 TargetName(CodeGenTarget(R).getName()),
328 allInsnClasses(), Records(R) {}
332 // writeTableAndAPI - Print out a table representing the DFA and the
333 // associated API to create a DFA packetizer.
336 // DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid
338 // DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable for
342 void DFA::writeTableAndAPI(raw_ostream &OS, const std::string &TargetName) {
343 std::set<State*, ltState>::iterator SI = states.begin();
344 // This table provides a map to the beginning of the transitions for State s
345 // in DFAStateInputTable.
346 std::vector<int> StateEntry(states.size());
348 OS << "namespace llvm {\n\n";
349 OS << "const int " << TargetName << "DFAStateInputTable[][2] = {\n";
351 // Tracks the total valid transitions encountered so far. It is used
352 // to construct the StateEntry table.
353 int ValidTransitions = 0;
354 for (unsigned i = 0; i < states.size(); ++i, ++SI) {
355 StateEntry[i] = ValidTransitions;
356 for (unsigned j = 0; j <= LargestInput; ++j) {
357 assert (((*SI)->stateNum == (int) i) && "Mismatch in state numbers");
358 State *To = getTransition(*SI, j);
362 OS << "{" << j << ", "
368 // If there are no valid transitions from this stage, we need a sentinel
370 if (ValidTransitions == StateEntry[i]) {
378 OS << "const unsigned int " << TargetName << "DFAStateEntryTable[] = {\n";
380 // Multiply i by 2 since each entry in DFAStateInputTable is a set of
382 for (unsigned i = 0; i < states.size(); ++i)
383 OS << StateEntry[i] << ", ";
386 OS << "} // namespace\n";
390 // Emit DFA Packetizer tables if the target is a VLIW machine.
392 std::string SubTargetClassName = TargetName + "GenSubtargetInfo";
393 OS << "\n" << "#include \"llvm/CodeGen/DFAPacketizer.h\"\n";
394 OS << "namespace llvm {\n";
395 OS << "DFAPacketizer *" << SubTargetClassName << "::"
396 << "createDFAPacketizer(const InstrItineraryData *IID) const {\n"
397 << " return new DFAPacketizer(IID, " << TargetName
398 << "DFAStateInputTable, " << TargetName << "DFAStateEntryTable);\n}\n\n";
399 OS << "} // End llvm namespace \n";
404 // collectAllInsnClasses - Populate allInsnClasses which is a set of units
405 // used in each stage.
407 void DFAPacketizerEmitter::collectAllInsnClasses(const std::string &Name,
411 // Collect processor itineraries.
412 std::vector<Record*> ProcItinList =
413 Records.getAllDerivedDefinitions("ProcessorItineraries");
415 // If just no itinerary then don't bother.
416 if (ProcItinList.size() < 2)
418 std::map<std::string, unsigned> NameToBitsMap;
420 // Parse functional units for all the itineraries.
421 for (unsigned i = 0, N = ProcItinList.size(); i < N; ++i) {
422 Record *Proc = ProcItinList[i];
423 std::vector<Record*> FUs = Proc->getValueAsListOfDefs("FU");
425 // Convert macros to bits for each stage.
426 for (unsigned i = 0, N = FUs.size(); i < N; ++i)
427 NameToBitsMap[FUs[i]->getName()] = (unsigned) (1U << i);
430 const std::vector<Record*> &StageList =
431 ItinData->getValueAsListOfDefs("Stages");
433 // The number of stages.
434 NStages = StageList.size();
437 unsigned UnitBitValue = 0;
439 // Compute the bitwise or of each unit used in this stage.
440 for (unsigned i = 0; i < NStages; ++i) {
441 const Record *Stage = StageList[i];
444 const std::vector<Record*> &UnitList =
445 Stage->getValueAsListOfDefs("Units");
447 for (unsigned j = 0, M = UnitList.size(); j < M; ++j) {
448 // Conduct bitwise or.
449 std::string UnitName = UnitList[j]->getName();
450 assert(NameToBitsMap.count(UnitName));
451 UnitBitValue |= NameToBitsMap[UnitName];
454 if (UnitBitValue != 0)
455 allInsnClasses.insert(UnitBitValue);
461 // Run the worklist algorithm to generate the DFA.
463 void DFAPacketizerEmitter::run(raw_ostream &OS) {
465 // Collect processor iteraries.
466 std::vector<Record*> ProcItinList =
467 Records.getAllDerivedDefinitions("ProcessorItineraries");
470 // Collect the instruction classes.
472 for (unsigned i = 0, N = ProcItinList.size(); i < N; i++) {
473 Record *Proc = ProcItinList[i];
475 // Get processor itinerary name.
476 const std::string &Name = Proc->getName();
479 if (Name == "NoItineraries")
482 // Sanity check for at least one instruction itinerary class.
483 unsigned NItinClasses =
484 Records.getAllDerivedDefinitions("InstrItinClass").size();
485 if (NItinClasses == 0)
488 // Get itinerary data list.
489 std::vector<Record*> ItinDataList = Proc->getValueAsListOfDefs("IID");
491 // Collect instruction classes for all itinerary data.
492 for (unsigned j = 0, M = ItinDataList.size(); j < M; j++) {
493 Record *ItinData = ItinDataList[j];
495 collectAllInsnClasses(Name, ItinData, NStages, OS);
501 // Run a worklist algorithm to generate the DFA.
504 State *Initial = new State;
505 Initial->isInitial = true;
506 Initial->stateInfo.insert(0x0);
508 SmallVector<State*, 32> WorkList;
509 std::map<std::set<unsigned>, State*> Visited;
511 WorkList.push_back(Initial);
514 // Worklist algorithm to create a DFA for processor resource tracking.
515 // C = {set of InsnClasses}
516 // Begin with initial node in worklist. Initial node does not have
517 // any consumed resources,
518 // ResourceState = 0x0
520 // While worklist != empty
521 // S = first element of worklist
522 // For every instruction class C
523 // if we can accommodate C in S:
524 // S' = state with resource states = {S Union C}
525 // Add a new transition: S x C -> S'
526 // If S' is not in Visited:
527 // Add S' to worklist
530 while (!WorkList.empty()) {
531 State *current = WorkList.pop_back_val();
532 for (DenseSet<unsigned>::iterator CI = allInsnClasses.begin(),
533 CE = allInsnClasses.end(); CI != CE; ++CI) {
534 unsigned InsnClass = *CI;
536 std::set<unsigned> NewStateResources;
538 // If we haven't already created a transition for this input
539 // and the state can accommodate this InsnClass, create a transition.
541 if (!D.getTransition(current, InsnClass) &&
542 current->canAddInsnClass(InsnClass)) {
543 State *NewState = NULL;
544 current->AddInsnClass(InsnClass, NewStateResources);
545 assert(NewStateResources.size() && "New states must be generated");
548 // If we have seen this state before, then do not create a new state.
551 std::map<std::set<unsigned>, State*>::iterator VI;
552 if ((VI = Visited.find(NewStateResources)) != Visited.end())
553 NewState = VI->second;
555 NewState = new State;
556 NewState->stateInfo = NewStateResources;
557 D.addState(NewState);
558 Visited[NewStateResources] = NewState;
559 WorkList.push_back(NewState);
562 Transition *NewTransition = new Transition(current, InsnClass,
564 D.addTransition(NewTransition);
569 // Print out the table.
570 D.writeTableAndAPI(OS, TargetName);
575 void EmitDFAPacketizer(RecordKeeper &RK, raw_ostream &OS) {
576 emitSourceFileHeader("Target DFA Packetizer Tables", OS);
577 DFAPacketizerEmitter(RK).run(OS);
580 } // End llvm namespace