64b7f481df41afb9c6e482bc236dd7711b0b7cec
[oota-llvm.git] / lib / CodeGen / DFAPacketizer.cpp
1 //=- llvm/CodeGen/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // This class implements a deterministic finite automaton (DFA) based
10 // packetizing mechanism for VLIW architectures. It provides APIs to
11 // determine whether there exists a legal mapping of instructions to
12 // functional unit assignments in a packet. The DFA is auto-generated from
13 // the target's Schedule.td file.
14 //
15 // A DFA consists of 3 major elements: states, inputs, and transitions. For
16 // the packetizing mechanism, the input is the set of instruction classes for
17 // a target. The state models all possible combinations of functional unit
18 // consumption for a given set of instructions in a packet. A transition
19 // models the addition of an instruction to a packet. In the DFA constructed
20 // by this class, if an instruction can be added to a packet, then a valid
21 // transition exists from the corresponding state. Invalid transitions
22 // indicate that the instruction cannot be added to the current packet.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/CodeGen/DFAPacketizer.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineInstrBundle.h"
29 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
30 #include "llvm/MC/MCInstrItineraries.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 using namespace llvm;
33
34 DFAPacketizer::DFAPacketizer(const InstrItineraryData *I,
35                              const DFAStateInput (*SIT)[2],
36                              const unsigned *SET):
37   InstrItins(I), CurrentState(0), DFAStateInputTable(SIT),
38   DFAStateEntryTable(SET) {
39   // Make sure DFA types are large enough for the number of terms & resources.
40   assert((DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <= (8 * sizeof(DFAInput))
41         && "(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAInput");
42   assert((DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <= (8 * sizeof(DFAStateInput))
43         && "(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAStateInput");
44 }
45
46
47 //
48 // ReadTable - Read the DFA transition table and update CachedTable.
49 //
50 // Format of the transition tables:
51 // DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid
52 //                           transitions
53 // DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable
54 //                         for the ith state
55 //
56 void DFAPacketizer::ReadTable(unsigned int state) {
57   unsigned ThisState = DFAStateEntryTable[state];
58   unsigned NextStateInTable = DFAStateEntryTable[state+1];
59   // Early exit in case CachedTable has already contains this
60   // state's transitions.
61   if (CachedTable.count(UnsignPair(state,
62                                    DFAStateInputTable[ThisState][0])))
63     return;
64
65   for (unsigned i = ThisState; i < NextStateInTable; i++)
66     CachedTable[UnsignPair(state, DFAStateInputTable[i][0])] =
67       DFAStateInputTable[i][1];
68 }
69
70 //
71 // getInsnInput - Return the DFAInput for an instruction class.
72 //
73 DFAInput DFAPacketizer::getInsnInput(unsigned InsnClass) {
74   // Note: this logic must match that in DFAPacketizerDefs.h for input vectors.
75   DFAInput InsnInput = 0;
76   unsigned i = 0;
77   for (const InstrStage *IS = InstrItins->beginStage(InsnClass),
78         *IE = InstrItins->endStage(InsnClass); IS != IE; ++IS, ++i) {
79     InsnInput = addDFAFuncUnits(InsnInput, IS->getUnits());
80     assert ((i < DFA_MAX_RESTERMS) && "Exceeded maximum number of DFA inputs");
81   }
82   return InsnInput;
83 }
84
85 // canReserveResources - Check if the resources occupied by a MCInstrDesc
86 // are available in the current state.
87 bool DFAPacketizer::canReserveResources(const llvm::MCInstrDesc *MID) {
88   unsigned InsnClass = MID->getSchedClass();
89   DFAInput InsnInput = getInsnInput(InsnClass);
90   UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
91   ReadTable(CurrentState);
92   return (CachedTable.count(StateTrans) != 0);
93 }
94
95 // reserveResources - Reserve the resources occupied by a MCInstrDesc and
96 // change the current state to reflect that change.
97 void DFAPacketizer::reserveResources(const llvm::MCInstrDesc *MID) {
98   unsigned InsnClass = MID->getSchedClass();
99   DFAInput InsnInput = getInsnInput(InsnClass);
100   UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
101   ReadTable(CurrentState);
102   assert(CachedTable.count(StateTrans) != 0);
103   CurrentState = CachedTable[StateTrans];
104 }
105
106
107 // canReserveResources - Check if the resources occupied by a machine
108 // instruction are available in the current state.
109 bool DFAPacketizer::canReserveResources(llvm::MachineInstr *MI) {
110   const llvm::MCInstrDesc &MID = MI->getDesc();
111   return canReserveResources(&MID);
112 }
113
114 // reserveResources - Reserve the resources occupied by a machine
115 // instruction and change the current state to reflect that change.
116 void DFAPacketizer::reserveResources(llvm::MachineInstr *MI) {
117   const llvm::MCInstrDesc &MID = MI->getDesc();
118   reserveResources(&MID);
119 }
120
121 namespace llvm {
122 // DefaultVLIWScheduler - This class extends ScheduleDAGInstrs and overrides
123 // Schedule method to build the dependence graph.
124 class DefaultVLIWScheduler : public ScheduleDAGInstrs {
125 public:
126   DefaultVLIWScheduler(MachineFunction &MF, MachineLoopInfo &MLI);
127   // Schedule - Actual scheduling work.
128   void schedule() override;
129 };
130 }
131
132 DefaultVLIWScheduler::DefaultVLIWScheduler(MachineFunction &MF,
133                                            MachineLoopInfo &MLI)
134     : ScheduleDAGInstrs(MF, &MLI) {
135   CanHandleTerminators = true;
136 }
137
138 void DefaultVLIWScheduler::schedule() {
139   // Build the scheduling graph.
140   buildSchedGraph(nullptr);
141 }
142
143 // VLIWPacketizerList Ctor
144 VLIWPacketizerList::VLIWPacketizerList(MachineFunction &MF,
145                                        MachineLoopInfo &MLI)
146     : MF(MF) {
147   TII = MF.getSubtarget().getInstrInfo();
148   ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());
149   VLIWScheduler = new DefaultVLIWScheduler(MF, MLI);
150 }
151
152 // VLIWPacketizerList Dtor
153 VLIWPacketizerList::~VLIWPacketizerList() {
154   if (VLIWScheduler)
155     delete VLIWScheduler;
156
157   if (ResourceTracker)
158     delete ResourceTracker;
159 }
160
161 // endPacket - End the current packet, bundle packet instructions and reset
162 // DFA state.
163 void VLIWPacketizerList::endPacket(MachineBasicBlock *MBB,
164                                          MachineInstr *MI) {
165   if (CurrentPacketMIs.size() > 1) {
166     MachineInstr *MIFirst = CurrentPacketMIs.front();
167     finalizeBundle(*MBB, MIFirst->getIterator(), MI->getIterator());
168   }
169   CurrentPacketMIs.clear();
170   ResourceTracker->clearResources();
171 }
172
173 // PacketizeMIs - Bundle machine instructions into packets.
174 void VLIWPacketizerList::PacketizeMIs(MachineBasicBlock *MBB,
175                                       MachineBasicBlock::iterator BeginItr,
176                                       MachineBasicBlock::iterator EndItr) {
177   assert(VLIWScheduler && "VLIW Scheduler is not initialized!");
178   VLIWScheduler->startBlock(MBB);
179   VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,
180                              std::distance(BeginItr, EndItr));
181   VLIWScheduler->schedule();
182
183   // Generate MI -> SU map.
184   MIToSUnit.clear();
185   for (unsigned i = 0, e = VLIWScheduler->SUnits.size(); i != e; ++i) {
186     SUnit *SU = &VLIWScheduler->SUnits[i];
187     MIToSUnit[SU->getInstr()] = SU;
188   }
189
190   // The main packetizer loop.
191   for (; BeginItr != EndItr; ++BeginItr) {
192     MachineInstr *MI = BeginItr;
193
194     this->initPacketizerState();
195
196     // End the current packet if needed.
197     if (this->isSoloInstruction(MI)) {
198       endPacket(MBB, MI);
199       continue;
200     }
201
202     // Ignore pseudo instructions.
203     if (this->ignorePseudoInstruction(MI, MBB))
204       continue;
205
206     SUnit *SUI = MIToSUnit[MI];
207     assert(SUI && "Missing SUnit Info!");
208
209     // Ask DFA if machine resource is available for MI.
210     bool ResourceAvail = ResourceTracker->canReserveResources(MI);
211     if (ResourceAvail) {
212       // Dependency check for MI with instructions in CurrentPacketMIs.
213       for (std::vector<MachineInstr*>::iterator VI = CurrentPacketMIs.begin(),
214            VE = CurrentPacketMIs.end(); VI != VE; ++VI) {
215         MachineInstr *MJ = *VI;
216         SUnit *SUJ = MIToSUnit[MJ];
217         assert(SUJ && "Missing SUnit Info!");
218
219         // Is it legal to packetize SUI and SUJ together.
220         if (!this->isLegalToPacketizeTogether(SUI, SUJ)) {
221           // Allow packetization if dependency can be pruned.
222           if (!this->isLegalToPruneDependencies(SUI, SUJ)) {
223             // End the packet if dependency cannot be pruned.
224             endPacket(MBB, MI);
225             break;
226           } // !isLegalToPruneDependencies.
227         } // !isLegalToPacketizeTogether.
228       } // For all instructions in CurrentPacketMIs.
229     } else {
230       // End the packet if resource is not available.
231       endPacket(MBB, MI);
232     }
233
234     // Add MI to the current packet.
235     BeginItr = this->addToPacket(MI);
236   } // For all instructions in BB.
237
238   // End any packet left behind.
239   endPacket(MBB, EndItr);
240   VLIWScheduler->exitRegion();
241   VLIWScheduler->finishBlock();
242 }