1 //===- SchedGraph.cpp - Scheduling Graph Implementation -------------------===//
3 // Scheduling graph based on SSA graph plus extra dependence edges capturing
4 // dependences due to machine resources (machine registers, CC registers, and
7 //===----------------------------------------------------------------------===//
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"
24 //*********************** Internal Data Structures *************************/
26 // The following two types need to be classes, not typedefs, so we can use
27 // opaque declarations in SchedGraph.h
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;
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;
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;
45 // class SchedGraphEdge
49 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
50 SchedGraphNode* _sink,
51 SchedGraphEdgeDepType _depType,
52 unsigned int _depOrderType,
57 depOrderType(_depOrderType),
58 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
61 assert(src != sink && "Self-loop in scheduling graph!");
62 src->addOutEdge(this);
63 sink->addInEdge(this);
68 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
69 SchedGraphNode* _sink,
71 unsigned int _depOrderType,
76 depOrderType(_depOrderType),
77 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
80 assert(src != sink && "Self-loop in scheduling graph!");
81 src->addOutEdge(this);
82 sink->addInEdge(this);
87 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
88 SchedGraphNode* _sink,
90 unsigned int _depOrderType,
94 depType(MachineRegister),
95 depOrderType(_depOrderType),
96 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
97 machineRegNum(_regNum)
99 assert(src != sink && "Self-loop in scheduling graph!");
100 src->addOutEdge(this);
101 sink->addInEdge(this);
106 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
107 SchedGraphNode* _sink,
108 ResourceId _resourceId,
112 depType(MachineResource),
113 depOrderType(NonDataDep),
114 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
115 resourceId(_resourceId)
117 assert(src != sink && "Self-loop in scheduling graph!");
118 src->addOutEdge(this);
119 sink->addInEdge(this);
123 SchedGraphEdge::~SchedGraphEdge()
127 void SchedGraphEdge::dump(int indent) const {
128 cerr << std::string(indent*2, ' ') << *this;
133 // class SchedGraphNode
137 SchedGraphNode::SchedGraphNode(unsigned int _nodeId,
138 const BasicBlock* _bb,
139 const MachineInstr* _minstr,
141 const TargetMachine& target)
145 origIndexInBB(indexInBB),
150 MachineOpCode mopCode = minstr->getOpCode();
151 latency = target.getInstrInfo().hasResultInterlock(mopCode)
152 ? target.getInstrInfo().minLatency(mopCode)
153 : target.getInstrInfo().maxLatency(mopCode);
159 SchedGraphNode::~SchedGraphNode()
161 // for each node, delete its out-edges
162 std::for_each(beginOutEdges(), endOutEdges(),
163 deleter<SchedGraphEdge>);
166 void SchedGraphNode::dump(int indent) const {
167 cerr << std::string(indent*2, ' ') << *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)
226 SchedGraph::~SchedGraph()
228 for (const_iterator I = begin(); I != end(); ++I)
236 SchedGraph::dump() const
238 cerr << " Sched Graph for Basic Blocks: ";
239 for (unsigned i=0, N=bbVec.size(); i < N; i++)
241 cerr << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
242 << " (" << bbVec[i] << ")"
243 << ((i == N-1)? "" : ", ");
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)? "" : ", ");
251 cerr << "\n Graph Nodes:\n";
252 for (const_iterator I=begin(); I != end(); ++I)
253 cerr << "\n" << *I->second;
260 SchedGraph::eraseIncomingEdges(SchedGraphNode* node, bool addDummyEdges)
262 // Delete and disconnect all in-edges for the node
263 for (SchedGraphNode::iterator I = node->beginInEdges();
264 I != node->endInEdges(); ++I)
266 SchedGraphNode* srcNode = (*I)->getSrc();
267 srcNode->removeOutEdge(*I);
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);
280 node->inEdges.clear();
284 SchedGraph::eraseOutgoingEdges(SchedGraphNode* node, bool addDummyEdges)
286 // Delete and disconnect all out-edges for the node
287 for (SchedGraphNode::iterator I = node->beginOutEdges();
288 I != node->endOutEdges(); ++I)
290 SchedGraphNode* sinkNode = (*I)->getSink();
291 sinkNode->removeInEdge(*I);
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);
304 node->outEdges.clear();
308 SchedGraph::eraseIncidentEdges(SchedGraphNode* node, bool addDummyEdges)
310 this->eraseIncomingEdges(node, addDummyEdges);
311 this->eraseOutgoingEdges(node, addDummyEdges);
316 SchedGraph::addDummyEdges()
318 assert(graphRoot->outEdges.size() == 0);
320 for (const_iterator I=begin(); I != end(); ++I)
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);
335 SchedGraph::addCDEdges(const TerminatorInst* term,
336 const TargetMachine& target)
338 const MachineInstrInfo& mii = target.getInstrInfo();
339 MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
341 // Find the first branch instr in the sequence of machine instrs for term
344 while (! mii.isBranch(termMvec[first]->getOpCode()) &&
345 ! mii.isReturn(termMvec[first]->getOpCode()))
347 assert(first < termMvec.size() &&
348 "No branch instructions for terminator? Ok, but weird!");
349 if (first == termMvec.size())
352 SchedGraphNode* firstBrNode = getGraphNodeForInstr(termMvec[first]);
354 // Add CD edges from each instruction in the sequence to the
355 // *last preceding* branch instr. in the sequence
356 // Use a latency of 0 because we only need to prevent out-of-order issue.
358 for (unsigned i = termMvec.size(); i > first+1; --i)
360 SchedGraphNode* toNode = getGraphNodeForInstr(termMvec[i-1]);
361 assert(toNode && "No node for instr generated for branch/ret?");
363 for (unsigned j = i-1; j != 0; --j)
364 if (mii.isBranch(termMvec[j-1]->getOpCode()) ||
365 mii.isReturn(termMvec[j-1]->getOpCode()))
367 SchedGraphNode* brNode = getGraphNodeForInstr(termMvec[j-1]);
368 assert(brNode && "No node for instr generated for branch/ret?");
369 (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
370 SchedGraphEdge::NonDataDep, 0);
371 break; // only one incoming edge is enough
375 // Add CD edges from each instruction preceding the first branch
376 // to the first branch. Use a latency of 0 as above.
378 for (unsigned i = first; i != 0; --i)
380 SchedGraphNode* fromNode = getGraphNodeForInstr(termMvec[i-1]);
381 assert(fromNode && "No node for instr generated for branch?");
382 (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
383 SchedGraphEdge::NonDataDep, 0);
386 // Now add CD edges to the first branch instruction in the sequence from
387 // all preceding instructions in the basic block. Use 0 latency again.
389 const BasicBlock* bb = firstBrNode->getBB();
390 const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
391 for (unsigned i=0, N=mvec.size(); i < N; i++)
393 if (mvec[i] == termMvec[first]) // reached the first branch
396 SchedGraphNode* fromNode = this->getGraphNodeForInstr(mvec[i]);
397 if (fromNode == NULL)
398 continue; // dummy instruction, e.g., PHI
400 (void) new SchedGraphEdge(fromNode, firstBrNode,
401 SchedGraphEdge::CtrlDep,
402 SchedGraphEdge::NonDataDep, 0);
404 // If we find any other machine instructions (other than due to
405 // the terminator) that also have delay slots, add an outgoing edge
406 // from the instruction to the instructions in the delay slots.
408 unsigned d = mii.getNumDelaySlots(mvec[i]->getOpCode());
409 assert(i+d < N && "Insufficient delay slots for instruction?");
411 for (unsigned j=1; j <= d; j++)
413 SchedGraphNode* toNode = this->getGraphNodeForInstr(mvec[i+j]);
414 assert(toNode && "No node for machine instr in delay slot?");
415 (void) new SchedGraphEdge(fromNode, toNode,
416 SchedGraphEdge::CtrlDep,
417 SchedGraphEdge::NonDataDep, 0);
422 static const int SG_LOAD_REF = 0;
423 static const int SG_STORE_REF = 1;
424 static const int SG_CALL_REF = 2;
426 static const unsigned int SG_DepOrderArray[][3] = {
427 { SchedGraphEdge::NonDataDep,
428 SchedGraphEdge::AntiDep,
429 SchedGraphEdge::AntiDep },
430 { SchedGraphEdge::TrueDep,
431 SchedGraphEdge::OutputDep,
432 SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
433 { SchedGraphEdge::TrueDep,
434 SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
435 SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
436 | SchedGraphEdge::OutputDep }
440 // Add a dependence edge between every pair of machine load/store/call
441 // instructions, where at least one is a store or a call.
442 // Use latency 1 just to ensure that memory operations are ordered;
443 // latency does not otherwise matter (true dependences enforce that).
446 SchedGraph::addMemEdges(const vector<SchedGraphNode*>& memNodeVec,
447 const TargetMachine& target)
449 const MachineInstrInfo& mii = target.getInstrInfo();
451 // Instructions in memNodeVec are in execution order within the basic block,
452 // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
454 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
456 MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
457 int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
458 : mii.isLoad(fromOpCode)? SG_LOAD_REF
460 for (unsigned jm=im+1; jm < NM; jm++)
462 MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
463 int toType = mii.isCall(toOpCode)? SG_CALL_REF
464 : mii.isLoad(toOpCode)? SG_LOAD_REF
467 if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
468 (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
469 SchedGraphEdge::MemoryDep,
470 SG_DepOrderArray[fromType][toType], 1);
475 // Add edges from/to CC reg instrs to/from call instrs.
476 // Essentially this prevents anything that sets or uses a CC reg from being
477 // reordered w.r.t. a call.
478 // Use a latency of 0 because we only need to prevent out-of-order issue,
479 // like with control dependences.
482 SchedGraph::addCallCCEdges(const vector<SchedGraphNode*>& memNodeVec,
483 MachineCodeForBasicBlock& bbMvec,
484 const TargetMachine& target)
486 const MachineInstrInfo& mii = target.getInstrInfo();
487 vector<SchedGraphNode*> callNodeVec;
489 // Find the call instruction nodes and put them in a vector.
490 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
491 if (mii.isCall(memNodeVec[im]->getOpCode()))
492 callNodeVec.push_back(memNodeVec[im]);
494 // Now walk the entire basic block, looking for CC instructions *and*
495 // call instructions, and keep track of the order of the instructions.
496 // Use the call node vec to quickly find earlier and later call nodes
497 // relative to the current CC instruction.
499 int lastCallNodeIdx = -1;
500 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
501 if (mii.isCall(bbMvec[i]->getOpCode()))
504 for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
505 if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
507 assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
509 else if (mii.isCCInstr(bbMvec[i]->getOpCode()))
510 { // Add incoming/outgoing edges from/to preceding/later calls
511 SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
513 for ( ; j <= lastCallNodeIdx; j++)
514 (void) new SchedGraphEdge(callNodeVec[j], ccNode,
515 MachineCCRegsRID, 0);
516 for ( ; j < (int) callNodeVec.size(); j++)
517 (void) new SchedGraphEdge(ccNode, callNodeVec[j],
518 MachineCCRegsRID, 0);
524 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
525 const TargetMachine& target)
527 assert(bbVec.size() == 1 && "Only handling a single basic block here");
529 // This assumes that such hardwired registers are never allocated
530 // to any LLVM value (since register allocation happens later), i.e.,
531 // any uses or defs of this register have been made explicit!
532 // Also assumes that two registers with different numbers are
535 for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
536 I != regToRefVecMap.end(); ++I)
538 int regNum = (*I).first;
539 RefVec& regRefVec = (*I).second;
541 // regRefVec is ordered by control flow order in the basic block
542 for (unsigned i=0; i < regRefVec.size(); ++i)
544 SchedGraphNode* node = regRefVec[i].first;
545 unsigned int opNum = regRefVec[i].second;
546 bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
548 node->getMachineInstr()->operandIsDefinedAndUsed(opNum);
550 for (unsigned p=0; p < i; ++p)
552 SchedGraphNode* prevNode = regRefVec[p].first;
553 if (prevNode != node)
555 unsigned int prevOpNum = regRefVec[p].second;
557 prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
558 bool prevIsDefAndUse =
559 prevNode->getMachineInstr()->operandIsDefinedAndUsed(prevOpNum);
563 new SchedGraphEdge(prevNode, node, regNum,
564 SchedGraphEdge::OutputDep);
565 if (!prevIsDef || prevIsDefAndUse)
566 new SchedGraphEdge(prevNode, node, regNum,
567 SchedGraphEdge::AntiDep);
571 if (!isDef || isDefAndUse)
572 new SchedGraphEdge(prevNode, node, regNum,
573 SchedGraphEdge::TrueDep);
581 // Adds dependences to/from refNode from/to all other defs
582 // in the basic block. refNode may be a use, a def, or both.
583 // We do not consider other uses because we are not building use-use deps.
586 SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
587 const RefVec& defVec,
588 const Value* defValue,
590 bool refNodeIsDefAndUse,
591 const TargetMachine& target)
593 bool refNodeIsUse = !refNodeIsDef || refNodeIsDefAndUse;
595 // Add true or output dep edges from all def nodes before refNode in BB.
596 // Add anti or output dep edges to all def nodes after refNode.
597 for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
599 if ((*I).first == refNode)
600 continue; // Dont add any self-loops
602 if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB())
603 { // (*).first is before refNode
605 (void) new SchedGraphEdge((*I).first, refNode, defValue,
606 SchedGraphEdge::OutputDep);
608 (void) new SchedGraphEdge((*I).first, refNode, defValue,
609 SchedGraphEdge::TrueDep);
612 { // (*).first is after refNode
614 (void) new SchedGraphEdge(refNode, (*I).first, defValue,
615 SchedGraphEdge::OutputDep);
617 (void) new SchedGraphEdge(refNode, (*I).first, defValue,
618 SchedGraphEdge::AntiDep);
625 SchedGraph::addEdgesForInstruction(const MachineInstr& minstr,
626 const ValueToDefVecMap& valueToDefVecMap,
627 const TargetMachine& target)
629 SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
633 // Add edges for all operands of the machine instruction.
635 for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
637 const MachineOperand& mop = minstr.getOperand(i);
638 switch(mop.getOperandType())
640 case MachineOperand::MO_VirtualRegister:
641 case MachineOperand::MO_CCRegister:
642 if (const Instruction* srcI =
643 dyn_cast_or_null<Instruction>(mop.getVRegValue()))
645 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
646 if (I != valueToDefVecMap.end())
647 addEdgesForValue(node, (*I).second, mop.getVRegValue(),
648 minstr.operandIsDefined(i),
649 minstr.operandIsDefinedAndUsed(i), target);
653 case MachineOperand::MO_MachineRegister:
656 case MachineOperand::MO_SignExtendedImmed:
657 case MachineOperand::MO_UnextendedImmed:
658 case MachineOperand::MO_PCRelativeDisp:
659 break; // nothing to do for immediate fields
662 assert(0 && "Unknown machine operand type in SchedGraph builder");
667 // Add edges for values implicitly used by the machine instruction.
668 // Examples include function arguments to a Call instructions or the return
669 // value of a Ret instruction.
671 for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
672 if (! minstr.implicitRefIsDefined(i) ||
673 minstr.implicitRefIsDefinedAndUsed(i))
674 if (const Instruction* srcI =
675 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
677 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
678 if (I != valueToDefVecMap.end())
679 addEdgesForValue(node, (*I).second, minstr.getImplicitRef(i),
680 minstr.implicitRefIsDefined(i),
681 minstr.implicitRefIsDefinedAndUsed(i), target);
687 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
688 SchedGraphNode* node,
689 vector<SchedGraphNode*>& memNodeVec,
690 RegToRefVecMap& regToRefVecMap,
691 ValueToDefVecMap& valueToDefVecMap)
693 const MachineInstrInfo& mii = target.getInstrInfo();
696 MachineOpCode opCode = node->getOpCode();
697 if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
698 memNodeVec.push_back(node);
700 // Collect the register references and value defs. for explicit operands
702 const MachineInstr& minstr = * node->getMachineInstr();
703 for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
705 const MachineOperand& mop = minstr.getOperand(i);
707 // if this references a register other than the hardwired
708 // "zero" register, record the reference.
709 if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
711 int regNum = mop.getMachineRegNum();
712 if (regNum != target.getRegInfo().getZeroRegNum())
713 regToRefVecMap[mop.getMachineRegNum()].push_back(
714 std::make_pair(node, i));
715 continue; // nothing more to do
718 // ignore all other non-def operands
719 if (! minstr.operandIsDefined(i))
722 // We must be defining a value.
723 assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
724 mop.getOperandType() == MachineOperand::MO_CCRegister)
725 && "Do not expect any other kind of operand to be defined!");
727 const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
728 valueToDefVecMap[defInstr].push_back(std::make_pair(node, i));
732 // Collect value defs. for implicit operands. The interface to extract
733 // them assumes they must be virtual registers!
735 for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
736 if (minstr.implicitRefIsDefined(i))
737 if (const Instruction* defInstr =
738 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
740 valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i));
746 SchedGraph::buildNodesforBB(const TargetMachine& target,
747 const BasicBlock* bb,
748 vector<SchedGraphNode*>& memNodeVec,
749 RegToRefVecMap& regToRefVecMap,
750 ValueToDefVecMap& valueToDefVecMap)
752 const MachineInstrInfo& mii = target.getInstrInfo();
754 // Build graph nodes for each VM instruction and gather def/use info.
755 // Do both those together in a single pass over all machine instructions.
756 const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
757 for (unsigned i=0; i < mvec.size(); i++)
758 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
760 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
762 this->noteGraphNodeForInstr(mvec[i], node);
764 // Remember all register references and value defs
765 findDefUseInfoAtInstr(target, node,
766 memNodeVec, regToRefVecMap,valueToDefVecMap);
769 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
770 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
771 // This is a BIG UGLY HACK. IT NEEDS TO BE ELIMINATED.
772 // Look for copy instructions inserted in this BB due to Phi instructions
773 // in the successor BBs.
774 // There MUST be exactly one copy per Phi in successor nodes.
776 for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
778 for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
781 if ((*PI)->getOpcode() != Instruction::PHINode)
782 break; // No more Phis in this successor
784 // Find the incoming value from block bb to block (*SI)
785 int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
786 assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
787 Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
788 assert(inVal != NULL && "There must be an in-value on every edge");
790 // Find the machine instruction that makes a copy of inval to (*PI).
791 // This must be in the current basic block (bb).
792 const MachineCodeForVMInstr& mvec = MachineCodeForBasicBlock::get(*PI);
793 const MachineInstr* theCopy = NULL;
794 for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
795 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
796 // not a Phi: assume this is a copy and examine its operands
797 for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
799 const MachineOperand& mop = mvec[i]->getOperand(o);
801 if (mvec[i]->operandIsDefined(o))
802 assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
804 if (! mvec[i]->operandIsDefined(o) ||
805 NOT NEEDED? mvec[i]->operandIsDefinedAndUsed(o))
806 if (mop.getVRegValue() == inVal)
813 // Found the dang instruction. Now create a node and do the rest...
816 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
817 theCopy, origIndexInBB++, target);
818 this->noteGraphNodeForInstr(theCopy, node);
819 findDefUseInfoAtInstr(target, node,
820 memNodeVec, regToRefVecMap,valueToDefVecMap);
823 #endif //REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
828 SchedGraph::buildGraph(const TargetMachine& target)
830 const BasicBlock* bb = bbVec[0];
832 assert(bbVec.size() == 1 && "Only handling a single basic block here");
834 // Use this data structure to note all machine operands that compute
835 // ordinary LLVM values. These must be computed defs (i.e., instructions).
836 // Note that there may be multiple machine instructions that define
838 ValueToDefVecMap valueToDefVecMap;
840 // Use this data structure to note all memory instructions.
841 // We use this to add memory dependence edges without a second full walk.
843 // vector<const Instruction*> memVec;
844 vector<SchedGraphNode*> memNodeVec;
846 // Use this data structure to note any uses or definitions of
847 // machine registers so we can add edges for those later without
848 // extra passes over the nodes.
849 // The vector holds an ordered list of references to the machine reg,
850 // ordered according to control-flow order. This only works for a
851 // single basic block, hence the assertion. Each reference is identified
852 // by the pair: <node, operand-number>.
854 RegToRefVecMap regToRefVecMap;
856 // Make a dummy root node. We'll add edges to the real roots later.
857 graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
858 graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
860 //----------------------------------------------------------------
861 // First add nodes for all the machine instructions in the basic block
862 // because this greatly simplifies identifying which edges to add.
863 // Do this one VM instruction at a time since the SchedGraphNode needs that.
864 // Also, remember the load/store instructions to add memory deps later.
865 //----------------------------------------------------------------
867 buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
869 //----------------------------------------------------------------
870 // Now add edges for the following (all are incoming edges except (4)):
871 // (1) operands of the machine instruction, including hidden operands
872 // (2) machine register dependences
873 // (3) memory load/store dependences
874 // (3) other resource dependences for the machine instruction, if any
875 // (4) output dependences when multiple machine instructions define the
876 // same value; all must have been generated from a single VM instrn
877 // (5) control dependences to branch instructions generated for the
878 // terminator instruction of the BB. Because of delay slots and
879 // 2-way conditional branches, multiple CD edges are needed
880 // (see addCDEdges for details).
881 // Also, note any uses or defs of machine registers.
883 //----------------------------------------------------------------
885 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(bb);
887 // First, add edges to the terminator instruction of the basic block.
888 this->addCDEdges(bb->getTerminator(), target);
890 // Then add memory dep edges: store->load, load->store, and store->store.
891 // Call instructions are treated as both load and store.
892 this->addMemEdges(memNodeVec, target);
894 // Then add edges between call instructions and CC set/use instructions
895 this->addCallCCEdges(memNodeVec, bbMvec, target);
897 // Then add incoming def-use (SSA) edges for each machine instruction.
898 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
899 addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
901 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
902 // Then add non-SSA edges for all VM instructions in the block.
903 // We assume that all machine instructions that define a value are
904 // generated from the VM instruction corresponding to that value.
905 // TODO: This could probably be done much more efficiently.
906 for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
907 this->addNonSSAEdgesForValue(*II, target);
908 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
910 // Then add edges for dependences on machine registers
911 this->addMachineRegEdges(regToRefVecMap, target);
913 // Finally, add edges from the dummy root and to dummy leaf
914 this->addDummyEdges();
919 // class SchedGraphSet
923 SchedGraphSet::SchedGraphSet(const Function* _function,
924 const TargetMachine& target) :
927 buildGraphsForMethod(method, target);
932 SchedGraphSet::~SchedGraphSet()
934 // delete all the graphs
935 for(iterator I = begin(), E = end(); I != E; ++I)
936 delete *I; // destructor is a friend
941 SchedGraphSet::dump() const
943 cerr << "======== Sched graphs for function `" << method->getName()
946 for (const_iterator I=begin(); I != end(); ++I)
949 cerr << "\n====== End graphs for function `" << method->getName()
955 SchedGraphSet::buildGraphsForMethod(const Function *F,
956 const TargetMachine& target)
958 for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
959 addGraph(new SchedGraph(BI, target));
963 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
965 os << "edge [" << edge.src->getNodeId() << "] -> ["
966 << edge.sink->getNodeId() << "] : ";
968 switch(edge.depType) {
969 case SchedGraphEdge::CtrlDep: os<< "Control Dep"; break;
970 case SchedGraphEdge::ValueDep: os<< "Reg Value " << edge.val; break;
971 case SchedGraphEdge::MemoryDep: os<< "Memory Dep"; break;
972 case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
973 case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
974 default: assert(0); break;
977 os << " : delay = " << edge.minDelay << "\n";
982 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
984 os << std::string(8, ' ')
985 << "Node " << node.nodeId << " : "
986 << "latency = " << node.latency << "\n" << std::string(12, ' ');
988 if (node.getMachineInstr() == NULL)
989 os << "(Dummy node)\n";
992 os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
993 os << node.inEdges.size() << " Incoming Edges:\n";
994 for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
995 os << std::string(16, ' ') << *node.inEdges[i];
997 os << std::string(12, ' ') << node.outEdges.size()
998 << " Outgoing Edges:\n";
999 for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
1000 os << std::string(16, ' ') << *node.outEdges[i];