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