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