11c627af58e2bdab274d86e4cb9cb88e963edf1d
[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     ++first;
346   assert(first < termMvec.size() &&
347          "No branch instructions for BR?  Ok, but weird!  Delete assertion.");
348   if (first == termMvec.size())
349     return;
350   
351   SchedGraphNode* firstBrNode = getGraphNodeForInstr(termMvec[first]);
352   
353   // Add CD edges from each instruction in the sequence to the
354   // *last preceding* branch instr. in the sequence 
355   // Use a latency of 0 because we only need to prevent out-of-order issue.
356   // 
357   for (unsigned i = termMvec.size(); i > first+1; --i)
358     {
359       SchedGraphNode* toNode = getGraphNodeForInstr(termMvec[i-1]);
360       assert(toNode && "No node for instr generated for branch?");
361       
362       for (unsigned j = i-1; j != 0; --j) 
363         if (mii.isBranch(termMvec[j-1]->getOpCode()))
364           {
365             SchedGraphNode* brNode = getGraphNodeForInstr(termMvec[j-1]);
366             assert(brNode && "No node for instr generated for branch?");
367             (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
368                                       SchedGraphEdge::NonDataDep, 0);
369             break;                      // only one incoming edge is enough
370           }
371     }
372   
373   // Add CD edges from each instruction preceding the first branch
374   // to the first branch.  Use a latency of 0 as above.
375   // 
376   for (unsigned i = first; i != 0; --i)
377     {
378       SchedGraphNode* fromNode = getGraphNodeForInstr(termMvec[i-1]);
379       assert(fromNode && "No node for instr generated for branch?");
380       (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
381                                 SchedGraphEdge::NonDataDep, 0);
382     }
383   
384   // Now add CD edges to the first branch instruction in the sequence from
385   // all preceding instructions in the basic block.  Use 0 latency again.
386   // 
387   const BasicBlock* bb = firstBrNode->getBB();
388   const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
389   for (unsigned i=0, N=mvec.size(); i < N; i++) 
390     {
391       if (mvec[i] == termMvec[first]) // reached the first branch
392         break;
393       
394       SchedGraphNode* fromNode = this->getGraphNodeForInstr(mvec[i]);
395       if (fromNode == NULL)
396         continue;                       // dummy instruction, e.g., PHI
397       
398       (void) new SchedGraphEdge(fromNode, firstBrNode,
399                                 SchedGraphEdge::CtrlDep,
400                                 SchedGraphEdge::NonDataDep, 0);
401       
402       // If we find any other machine instructions (other than due to
403       // the terminator) that also have delay slots, add an outgoing edge
404       // from the instruction to the instructions in the delay slots.
405       // 
406       unsigned d = mii.getNumDelaySlots(mvec[i]->getOpCode());
407       assert(i+d < N && "Insufficient delay slots for instruction?");
408       
409       for (unsigned j=1; j <= d; j++)
410         {
411           SchedGraphNode* toNode = this->getGraphNodeForInstr(mvec[i+j]);
412           assert(toNode && "No node for machine instr in delay slot?");
413           (void) new SchedGraphEdge(fromNode, toNode,
414                                     SchedGraphEdge::CtrlDep,
415                                     SchedGraphEdge::NonDataDep, 0);
416         }
417     }
418 }
419
420 static const int SG_LOAD_REF  = 0;
421 static const int SG_STORE_REF = 1;
422 static const int SG_CALL_REF  = 2;
423
424 static const unsigned int SG_DepOrderArray[][3] = {
425   { SchedGraphEdge::NonDataDep,
426             SchedGraphEdge::AntiDep,
427                         SchedGraphEdge::AntiDep },
428   { SchedGraphEdge::TrueDep,
429             SchedGraphEdge::OutputDep,
430                         SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
431   { SchedGraphEdge::TrueDep,
432             SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
433                         SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
434                                                 | SchedGraphEdge::OutputDep }
435 };
436
437
438 // Add a dependence edge between every pair of machine load/store/call
439 // instructions, where at least one is a store or a call.
440 // Use latency 1 just to ensure that memory operations are ordered;
441 // latency does not otherwise matter (true dependences enforce that).
442 // 
443 void
444 SchedGraph::addMemEdges(const vector<SchedGraphNode*>& memNodeVec,
445                         const TargetMachine& target)
446 {
447   const MachineInstrInfo& mii = target.getInstrInfo();
448   
449   // Instructions in memNodeVec are in execution order within the basic block,
450   // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
451   // 
452   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
453     {
454       MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
455       int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
456                        : mii.isLoad(fromOpCode)? SG_LOAD_REF
457                                                : SG_STORE_REF;
458       for (unsigned jm=im+1; jm < NM; jm++)
459         {
460           MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
461           int toType = mii.isCall(toOpCode)? SG_CALL_REF
462                          : mii.isLoad(toOpCode)? SG_LOAD_REF
463                                                : SG_STORE_REF;
464           
465           if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
466             (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
467                                       SchedGraphEdge::MemoryDep,
468                                       SG_DepOrderArray[fromType][toType], 1);
469         }
470     }
471
472
473 // Add edges from/to CC reg instrs to/from call instrs.
474 // Essentially this prevents anything that sets or uses a CC reg from being
475 // reordered w.r.t. a call.
476 // Use a latency of 0 because we only need to prevent out-of-order issue,
477 // like with control dependences.
478 // 
479 void
480 SchedGraph::addCallCCEdges(const vector<SchedGraphNode*>& memNodeVec,
481                            MachineCodeForBasicBlock& bbMvec,
482                            const TargetMachine& target)
483 {
484   const MachineInstrInfo& mii = target.getInstrInfo();
485   vector<SchedGraphNode*> callNodeVec;
486   
487   // Find the call instruction nodes and put them in a vector.
488   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
489     if (mii.isCall(memNodeVec[im]->getOpCode()))
490       callNodeVec.push_back(memNodeVec[im]);
491   
492   // Now walk the entire basic block, looking for CC instructions *and*
493   // call instructions, and keep track of the order of the instructions.
494   // Use the call node vec to quickly find earlier and later call nodes
495   // relative to the current CC instruction.
496   // 
497   int lastCallNodeIdx = -1;
498   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
499     if (mii.isCall(bbMvec[i]->getOpCode()))
500       {
501         ++lastCallNodeIdx;
502         for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
503           if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
504             break;
505         assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
506       }
507     else if (mii.isCCInstr(bbMvec[i]->getOpCode()))
508       { // Add incoming/outgoing edges from/to preceding/later calls
509         SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
510         int j=0;
511         for ( ; j <= lastCallNodeIdx; j++)
512           (void) new SchedGraphEdge(callNodeVec[j], ccNode,
513                                     MachineCCRegsRID, 0);
514         for ( ; j < (int) callNodeVec.size(); j++)
515           (void) new SchedGraphEdge(ccNode, callNodeVec[j],
516                                     MachineCCRegsRID, 0);
517       }
518 }
519
520
521 void
522 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
523                                const TargetMachine& target)
524 {
525   assert(bbVec.size() == 1 && "Only handling a single basic block here");
526   
527   // This assumes that such hardwired registers are never allocated
528   // to any LLVM value (since register allocation happens later), i.e.,
529   // any uses or defs of this register have been made explicit!
530   // Also assumes that two registers with different numbers are
531   // not aliased!
532   // 
533   for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
534        I != regToRefVecMap.end(); ++I)
535     {
536       int regNum        = (*I).first;
537       RefVec& regRefVec = (*I).second;
538       
539       // regRefVec is ordered by control flow order in the basic block
540       for (unsigned i=0; i < regRefVec.size(); ++i)
541         {
542           SchedGraphNode* node = regRefVec[i].first;
543           unsigned int opNum   = regRefVec[i].second;
544           bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
545           bool isDefAndUse =
546             node->getMachineInstr()->operandIsDefinedAndUsed(opNum);
547           
548           for (unsigned p=0; p < i; ++p)
549             {
550               SchedGraphNode* prevNode = regRefVec[p].first;
551               if (prevNode != node)
552                 {
553                   unsigned int prevOpNum = regRefVec[p].second;
554                   bool prevIsDef =
555                     prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
556                   bool prevIsDefAndUse =
557                     prevNode->getMachineInstr()->operandIsDefinedAndUsed(prevOpNum);
558                   if (isDef)
559                     {
560                       if (prevIsDef)
561                         new SchedGraphEdge(prevNode, node, regNum,
562                                            SchedGraphEdge::OutputDep);
563                       if (!prevIsDef || prevIsDefAndUse)
564                         new SchedGraphEdge(prevNode, node, regNum,
565                                            SchedGraphEdge::AntiDep);
566                     }
567                   
568                   if (prevIsDef)
569                     if (!isDef || isDefAndUse)
570                       new SchedGraphEdge(prevNode, node, regNum,
571                                          SchedGraphEdge::TrueDep);
572                 }
573             }
574         }
575     }
576 }
577
578
579 // Adds dependences to/from refNode from/to all other defs
580 // in the basic block.  refNode may be a use, a def, or both.
581 // We do not consider other uses because we are not building use-use deps.
582 // 
583 void
584 SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
585                              const RefVec& defVec,
586                              const Value* defValue,
587                              bool  refNodeIsDef,
588                              bool  refNodeIsDefAndUse,
589                              const TargetMachine& target)
590 {
591   bool refNodeIsUse = !refNodeIsDef || refNodeIsDefAndUse;
592   
593   // Add true or output dep edges from all def nodes before refNode in BB.
594   // Add anti or output dep edges to all def nodes after refNode.
595   for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
596     {
597       if ((*I).first == refNode)
598         continue;                       // Dont add any self-loops
599       
600       if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB())
601         { // (*).first is before refNode
602           if (refNodeIsDef)
603             (void) new SchedGraphEdge((*I).first, refNode, defValue,
604                                       SchedGraphEdge::OutputDep);
605           if (refNodeIsUse)
606             (void) new SchedGraphEdge((*I).first, refNode, defValue,
607                                       SchedGraphEdge::TrueDep);
608         }
609       else
610         { // (*).first is after refNode
611           if (refNodeIsDef)
612             (void) new SchedGraphEdge(refNode, (*I).first, defValue,
613                                       SchedGraphEdge::OutputDep);
614           if (refNodeIsUse)
615             (void) new SchedGraphEdge(refNode, (*I).first, defValue,
616                                       SchedGraphEdge::AntiDep);
617         }
618     }
619 }
620
621
622 void
623 SchedGraph::addEdgesForInstruction(const MachineInstr& minstr,
624                                    const ValueToDefVecMap& valueToDefVecMap,
625                                    const TargetMachine& target)
626 {
627   SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
628   if (node == NULL)
629     return;
630   
631   // Add edges for all operands of the machine instruction.
632   // 
633   for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
634     {
635       const MachineOperand& mop = minstr.getOperand(i);
636       switch(mop.getOperandType())
637         {
638         case MachineOperand::MO_VirtualRegister:
639         case MachineOperand::MO_CCRegister:
640           if (const Instruction* srcI =
641               dyn_cast_or_null<Instruction>(mop.getVRegValue()))
642             {
643               ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
644               if (I != valueToDefVecMap.end())
645                 addEdgesForValue(node, (*I).second, mop.getVRegValue(),
646                                  minstr.operandIsDefined(i),
647                                  minstr.operandIsDefinedAndUsed(i), target);
648             }
649           break;
650           
651         case MachineOperand::MO_MachineRegister:
652           break; 
653           
654         case MachineOperand::MO_SignExtendedImmed:
655         case MachineOperand::MO_UnextendedImmed:
656         case MachineOperand::MO_PCRelativeDisp:
657           break;        // nothing to do for immediate fields
658           
659         default:
660           assert(0 && "Unknown machine operand type in SchedGraph builder");
661           break;
662         }
663     }
664   
665   // Add edges for values implicitly used by the machine instruction.
666   // Examples include function arguments to a Call instructions or the return
667   // value of a Ret instruction.
668   // 
669   for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
670     if (! minstr.implicitRefIsDefined(i) ||
671         minstr.implicitRefIsDefinedAndUsed(i))
672       if (const Instruction* srcI =
673           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
674         {
675           ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
676           if (I != valueToDefVecMap.end())
677             addEdgesForValue(node, (*I).second, minstr.getImplicitRef(i),
678                              minstr.implicitRefIsDefined(i),
679                              minstr.implicitRefIsDefinedAndUsed(i), target);
680         }
681 }
682
683
684 void
685 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
686                                   SchedGraphNode* node,
687                                   vector<SchedGraphNode*>& memNodeVec,
688                                   RegToRefVecMap& regToRefVecMap,
689                                   ValueToDefVecMap& valueToDefVecMap)
690 {
691   const MachineInstrInfo& mii = target.getInstrInfo();
692   
693   
694   MachineOpCode opCode = node->getOpCode();
695   if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
696     memNodeVec.push_back(node);
697   
698   // Collect the register references and value defs. for explicit operands
699   // 
700   const MachineInstr& minstr = * node->getMachineInstr();
701   for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
702     {
703       const MachineOperand& mop = minstr.getOperand(i);
704       
705       // if this references a register other than the hardwired
706       // "zero" register, record the reference.
707       if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
708         {
709           int regNum = mop.getMachineRegNum();
710           if (regNum != target.getRegInfo().getZeroRegNum())
711             regToRefVecMap[mop.getMachineRegNum()].push_back(
712                                                   std::make_pair(node, i));
713           continue;                     // nothing more to do
714         }
715       
716       // ignore all other non-def operands
717       if (! minstr.operandIsDefined(i))
718         continue;
719       
720       // We must be defining a value.
721       assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
722               mop.getOperandType() == MachineOperand::MO_CCRegister)
723              && "Do not expect any other kind of operand to be defined!");
724       
725       const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
726       valueToDefVecMap[defInstr].push_back(std::make_pair(node, i)); 
727     }
728   
729   // 
730   // Collect value defs. for implicit operands.  The interface to extract
731   // them assumes they must be virtual registers!
732   // 
733   for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
734     if (minstr.implicitRefIsDefined(i))
735       if (const Instruction* defInstr =
736           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
737         {
738           valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i)); 
739         }
740 }
741
742
743 void
744 SchedGraph::buildNodesforBB(const TargetMachine& target,
745                             const BasicBlock* bb,
746                             vector<SchedGraphNode*>& memNodeVec,
747                             RegToRefVecMap& regToRefVecMap,
748                             ValueToDefVecMap& valueToDefVecMap)
749 {
750   const MachineInstrInfo& mii = target.getInstrInfo();
751   
752   // Build graph nodes for each VM instruction and gather def/use info.
753   // Do both those together in a single pass over all machine instructions.
754   const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
755   for (unsigned i=0; i < mvec.size(); i++)
756     if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
757       {
758         SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
759                                                   mvec[i], i, target);
760         this->noteGraphNodeForInstr(mvec[i], node);
761         
762         // Remember all register references and value defs
763         findDefUseInfoAtInstr(target, node,
764                               memNodeVec, regToRefVecMap,valueToDefVecMap);
765       }
766   
767 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
768 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
769   // This is a BIG UGLY HACK.  IT NEEDS TO BE ELIMINATED.
770   // Look for copy instructions inserted in this BB due to Phi instructions
771   // in the successor BBs.
772   // There MUST be exactly one copy per Phi in successor nodes.
773   // 
774   for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
775        SI != SE; ++SI)
776     for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
777          PI != PE; ++PI)
778       {
779         if ((*PI)->getOpcode() != Instruction::PHINode)
780           break;                        // No more Phis in this successor
781         
782         // Find the incoming value from block bb to block (*SI)
783         int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
784         assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
785         Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
786         assert(inVal != NULL && "There must be an in-value on every edge");
787         
788         // Find the machine instruction that makes a copy of inval to (*PI).
789         // This must be in the current basic block (bb).
790         const MachineCodeForVMInstr& mvec = MachineCodeForBasicBlock::get(*PI);
791         const MachineInstr* theCopy = NULL;
792         for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
793           if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
794             // not a Phi: assume this is a copy and examine its operands
795             for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
796               {
797                 const MachineOperand& mop = mvec[i]->getOperand(o);
798                 
799                 if (mvec[i]->operandIsDefined(o))
800                   assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
801                 
802                 if (! mvec[i]->operandIsDefined(o) ||
803                     NOT NEEDED? mvec[i]->operandIsDefinedAndUsed(o))
804                   if (mop.getVRegValue() == inVal)
805                     { // found the copy!
806                       theCopy = mvec[i];
807                       break;
808                     }
809               }
810         
811         // Found the dang instruction.  Now create a node and do the rest...
812         if (theCopy != NULL)
813           {
814             SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
815                                             theCopy, origIndexInBB++, target);
816             this->noteGraphNodeForInstr(theCopy, node);
817             findDefUseInfoAtInstr(target, node,
818                                   memNodeVec, regToRefVecMap,valueToDefVecMap);
819           }
820       }
821 #endif  //REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
822 }
823
824
825 void
826 SchedGraph::buildGraph(const TargetMachine& target)
827 {
828   const BasicBlock* bb = bbVec[0];
829   
830   assert(bbVec.size() == 1 && "Only handling a single basic block here");
831   
832   // Use this data structure to note all machine operands that compute
833   // ordinary LLVM values.  These must be computed defs (i.e., instructions). 
834   // Note that there may be multiple machine instructions that define
835   // each Value.
836   ValueToDefVecMap valueToDefVecMap;
837   
838   // Use this data structure to note all memory instructions.
839   // We use this to add memory dependence edges without a second full walk.
840   // 
841   // vector<const Instruction*> memVec;
842   vector<SchedGraphNode*> memNodeVec;
843   
844   // Use this data structure to note any uses or definitions of
845   // machine registers so we can add edges for those later without
846   // extra passes over the nodes.
847   // The vector holds an ordered list of references to the machine reg,
848   // ordered according to control-flow order.  This only works for a
849   // single basic block, hence the assertion.  Each reference is identified
850   // by the pair: <node, operand-number>.
851   // 
852   RegToRefVecMap regToRefVecMap;
853   
854   // Make a dummy root node.  We'll add edges to the real roots later.
855   graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
856   graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
857
858   //----------------------------------------------------------------
859   // First add nodes for all the machine instructions in the basic block
860   // because this greatly simplifies identifying which edges to add.
861   // Do this one VM instruction at a time since the SchedGraphNode needs that.
862   // Also, remember the load/store instructions to add memory deps later.
863   //----------------------------------------------------------------
864   
865   buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
866   
867   //----------------------------------------------------------------
868   // Now add edges for the following (all are incoming edges except (4)):
869   // (1) operands of the machine instruction, including hidden operands
870   // (2) machine register dependences
871   // (3) memory load/store dependences
872   // (3) other resource dependences for the machine instruction, if any
873   // (4) output dependences when multiple machine instructions define the
874   //     same value; all must have been generated from a single VM instrn
875   // (5) control dependences to branch instructions generated for the
876   //     terminator instruction of the BB. Because of delay slots and
877   //     2-way conditional branches, multiple CD edges are needed
878   //     (see addCDEdges for details).
879   // Also, note any uses or defs of machine registers.
880   // 
881   //----------------------------------------------------------------
882       
883   MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(bb);
884   
885   // First, add edges to the terminator instruction of the basic block.
886   this->addCDEdges(bb->getTerminator(), target);
887       
888   // Then add memory dep edges: store->load, load->store, and store->store.
889   // Call instructions are treated as both load and store.
890   this->addMemEdges(memNodeVec, target);
891
892   // Then add edges between call instructions and CC set/use instructions
893   this->addCallCCEdges(memNodeVec, bbMvec, target);
894   
895   // Then add incoming def-use (SSA) edges for each machine instruction.
896   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
897     addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
898   
899 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
900   // Then add non-SSA edges for all VM instructions in the block.
901   // We assume that all machine instructions that define a value are
902   // generated from the VM instruction corresponding to that value.
903   // TODO: This could probably be done much more efficiently.
904   for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
905     this->addNonSSAEdgesForValue(*II, target);
906 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
907   
908   // Then add edges for dependences on machine registers
909   this->addMachineRegEdges(regToRefVecMap, target);
910   
911   // Finally, add edges from the dummy root and to dummy leaf
912   this->addDummyEdges();                
913 }
914
915
916 // 
917 // class SchedGraphSet
918 // 
919
920 /*ctor*/
921 SchedGraphSet::SchedGraphSet(const Function* _function,
922                              const TargetMachine& target) :
923   method(_function)
924 {
925   buildGraphsForMethod(method, target);
926 }
927
928
929 /*dtor*/
930 SchedGraphSet::~SchedGraphSet()
931 {
932   // delete all the graphs
933   for(iterator I = begin(), E = end(); I != E; ++I)
934     delete *I;  // destructor is a friend
935 }
936
937
938 void
939 SchedGraphSet::dump() const
940 {
941   cerr << "======== Sched graphs for function `" << method->getName()
942        << "' ========\n\n";
943   
944   for (const_iterator I=begin(); I != end(); ++I)
945     (*I)->dump();
946   
947   cerr << "\n====== End graphs for function `" << method->getName()
948        << "' ========\n\n";
949 }
950
951
952 void
953 SchedGraphSet::buildGraphsForMethod(const Function *F,
954                                     const TargetMachine& target)
955 {
956   for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
957     addGraph(new SchedGraph(BI, target));
958 }
959
960
961 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
962 {
963   os << "edge [" << edge.src->getNodeId() << "] -> ["
964      << edge.sink->getNodeId() << "] : ";
965   
966   switch(edge.depType) {
967   case SchedGraphEdge::CtrlDep:         os<< "Control Dep"; break;
968   case SchedGraphEdge::ValueDep:        os<< "Reg Value " << edge.val; break;
969   case SchedGraphEdge::MemoryDep:       os<< "Memory Dep"; break;
970   case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
971   case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
972   default: assert(0); break;
973   }
974   
975   os << " : delay = " << edge.minDelay << "\n";
976   
977   return os;
978 }
979
980 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
981 {
982   os << std::string(8, ' ')
983      << "Node " << node.nodeId << " : "
984      << "latency = " << node.latency << "\n" << std::string(12, ' ');
985   
986   if (node.getMachineInstr() == NULL)
987     os << "(Dummy node)\n";
988   else
989     {
990       os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
991       os << node.inEdges.size() << " Incoming Edges:\n";
992       for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
993           os << std::string(16, ' ') << *node.inEdges[i];
994   
995       os << std::string(12, ' ') << node.outEdges.size()
996          << " Outgoing Edges:\n";
997       for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
998         os << std::string(16, ' ') << *node.outEdges[i];
999     }
1000   
1001   return os;
1002 }