Simplify this code; use a while instead of an if and a do-while.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGSDNodes.cpp
1 //===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
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 //
10 // This implements the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "ScheduleDAGSDNodes.h"
17 #include "llvm/CodeGen/SelectionDAG.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24
25 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
26   : ScheduleDAG(mf) {
27 }
28
29 /// Run - perform scheduling.
30 ///
31 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
32                              MachineBasicBlock::iterator insertPos) {
33   DAG = dag;
34   ScheduleDAG::Run(bb, insertPos);
35 }
36
37 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
38   SUnit *SU = NewSUnit(Old->getNode());
39   SU->OrigNode = Old->OrigNode;
40   SU->Latency = Old->Latency;
41   SU->isTwoAddress = Old->isTwoAddress;
42   SU->isCommutable = Old->isCommutable;
43   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
44   Old->isCloned = true;
45   return SU;
46 }
47
48 /// CheckForPhysRegDependency - Check if the dependency between def and use of
49 /// a specified operand is a physical register dependency. If so, returns the
50 /// register and the cost of copying the register.
51 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
52                                       const TargetRegisterInfo *TRI, 
53                                       const TargetInstrInfo *TII,
54                                       unsigned &PhysReg, int &Cost) {
55   if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
56     return;
57
58   unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
59   if (TargetRegisterInfo::isVirtualRegister(Reg))
60     return;
61
62   unsigned ResNo = User->getOperand(2).getResNo();
63   if (Def->isMachineOpcode()) {
64     const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
65     if (ResNo >= II.getNumDefs() &&
66         II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
67       PhysReg = Reg;
68       const TargetRegisterClass *RC =
69         TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
70       Cost = RC->getCopyCost();
71     }
72   }
73 }
74
75 void ScheduleDAGSDNodes::BuildSchedUnits() {
76   // During scheduling, the NodeId field of SDNode is used to map SDNodes
77   // to their associated SUnits by holding SUnits table indices. A value
78   // of -1 means the SDNode does not yet have an associated SUnit.
79   unsigned NumNodes = 0;
80   for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
81        E = DAG->allnodes_end(); NI != E; ++NI) {
82     NI->setNodeId(-1);
83     ++NumNodes;
84   }
85
86   // Reserve entries in the vector for each of the SUnits we are creating.  This
87   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
88   // invalidated.
89   // FIXME: Multiply by 2 because we may clone nodes during scheduling.
90   // This is a temporary workaround.
91   SUnits.reserve(NumNodes * 2);
92   
93   // Check to see if the scheduler cares about latencies.
94   bool UnitLatencies = ForceUnitLatencies();
95
96   for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
97        E = DAG->allnodes_end(); NI != E; ++NI) {
98     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
99       continue;
100     
101     // If this node has already been processed, stop now.
102     if (NI->getNodeId() != -1) continue;
103     
104     SUnit *NodeSUnit = NewSUnit(NI);
105     
106     // See if anything is flagged to this node, if so, add them to flagged
107     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
108     // are required to be the last operand and result of a node.
109     
110     // Scan up to find flagged preds.
111     SDNode *N = NI;
112     while (N->getNumOperands() &&
113            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
114       N = N->getOperand(N->getNumOperands()-1).getNode();
115       assert(N->getNodeId() == -1 && "Node already inserted!");
116       N->setNodeId(NodeSUnit->NodeNum);
117     }
118     
119     // Scan down to find any flagged succs.
120     N = NI;
121     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
122       SDValue FlagVal(N, N->getNumValues()-1);
123       
124       // There are either zero or one users of the Flag result.
125       bool HasFlagUse = false;
126       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
127            UI != E; ++UI)
128         if (FlagVal.isOperandOf(*UI)) {
129           HasFlagUse = true;
130           assert(N->getNodeId() == -1 && "Node already inserted!");
131           N->setNodeId(NodeSUnit->NodeNum);
132           N = *UI;
133           break;
134         }
135       if (!HasFlagUse) break;
136     }
137     
138     // If there are flag operands involved, N is now the bottom-most node
139     // of the sequence of nodes that are flagged together.
140     // Update the SUnit.
141     NodeSUnit->setNode(N);
142     assert(N->getNodeId() == -1 && "Node already inserted!");
143     N->setNodeId(NodeSUnit->NodeNum);
144
145     // Assign the Latency field of NodeSUnit using target-provided information.
146     if (UnitLatencies)
147       NodeSUnit->Latency = 1;
148     else
149       ComputeLatency(NodeSUnit);
150   }
151 }
152
153 void ScheduleDAGSDNodes::AddSchedEdges() {
154   // Pass 2: add the preds, succs, etc.
155   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
156     SUnit *SU = &SUnits[su];
157     SDNode *MainNode = SU->getNode();
158     
159     if (MainNode->isMachineOpcode()) {
160       unsigned Opc = MainNode->getMachineOpcode();
161       const TargetInstrDesc &TID = TII->get(Opc);
162       for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
163         if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
164           SU->isTwoAddress = true;
165           break;
166         }
167       }
168       if (TID.isCommutable())
169         SU->isCommutable = true;
170     }
171     
172     // Find all predecessors and successors of the group.
173     for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode()) {
174       if (N->isMachineOpcode() &&
175           TII->get(N->getMachineOpcode()).getImplicitDefs() &&
176           CountResults(N) > TII->get(N->getMachineOpcode()).getNumDefs())
177         SU->hasPhysRegDefs = true;
178       
179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
180         SDNode *OpN = N->getOperand(i).getNode();
181         if (isPassiveNode(OpN)) continue;   // Not scheduled.
182         SUnit *OpSU = &SUnits[OpN->getNodeId()];
183         assert(OpSU && "Node has no SUnit!");
184         if (OpSU == SU) continue;           // In the same group.
185
186         MVT OpVT = N->getOperand(i).getValueType();
187         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
188         bool isChain = OpVT == MVT::Other;
189
190         unsigned PhysReg = 0;
191         int Cost = 1;
192         // Determine if this is a physical register dependency.
193         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
194         assert((PhysReg == 0 || !isChain) &&
195                "Chain dependence via physreg data?");
196         // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
197         // emits a copy from the physical register to a virtual register unless
198         // it requires a cross class copy (cost < 0). That means we are only
199         // treating "expensive to copy" register dependency as physical register
200         // dependency. This may change in the future though.
201         if (Cost >= 0)
202           PhysReg = 0;
203         SU->addPred(SDep(OpSU, isChain ? SDep::Order : SDep::Data,
204                          OpSU->Latency, PhysReg));
205       }
206     }
207   }
208 }
209
210 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
211 /// are input.  This SUnit graph is similar to the SelectionDAG, but
212 /// excludes nodes that aren't interesting to scheduling, and represents
213 /// flagged together nodes with a single SUnit.
214 void ScheduleDAGSDNodes::BuildSchedGraph() {
215   // Populate the SUnits array.
216   BuildSchedUnits();
217   // Compute all the scheduling dependencies between nodes.
218   AddSchedEdges();
219 }
220
221 void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
222   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
223   
224   // Compute the latency for the node.  We use the sum of the latencies for
225   // all nodes flagged together into this SUnit.
226   SU->Latency = 0;
227   bool SawMachineOpcode = false;
228   for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())
229     if (N->isMachineOpcode()) {
230       SawMachineOpcode = true;
231       SU->Latency +=
232         InstrItins.getLatency(TII->get(N->getMachineOpcode()).getSchedClass());
233     }
234 }
235
236 /// CountResults - The results of target nodes have register or immediate
237 /// operands first, then an optional chain, and optional flag operands (which do
238 /// not go into the resulting MachineInstr).
239 unsigned ScheduleDAGSDNodes::CountResults(SDNode *Node) {
240   unsigned N = Node->getNumValues();
241   while (N && Node->getValueType(N - 1) == MVT::Flag)
242     --N;
243   if (N && Node->getValueType(N - 1) == MVT::Other)
244     --N;    // Skip over chain result.
245   return N;
246 }
247
248 /// CountOperands - The inputs to target nodes have any actual inputs first,
249 /// followed by special operands that describe memory references, then an
250 /// optional chain operand, then an optional flag operand.  Compute the number
251 /// of actual operands that will go into the resulting MachineInstr.
252 unsigned ScheduleDAGSDNodes::CountOperands(SDNode *Node) {
253   unsigned N = ComputeMemOperandsEnd(Node);
254   while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).getNode()))
255     --N; // Ignore MEMOPERAND nodes
256   return N;
257 }
258
259 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
260 /// operand
261 unsigned ScheduleDAGSDNodes::ComputeMemOperandsEnd(SDNode *Node) {
262   unsigned N = Node->getNumOperands();
263   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
264     --N;
265   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
266     --N; // Ignore chain if it exists.
267   return N;
268 }
269
270
271 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
272   if (!SU->getNode()) {
273     cerr << "PHYS REG COPY\n";
274     return;
275   }
276
277   SU->getNode()->dump(DAG);
278   cerr << "\n";
279   SmallVector<SDNode *, 4> FlaggedNodes;
280   for (SDNode *N = SU->getNode()->getFlaggedNode(); N; N = N->getFlaggedNode())
281     FlaggedNodes.push_back(N);
282   while (!FlaggedNodes.empty()) {
283     cerr << "    ";
284     FlaggedNodes.back()->dump(DAG);
285     cerr << "\n";
286     FlaggedNodes.pop_back();
287   }
288 }