*** empty log message ***
[oota-llvm.git] / lib / CodeGen / InstrSched / SchedGraph.cpp
1 // $Id$
2 //***************************************************************************
3 // File:
4 //      SchedGraph.cpp
5 // 
6 // Purpose:
7 //      Scheduling graph based on SSA graph plus extra dependence edges
8 //      capturing dependences due to machine resources (machine registers,
9 //      CC registers, and any others).
10 // 
11 // History:
12 //      7/20/01  -  Vikram Adve  -  Created
13 //**************************************************************************/
14
15 #include "SchedGraph.h"
16 #include "llvm/CodeGen/InstrSelection.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
19 #include "llvm/Target/MachineRegInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Function.h"
23 #include "llvm/iOther.h"
24 #include "Support/StringExtras.h"
25 #include "Support/STLExtras.h"
26 #include <iostream>
27
28 using std::vector;
29 using std::pair;
30 using std::cerr;
31
32 //*********************** Internal Data Structures *************************/
33
34 // The following two types need to be classes, not typedefs, so we can use
35 // opaque declarations in SchedGraph.h
36 // 
37 struct RefVec: public vector< pair<SchedGraphNode*, int> > {
38   typedef vector< pair<SchedGraphNode*, int> >::      iterator       iterator;
39   typedef vector< pair<SchedGraphNode*, int> >::const_iterator const_iterator;
40 };
41
42 struct RegToRefVecMap: public hash_map<int, RefVec> {
43   typedef hash_map<int, RefVec>::      iterator       iterator;
44   typedef hash_map<int, RefVec>::const_iterator const_iterator;
45 };
46
47 struct ValueToDefVecMap: public hash_map<const Instruction*, RefVec> {
48   typedef hash_map<const Instruction*, RefVec>::      iterator       iterator;
49   typedef hash_map<const Instruction*, RefVec>::const_iterator const_iterator;
50 };
51
52 // 
53 // class SchedGraphEdge
54 // 
55
56 /*ctor*/
57 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
58                                SchedGraphNode* _sink,
59                                SchedGraphEdgeDepType _depType,
60                                unsigned int     _depOrderType,
61                                int _minDelay)
62   : src(_src),
63     sink(_sink),
64     depType(_depType),
65     depOrderType(_depOrderType),
66     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
67     val(NULL)
68 {
69   assert(src != sink && "Self-loop in scheduling graph!");
70   src->addOutEdge(this);
71   sink->addInEdge(this);
72 }
73
74
75 /*ctor*/
76 SchedGraphEdge::SchedGraphEdge(SchedGraphNode*  _src,
77                                SchedGraphNode*  _sink,
78                                const Value*     _val,
79                                unsigned int     _depOrderType,
80                                int              _minDelay)
81   : src(_src),
82     sink(_sink),
83     depType(ValueDep),
84     depOrderType(_depOrderType),
85     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
86     val(_val)
87 {
88   assert(src != sink && "Self-loop in scheduling graph!");
89   src->addOutEdge(this);
90   sink->addInEdge(this);
91 }
92
93
94 /*ctor*/
95 SchedGraphEdge::SchedGraphEdge(SchedGraphNode*  _src,
96                                SchedGraphNode*  _sink,
97                                unsigned int     _regNum,
98                                unsigned int     _depOrderType,
99                                int             _minDelay)
100   : src(_src),
101     sink(_sink),
102     depType(MachineRegister),
103     depOrderType(_depOrderType),
104     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
105     machineRegNum(_regNum)
106 {
107   assert(src != sink && "Self-loop in scheduling graph!");
108   src->addOutEdge(this);
109   sink->addInEdge(this);
110 }
111
112
113 /*ctor*/
114 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
115                                SchedGraphNode* _sink,
116                                ResourceId      _resourceId,
117                                int             _minDelay)
118   : src(_src),
119     sink(_sink),
120     depType(MachineResource),
121     depOrderType(NonDataDep),
122     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
123     resourceId(_resourceId)
124 {
125   assert(src != sink && "Self-loop in scheduling graph!");
126   src->addOutEdge(this);
127   sink->addInEdge(this);
128 }
129
130 /*dtor*/
131 SchedGraphEdge::~SchedGraphEdge()
132 {
133 }
134
135 void SchedGraphEdge::dump(int indent) const {
136   cerr << std::string(indent*2, ' ') << *this; 
137 }
138
139
140 // 
141 // class SchedGraphNode
142 // 
143
144 /*ctor*/
145 SchedGraphNode::SchedGraphNode(unsigned int _nodeId,
146                                const BasicBlock*   _bb,
147                                const MachineInstr* _minstr,
148                                int   indexInBB,
149                                const TargetMachine& target)
150   : nodeId(_nodeId),
151     bb(_bb),
152     minstr(_minstr),
153     origIndexInBB(indexInBB),
154     latency(0)
155 {
156   if (minstr)
157     {
158       MachineOpCode mopCode = minstr->getOpCode();
159       latency = target.getInstrInfo().hasResultInterlock(mopCode)
160         ? target.getInstrInfo().minLatency(mopCode)
161         : target.getInstrInfo().maxLatency(mopCode);
162     }
163 }
164
165
166 /*dtor*/
167 SchedGraphNode::~SchedGraphNode()
168 {
169   // for each node, delete its out-edges
170   std::for_each(beginOutEdges(), endOutEdges(),
171                 deleter<SchedGraphEdge>);
172 }
173
174 void SchedGraphNode::dump(int indent) const {
175   cerr << std::string(indent*2, ' ') << *this; 
176 }
177
178
179 inline void
180 SchedGraphNode::addInEdge(SchedGraphEdge* edge)
181 {
182   inEdges.push_back(edge);
183 }
184
185
186 inline void
187 SchedGraphNode::addOutEdge(SchedGraphEdge* edge)
188 {
189   outEdges.push_back(edge);
190 }
191
192 inline void
193 SchedGraphNode::removeInEdge(const SchedGraphEdge* edge)
194 {
195   assert(edge->getSink() == this);
196   
197   for (iterator I = beginInEdges(); I != endInEdges(); ++I)
198     if ((*I) == edge)
199       {
200         inEdges.erase(I);
201         break;
202       }
203 }
204
205 inline void
206 SchedGraphNode::removeOutEdge(const SchedGraphEdge* edge)
207 {
208   assert(edge->getSrc() == this);
209   
210   for (iterator I = beginOutEdges(); I != endOutEdges(); ++I)
211     if ((*I) == edge)
212       {
213         outEdges.erase(I);
214         break;
215       }
216 }
217
218
219 // 
220 // class SchedGraph
221 // 
222
223
224 /*ctor*/
225 SchedGraph::SchedGraph(const BasicBlock* bb,
226                        const TargetMachine& target)
227 {
228   bbVec.push_back(bb);
229   buildGraph(target);
230 }
231
232
233 /*dtor*/
234 SchedGraph::~SchedGraph()
235 {
236   for (const_iterator I = begin(); I != end(); ++I)
237     delete I->second;
238   delete graphRoot;
239   delete graphLeaf;
240 }
241
242
243 void
244 SchedGraph::dump() const
245 {
246   cerr << "  Sched Graph for Basic Blocks: ";
247   for (unsigned i=0, N=bbVec.size(); i < N; i++)
248     {
249       cerr << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
250            << " (" << bbVec[i] << ")"
251            << ((i == N-1)? "" : ", ");
252     }
253   
254   cerr << "\n\n    Actual Root nodes : ";
255   for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
256     cerr << graphRoot->outEdges[i]->getSink()->getNodeId()
257          << ((i == N-1)? "" : ", ");
258   
259   cerr << "\n    Graph Nodes:\n";
260   for (const_iterator I=begin(); I != end(); ++I)
261     cerr << "\n" << *I->second;
262   
263   cerr << "\n";
264 }
265
266
267 void
268 SchedGraph::eraseIncomingEdges(SchedGraphNode* node, bool addDummyEdges)
269 {
270   // Delete and disconnect all in-edges for the node
271   for (SchedGraphNode::iterator I = node->beginInEdges();
272        I != node->endInEdges(); ++I)
273     {
274       SchedGraphNode* srcNode = (*I)->getSrc();
275       srcNode->removeOutEdge(*I);
276       delete *I;
277       
278       if (addDummyEdges &&
279           srcNode != getRoot() &&
280           srcNode->beginOutEdges() == srcNode->endOutEdges())
281         { // srcNode has no more out edges, so add an edge to dummy EXIT node
282           assert(node != getLeaf() && "Adding edge that was just removed?");
283           (void) new SchedGraphEdge(srcNode, getLeaf(),
284                     SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
285         }
286     }
287   
288   node->inEdges.clear();
289 }
290
291 void
292 SchedGraph::eraseOutgoingEdges(SchedGraphNode* node, bool addDummyEdges)
293 {
294   // Delete and disconnect all out-edges for the node
295   for (SchedGraphNode::iterator I = node->beginOutEdges();
296        I != node->endOutEdges(); ++I)
297     {
298       SchedGraphNode* sinkNode = (*I)->getSink();
299       sinkNode->removeInEdge(*I);
300       delete *I;
301       
302       if (addDummyEdges &&
303           sinkNode != getLeaf() &&
304           sinkNode->beginInEdges() == sinkNode->endInEdges())
305         { //sinkNode has no more in edges, so add an edge from dummy ENTRY node
306           assert(node != getRoot() && "Adding edge that was just removed?");
307           (void) new SchedGraphEdge(getRoot(), sinkNode,
308                     SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
309         }
310     }
311   
312   node->outEdges.clear();
313 }
314
315 void
316 SchedGraph::eraseIncidentEdges(SchedGraphNode* node, bool addDummyEdges)
317 {
318   this->eraseIncomingEdges(node, addDummyEdges);        
319   this->eraseOutgoingEdges(node, addDummyEdges);        
320 }
321
322
323 void
324 SchedGraph::addDummyEdges()
325 {
326   assert(graphRoot->outEdges.size() == 0);
327   
328   for (const_iterator I=begin(); I != end(); ++I)
329     {
330       SchedGraphNode* node = (*I).second;
331       assert(node != graphRoot && node != graphLeaf);
332       if (node->beginInEdges() == node->endInEdges())
333         (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
334                                   SchedGraphEdge::NonDataDep, 0);
335       if (node->beginOutEdges() == node->endOutEdges())
336         (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
337                                   SchedGraphEdge::NonDataDep, 0);
338     }
339 }
340
341
342 void
343 SchedGraph::addCDEdges(const TerminatorInst* term,
344                        const TargetMachine& target)
345 {
346   const MachineInstrInfo& mii = target.getInstrInfo();
347   MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
348   
349   // Find the first branch instr in the sequence of machine instrs for term
350   // 
351   unsigned first = 0;
352   while (!mii.isBranch(termMvec[first]->getOpCode()))
353     ++first;
354   assert(first < termMvec.size() &&
355          "No branch instructions for BR?  Ok, but weird!  Delete assertion.");
356   if (first == termMvec.size())
357     return;
358   
359   SchedGraphNode* firstBrNode = this->getGraphNodeForInstr(termMvec[first]);
360   
361   // Add CD edges from each instruction in the sequence to the
362   // *last preceding* branch instr. in the sequence 
363   // Use a latency of 0 because we only need to prevent out-of-order issue.
364   // 
365   for (int i = (int) termMvec.size()-1; i > (int) first; i--) 
366     {
367       SchedGraphNode* toNode = this->getGraphNodeForInstr(termMvec[i]);
368       assert(toNode && "No node for instr generated for branch?");
369       
370       for (int j = i-1; j >= 0; j--) 
371         if (mii.isBranch(termMvec[j]->getOpCode()))
372           {
373             SchedGraphNode* brNode = this->getGraphNodeForInstr(termMvec[j]);
374             assert(brNode && "No node for instr generated for branch?");
375             (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
376                                       SchedGraphEdge::NonDataDep, 0);
377             break;                      // only one incoming edge is enough
378           }
379     }
380   
381   // Add CD edges from each instruction preceding the first branch
382   // to the first branch.  Use a latency of 0 as above.
383   // 
384   for (int i = first-1; i >= 0; i--) 
385     {
386       SchedGraphNode* fromNode = this->getGraphNodeForInstr(termMvec[i]);
387       assert(fromNode && "No node for instr generated for branch?");
388       (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
389                                 SchedGraphEdge::NonDataDep, 0);
390     }
391   
392   // Now add CD edges to the first branch instruction in the sequence from
393   // all preceding instructions in the basic block.  Use 0 latency again.
394   // 
395   const BasicBlock* bb = firstBrNode->getBB();
396   const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
397   for (unsigned i=0, N=mvec.size(); i < N; i++) 
398     {
399       if (mvec[i] == termMvec[first]) // reached the first branch
400         break;
401       
402       SchedGraphNode* fromNode = this->getGraphNodeForInstr(mvec[i]);
403       if (fromNode == NULL)
404         continue;                       // dummy instruction, e.g., PHI
405       
406       (void) new SchedGraphEdge(fromNode, firstBrNode,
407                                 SchedGraphEdge::CtrlDep,
408                                 SchedGraphEdge::NonDataDep, 0);
409       
410       // If we find any other machine instructions (other than due to
411       // the terminator) that also have delay slots, add an outgoing edge
412       // from the instruction to the instructions in the delay slots.
413       // 
414       unsigned d = mii.getNumDelaySlots(mvec[i]->getOpCode());
415       assert(i+d < N && "Insufficient delay slots for instruction?");
416       
417       for (unsigned j=1; j <= d; j++)
418         {
419           SchedGraphNode* toNode = this->getGraphNodeForInstr(mvec[i+j]);
420           assert(toNode && "No node for machine instr in delay slot?");
421           (void) new SchedGraphEdge(fromNode, toNode,
422                                     SchedGraphEdge::CtrlDep,
423                                     SchedGraphEdge::NonDataDep, 0);
424         }
425     }
426 }
427
428 static const int SG_LOAD_REF  = 0;
429 static const int SG_STORE_REF = 1;
430 static const int SG_CALL_REF  = 2;
431
432 static const unsigned int SG_DepOrderArray[][3] = {
433   { SchedGraphEdge::NonDataDep,
434             SchedGraphEdge::AntiDep,
435                         SchedGraphEdge::AntiDep },
436   { SchedGraphEdge::TrueDep,
437             SchedGraphEdge::OutputDep,
438                         SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
439   { SchedGraphEdge::TrueDep,
440             SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
441                         SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
442                                                 | SchedGraphEdge::OutputDep }
443 };
444
445
446 // Add a dependence edge between every pair of machine load/store/call
447 // instructions, where at least one is a store or a call.
448 // Use latency 1 just to ensure that memory operations are ordered;
449 // latency does not otherwise matter (true dependences enforce that).
450 // 
451 void
452 SchedGraph::addMemEdges(const vector<SchedGraphNode*>& memNodeVec,
453                         const TargetMachine& target)
454 {
455   const MachineInstrInfo& mii = target.getInstrInfo();
456   
457   // Instructions in memNodeVec are in execution order within the basic block,
458   // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
459   // 
460   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
461     {
462       MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
463       int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
464                        : mii.isLoad(fromOpCode)? SG_LOAD_REF
465                                                : SG_STORE_REF;
466       for (unsigned jm=im+1; jm < NM; jm++)
467         {
468           MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
469           int toType = mii.isCall(toOpCode)? SG_CALL_REF
470                          : mii.isLoad(toOpCode)? SG_LOAD_REF
471                                                : SG_STORE_REF;
472           
473           if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
474             (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
475                                       SchedGraphEdge::MemoryDep,
476                                       SG_DepOrderArray[fromType][toType], 1);
477         }
478     }
479
480
481 // Add edges from/to CC reg instrs to/from call instrs.
482 // Essentially this prevents anything that sets or uses a CC reg from being
483 // reordered w.r.t. a call.
484 // Use a latency of 0 because we only need to prevent out-of-order issue,
485 // like with control dependences.
486 // 
487 void
488 SchedGraph::addCallCCEdges(const vector<SchedGraphNode*>& memNodeVec,
489                            MachineCodeForBasicBlock& bbMvec,
490                            const TargetMachine& target)
491 {
492   const MachineInstrInfo& mii = target.getInstrInfo();
493   vector<SchedGraphNode*> callNodeVec;
494   
495   // Find the call instruction nodes and put them in a vector.
496   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
497     if (mii.isCall(memNodeVec[im]->getOpCode()))
498       callNodeVec.push_back(memNodeVec[im]);
499   
500   // Now walk the entire basic block, looking for CC instructions *and*
501   // call instructions, and keep track of the order of the instructions.
502   // Use the call node vec to quickly find earlier and later call nodes
503   // relative to the current CC instruction.
504   // 
505   int lastCallNodeIdx = -1;
506   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
507     if (mii.isCall(bbMvec[i]->getOpCode()))
508       {
509         ++lastCallNodeIdx;
510         for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
511           if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
512             break;
513         assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
514       }
515     else if (mii.isCCInstr(bbMvec[i]->getOpCode()))
516       { // Add incoming/outgoing edges from/to preceding/later calls
517         SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
518         int j=0;
519         for ( ; j <= lastCallNodeIdx; j++)
520           (void) new SchedGraphEdge(callNodeVec[j], ccNode,
521                                     MachineCCRegsRID, 0);
522         for ( ; j < (int) callNodeVec.size(); j++)
523           (void) new SchedGraphEdge(ccNode, callNodeVec[j],
524                                     MachineCCRegsRID, 0);
525       }
526 }
527
528
529 void
530 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
531                                const TargetMachine& target)
532 {
533   assert(bbVec.size() == 1 && "Only handling a single basic block here");
534   
535   // This assumes that such hardwired registers are never allocated
536   // to any LLVM value (since register allocation happens later), i.e.,
537   // any uses or defs of this register have been made explicit!
538   // Also assumes that two registers with different numbers are
539   // not aliased!
540   // 
541   for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
542        I != regToRefVecMap.end(); ++I)
543     {
544       int regNum        = (*I).first;
545       RefVec& regRefVec = (*I).second;
546       
547       // regRefVec is ordered by control flow order in the basic block
548       for (unsigned i=0; i < regRefVec.size(); ++i)
549         {
550           SchedGraphNode* node = regRefVec[i].first;
551           unsigned int opNum   = regRefVec[i].second;
552           bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
553           bool isDefAndUse =
554             node->getMachineInstr()->operandIsDefinedAndUsed(opNum);
555           
556           for (unsigned p=0; p < i; ++p)
557             {
558               SchedGraphNode* prevNode = regRefVec[p].first;
559               if (prevNode != node)
560                 {
561                   unsigned int prevOpNum = regRefVec[p].second;
562                   bool prevIsDef =
563                     prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
564                   bool prevIsDefAndUse =
565                     prevNode->getMachineInstr()->operandIsDefinedAndUsed(prevOpNum);
566                   if (isDef)
567                     {
568                       if (prevIsDef)
569                         new SchedGraphEdge(prevNode, node, regNum,
570                                            SchedGraphEdge::OutputDep);
571                       if (!prevIsDef || prevIsDefAndUse)
572                         new SchedGraphEdge(prevNode, node, regNum,
573                                            SchedGraphEdge::AntiDep);
574                     }
575                   
576                   if (prevIsDef)
577                     if (!isDef || isDefAndUse)
578                       new SchedGraphEdge(prevNode, node, regNum,
579                                          SchedGraphEdge::TrueDep);
580                 }
581             }
582         }
583     }
584 }
585
586
587 // Adds dependences to/from refNode from/to all other defs
588 // in the basic block.  refNode may be a use, a def, or both.
589 // We do not consider other uses because we are not building use-use deps.
590 // 
591 void
592 SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
593                              const RefVec& defVec,
594                              const Value* defValue,
595                              bool  refNodeIsDef,
596                              bool  refNodeIsDefAndUse,
597                              const TargetMachine& target)
598 {
599   bool refNodeIsUse = !refNodeIsDef || refNodeIsDefAndUse;
600   
601   // Add true or output dep edges from all def nodes before refNode in BB.
602   // Add anti or output dep edges to all def nodes after refNode.
603   for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
604     {
605       if ((*I).first == refNode)
606         continue;                       // Dont add any self-loops
607       
608       if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB())
609         { // (*).first is before refNode
610           if (refNodeIsDef)
611             (void) new SchedGraphEdge((*I).first, refNode, defValue,
612                                       SchedGraphEdge::OutputDep);
613           if (refNodeIsUse)
614             (void) new SchedGraphEdge((*I).first, refNode, defValue,
615                                       SchedGraphEdge::TrueDep);
616         }
617       else
618         { // (*).first is after refNode
619           if (refNodeIsDef)
620             (void) new SchedGraphEdge(refNode, (*I).first, defValue,
621                                       SchedGraphEdge::OutputDep);
622           if (refNodeIsUse)
623             (void) new SchedGraphEdge(refNode, (*I).first, defValue,
624                                       SchedGraphEdge::AntiDep);
625         }
626     }
627 }
628
629
630 void
631 SchedGraph::addEdgesForInstruction(const MachineInstr& minstr,
632                                    const ValueToDefVecMap& valueToDefVecMap,
633                                    const TargetMachine& target)
634 {
635   SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
636   if (node == NULL)
637     return;
638   
639   // Add edges for all operands of the machine instruction.
640   // 
641   for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
642     {
643       const MachineOperand& mop = minstr.getOperand(i);
644       switch(mop.getOperandType())
645         {
646         case MachineOperand::MO_VirtualRegister:
647         case MachineOperand::MO_CCRegister:
648           if (const Instruction* srcI =
649               dyn_cast_or_null<Instruction>(mop.getVRegValue()))
650             {
651               ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
652               if (I != valueToDefVecMap.end())
653                 addEdgesForValue(node, (*I).second, mop.getVRegValue(),
654                                  minstr.operandIsDefined(i),
655                                  minstr.operandIsDefinedAndUsed(i), target);
656             }
657           break;
658           
659         case MachineOperand::MO_MachineRegister:
660           break; 
661           
662         case MachineOperand::MO_SignExtendedImmed:
663         case MachineOperand::MO_UnextendedImmed:
664         case MachineOperand::MO_PCRelativeDisp:
665           break;        // nothing to do for immediate fields
666           
667         default:
668           assert(0 && "Unknown machine operand type in SchedGraph builder");
669           break;
670         }
671     }
672   
673   // Add edges for values implicitly used by the machine instruction.
674   // Examples include function arguments to a Call instructions or the return
675   // value of a Ret instruction.
676   // 
677   for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
678     if (! minstr.implicitRefIsDefined(i) ||
679         minstr.implicitRefIsDefinedAndUsed(i))
680       if (const Instruction* srcI =
681           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
682         {
683           ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
684           if (I != valueToDefVecMap.end())
685             addEdgesForValue(node, (*I).second, minstr.getImplicitRef(i),
686                              minstr.implicitRefIsDefined(i),
687                              minstr.implicitRefIsDefinedAndUsed(i), target);
688         }
689 }
690
691
692 void
693 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
694                                   SchedGraphNode* node,
695                                   vector<SchedGraphNode*>& memNodeVec,
696                                   RegToRefVecMap& regToRefVecMap,
697                                   ValueToDefVecMap& valueToDefVecMap)
698 {
699   const MachineInstrInfo& mii = target.getInstrInfo();
700   
701   
702   MachineOpCode opCode = node->getOpCode();
703   if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
704     memNodeVec.push_back(node);
705   
706   // Collect the register references and value defs. for explicit operands
707   // 
708   const MachineInstr& minstr = * node->getMachineInstr();
709   for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
710     {
711       const MachineOperand& mop = minstr.getOperand(i);
712       
713       // if this references a register other than the hardwired
714       // "zero" register, record the reference.
715       if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
716         {
717           int regNum = mop.getMachineRegNum();
718           if (regNum != target.getRegInfo().getZeroRegNum())
719             regToRefVecMap[mop.getMachineRegNum()].push_back(
720                                                   std::make_pair(node, i));
721           continue;                     // nothing more to do
722         }
723       
724       // ignore all other non-def operands
725       if (! minstr.operandIsDefined(i))
726         continue;
727       
728       // We must be defining a value.
729       assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
730               mop.getOperandType() == MachineOperand::MO_CCRegister)
731              && "Do not expect any other kind of operand to be defined!");
732       
733       const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
734       valueToDefVecMap[defInstr].push_back(std::make_pair(node, i)); 
735     }
736   
737   // 
738   // Collect value defs. for implicit operands.  The interface to extract
739   // them assumes they must be virtual registers!
740   // 
741   for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
742     if (minstr.implicitRefIsDefined(i))
743       if (const Instruction* defInstr =
744           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
745         {
746           valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i)); 
747         }
748 }
749
750
751 void
752 SchedGraph::buildNodesforBB(const TargetMachine& target,
753                             const BasicBlock* bb,
754                             vector<SchedGraphNode*>& memNodeVec,
755                             RegToRefVecMap& regToRefVecMap,
756                             ValueToDefVecMap& valueToDefVecMap)
757 {
758   const MachineInstrInfo& mii = target.getInstrInfo();
759   
760   // Build graph nodes for each VM instruction and gather def/use info.
761   // Do both those together in a single pass over all machine instructions.
762   const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
763   for (unsigned i=0; i < mvec.size(); i++)
764     if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
765       {
766         SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
767                                                   mvec[i], i, target);
768         this->noteGraphNodeForInstr(mvec[i], node);
769         
770         // Remember all register references and value defs
771         findDefUseInfoAtInstr(target, node,
772                               memNodeVec, regToRefVecMap,valueToDefVecMap);
773       }
774   
775 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
776 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
777   // This is a BIG UGLY HACK.  IT NEEDS TO BE ELIMINATED.
778   // Look for copy instructions inserted in this BB due to Phi instructions
779   // in the successor BBs.
780   // There MUST be exactly one copy per Phi in successor nodes.
781   // 
782   for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
783        SI != SE; ++SI)
784     for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
785          PI != PE; ++PI)
786       {
787         if ((*PI)->getOpcode() != Instruction::PHINode)
788           break;                        // No more Phis in this successor
789         
790         // Find the incoming value from block bb to block (*SI)
791         int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
792         assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
793         Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
794         assert(inVal != NULL && "There must be an in-value on every edge");
795         
796         // Find the machine instruction that makes a copy of inval to (*PI).
797         // This must be in the current basic block (bb).
798         const MachineCodeForVMInstr& mvec = MachineCodeForBasicBlock::get(*PI);
799         const MachineInstr* theCopy = NULL;
800         for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
801           if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
802             // not a Phi: assume this is a copy and examine its operands
803             for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
804               {
805                 const MachineOperand& mop = mvec[i]->getOperand(o);
806                 
807                 if (mvec[i]->operandIsDefined(o))
808                   assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
809                 
810                 if (! mvec[i]->operandIsDefined(o) ||
811                     NOT NEEDED? mvec[i]->operandIsDefinedAndUsed(o))
812                   if (mop.getVRegValue() == inVal)
813                     { // found the copy!
814                       theCopy = mvec[i];
815                       break;
816                     }
817               }
818         
819         // Found the dang instruction.  Now create a node and do the rest...
820         if (theCopy != NULL)
821           {
822             SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
823                                             theCopy, origIndexInBB++, target);
824             this->noteGraphNodeForInstr(theCopy, node);
825             findDefUseInfoAtInstr(target, node,
826                                   memNodeVec, regToRefVecMap,valueToDefVecMap);
827           }
828       }
829 #endif  //REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
830 }
831
832
833 void
834 SchedGraph::buildGraph(const TargetMachine& target)
835 {
836   const BasicBlock* bb = bbVec[0];
837   
838   assert(bbVec.size() == 1 && "Only handling a single basic block here");
839   
840   // Use this data structure to note all machine operands that compute
841   // ordinary LLVM values.  These must be computed defs (i.e., instructions). 
842   // Note that there may be multiple machine instructions that define
843   // each Value.
844   ValueToDefVecMap valueToDefVecMap;
845   
846   // Use this data structure to note all memory instructions.
847   // We use this to add memory dependence edges without a second full walk.
848   // 
849   // vector<const Instruction*> memVec;
850   vector<SchedGraphNode*> memNodeVec;
851   
852   // Use this data structure to note any uses or definitions of
853   // machine registers so we can add edges for those later without
854   // extra passes over the nodes.
855   // The vector holds an ordered list of references to the machine reg,
856   // ordered according to control-flow order.  This only works for a
857   // single basic block, hence the assertion.  Each reference is identified
858   // by the pair: <node, operand-number>.
859   // 
860   RegToRefVecMap regToRefVecMap;
861   
862   // Make a dummy root node.  We'll add edges to the real roots later.
863   graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
864   graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
865
866   //----------------------------------------------------------------
867   // First add nodes for all the machine instructions in the basic block
868   // because this greatly simplifies identifying which edges to add.
869   // Do this one VM instruction at a time since the SchedGraphNode needs that.
870   // Also, remember the load/store instructions to add memory deps later.
871   //----------------------------------------------------------------
872   
873   buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
874   
875   //----------------------------------------------------------------
876   // Now add edges for the following (all are incoming edges except (4)):
877   // (1) operands of the machine instruction, including hidden operands
878   // (2) machine register dependences
879   // (3) memory load/store dependences
880   // (3) other resource dependences for the machine instruction, if any
881   // (4) output dependences when multiple machine instructions define the
882   //     same value; all must have been generated from a single VM instrn
883   // (5) control dependences to branch instructions generated for the
884   //     terminator instruction of the BB. Because of delay slots and
885   //     2-way conditional branches, multiple CD edges are needed
886   //     (see addCDEdges for details).
887   // Also, note any uses or defs of machine registers.
888   // 
889   //----------------------------------------------------------------
890       
891   MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(bb);
892   
893   // First, add edges to the terminator instruction of the basic block.
894   this->addCDEdges(bb->getTerminator(), target);
895       
896   // Then add memory dep edges: store->load, load->store, and store->store.
897   // Call instructions are treated as both load and store.
898   this->addMemEdges(memNodeVec, target);
899
900   // Then add edges between call instructions and CC set/use instructions
901   this->addCallCCEdges(memNodeVec, bbMvec, target);
902   
903   // Then add incoming def-use (SSA) edges for each machine instruction.
904   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
905     addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
906   
907 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
908   // Then add non-SSA edges for all VM instructions in the block.
909   // We assume that all machine instructions that define a value are
910   // generated from the VM instruction corresponding to that value.
911   // TODO: This could probably be done much more efficiently.
912   for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
913     this->addNonSSAEdgesForValue(*II, target);
914 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
915   
916   // Then add edges for dependences on machine registers
917   this->addMachineRegEdges(regToRefVecMap, target);
918   
919   // Finally, add edges from the dummy root and to dummy leaf
920   this->addDummyEdges();                
921 }
922
923
924 // 
925 // class SchedGraphSet
926 // 
927
928 /*ctor*/
929 SchedGraphSet::SchedGraphSet(const Function* _function,
930                              const TargetMachine& target) :
931   method(_function)
932 {
933   buildGraphsForMethod(method, target);
934 }
935
936
937 /*dtor*/
938 SchedGraphSet::~SchedGraphSet()
939 {
940   // delete all the graphs
941   for(iterator I = begin(), E = end(); I != E; ++I)
942     delete *I;  // destructor is a friend
943 }
944
945
946 void
947 SchedGraphSet::dump() const
948 {
949   cerr << "======== Sched graphs for function `" << method->getName()
950        << "' ========\n\n";
951   
952   for (const_iterator I=begin(); I != end(); ++I)
953     (*I)->dump();
954   
955   cerr << "\n====== End graphs for function `" << method->getName()
956        << "' ========\n\n";
957 }
958
959
960 void
961 SchedGraphSet::buildGraphsForMethod(const Function *F,
962                                     const TargetMachine& target)
963 {
964   for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
965     addGraph(new SchedGraph(BI, target));
966 }
967
968
969 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
970 {
971   os << "edge [" << edge.src->getNodeId() << "] -> ["
972      << edge.sink->getNodeId() << "] : ";
973   
974   switch(edge.depType) {
975   case SchedGraphEdge::CtrlDep:         os<< "Control Dep"; break;
976   case SchedGraphEdge::ValueDep:        os<< "Reg Value " << edge.val; break;
977   case SchedGraphEdge::MemoryDep:       os<< "Memory Dep"; break;
978   case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
979   case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
980   default: assert(0); break;
981   }
982   
983   os << " : delay = " << edge.minDelay << "\n";
984   
985   return os;
986 }
987
988 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
989 {
990   os << std::string(8, ' ')
991      << "Node " << node.nodeId << " : "
992      << "latency = " << node.latency << "\n" << std::string(12, ' ');
993   
994   if (node.getMachineInstr() == NULL)
995     os << "(Dummy node)\n";
996   else
997     {
998       os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
999       os << node.inEdges.size() << " Incoming Edges:\n";
1000       for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
1001           os << std::string(16, ' ') << *node.inEdges[i];
1002   
1003       os << std::string(12, ' ') << node.outEdges.size()
1004          << " Outgoing Edges:\n";
1005       for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
1006         os << std::string(16, ' ') << *node.outEdges[i];
1007     }
1008   
1009   return os;
1010 }