2 //***************************************************************************
7 // Scheduling graph based on SSA graph plus extra dependence edges
8 // capturing dependences due to machine resources (machine registers,
9 // CC registers, and any others).
12 // 7/20/01 - Vikram Adve - Created
13 //**************************************************************************/
15 #include "SchedGraph.h"
16 #include "llvm/InstrTypes.h"
17 #include "llvm/Instruction.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Method.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/InstrSelection.h"
22 #include "llvm/Target/MachineInstrInfo.h"
23 #include "llvm/Target/MachineRegInfo.h"
24 #include "llvm/Support/StringExtras.h"
25 #include "llvm/iOther.h"
31 //*********************** Internal Data Structures *************************/
33 // The following two types need to be classes, not typedefs, so we can use
34 // opaque declarations in SchedGraph.h
36 struct RefVec: public vector< pair<SchedGraphNode*, int> > {
37 typedef vector< pair<SchedGraphNode*, int> >:: iterator iterator;
38 typedef vector< pair<SchedGraphNode*, int> >::const_iterator const_iterator;
41 struct RegToRefVecMap: public hash_map<int, RefVec> {
42 typedef hash_map<int, RefVec>:: iterator iterator;
43 typedef hash_map<int, RefVec>::const_iterator const_iterator;
46 struct ValueToDefVecMap: public hash_map<const Instruction*, RefVec> {
47 typedef hash_map<const Instruction*, RefVec>:: iterator iterator;
48 typedef hash_map<const Instruction*, RefVec>::const_iterator const_iterator;
52 // class SchedGraphEdge
56 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
57 SchedGraphNode* _sink,
58 SchedGraphEdgeDepType _depType,
59 unsigned int _depOrderType,
64 depOrderType(_depOrderType),
65 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
68 src->addOutEdge(this);
69 sink->addInEdge(this);
74 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
75 SchedGraphNode* _sink,
77 unsigned int _depOrderType,
82 depOrderType(_depOrderType),
83 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
86 src->addOutEdge(this);
87 sink->addInEdge(this);
92 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
93 SchedGraphNode* _sink,
95 unsigned int _depOrderType,
99 depType(MachineRegister),
100 depOrderType(_depOrderType),
101 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
102 machineRegNum(_regNum)
104 src->addOutEdge(this);
105 sink->addInEdge(this);
110 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
111 SchedGraphNode* _sink,
112 ResourceId _resourceId,
116 depType(MachineResource),
117 depOrderType(NonDataDep),
118 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
119 resourceId(_resourceId)
121 src->addOutEdge(this);
122 sink->addInEdge(this);
126 SchedGraphEdge::~SchedGraphEdge()
130 void SchedGraphEdge::dump(int indent=0) const {
131 printIndent(indent); cout << *this;
136 // class SchedGraphNode
140 SchedGraphNode::SchedGraphNode(unsigned int _nodeId,
141 const BasicBlock* _bb,
142 const MachineInstr* _minstr,
144 const TargetMachine& target)
148 origIndexInBB(indexInBB),
153 MachineOpCode mopCode = minstr->getOpCode();
154 latency = target.getInstrInfo().hasResultInterlock(mopCode)
155 ? target.getInstrInfo().minLatency(mopCode)
156 : target.getInstrInfo().maxLatency(mopCode);
162 SchedGraphNode::~SchedGraphNode()
166 void SchedGraphNode::dump(int indent=0) const {
167 printIndent(indent); cout << *this;
172 SchedGraphNode::addInEdge(SchedGraphEdge* edge)
174 inEdges.push_back(edge);
179 SchedGraphNode::addOutEdge(SchedGraphEdge* edge)
181 outEdges.push_back(edge);
185 SchedGraphNode::removeInEdge(const SchedGraphEdge* edge)
187 assert(edge->getSink() == this);
189 for (iterator I = beginInEdges(); I != endInEdges(); ++I)
198 SchedGraphNode::removeOutEdge(const SchedGraphEdge* edge)
200 assert(edge->getSrc() == this);
202 for (iterator I = beginOutEdges(); I != endOutEdges(); ++I)
217 SchedGraph::SchedGraph(const BasicBlock* bb,
218 const TargetMachine& target)
221 this->buildGraph(target);
226 SchedGraph::~SchedGraph()
228 for (iterator I=begin(); I != end(); ++I)
230 SchedGraphNode* node = (*I).second;
232 // for each node, delete its out-edges
233 for (SchedGraphNode::iterator I = node->beginOutEdges();
234 I != node->endOutEdges(); ++I)
237 // then delete the node itself.
244 SchedGraph::dump() const
246 cout << " Sched Graph for Basic Blocks: ";
247 for (unsigned i=0, N=bbVec.size(); i < N; i++)
249 cout << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
250 << " (" << bbVec[i] << ")"
251 << ((i == N-1)? "" : ", ");
254 cout << endl << endl << " Actual Root nodes : ";
255 for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
256 cout << graphRoot->outEdges[i]->getSink()->getNodeId()
257 << ((i == N-1)? "" : ", ");
259 cout << endl << " Graph Nodes:" << endl;
260 for (const_iterator I=begin(); I != end(); ++I)
261 cout << endl << * (*I).second;
268 SchedGraph::eraseIncomingEdges(SchedGraphNode* node, bool addDummyEdges)
270 // Delete and disconnect all in-edges for the node
271 for (SchedGraphNode::iterator I = node->beginInEdges();
272 I != node->endInEdges(); ++I)
274 SchedGraphNode* srcNode = (*I)->getSrc();
275 srcNode->removeOutEdge(*I);
279 srcNode != getRoot() &&
280 srcNode->beginOutEdges() == srcNode->endOutEdges())
281 { // srcNode has no more out edges, so add an edge to dummy EXIT node
282 assert(node != getLeaf() && "Adding edge that was just removed?");
283 (void) new SchedGraphEdge(srcNode, getLeaf(),
284 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
288 node->inEdges.clear();
292 SchedGraph::eraseOutgoingEdges(SchedGraphNode* node, bool addDummyEdges)
294 // Delete and disconnect all out-edges for the node
295 for (SchedGraphNode::iterator I = node->beginOutEdges();
296 I != node->endOutEdges(); ++I)
298 SchedGraphNode* sinkNode = (*I)->getSink();
299 sinkNode->removeInEdge(*I);
303 sinkNode != getLeaf() &&
304 sinkNode->beginInEdges() == sinkNode->endInEdges())
305 { //sinkNode has no more in edges, so add an edge from dummy ENTRY node
306 assert(node != getRoot() && "Adding edge that was just removed?");
307 (void) new SchedGraphEdge(getRoot(), sinkNode,
308 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
312 node->outEdges.clear();
316 SchedGraph::eraseIncidentEdges(SchedGraphNode* node, bool addDummyEdges)
318 this->eraseIncomingEdges(node, addDummyEdges);
319 this->eraseOutgoingEdges(node, addDummyEdges);
324 SchedGraph::addDummyEdges()
326 assert(graphRoot->outEdges.size() == 0);
328 for (const_iterator I=begin(); I != end(); ++I)
330 SchedGraphNode* node = (*I).second;
331 assert(node != graphRoot && node != graphLeaf);
332 if (node->beginInEdges() == node->endInEdges())
333 (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
334 SchedGraphEdge::NonDataDep, 0);
335 if (node->beginOutEdges() == node->endOutEdges())
336 (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
337 SchedGraphEdge::NonDataDep, 0);
343 SchedGraph::addCDEdges(const TerminatorInst* term,
344 const TargetMachine& target)
346 const MachineInstrInfo& mii = target.getInstrInfo();
347 MachineCodeForVMInstr& termMvec = term->getMachineInstrVec();
349 // Find the first branch instr in the sequence of machine instrs for term
352 while (! mii.isBranch(termMvec[first]->getOpCode()))
354 assert(first < termMvec.size() &&
355 "No branch instructions for BR? Ok, but weird! Delete assertion.");
356 if (first == termMvec.size())
359 SchedGraphNode* firstBrNode = this->getGraphNodeForInstr(termMvec[first]);
361 // Add CD edges from each instruction in the sequence to the
362 // *last preceding* branch instr. in the sequence
363 // Use a latency of 0 because we only need to prevent out-of-order issue.
365 for (int i = (int) termMvec.size()-1; i > (int) first; i--)
367 SchedGraphNode* toNode = this->getGraphNodeForInstr(termMvec[i]);
368 assert(toNode && "No node for instr generated for branch?");
370 for (int j = i-1; j >= 0; j--)
371 if (mii.isBranch(termMvec[j]->getOpCode()))
373 SchedGraphNode* brNode = this->getGraphNodeForInstr(termMvec[j]);
374 assert(brNode && "No node for instr generated for branch?");
375 (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
376 SchedGraphEdge::NonDataDep, 0);
377 break; // only one incoming edge is enough
381 // Add CD edges from each instruction preceding the first branch
382 // to the first branch. Use a latency of 0 as above.
384 for (int i = first-1; i >= 0; i--)
386 SchedGraphNode* fromNode = this->getGraphNodeForInstr(termMvec[i]);
387 assert(fromNode && "No node for instr generated for branch?");
388 (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
389 SchedGraphEdge::NonDataDep, 0);
392 // Now add CD edges to the first branch instruction in the sequence from
393 // all preceding instructions in the basic block. Use 0 latency again.
395 const BasicBlock* bb = term->getParent();
396 for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
398 if ((*II) == (const Instruction*) term) // special case, handled above
401 assert(! (*II)->isTerminator() && "Two terminators in basic block?");
403 const MachineCodeForVMInstr& mvec = (*II)->getMachineInstrVec();
404 for (unsigned i=0, N=mvec.size(); i < N; i++)
406 SchedGraphNode* fromNode = this->getGraphNodeForInstr(mvec[i]);
407 if (fromNode == NULL)
408 continue; // dummy instruction, e.g., PHI
410 (void) new SchedGraphEdge(fromNode, firstBrNode,
411 SchedGraphEdge::CtrlDep,
412 SchedGraphEdge::NonDataDep, 0);
414 // If we find any other machine instructions (other than due to
415 // the terminator) that also have delay slots, add an outgoing edge
416 // from the instruction to the instructions in the delay slots.
418 unsigned d = mii.getNumDelaySlots(mvec[i]->getOpCode());
419 assert(i+d < N && "Insufficient delay slots for instruction?");
421 for (unsigned j=1; j <= d; j++)
423 SchedGraphNode* toNode = this->getGraphNodeForInstr(mvec[i+j]);
424 assert(toNode && "No node for machine instr in delay slot?");
425 (void) new SchedGraphEdge(fromNode, toNode,
426 SchedGraphEdge::CtrlDep,
427 SchedGraphEdge::NonDataDep, 0);
433 static const int SG_LOAD_REF = 0;
434 static const int SG_STORE_REF = 1;
435 static const int SG_CALL_REF = 2;
437 static const unsigned int SG_DepOrderArray[][3] = {
438 { SchedGraphEdge::NonDataDep,
439 SchedGraphEdge::AntiDep,
440 SchedGraphEdge::AntiDep },
441 { SchedGraphEdge::TrueDep,
442 SchedGraphEdge::OutputDep,
443 SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
444 { SchedGraphEdge::TrueDep,
445 SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
446 SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
447 | SchedGraphEdge::OutputDep }
451 // Add a dependence edge between every pair of machine load/store/call
452 // instructions, where at least one is a store or a call.
453 // Use latency 1 just to ensure that memory operations are ordered;
454 // latency does not otherwise matter (true dependences enforce that).
457 SchedGraph::addMemEdges(const vector<SchedGraphNode*>& memNodeVec,
458 const TargetMachine& target)
460 const MachineInstrInfo& mii = target.getInstrInfo();
462 // Instructions in memNodeVec are in execution order within the basic block,
463 // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
465 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
467 MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
468 int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
469 : mii.isLoad(fromOpCode)? SG_LOAD_REF
471 for (unsigned jm=im+1; jm < NM; jm++)
473 MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
474 int toType = mii.isCall(toOpCode)? SG_CALL_REF
475 : mii.isLoad(toOpCode)? SG_LOAD_REF
478 if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
479 (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
480 SchedGraphEdge::MemoryDep,
481 SG_DepOrderArray[fromType][toType], 1);
486 // Add edges from/to CC reg instrs to/from call instrs.
487 // Essentially this prevents anything that sets or uses a CC reg from being
488 // reordered w.r.t. a call.
489 // Use a latency of 0 because we only need to prevent out-of-order issue,
490 // like with control dependences.
493 SchedGraph::addCallCCEdges(const vector<SchedGraphNode*>& memNodeVec,
494 MachineCodeForBasicBlock& bbMvec,
495 const TargetMachine& target)
497 const MachineInstrInfo& mii = target.getInstrInfo();
498 vector<SchedGraphNode*> callNodeVec;
500 // Find the call instruction nodes and put them in a vector.
501 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
502 if (mii.isCall(memNodeVec[im]->getOpCode()))
503 callNodeVec.push_back(memNodeVec[im]);
505 // Now walk the entire basic block, looking for CC instructions *and*
506 // call instructions, and keep track of the order of the instructions.
507 // Use the call node vec to quickly find earlier and later call nodes
508 // relative to the current CC instruction.
510 int lastCallNodeIdx = -1;
511 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
512 if (mii.isCall(bbMvec[i]->getOpCode()))
515 for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
516 if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
518 assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
520 else if (mii.isCCInstr(bbMvec[i]->getOpCode()))
521 { // Add incoming/outgoing edges from/to preceding/later calls
522 SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
524 for ( ; j <= lastCallNodeIdx; j++)
525 (void) new SchedGraphEdge(callNodeVec[j], ccNode,
526 MachineCCRegsRID, 0);
527 for ( ; j < (int) callNodeVec.size(); j++)
528 (void) new SchedGraphEdge(ccNode, callNodeVec[j],
529 MachineCCRegsRID, 0);
535 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
536 const TargetMachine& target)
538 assert(bbVec.size() == 1 && "Only handling a single basic block here");
540 // This assumes that such hardwired registers are never allocated
541 // to any LLVM value (since register allocation happens later), i.e.,
542 // any uses or defs of this register have been made explicit!
543 // Also assumes that two registers with different numbers are
546 for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
547 I != regToRefVecMap.end(); ++I)
549 int regNum = (*I).first;
550 RefVec& regRefVec = (*I).second;
552 // regRefVec is ordered by control flow order in the basic block
553 for (unsigned i=0; i < regRefVec.size(); ++i)
555 SchedGraphNode* node = regRefVec[i].first;
556 unsigned int opNum = regRefVec[i].second;
557 bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
559 for (unsigned p=0; p < i; ++p)
561 SchedGraphNode* prevNode = regRefVec[p].first;
562 if (prevNode != node)
564 unsigned int prevOpNum = regRefVec[p].second;
566 prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
569 new SchedGraphEdge(prevNode, node, regNum,
570 (prevIsDef)? SchedGraphEdge::OutputDep
571 : SchedGraphEdge::AntiDep);
573 new SchedGraphEdge(prevNode, node, regNum,
574 SchedGraphEdge::TrueDep);
583 SchedGraph::addSSAEdge(SchedGraphNode* destNode,
584 const RefVec& defVec,
585 const Value* defValue,
586 const TargetMachine& target)
588 // Add edges from all def nodes that are before destNode in the BB.
590 // We could probably add non-SSA edges here too! But I'll do that later.
591 for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
592 if ((*I).first->getOrigIndexInBB() < destNode->getOrigIndexInBB())
593 (void) new SchedGraphEdge((*I).first, destNode, defValue);
598 SchedGraph::addEdgesForInstruction(const MachineInstr& minstr,
599 const ValueToDefVecMap& valueToDefVecMap,
600 const TargetMachine& target)
602 SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
606 // Add edges for all operands of the machine instruction.
608 for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
610 // ignore def operands here
611 if (minstr.operandIsDefined(i))
614 const MachineOperand& mop = minstr.getOperand(i);
616 switch(mop.getOperandType())
618 case MachineOperand::MO_VirtualRegister:
619 case MachineOperand::MO_CCRegister:
620 if (const Instruction* srcI =
621 dyn_cast_or_null<Instruction>(mop.getVRegValue()))
623 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
624 if (I != valueToDefVecMap.end())
625 addSSAEdge(node, (*I).second, mop.getVRegValue(), target);
629 case MachineOperand::MO_MachineRegister:
632 case MachineOperand::MO_SignExtendedImmed:
633 case MachineOperand::MO_UnextendedImmed:
634 case MachineOperand::MO_PCRelativeDisp:
635 break; // nothing to do for immediate fields
638 assert(0 && "Unknown machine operand type in SchedGraph builder");
643 // Add edges for values implicitly used by the machine instruction.
644 // Examples include function arguments to a Call instructions or the return
645 // value of a Ret instruction.
647 for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
648 if (! minstr.implicitRefIsDefined(i))
649 if (const Instruction* srcI =
650 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
652 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
653 if (I != valueToDefVecMap.end())
654 addSSAEdge(node, (*I).second, minstr.getImplicitRef(i), target);
660 SchedGraph::addNonSSAEdgesForValue(const Instruction* instr,
661 const TargetMachine& target)
663 if (isa<PHINode>(instr))
666 MachineCodeForVMInstr& mvec = instr->getMachineInstrVec();
667 const MachineInstrInfo& mii = target.getInstrInfo();
670 for (unsigned i=0, N=mvec.size(); i < N; i++)
671 for (int o=0, N = mii.getNumOperands(mvec[i]->getOpCode()); o < N; o++)
673 const MachineOperand& mop = mvec[i]->getOperand(o);
675 if ((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
676 mop.getOperandType() == MachineOperand::MO_CCRegister)
677 && mop.getVRegValue() == (Value*) instr)
679 // this operand is a definition or use of value `instr'
680 SchedGraphNode* node = this->getGraphNodeForInstr(mvec[i]);
681 assert(node && "No node for machine instruction in this BB?");
682 refVec.push_back(make_pair(node, o));
686 // refVec is ordered by control flow order of the machine instructions
687 for (unsigned i=0; i < refVec.size(); ++i)
689 SchedGraphNode* node = refVec[i].first;
690 unsigned int opNum = refVec[i].second;
691 bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
694 // add output and/or anti deps to this definition
695 for (unsigned p=0; p < i; ++p)
697 SchedGraphNode* prevNode = refVec[p].first;
698 if (prevNode != node)
700 bool prevIsDef = prevNode->getMachineInstr()->
701 operandIsDefined(refVec[p].second);
702 new SchedGraphEdge(prevNode, node, SchedGraphEdge::DefUseDep,
703 (prevIsDef)? SchedGraphEdge::OutputDep
704 : SchedGraphEdge::AntiDep);
712 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
713 SchedGraphNode* node,
714 vector<SchedGraphNode*>& memNodeVec,
715 RegToRefVecMap& regToRefVecMap,
716 ValueToDefVecMap& valueToDefVecMap)
718 const MachineInstrInfo& mii = target.getInstrInfo();
721 MachineOpCode opCode = node->getOpCode();
722 if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
723 memNodeVec.push_back(node);
725 // Collect the register references and value defs. for explicit operands
727 const MachineInstr& minstr = * node->getMachineInstr();
728 for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
730 const MachineOperand& mop = minstr.getOperand(i);
732 // if this references a register other than the hardwired
733 // "zero" register, record the reference.
734 if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
736 int regNum = mop.getMachineRegNum();
737 if (regNum != target.getRegInfo().getZeroRegNum())
738 regToRefVecMap[mop.getMachineRegNum()].push_back(make_pair(node,
740 continue; // nothing more to do
743 // ignore all other non-def operands
744 if (! minstr.operandIsDefined(i))
747 // We must be defining a value.
748 assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
749 mop.getOperandType() == MachineOperand::MO_CCRegister)
750 && "Do not expect any other kind of operand to be defined!");
752 const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
753 valueToDefVecMap[defInstr].push_back(make_pair(node, i));
757 // Collect value defs. for implicit operands. The interface to extract
758 // them assumes they must be virtual registers!
760 for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
761 if (minstr.implicitRefIsDefined(i))
762 if (const Instruction* defInstr =
763 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
765 valueToDefVecMap[defInstr].push_back(make_pair(node, -i));
771 SchedGraph::buildNodesforBB(const TargetMachine& target,
772 const BasicBlock* bb,
773 vector<SchedGraphNode*>& memNodeVec,
774 RegToRefVecMap& regToRefVecMap,
775 ValueToDefVecMap& valueToDefVecMap)
777 const MachineInstrInfo& mii = target.getInstrInfo();
779 // Build graph nodes for each VM instruction and gather def/use info.
780 // Do both those together in a single pass over all machine instructions.
781 const MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
782 for (unsigned i=0; i < mvec.size(); i++)
783 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
785 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
787 this->noteGraphNodeForInstr(mvec[i], node);
789 // Remember all register references and value defs
790 findDefUseInfoAtInstr(target, node,
791 memNodeVec, regToRefVecMap,valueToDefVecMap);
794 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
795 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
796 // This is a BIG UGLY HACK. IT NEEDS TO BE ELIMINATED.
797 // Look for copy instructions inserted in this BB due to Phi instructions
798 // in the successor BBs.
799 // There MUST be exactly one copy per Phi in successor nodes.
801 for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
803 for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
806 if ((*PI)->getOpcode() != Instruction::PHINode)
807 break; // No more Phis in this successor
809 // Find the incoming value from block bb to block (*SI)
810 int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
811 assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
812 Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
813 assert(inVal != NULL && "There must be an in-value on every edge");
815 // Find the machine instruction that makes a copy of inval to (*PI).
816 // This must be in the current basic block (bb).
817 const MachineCodeForVMInstr& mvec = (*PI)->getMachineInstrVec();
818 const MachineInstr* theCopy = NULL;
819 for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
820 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
821 // not a Phi: assume this is a copy and examine its operands
822 for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
824 const MachineOperand& mop = mvec[i]->getOperand(o);
825 if (mvec[i]->operandIsDefined(o))
826 assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
827 else if (mop.getVRegValue() == inVal)
834 // Found the dang instruction. Now create a node and do the rest...
837 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
838 theCopy, origIndexInBB++, target);
839 this->noteGraphNodeForInstr(theCopy, node);
840 findDefUseInfoAtInstr(target, node,
841 memNodeVec, regToRefVecMap,valueToDefVecMap);
844 #endif REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
849 SchedGraph::buildGraph(const TargetMachine& target)
851 const MachineInstrInfo& mii = target.getInstrInfo();
852 const BasicBlock* bb = bbVec[0];
854 assert(bbVec.size() == 1 && "Only handling a single basic block here");
856 // Use this data structure to note all machine operands that compute
857 // ordinary LLVM values. These must be computed defs (i.e., instructions).
858 // Note that there may be multiple machine instructions that define
860 ValueToDefVecMap valueToDefVecMap;
862 // Use this data structure to note all memory instructions.
863 // We use this to add memory dependence edges without a second full walk.
865 // vector<const Instruction*> memVec;
866 vector<SchedGraphNode*> memNodeVec;
868 // Use this data structure to note any uses or definitions of
869 // machine registers so we can add edges for those later without
870 // extra passes over the nodes.
871 // The vector holds an ordered list of references to the machine reg,
872 // ordered according to control-flow order. This only works for a
873 // single basic block, hence the assertion. Each reference is identified
874 // by the pair: <node, operand-number>.
876 RegToRefVecMap regToRefVecMap;
878 // Make a dummy root node. We'll add edges to the real roots later.
879 graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
880 graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
882 //----------------------------------------------------------------
883 // First add nodes for all the machine instructions in the basic block
884 // because this greatly simplifies identifying which edges to add.
885 // Do this one VM instruction at a time since the SchedGraphNode needs that.
886 // Also, remember the load/store instructions to add memory deps later.
887 //----------------------------------------------------------------
889 buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
891 //----------------------------------------------------------------
892 // Now add edges for the following (all are incoming edges except (4)):
893 // (1) operands of the machine instruction, including hidden operands
894 // (2) machine register dependences
895 // (3) memory load/store dependences
896 // (3) other resource dependences for the machine instruction, if any
897 // (4) output dependences when multiple machine instructions define the
898 // same value; all must have been generated from a single VM instrn
899 // (5) control dependences to branch instructions generated for the
900 // terminator instruction of the BB. Because of delay slots and
901 // 2-way conditional branches, multiple CD edges are needed
902 // (see addCDEdges for details).
903 // Also, note any uses or defs of machine registers.
905 //----------------------------------------------------------------
907 MachineCodeForBasicBlock& bbMvec = bb->getMachineInstrVec();
909 // First, add edges to the terminator instruction of the basic block.
910 this->addCDEdges(bb->getTerminator(), target);
912 // Then add memory dep edges: store->load, load->store, and store->store.
913 // Call instructions are treated as both load and store.
914 this->addMemEdges(memNodeVec, target);
916 // Then add edges between call instructions and CC set/use instructions
917 this->addCallCCEdges(memNodeVec, bbMvec, target);
919 // Then add incoming def-use (SSA) edges for each machine instruction.
920 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
921 addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
923 // Then add non-SSA edges for all VM instructions in the block.
924 // We assume that all machine instructions that define a value are
925 // generated from the VM instruction corresponding to that value.
926 // TODO: This could probably be done much more efficiently.
927 for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
928 this->addNonSSAEdgesForValue(*II, target);
930 // Then add edges for dependences on machine registers
931 this->addMachineRegEdges(regToRefVecMap, target);
933 // Finally, add edges from the dummy root and to dummy leaf
934 this->addDummyEdges();
939 // class SchedGraphSet
943 SchedGraphSet::SchedGraphSet(const Method* _method,
944 const TargetMachine& target) :
947 buildGraphsForMethod(method, target);
952 SchedGraphSet::~SchedGraphSet()
954 // delete all the graphs
955 for (iterator I=begin(); I != end(); ++I)
961 SchedGraphSet::dump() const
963 cout << "======== Sched graphs for method `"
964 << (method->hasName()? method->getName() : "???")
965 << "' ========" << endl << endl;
967 for (const_iterator I=begin(); I != end(); ++I)
970 cout << endl << "====== End graphs for method `"
971 << (method->hasName()? method->getName() : "")
972 << "' ========" << endl << endl;
977 SchedGraphSet::buildGraphsForMethod(const Method *method,
978 const TargetMachine& target)
980 for (Method::const_iterator BI = method->begin(); BI != method->end(); ++BI)
982 SchedGraph* graph = new SchedGraph(*BI, target);
983 this->noteGraphForBlock(*BI, graph);
990 operator<<(ostream& os, const SchedGraphEdge& edge)
992 os << "edge [" << edge.src->getNodeId() << "] -> ["
993 << edge.sink->getNodeId() << "] : ";
995 switch(edge.depType) {
996 case SchedGraphEdge::CtrlDep: os<< "Control Dep"; break;
997 case SchedGraphEdge::DefUseDep: os<< "Reg Value " << edge.val; break;
998 case SchedGraphEdge::MemoryDep: os<< "Mem Value " << edge.val; break;
999 case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
1000 case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
1001 default: assert(0); break;
1004 os << " : delay = " << edge.minDelay << endl;
1010 operator<<(ostream& os, const SchedGraphNode& node)
1013 os << "Node " << node.nodeId << " : "
1014 << "latency = " << node.latency << endl;
1018 if (node.getMachineInstr() == NULL)
1019 os << "(Dummy node)" << endl;
1022 os << *node.getMachineInstr() << endl;
1025 os << node.inEdges.size() << " Incoming Edges:" << endl;
1026 for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
1029 os << * node.inEdges[i];
1033 os << node.outEdges.size() << " Outgoing Edges:" << endl;
1034 for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
1037 os << * node.outEdges[i];