Fix for PR341
[oota-llvm.git] / lib / CodeGen / InstrSched / SchedGraph.cpp
1 //===- SchedGraph.cpp - Scheduling Graph Implementation -------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // Scheduling graph based on SSA graph plus extra dependence edges capturing
11 // dependences due to machine resources (machine registers, CC registers, and
12 // any others).
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "SchedGraph.h"
17 #include "llvm/Function.h"
18 #include "llvm/iOther.h"
19 #include "llvm/CodeGen/MachineCodeForInstruction.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "../../Target/SparcV9/SparcV9RegInfo.h"
24 #include "Support/STLExtras.h"
25 #include <iostream>
26
27 namespace llvm {
28
29 //*********************** Internal Data Structures *************************/
30
31 // The following two types need to be classes, not typedefs, so we can use
32 // opaque declarations in SchedGraph.h
33 // 
34 struct RefVec: public std::vector<std::pair<SchedGraphNode*, int> > {
35   typedef std::vector<std::pair<SchedGraphNode*,int> >::iterator iterator;
36   typedef
37   std::vector<std::pair<SchedGraphNode*,int> >::const_iterator const_iterator;
38 };
39
40 struct RegToRefVecMap: public hash_map<int, RefVec> {
41   typedef hash_map<int, RefVec>::      iterator       iterator;
42   typedef hash_map<int, RefVec>::const_iterator const_iterator;
43 };
44
45 struct ValueToDefVecMap: public hash_map<const Value*, RefVec> {
46   typedef hash_map<const Value*, RefVec>::      iterator       iterator;
47   typedef hash_map<const Value*, RefVec>::const_iterator const_iterator;
48 };
49
50
51 // 
52 // class SchedGraphNode
53 // 
54
55 SchedGraphNode::SchedGraphNode(unsigned NID, MachineBasicBlock *mbb,
56                                int   indexInBB, const TargetMachine& Target)
57   : SchedGraphNodeCommon(NID,indexInBB), MBB(mbb), MI(0) {
58   if (mbb) {
59     MachineBasicBlock::iterator I = MBB->begin();
60     std::advance(I, indexInBB);
61     MI = I;
62
63     MachineOpCode mopCode = MI->getOpcode();
64     latency = Target.getInstrInfo()->hasResultInterlock(mopCode)
65       ? Target.getInstrInfo()->minLatency(mopCode)
66       : Target.getInstrInfo()->maxLatency(mopCode);
67   }
68 }
69
70 //
71 // Method: SchedGraphNode Destructor
72 //
73 // Description:
74 //      Free memory allocated by the SchedGraphNode object.
75 //
76 // Notes:
77 //      Do not delete the edges here.  The base class will take care of that.
78 //      Only handle subclass specific stuff here (where currently there is
79 //      none).
80 //
81 SchedGraphNode::~SchedGraphNode() {
82 }
83
84 // 
85 // class SchedGraph
86 // 
87 SchedGraph::SchedGraph(MachineBasicBlock &mbb, const TargetMachine& target)
88   : MBB(mbb) {
89   buildGraph(target);
90 }
91
92 //
93 // Method: SchedGraph Destructor
94 //
95 // Description:
96 //      This method deletes memory allocated by the SchedGraph object.
97 //
98 // Notes:
99 //      Do not delete the graphRoot or graphLeaf here.  The base class handles
100 //      that bit of work.
101 //
102 SchedGraph::~SchedGraph() {
103   for (const_iterator I = begin(); I != end(); ++I)
104     delete I->second;
105 }
106
107 void SchedGraph::dump() const {
108   std::cerr << "  Sched Graph for Basic Block: "
109             << MBB.getBasicBlock()->getName()
110             << " (" << *MBB.getBasicBlock() << ")"
111             << "\n\n    Actual Root nodes: ";
112   for (SchedGraphNodeCommon::const_iterator I = graphRoot->beginOutEdges(),
113                                             E = graphRoot->endOutEdges();
114        I != E; ++I) {
115     std::cerr << (*I)->getSink ()->getNodeId ();
116     if (I + 1 != E) { std::cerr << ", "; }
117   }
118   std::cerr << "\n    Graph Nodes:\n";
119   for (const_iterator I = begin(), E = end(); I != E; ++I)
120     std::cerr << "\n" << *I->second;
121   std::cerr << "\n";
122 }
123
124 void SchedGraph::addDummyEdges() {
125   assert(graphRoot->getNumOutEdges() == 0);
126   
127   for (const_iterator I=begin(); I != end(); ++I) {
128     SchedGraphNode* node = (*I).second;
129     assert(node != graphRoot && node != graphLeaf);
130     if (node->beginInEdges() == node->endInEdges())
131       (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
132                                 SchedGraphEdge::NonDataDep, 0);
133     if (node->beginOutEdges() == node->endOutEdges())
134       (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
135                                 SchedGraphEdge::NonDataDep, 0);
136   }
137 }
138
139
140 void SchedGraph::addCDEdges(const TerminatorInst* term,
141                             const TargetMachine& target) {
142   const TargetInstrInfo& mii = *target.getInstrInfo();
143   MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
144   
145   // Find the first branch instr in the sequence of machine instrs for term
146   // 
147   unsigned first = 0;
148   while (! mii.isBranch(termMvec[first]->getOpcode()) &&
149          ! mii.isReturn(termMvec[first]->getOpcode()))
150     ++first;
151   assert(first < termMvec.size() &&
152          "No branch instructions for terminator?  Ok, but weird!");
153   if (first == termMvec.size())
154     return;
155   
156   SchedGraphNode* firstBrNode = getGraphNodeForInstr(termMvec[first]);
157   
158   // Add CD edges from each instruction in the sequence to the
159   // *last preceding* branch instr. in the sequence 
160   // Use a latency of 0 because we only need to prevent out-of-order issue.
161   // 
162   for (unsigned i = termMvec.size(); i > first+1; --i) {
163     SchedGraphNode* toNode = getGraphNodeForInstr(termMvec[i-1]);
164     assert(toNode && "No node for instr generated for branch/ret?");
165     
166     for (unsigned j = i-1; j != 0; --j) 
167       if (mii.isBranch(termMvec[j-1]->getOpcode()) ||
168           mii.isReturn(termMvec[j-1]->getOpcode())) {
169         SchedGraphNode* brNode = getGraphNodeForInstr(termMvec[j-1]);
170         assert(brNode && "No node for instr generated for branch/ret?");
171         (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
172                                   SchedGraphEdge::NonDataDep, 0);
173         break;                  // only one incoming edge is enough
174       }
175   }
176   
177   // Add CD edges from each instruction preceding the first branch
178   // to the first branch.  Use a latency of 0 as above.
179   // 
180   for (unsigned i = first; i != 0; --i) {
181     SchedGraphNode* fromNode = getGraphNodeForInstr(termMvec[i-1]);
182     assert(fromNode && "No node for instr generated for branch?");
183     (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
184                               SchedGraphEdge::NonDataDep, 0);
185   }
186   
187   // Now add CD edges to the first branch instruction in the sequence from
188   // all preceding instructions in the basic block.  Use 0 latency again.
189   // 
190   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
191     if (&*I == termMvec[first])   // reached the first branch
192       break;
193     
194     SchedGraphNode* fromNode = getGraphNodeForInstr(I);
195     if (fromNode == NULL)
196       continue;                 // dummy instruction, e.g., PHI
197     
198     (void) new SchedGraphEdge(fromNode, firstBrNode,
199                               SchedGraphEdge::CtrlDep,
200                               SchedGraphEdge::NonDataDep, 0);
201       
202     // If we find any other machine instructions (other than due to
203     // the terminator) that also have delay slots, add an outgoing edge
204     // from the instruction to the instructions in the delay slots.
205     // 
206     unsigned d = mii.getNumDelaySlots(I->getOpcode());
207
208     MachineBasicBlock::iterator J = I; ++J;
209     for (unsigned j=1; j <= d; j++, ++J) {
210       SchedGraphNode* toNode = this->getGraphNodeForInstr(J);
211       assert(toNode && "No node for machine instr in delay slot?");
212       (void) new SchedGraphEdge(fromNode, toNode,
213                                 SchedGraphEdge::CtrlDep,
214                                 SchedGraphEdge::NonDataDep, 0);
215     }
216   }
217 }
218
219 static const int SG_LOAD_REF  = 0;
220 static const int SG_STORE_REF = 1;
221 static const int SG_CALL_REF  = 2;
222
223 static const unsigned int SG_DepOrderArray[][3] = {
224   { SchedGraphEdge::NonDataDep,
225     SchedGraphEdge::AntiDep,
226     SchedGraphEdge::AntiDep },
227   { SchedGraphEdge::TrueDep,
228     SchedGraphEdge::OutputDep,
229     SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
230   { SchedGraphEdge::TrueDep,
231     SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
232     SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
233     | SchedGraphEdge::OutputDep }
234 };
235
236
237 // Add a dependence edge between every pair of machine load/store/call
238 // instructions, where at least one is a store or a call.
239 // Use latency 1 just to ensure that memory operations are ordered;
240 // latency does not otherwise matter (true dependences enforce that).
241 // 
242 void SchedGraph::addMemEdges(const std::vector<SchedGraphNode*>& memNodeVec,
243                              const TargetMachine& target) {
244   const TargetInstrInfo& mii = *target.getInstrInfo();
245   
246   // Instructions in memNodeVec are in execution order within the basic block,
247   // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
248   // 
249   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++) {
250     MachineOpCode fromOpCode = memNodeVec[im]->getOpcode();
251     int fromType = (mii.isCall(fromOpCode)? SG_CALL_REF
252                     : (mii.isLoad(fromOpCode)? SG_LOAD_REF
253                        : SG_STORE_REF));
254     for (unsigned jm=im+1; jm < NM; jm++) {
255       MachineOpCode toOpCode = memNodeVec[jm]->getOpcode();
256       int toType = (mii.isCall(toOpCode)? SG_CALL_REF
257                     : (mii.isLoad(toOpCode)? SG_LOAD_REF
258                        : SG_STORE_REF));
259       
260       if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
261         (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
262                                   SchedGraphEdge::MemoryDep,
263                                   SG_DepOrderArray[fromType][toType], 1);
264     }
265   }
266
267
268 // Add edges from/to CC reg instrs to/from call instrs.
269 // Essentially this prevents anything that sets or uses a CC reg from being
270 // reordered w.r.t. a call.
271 // Use a latency of 0 because we only need to prevent out-of-order issue,
272 // like with control dependences.
273 // 
274 void SchedGraph::addCallDepEdges(const std::vector<SchedGraphNode*>& callDepNodeVec,
275                                  const TargetMachine& target) {
276   const TargetInstrInfo& mii = *target.getInstrInfo();
277   
278   // Instructions in memNodeVec are in execution order within the basic block,
279   // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
280   // 
281   for (unsigned ic=0, NC=callDepNodeVec.size(); ic < NC; ic++)
282     if (mii.isCall(callDepNodeVec[ic]->getOpcode())) {
283       // Add SG_CALL_REF edges from all preds to this instruction.
284       for (unsigned jc=0; jc < ic; jc++)
285         (void) new SchedGraphEdge(callDepNodeVec[jc], callDepNodeVec[ic],
286                                   SchedGraphEdge::MachineRegister,
287                                   MachineIntRegsRID,  0);
288       
289       // And do the same from this instruction to all successors.
290       for (unsigned jc=ic+1; jc < NC; jc++)
291         (void) new SchedGraphEdge(callDepNodeVec[ic], callDepNodeVec[jc],
292                                   SchedGraphEdge::MachineRegister,
293                                   MachineIntRegsRID,  0);
294     }
295   
296 #ifdef CALL_DEP_NODE_VEC_CANNOT_WORK
297   // Find the call instruction nodes and put them in a vector.
298   std::vector<SchedGraphNode*> callNodeVec;
299   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
300     if (mii.isCall(memNodeVec[im]->getOpcode()))
301       callNodeVec.push_back(memNodeVec[im]);
302   
303   // Now walk the entire basic block, looking for CC instructions *and*
304   // call instructions, and keep track of the order of the instructions.
305   // Use the call node vec to quickly find earlier and later call nodes
306   // relative to the current CC instruction.
307   // 
308   int lastCallNodeIdx = -1;
309   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
310     if (mii.isCall(bbMvec[i]->getOpcode())) {
311       ++lastCallNodeIdx;
312       for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
313         if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
314           break;
315       assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
316     }
317     else if (mii.isCCInstr(bbMvec[i]->getOpcode())) {
318       // Add incoming/outgoing edges from/to preceding/later calls
319       SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
320       int j=0;
321       for ( ; j <= lastCallNodeIdx; j++)
322         (void) new SchedGraphEdge(callNodeVec[j], ccNode,
323                                   MachineCCRegsRID, 0);
324       for ( ; j < (int) callNodeVec.size(); j++)
325         (void) new SchedGraphEdge(ccNode, callNodeVec[j],
326                                   MachineCCRegsRID, 0);
327     }
328 #endif
329 }
330
331
332 void SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
333                                     const TargetMachine& target) {
334   // This code assumes that two registers with different numbers are
335   // not aliased!
336   // 
337   for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
338        I != regToRefVecMap.end(); ++I) {
339     int regNum        = (*I).first;
340     RefVec& regRefVec = (*I).second;
341     
342     // regRefVec is ordered by control flow order in the basic block
343     for (unsigned i=0; i < regRefVec.size(); ++i) {
344       SchedGraphNode* node = regRefVec[i].first;
345       unsigned int opNum   = regRefVec[i].second;
346       const MachineOperand& mop =
347         node->getMachineInstr()->getExplOrImplOperand(opNum);
348       bool isDef = mop.isDef() && !mop.isUse();
349       bool isDefAndUse = mop.isDef() && mop.isUse();
350           
351       for (unsigned p=0; p < i; ++p) {
352         SchedGraphNode* prevNode = regRefVec[p].first;
353         if (prevNode != node) {
354           unsigned int prevOpNum = regRefVec[p].second;
355           const MachineOperand& prevMop =
356             prevNode->getMachineInstr()->getExplOrImplOperand(prevOpNum);
357           bool prevIsDef = prevMop.isDef() && !prevMop.isUse();
358           bool prevIsDefAndUse = prevMop.isDef() && prevMop.isUse();
359           if (isDef) {
360             if (prevIsDef)
361               new SchedGraphEdge(prevNode, node, regNum,
362                                  SchedGraphEdge::OutputDep);
363             if (!prevIsDef || prevIsDefAndUse)
364               new SchedGraphEdge(prevNode, node, regNum,
365                                  SchedGraphEdge::AntiDep);
366           }
367           
368           if (prevIsDef)
369             if (!isDef || isDefAndUse)
370               new SchedGraphEdge(prevNode, node, regNum,
371                                  SchedGraphEdge::TrueDep);
372         }
373       }
374     }
375   }
376 }
377
378
379 // Adds dependences to/from refNode from/to all other defs
380 // in the basic block.  refNode may be a use, a def, or both.
381 // We do not consider other uses because we are not building use-use deps.
382 // 
383 void SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
384                                   const RefVec& defVec,
385                                   const Value* defValue,
386                                   bool  refNodeIsDef,
387                                   bool  refNodeIsUse,
388                                   const TargetMachine& target) {
389   // Add true or output dep edges from all def nodes before refNode in BB.
390   // Add anti or output dep edges to all def nodes after refNode.
391   for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I) {
392     if ((*I).first == refNode)
393       continue;                       // Dont add any self-loops
394     
395     if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB()) {
396       // (*).first is before refNode
397       if (refNodeIsDef && !refNodeIsUse)
398         (void) new SchedGraphEdge((*I).first, refNode, defValue,
399                                   SchedGraphEdge::OutputDep);
400       if (refNodeIsUse)
401         (void) new SchedGraphEdge((*I).first, refNode, defValue,
402                                   SchedGraphEdge::TrueDep);
403     } else {
404       // (*).first is after refNode
405       if (refNodeIsDef && !refNodeIsUse)
406         (void) new SchedGraphEdge(refNode, (*I).first, defValue,
407                                   SchedGraphEdge::OutputDep);
408       if (refNodeIsUse)
409         (void) new SchedGraphEdge(refNode, (*I).first, defValue,
410                                   SchedGraphEdge::AntiDep);
411     }
412   }
413 }
414
415
416 void SchedGraph::addEdgesForInstruction(const MachineInstr& MI,
417                                         const ValueToDefVecMap& valueToDefVecMap,
418                                         const TargetMachine& target) {
419   SchedGraphNode* node = getGraphNodeForInstr(&MI);
420   if (node == NULL)
421     return;
422   
423   // Add edges for all operands of the machine instruction.
424   // 
425   for (unsigned i = 0, numOps = MI.getNumOperands(); i != numOps; ++i) {
426     switch (MI.getOperand(i).getType()) {
427     case MachineOperand::MO_VirtualRegister:
428     case MachineOperand::MO_CCRegister:
429       if (const Value* srcI = MI.getOperand(i).getVRegValue()) {
430         ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
431         if (I != valueToDefVecMap.end())
432           addEdgesForValue(node, I->second, srcI,
433                            MI.getOperand(i).isDef(), MI.getOperand(i).isUse(),
434                            target);
435       }
436       break;
437       
438     case MachineOperand::MO_MachineRegister:
439       break; 
440       
441     case MachineOperand::MO_SignExtendedImmed:
442     case MachineOperand::MO_UnextendedImmed:
443     case MachineOperand::MO_PCRelativeDisp:
444     case MachineOperand::MO_ConstantPoolIndex:
445       break;    // nothing to do for immediate fields
446       
447     default:
448       assert(0 && "Unknown machine operand type in SchedGraph builder");
449       break;
450     }
451   }
452   
453   // Add edges for values implicitly used by the machine instruction.
454   // Examples include function arguments to a Call instructions or the return
455   // value of a Ret instruction.
456   // 
457   for (unsigned i=0, N=MI.getNumImplicitRefs(); i < N; ++i)
458     if (MI.getImplicitOp(i).isUse())
459       if (const Value* srcI = MI.getImplicitRef(i)) {
460         ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
461         if (I != valueToDefVecMap.end())
462           addEdgesForValue(node, I->second, srcI,
463                            MI.getImplicitOp(i).isDef(),
464                            MI.getImplicitOp(i).isUse(), target);
465       }
466 }
467
468
469 void SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
470                                        SchedGraphNode* node,
471                                        std::vector<SchedGraphNode*>& memNodeVec,
472                                        std::vector<SchedGraphNode*>& callDepNodeVec,
473                                        RegToRefVecMap& regToRefVecMap,
474                                        ValueToDefVecMap& valueToDefVecMap) {
475   const TargetInstrInfo& mii = *target.getInstrInfo();
476   
477   MachineOpCode opCode = node->getOpcode();
478   
479   if (mii.isCall(opCode) || mii.isCCInstr(opCode))
480     callDepNodeVec.push_back(node);
481   
482   if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
483     memNodeVec.push_back(node);
484   
485   // Collect the register references and value defs. for explicit operands
486   // 
487   const MachineInstr& MI = *node->getMachineInstr();
488   for (int i=0, numOps = (int) MI.getNumOperands(); i < numOps; i++) {
489     const MachineOperand& mop = MI.getOperand(i);
490     
491     // if this references a register other than the hardwired
492     // "zero" register, record the reference.
493     if (mop.hasAllocatedReg()) {
494       unsigned regNum = mop.getReg();
495       
496       // If this is not a dummy zero register, record the reference in order
497       if (regNum != target.getRegInfo()->getZeroRegNum())
498         regToRefVecMap[mop.getReg()]
499           .push_back(std::make_pair(node, i));
500
501       // If this is a volatile register, add the instruction to callDepVec
502       // (only if the node is not already on the callDepVec!)
503       if (callDepNodeVec.size() == 0 || callDepNodeVec.back() != node)
504         {
505           unsigned rcid;
506           int regInClass = target.getRegInfo()->getClassRegNum(regNum, rcid);
507           if (target.getRegInfo()->getMachineRegClass(rcid)
508               ->isRegVolatile(regInClass))
509             callDepNodeVec.push_back(node);
510         }
511           
512       continue;                     // nothing more to do
513     }
514     
515     // ignore all other non-def operands
516     if (!MI.getOperand(i).isDef())
517       continue;
518       
519     // We must be defining a value.
520     assert((mop.getType() == MachineOperand::MO_VirtualRegister ||
521             mop.getType() == MachineOperand::MO_CCRegister)
522            && "Do not expect any other kind of operand to be defined!");
523     assert(mop.getVRegValue() != NULL && "Null value being defined?");
524     
525     valueToDefVecMap[mop.getVRegValue()].push_back(std::make_pair(node, i)); 
526   }
527   
528   // 
529   // Collect value defs. for implicit operands.  They may have allocated
530   // physical registers also.
531   // 
532   for (unsigned i=0, N = MI.getNumImplicitRefs(); i != N; ++i) {
533     const MachineOperand& mop = MI.getImplicitOp(i);
534     if (mop.hasAllocatedReg()) {
535       unsigned regNum = mop.getReg();
536       if (regNum != target.getRegInfo()->getZeroRegNum())
537         regToRefVecMap[mop.getReg()]
538           .push_back(std::make_pair(node, i + MI.getNumOperands()));
539       continue;                     // nothing more to do
540     }
541
542     if (mop.isDef()) {
543       assert(MI.getImplicitRef(i) != NULL && "Null value being defined?");
544       valueToDefVecMap[MI.getImplicitRef(i)].push_back(
545         std::make_pair(node, -i)); 
546     }
547   }
548 }
549
550
551 void SchedGraph::buildNodesForBB(const TargetMachine& target,
552                                  MachineBasicBlock& MBB,
553                                  std::vector<SchedGraphNode*>& memNodeVec,
554                                  std::vector<SchedGraphNode*>& callDepNodeVec,
555                                  RegToRefVecMap& regToRefVecMap,
556                                  ValueToDefVecMap& valueToDefVecMap) {
557   const TargetInstrInfo& mii = *target.getInstrInfo();
558   
559   // Build graph nodes for each VM instruction and gather def/use info.
560   // Do both those together in a single pass over all machine instructions.
561   unsigned i = 0;
562   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
563        ++I, ++i)
564     if (!mii.isDummyPhiInstr(I->getOpcode())) {
565       SchedGraphNode* node = new SchedGraphNode(getNumNodes(), &MBB, i, target);
566       noteGraphNodeForInstr(I, node);
567       
568       // Remember all register references and value defs
569       findDefUseInfoAtInstr(target, node, memNodeVec, callDepNodeVec,
570                             regToRefVecMap, valueToDefVecMap);
571     }
572 }
573
574
575 void SchedGraph::buildGraph(const TargetMachine& target) {
576   // Use this data structure to note all machine operands that compute
577   // ordinary LLVM values.  These must be computed defs (i.e., instructions). 
578   // Note that there may be multiple machine instructions that define
579   // each Value.
580   ValueToDefVecMap valueToDefVecMap;
581   
582   // Use this data structure to note all memory instructions.
583   // We use this to add memory dependence edges without a second full walk.
584   std::vector<SchedGraphNode*> memNodeVec;
585
586   // Use this data structure to note all instructions that access physical
587   // registers that can be modified by a call (including call instructions)
588   std::vector<SchedGraphNode*> callDepNodeVec;
589   
590   // Use this data structure to note any uses or definitions of
591   // machine registers so we can add edges for those later without
592   // extra passes over the nodes.
593   // The vector holds an ordered list of references to the machine reg,
594   // ordered according to control-flow order.  This only works for a
595   // single basic block, hence the assertion.  Each reference is identified
596   // by the pair: <node, operand-number>.
597   // 
598   RegToRefVecMap regToRefVecMap;
599   
600   // Make a dummy root node.  We'll add edges to the real roots later.
601   graphRoot = new SchedGraphNode(0, NULL, -1, target);
602   graphLeaf = new SchedGraphNode(1, NULL, -1, target);
603
604   //----------------------------------------------------------------
605   // First add nodes for all the machine instructions in the basic block
606   // because this greatly simplifies identifying which edges to add.
607   // Do this one VM instruction at a time since the SchedGraphNode needs that.
608   // Also, remember the load/store instructions to add memory deps later.
609   //----------------------------------------------------------------
610
611   buildNodesForBB(target, MBB, memNodeVec, callDepNodeVec,
612                   regToRefVecMap, valueToDefVecMap);
613   
614   //----------------------------------------------------------------
615   // Now add edges for the following (all are incoming edges except (4)):
616   // (1) operands of the machine instruction, including hidden operands
617   // (2) machine register dependences
618   // (3) memory load/store dependences
619   // (3) other resource dependences for the machine instruction, if any
620   // (4) output dependences when multiple machine instructions define the
621   //     same value; all must have been generated from a single VM instrn
622   // (5) control dependences to branch instructions generated for the
623   //     terminator instruction of the BB. Because of delay slots and
624   //     2-way conditional branches, multiple CD edges are needed
625   //     (see addCDEdges for details).
626   // Also, note any uses or defs of machine registers.
627   // 
628   //----------------------------------------------------------------
629       
630   // First, add edges to the terminator instruction of the basic block.
631   this->addCDEdges(MBB.getBasicBlock()->getTerminator(), target);
632       
633   // Then add memory dep edges: store->load, load->store, and store->store.
634   // Call instructions are treated as both load and store.
635   this->addMemEdges(memNodeVec, target);
636
637   // Then add edges between call instructions and CC set/use instructions
638   this->addCallDepEdges(callDepNodeVec, target);
639   
640   // Then add incoming def-use (SSA) edges for each machine instruction.
641   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
642     addEdgesForInstruction(*I, valueToDefVecMap, target);
643
644   // Then add edges for dependences on machine registers
645   this->addMachineRegEdges(regToRefVecMap, target);
646
647   // Finally, add edges from the dummy root and to dummy leaf
648   this->addDummyEdges();                
649 }
650
651
652 // 
653 // class SchedGraphSet
654 // 
655 SchedGraphSet::SchedGraphSet(const Function* _function,
656                              const TargetMachine& target) :
657   function(_function) {
658   buildGraphsForMethod(function, target);
659 }
660
661 SchedGraphSet::~SchedGraphSet() {
662   // delete all the graphs
663   for(iterator I = begin(), E = end(); I != E; ++I)
664     delete *I;  // destructor is a friend
665 }
666
667
668 void SchedGraphSet::dump() const {
669   std::cerr << "======== Sched graphs for function `" << function->getName()
670             << "' ========\n\n";
671   
672   for (const_iterator I=begin(); I != end(); ++I)
673     (*I)->dump();
674   
675   std::cerr << "\n====== End graphs for function `" << function->getName()
676             << "' ========\n\n";
677 }
678
679
680 void SchedGraphSet::buildGraphsForMethod(const Function *F,
681                                          const TargetMachine& target) {
682   MachineFunction &MF = MachineFunction::get(F);
683   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
684     addGraph(new SchedGraph(*I, target));
685 }
686
687
688 void SchedGraphEdge::print(std::ostream &os) const {
689   os << "edge [" << src->getNodeId() << "] -> ["
690      << sink->getNodeId() << "] : ";
691   
692   switch(depType) {
693   case SchedGraphEdge::CtrlDep:         
694     os<< "Control Dep"; 
695     break;
696   case SchedGraphEdge::ValueDep:        
697     os<< "Reg Value " << *val; 
698     break;
699   case SchedGraphEdge::MemoryDep:       
700     os<< "Memory Dep"; 
701     break;
702   case SchedGraphEdge::MachineRegister: 
703     os<< "Reg " << machineRegNum;
704     break;
705   case SchedGraphEdge::MachineResource:
706     os<<"Resource "<< resourceId;
707     break;
708   default: 
709     assert(0); 
710     break;
711   }
712   
713   os << " : delay = " << minDelay << "\n";
714 }
715
716 void SchedGraphNode::print(std::ostream &os) const {
717   os << std::string(8, ' ')
718      << "Node " << ID << " : "
719      << "latency = " << latency << "\n" << std::string(12, ' ');
720   
721   if (getMachineInstr() == NULL)
722     os << "(Dummy node)\n";
723   else {
724     os << *getMachineInstr() << "\n" << std::string(12, ' ');
725     os << inEdges.size() << " Incoming Edges:\n";
726     for (unsigned i=0, N = inEdges.size(); i < N; i++)
727       os << std::string(16, ' ') << *inEdges[i];
728   
729     os << std::string(12, ' ') << outEdges.size()
730        << " Outgoing Edges:\n";
731     for (unsigned i=0, N= outEdges.size(); i < N; i++)
732       os << std::string(16, ' ') << *outEdges[i];
733   }
734 }
735
736 } // End llvm namespace