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