1 //===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "SDNodeDbgValue.h"
17 #include "ScheduleDAGSDNodes.h"
18 #include "InstrEmitter.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/MC/MCInstrItineraries.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
38 STATISTIC(LoadsClustered, "Number of loads clustered together");
40 // This allows latency based scheduler to notice high latency instructions
41 // without a target itinerary. The choise if number here has more to do with
42 // balancing scheduler heursitics than with the actual machine latency.
43 static cl::opt<int> HighLatencyCycles(
44 "sched-high-latency-cycles", cl::Hidden, cl::init(10),
45 cl::desc("Roughly estimate the number of cycles that 'long latency'"
46 "instructions take for targets with no itinerary"));
48 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
49 : ScheduleDAG(mf), BB(0), DAG(0),
50 InstrItins(mf.getTarget().getInstrItineraryData()) {}
52 /// Run - perform scheduling.
54 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
58 // Clear the scheduler's SUnit DAG.
59 ScheduleDAG::clearDAG();
62 // Invoke the target's selection of scheduler.
66 /// NewSUnit - Creates a new SUnit and return a ptr to it.
68 SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
70 const SUnit *Addr = 0;
74 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
75 assert((Addr == 0 || Addr == &SUnits[0]) &&
76 "SUnits std::vector reallocated on the fly!");
77 SUnits.back().OrigNode = &SUnits.back();
78 SUnit *SU = &SUnits.back();
79 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
81 (N->isMachineOpcode() &&
82 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
83 SU->SchedulingPref = Sched::None;
85 SU->SchedulingPref = TLI.getSchedulingPreference(N);
89 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
90 SUnit *SU = newSUnit(Old->getNode());
91 SU->OrigNode = Old->OrigNode;
92 SU->Latency = Old->Latency;
93 SU->isVRegCycle = Old->isVRegCycle;
94 SU->isCall = Old->isCall;
95 SU->isCallOp = Old->isCallOp;
96 SU->isTwoAddress = Old->isTwoAddress;
97 SU->isCommutable = Old->isCommutable;
98 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
99 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
100 SU->isScheduleHigh = Old->isScheduleHigh;
101 SU->isScheduleLow = Old->isScheduleLow;
102 SU->SchedulingPref = Old->SchedulingPref;
103 Old->isCloned = true;
107 /// CheckForPhysRegDependency - Check if the dependency between def and use of
108 /// a specified operand is a physical register dependency. If so, returns the
109 /// register and the cost of copying the register.
110 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
111 const TargetRegisterInfo *TRI,
112 const TargetInstrInfo *TII,
113 unsigned &PhysReg, int &Cost) {
114 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
117 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
118 if (TargetRegisterInfo::isVirtualRegister(Reg))
121 unsigned ResNo = User->getOperand(2).getResNo();
122 if (Def->isMachineOpcode()) {
123 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
124 if (ResNo >= II.getNumDefs() &&
125 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
127 const TargetRegisterClass *RC =
128 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
129 Cost = RC->getCopyCost();
134 static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
135 SmallVector<EVT, 4> VTs;
136 SDNode *GlueDestNode = Glue.getNode();
138 // Don't add glue from a node to itself.
139 if (GlueDestNode == N) return;
141 // Don't add glue to something that already has it, either as a use or value.
142 if (N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue ||
143 N->getValueType(N->getNumValues() - 1) == MVT::Glue) {
146 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
147 VTs.push_back(N->getValueType(I));
150 VTs.push_back(MVT::Glue);
152 SmallVector<SDValue, 4> Ops;
153 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
154 Ops.push_back(N->getOperand(I));
159 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
160 MachineSDNode::mmo_iterator Begin = 0, End = 0;
161 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
163 // Store memory references.
165 Begin = MN->memoperands_begin();
166 End = MN->memoperands_end();
169 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
171 // Reset the memory references
173 MN->setMemRefs(Begin, End);
176 /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
177 /// This function finds loads of the same base and different offsets. If the
178 /// offsets are not far apart (target specific), it add MVT::Glue inputs and
179 /// outputs to ensure they are scheduled together and in order. This
180 /// optimization may benefit some targets by improving cache locality.
181 void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
183 unsigned NumOps = Node->getNumOperands();
184 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
185 Chain = Node->getOperand(NumOps-1).getNode();
189 // Look for other loads of the same chain. Find loads that are loading from
190 // the same base pointer and different offsets.
191 SmallPtrSet<SDNode*, 16> Visited;
192 SmallVector<int64_t, 4> Offsets;
193 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
194 bool Cluster = false;
196 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
199 if (User == Node || !Visited.insert(User))
201 int64_t Offset1, Offset2;
202 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
204 // FIXME: Should be ok if they addresses are identical. But earlier
205 // optimizations really should have eliminated one of the loads.
207 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
208 Offsets.push_back(Offset1);
209 O2SMap.insert(std::make_pair(Offset2, User));
210 Offsets.push_back(Offset2);
211 if (Offset2 < Offset1)
219 // Sort them in increasing order.
220 std::sort(Offsets.begin(), Offsets.end());
222 // Check if the loads are close enough.
223 SmallVector<SDNode*, 4> Loads;
224 unsigned NumLoads = 0;
225 int64_t BaseOff = Offsets[0];
226 SDNode *BaseLoad = O2SMap[BaseOff];
227 Loads.push_back(BaseLoad);
228 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
229 int64_t Offset = Offsets[i];
230 SDNode *Load = O2SMap[Offset];
231 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
232 break; // Stop right here. Ignore loads that are further away.
233 Loads.push_back(Load);
240 // Cluster loads by adding MVT::Glue outputs and inputs. This also
241 // ensure they are scheduled in order of increasing addresses.
242 SDNode *Lead = Loads[0];
243 AddGlue(Lead, SDValue(0, 0), true, DAG);
245 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1);
246 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
247 bool OutGlue = I < E - 1;
248 SDNode *Load = Loads[I];
250 AddGlue(Load, InGlue, OutGlue, DAG);
253 InGlue = SDValue(Load, Load->getNumValues() - 1);
259 /// ClusterNodes - Cluster certain nodes which should be scheduled together.
261 void ScheduleDAGSDNodes::ClusterNodes() {
262 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
263 E = DAG->allnodes_end(); NI != E; ++NI) {
265 if (!Node || !Node->isMachineOpcode())
268 unsigned Opc = Node->getMachineOpcode();
269 const MCInstrDesc &MCID = TII->get(Opc);
271 // Cluster loads from "near" addresses into combined SUnits.
272 ClusterNeighboringLoads(Node);
276 void ScheduleDAGSDNodes::BuildSchedUnits() {
277 // During scheduling, the NodeId field of SDNode is used to map SDNodes
278 // to their associated SUnits by holding SUnits table indices. A value
279 // of -1 means the SDNode does not yet have an associated SUnit.
280 unsigned NumNodes = 0;
281 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
282 E = DAG->allnodes_end(); NI != E; ++NI) {
287 // Reserve entries in the vector for each of the SUnits we are creating. This
288 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
290 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
291 // This is a temporary workaround.
292 SUnits.reserve(NumNodes * 2);
294 // Add all nodes in depth first order.
295 SmallVector<SDNode*, 64> Worklist;
296 SmallPtrSet<SDNode*, 64> Visited;
297 Worklist.push_back(DAG->getRoot().getNode());
298 Visited.insert(DAG->getRoot().getNode());
300 SmallVector<SUnit*, 8> CallSUnits;
301 while (!Worklist.empty()) {
302 SDNode *NI = Worklist.pop_back_val();
304 // Add all operands to the worklist unless they've already been added.
305 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
306 if (Visited.insert(NI->getOperand(i).getNode()))
307 Worklist.push_back(NI->getOperand(i).getNode());
309 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
312 // If this node has already been processed, stop now.
313 if (NI->getNodeId() != -1) continue;
315 SUnit *NodeSUnit = newSUnit(NI);
317 // See if anything is glued to this node, if so, add them to glued
318 // nodes. Nodes can have at most one glue input and one glue output. Glue
319 // is required to be the last operand and result of a node.
321 // Scan up to find glued preds.
323 while (N->getNumOperands() &&
324 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
325 N = N->getOperand(N->getNumOperands()-1).getNode();
326 assert(N->getNodeId() == -1 && "Node already inserted!");
327 N->setNodeId(NodeSUnit->NodeNum);
328 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
329 NodeSUnit->isCall = true;
332 // Scan down to find any glued succs.
334 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
335 SDValue GlueVal(N, N->getNumValues()-1);
337 // There are either zero or one users of the Glue result.
338 bool HasGlueUse = false;
339 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
341 if (GlueVal.isOperandOf(*UI)) {
343 assert(N->getNodeId() == -1 && "Node already inserted!");
344 N->setNodeId(NodeSUnit->NodeNum);
346 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
347 NodeSUnit->isCall = true;
350 if (!HasGlueUse) break;
353 if (NodeSUnit->isCall)
354 CallSUnits.push_back(NodeSUnit);
356 // Schedule zero-latency TokenFactor below any nodes that may increase the
357 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
358 // have false stalls.
359 if (NI->getOpcode() == ISD::TokenFactor)
360 NodeSUnit->isScheduleLow = true;
362 // If there are glue operands involved, N is now the bottom-most node
363 // of the sequence of nodes that are glued together.
365 NodeSUnit->setNode(N);
366 assert(N->getNodeId() == -1 && "Node already inserted!");
367 N->setNodeId(NodeSUnit->NodeNum);
369 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
370 InitNumRegDefsLeft(NodeSUnit);
372 // Assign the Latency field of NodeSUnit using target-provided information.
373 computeLatency(NodeSUnit);
376 // Find all call operands.
377 while (!CallSUnits.empty()) {
378 SUnit *SU = CallSUnits.pop_back_val();
379 for (const SDNode *SUNode = SU->getNode(); SUNode;
380 SUNode = SUNode->getGluedNode()) {
381 if (SUNode->getOpcode() != ISD::CopyToReg)
383 SDNode *SrcN = SUNode->getOperand(2).getNode();
384 if (isPassiveNode(SrcN)) continue; // Not scheduled.
385 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
386 SrcSU->isCallOp = true;
391 void ScheduleDAGSDNodes::AddSchedEdges() {
392 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
394 // Check to see if the scheduler cares about latencies.
395 bool UnitLatencies = forceUnitLatencies();
397 // Pass 2: add the preds, succs, etc.
398 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
399 SUnit *SU = &SUnits[su];
400 SDNode *MainNode = SU->getNode();
402 if (MainNode->isMachineOpcode()) {
403 unsigned Opc = MainNode->getMachineOpcode();
404 const MCInstrDesc &MCID = TII->get(Opc);
405 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
406 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
407 SU->isTwoAddress = true;
411 if (MCID.isCommutable())
412 SU->isCommutable = true;
415 // Find all predecessors and successors of the group.
416 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
417 if (N->isMachineOpcode() &&
418 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
419 SU->hasPhysRegClobbers = true;
420 unsigned NumUsed = InstrEmitter::CountResults(N);
421 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
422 --NumUsed; // Skip over unused values at the end.
423 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
424 SU->hasPhysRegDefs = true;
427 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
428 SDNode *OpN = N->getOperand(i).getNode();
429 if (isPassiveNode(OpN)) continue; // Not scheduled.
430 SUnit *OpSU = &SUnits[OpN->getNodeId()];
431 assert(OpSU && "Node has no SUnit!");
432 if (OpSU == SU) continue; // In the same group.
434 EVT OpVT = N->getOperand(i).getValueType();
435 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
436 bool isChain = OpVT == MVT::Other;
438 unsigned PhysReg = 0;
440 // Determine if this is a physical register dependency.
441 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
442 assert((PhysReg == 0 || !isChain) &&
443 "Chain dependence via physreg data?");
444 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
445 // emits a copy from the physical register to a virtual register unless
446 // it requires a cross class copy (cost < 0). That means we are only
447 // treating "expensive to copy" register dependency as physical register
448 // dependency. This may change in the future though.
449 if (Cost >= 0 && !StressSched)
452 // If this is a ctrl dep, latency is 1.
453 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
454 // Special-case TokenFactor chains as zero-latency.
455 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
458 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
460 if (!isChain && !UnitLatencies) {
461 computeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
462 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
465 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
466 // Multiple register uses are combined in the same SUnit. For example,
467 // we could have a set of glued nodes with all their defs consumed by
468 // another set of glued nodes. Register pressure tracking sees this as
469 // a single use, so to keep pressure balanced we reduce the defs.
471 // We can't tell (without more book-keeping) if this results from
472 // glued nodes or duplicate operands. As long as we don't reduce
473 // NumRegDefsLeft to zero, we handle the common cases well.
474 --OpSU->NumRegDefsLeft;
481 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
482 /// are input. This SUnit graph is similar to the SelectionDAG, but
483 /// excludes nodes that aren't interesting to scheduling, and represents
484 /// glued together nodes with a single SUnit.
485 void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
486 // Cluster certain nodes which should be scheduled together.
488 // Populate the SUnits array.
490 // Compute all the scheduling dependencies between nodes.
494 // Initialize NumNodeDefs for the current Node's opcode.
495 void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
496 // Check for phys reg copy.
500 if (!Node->isMachineOpcode()) {
501 if (Node->getOpcode() == ISD::CopyFromReg)
507 unsigned POpc = Node->getMachineOpcode();
508 if (POpc == TargetOpcode::IMPLICIT_DEF) {
509 // No register need be allocated for this.
513 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
514 // Some instructions define regs that are not represented in the selection DAG
515 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
516 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
520 // Construct a RegDefIter for this SUnit and find the first valid value.
521 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
522 const ScheduleDAGSDNodes *SD)
523 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
528 // Advance to the next valid value defined by the SUnit.
529 void ScheduleDAGSDNodes::RegDefIter::Advance() {
530 for (;Node;) { // Visit all glued nodes.
531 for (;DefIdx < NodeNumDefs; ++DefIdx) {
532 if (!Node->hasAnyUseOfValue(DefIdx))
534 ValueType = Node->getValueType(DefIdx);
536 return; // Found a normal regdef.
538 Node = Node->getGluedNode();
540 return; // No values left to visit.
546 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
547 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
548 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
549 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
550 ++SU->NumRegDefsLeft;
554 void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
555 SDNode *N = SU->getNode();
557 // TokenFactor operands are considered zero latency, and some schedulers
558 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
559 // whenever node latency is nonzero.
560 if (N && N->getOpcode() == ISD::TokenFactor) {
565 // Check to see if the scheduler cares about latencies.
566 if (forceUnitLatencies()) {
571 if (!InstrItins || InstrItins->isEmpty()) {
572 if (N && N->isMachineOpcode() &&
573 TII->isHighLatencyDef(N->getMachineOpcode()))
574 SU->Latency = HighLatencyCycles;
580 // Compute the latency for the node. We use the sum of the latencies for
581 // all nodes glued together into this SUnit.
583 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
584 if (N->isMachineOpcode())
585 SU->Latency += TII->getInstrLatency(InstrItins, N);
588 void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
589 unsigned OpIdx, SDep& dep) const{
590 // Check to see if the scheduler cares about latencies.
591 if (forceUnitLatencies())
594 if (dep.getKind() != SDep::Data)
597 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
598 if (Use->isMachineOpcode())
599 // Adjust the use operand index by num of defs.
600 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
601 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
602 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
604 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
605 if (TargetRegisterInfo::isVirtualRegister(Reg))
606 // This copy is a liveout value. It is likely coalesced, so reduce the
607 // latency so not to penalize the def.
608 // FIXME: need target specific adjustment here?
609 Latency = (Latency > 1) ? Latency - 1 : 1;
612 dep.setLatency(Latency);
615 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
616 if (!SU->getNode()) {
617 dbgs() << "PHYS REG COPY\n";
621 SU->getNode()->dump(DAG);
623 SmallVector<SDNode *, 4> GluedNodes;
624 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
625 GluedNodes.push_back(N);
626 while (!GluedNodes.empty()) {
628 GluedNodes.back()->dump(DAG);
630 GluedNodes.pop_back();
634 void ScheduleDAGSDNodes::dumpSchedule() const {
635 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
636 if (SUnit *SU = Sequence[i])
639 dbgs() << "**** NOOP ****\n";
644 /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
645 /// their state is consistent with the nodes listed in Sequence.
647 void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
648 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
650 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
653 assert(Sequence.size() - Noops == ScheduledNodes &&
654 "The number of nodes scheduled doesn't match the expected number!");
660 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
661 const std::pair<unsigned, MachineInstr*> &B) {
662 return A.first < B.first;
667 /// ProcessSDDbgValues - Process SDDbgValues associated with this node.
668 static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
669 InstrEmitter &Emitter,
670 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
671 DenseMap<SDValue, unsigned> &VRBaseMap,
673 if (!N->getHasDebugValue())
676 // Opportunistically insert immediate dbg_value uses, i.e. those with source
677 // order number right after the N.
678 MachineBasicBlock *BB = Emitter.getBlock();
679 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
680 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
681 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
682 if (DVs[i]->isInvalidated())
684 unsigned DVOrder = DVs[i]->getOrder();
685 if (!Order || DVOrder == ++Order) {
686 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
688 Orders.push_back(std::make_pair(DVOrder, DbgMI));
689 BB->insert(InsertPos, DbgMI);
691 DVs[i]->setIsInvalidated();
696 // ProcessSourceNode - Process nodes with source order numbers. These are added
697 // to a vector which EmitSchedule uses to determine how to insert dbg_value
698 // instructions in the right order.
699 static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
700 InstrEmitter &Emitter,
701 DenseMap<SDValue, unsigned> &VRBaseMap,
702 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
703 SmallSet<unsigned, 8> &Seen) {
704 unsigned Order = DAG->GetOrdering(N);
705 if (!Order || !Seen.insert(Order)) {
706 // Process any valid SDDbgValues even if node does not have any order
708 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
712 MachineBasicBlock *BB = Emitter.getBlock();
713 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
714 // Did not insert any instruction.
715 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
719 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
720 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
723 void ScheduleDAGSDNodes::
724 EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
725 MachineBasicBlock::iterator InsertPos) {
726 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
728 if (I->isCtrl()) continue; // ignore chain preds
729 if (I->getSUnit()->CopyDstRC) {
730 // Copy to physical register.
731 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
732 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
733 // Find the destination physical register.
735 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
736 EE = SU->Succs.end(); II != EE; ++II) {
737 if (II->isCtrl()) continue; // ignore chain preds
743 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
744 .addReg(VRI->second);
746 // Copy from physical register.
747 assert(I->getReg() && "Unknown physical register!");
748 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
749 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
750 (void)isNew; // Silence compiler warning.
751 assert(isNew && "Node emitted out of order - early");
752 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
753 .addReg(I->getReg());
759 /// EmitSchedule - Emit the machine code in scheduled order. Return the new
760 /// InsertPos and MachineBasicBlock that contains this insertion
761 /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
762 /// not necessarily refer to returned BB. The emitter may split blocks.
763 MachineBasicBlock *ScheduleDAGSDNodes::
764 EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
765 InstrEmitter Emitter(BB, InsertPos);
766 DenseMap<SDValue, unsigned> VRBaseMap;
767 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
768 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
769 SmallSet<unsigned, 8> Seen;
770 bool HasDbg = DAG->hasDebugValues();
772 // If this is the first BB, emit byval parameter dbg_value's.
773 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
774 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
775 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
776 for (; PDI != PDE; ++PDI) {
777 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
779 BB->insert(InsertPos, DbgMI);
783 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
784 SUnit *SU = Sequence[i];
786 // Null SUnit* is a noop.
787 TII->insertNoop(*Emitter.getBlock(), InsertPos);
791 // For pre-regalloc scheduling, create instructions corresponding to the
792 // SDNode and any glued SDNodes and append them to the block.
793 if (!SU->getNode()) {
795 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
799 SmallVector<SDNode *, 4> GluedNodes;
800 for (SDNode *N = SU->getNode()->getGluedNode(); N;
801 N = N->getGluedNode())
802 GluedNodes.push_back(N);
803 while (!GluedNodes.empty()) {
804 SDNode *N = GluedNodes.back();
805 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
807 // Remember the source order of the inserted instruction.
809 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
810 GluedNodes.pop_back();
812 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
814 // Remember the source order of the inserted instruction.
816 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
820 // Insert all the dbg_values which have not already been inserted in source
823 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
825 // Sort the source order instructions and use the order to insert debug
827 std::sort(Orders.begin(), Orders.end(), OrderSorter());
829 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
830 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
831 // Now emit the rest according to source order.
832 unsigned LastOrder = 0;
833 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
834 unsigned Order = Orders[i].first;
835 MachineInstr *MI = Orders[i].second;
836 // Insert all SDDbgValue's whose order(s) are before "Order".
840 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
841 if ((*DI)->isInvalidated())
843 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
846 // Insert to start of the BB (after PHIs).
847 BB->insert(BBBegin, DbgMI);
849 // Insert at the instruction, which may be in a different
850 // block, if the block was split by a custom inserter.
851 MachineBasicBlock::iterator Pos = MI;
852 MI->getParent()->insert(llvm::next(Pos), DbgMI);
858 // Add trailing DbgValue's before the terminator. FIXME: May want to add
859 // some of them before one or more conditional branches?
860 SmallVector<MachineInstr*, 8> DbgMIs;
862 if (!(*DI)->isInvalidated())
863 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
864 DbgMIs.push_back(DbgMI);
868 MachineBasicBlock *InsertBB = Emitter.getBlock();
869 MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
870 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
873 InsertPos = Emitter.getInsertPos();
874 return Emitter.getBlock();
877 /// Return the basic block label.
878 std::string ScheduleDAGSDNodes::getDAGName() const {
879 return "sunit-dag." + BB->getFullName();