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)
50 InstrItins(mf.getTarget().getInstrItineraryData()) {}
52 /// Run - perform scheduling.
54 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
55 MachineBasicBlock::iterator insertPos) {
57 ScheduleDAG::Run(bb, insertPos);
60 /// NewSUnit - Creates a new SUnit and return a ptr to it.
62 SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) {
64 const SUnit *Addr = 0;
68 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
69 assert((Addr == 0 || Addr == &SUnits[0]) &&
70 "SUnits std::vector reallocated on the fly!");
71 SUnits.back().OrigNode = &SUnits.back();
72 SUnit *SU = &SUnits.back();
73 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
75 (N->isMachineOpcode() &&
76 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
77 SU->SchedulingPref = Sched::None;
79 SU->SchedulingPref = TLI.getSchedulingPreference(N);
83 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
84 SUnit *SU = NewSUnit(Old->getNode());
85 SU->OrigNode = Old->OrigNode;
86 SU->Latency = Old->Latency;
87 SU->isVRegCycle = Old->isVRegCycle;
88 SU->isCall = Old->isCall;
89 SU->isCallOp = Old->isCallOp;
90 SU->isTwoAddress = Old->isTwoAddress;
91 SU->isCommutable = Old->isCommutable;
92 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
93 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
94 SU->isScheduleHigh = Old->isScheduleHigh;
95 SU->isScheduleLow = Old->isScheduleLow;
96 SU->SchedulingPref = Old->SchedulingPref;
101 /// CheckForPhysRegDependency - Check if the dependency between def and use of
102 /// a specified operand is a physical register dependency. If so, returns the
103 /// register and the cost of copying the register.
104 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
105 const TargetRegisterInfo *TRI,
106 const TargetInstrInfo *TII,
107 unsigned &PhysReg, int &Cost) {
108 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
111 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
112 if (TargetRegisterInfo::isVirtualRegister(Reg))
115 unsigned ResNo = User->getOperand(2).getResNo();
116 if (Def->isMachineOpcode()) {
117 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
118 if (ResNo >= II.getNumDefs() &&
119 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
121 const TargetRegisterClass *RC =
122 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
123 Cost = RC->getCopyCost();
128 static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
129 SmallVector<EVT, 4> VTs;
130 SDNode *GlueDestNode = Glue.getNode();
132 // Don't add glue from a node to itself.
133 if (GlueDestNode == N) return;
135 // Don't add glue to something which already has glue.
136 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return;
138 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
139 VTs.push_back(N->getValueType(I));
142 VTs.push_back(MVT::Glue);
144 SmallVector<SDValue, 4> Ops;
145 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
146 Ops.push_back(N->getOperand(I));
151 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
152 MachineSDNode::mmo_iterator Begin = 0, End = 0;
153 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
155 // Store memory references.
157 Begin = MN->memoperands_begin();
158 End = MN->memoperands_end();
161 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
163 // Reset the memory references
165 MN->setMemRefs(Begin, End);
168 /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
169 /// This function finds loads of the same base and different offsets. If the
170 /// offsets are not far apart (target specific), it add MVT::Glue inputs and
171 /// outputs to ensure they are scheduled together and in order. This
172 /// optimization may benefit some targets by improving cache locality.
173 void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
175 unsigned NumOps = Node->getNumOperands();
176 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
177 Chain = Node->getOperand(NumOps-1).getNode();
181 // Look for other loads of the same chain. Find loads that are loading from
182 // the same base pointer and different offsets.
183 SmallPtrSet<SDNode*, 16> Visited;
184 SmallVector<int64_t, 4> Offsets;
185 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
186 bool Cluster = false;
188 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
191 if (User == Node || !Visited.insert(User))
193 int64_t Offset1, Offset2;
194 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
196 // FIXME: Should be ok if they addresses are identical. But earlier
197 // optimizations really should have eliminated one of the loads.
199 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
200 Offsets.push_back(Offset1);
201 O2SMap.insert(std::make_pair(Offset2, User));
202 Offsets.push_back(Offset2);
203 if (Offset2 < Offset1)
211 // Sort them in increasing order.
212 std::sort(Offsets.begin(), Offsets.end());
214 // Check if the loads are close enough.
215 SmallVector<SDNode*, 4> Loads;
216 unsigned NumLoads = 0;
217 int64_t BaseOff = Offsets[0];
218 SDNode *BaseLoad = O2SMap[BaseOff];
219 Loads.push_back(BaseLoad);
220 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
221 int64_t Offset = Offsets[i];
222 SDNode *Load = O2SMap[Offset];
223 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
224 break; // Stop right here. Ignore loads that are further away.
225 Loads.push_back(Load);
232 // Cluster loads by adding MVT::Glue outputs and inputs. This also
233 // ensure they are scheduled in order of increasing addresses.
234 SDNode *Lead = Loads[0];
235 AddGlue(Lead, SDValue(0, 0), true, DAG);
237 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1);
238 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
239 bool OutGlue = I < E - 1;
240 SDNode *Load = Loads[I];
242 AddGlue(Load, InGlue, OutGlue, DAG);
245 InGlue = SDValue(Load, Load->getNumValues() - 1);
251 /// ClusterNodes - Cluster certain nodes which should be scheduled together.
253 void ScheduleDAGSDNodes::ClusterNodes() {
254 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
255 E = DAG->allnodes_end(); NI != E; ++NI) {
257 if (!Node || !Node->isMachineOpcode())
260 unsigned Opc = Node->getMachineOpcode();
261 const MCInstrDesc &MCID = TII->get(Opc);
263 // Cluster loads from "near" addresses into combined SUnits.
264 ClusterNeighboringLoads(Node);
268 void ScheduleDAGSDNodes::BuildSchedUnits() {
269 // During scheduling, the NodeId field of SDNode is used to map SDNodes
270 // to their associated SUnits by holding SUnits table indices. A value
271 // of -1 means the SDNode does not yet have an associated SUnit.
272 unsigned NumNodes = 0;
273 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
274 E = DAG->allnodes_end(); NI != E; ++NI) {
279 // Reserve entries in the vector for each of the SUnits we are creating. This
280 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
282 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
283 // This is a temporary workaround.
284 SUnits.reserve(NumNodes * 2);
286 // Add all nodes in depth first order.
287 SmallVector<SDNode*, 64> Worklist;
288 SmallPtrSet<SDNode*, 64> Visited;
289 Worklist.push_back(DAG->getRoot().getNode());
290 Visited.insert(DAG->getRoot().getNode());
292 SmallVector<SUnit*, 8> CallSUnits;
293 while (!Worklist.empty()) {
294 SDNode *NI = Worklist.pop_back_val();
296 // Add all operands to the worklist unless they've already been added.
297 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
298 if (Visited.insert(NI->getOperand(i).getNode()))
299 Worklist.push_back(NI->getOperand(i).getNode());
301 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
304 // If this node has already been processed, stop now.
305 if (NI->getNodeId() != -1) continue;
307 SUnit *NodeSUnit = NewSUnit(NI);
309 // See if anything is glued to this node, if so, add them to glued
310 // nodes. Nodes can have at most one glue input and one glue output. Glue
311 // is required to be the last operand and result of a node.
313 // Scan up to find glued preds.
315 while (N->getNumOperands() &&
316 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
317 N = N->getOperand(N->getNumOperands()-1).getNode();
318 assert(N->getNodeId() == -1 && "Node already inserted!");
319 N->setNodeId(NodeSUnit->NodeNum);
320 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
321 NodeSUnit->isCall = true;
324 // Scan down to find any glued succs.
326 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
327 SDValue GlueVal(N, N->getNumValues()-1);
329 // There are either zero or one users of the Glue result.
330 bool HasGlueUse = false;
331 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
333 if (GlueVal.isOperandOf(*UI)) {
335 assert(N->getNodeId() == -1 && "Node already inserted!");
336 N->setNodeId(NodeSUnit->NodeNum);
338 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
339 NodeSUnit->isCall = true;
342 if (!HasGlueUse) break;
345 if (NodeSUnit->isCall)
346 CallSUnits.push_back(NodeSUnit);
348 // Schedule zero-latency TokenFactor below any nodes that may increase the
349 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
350 // have false stalls.
351 if (NI->getOpcode() == ISD::TokenFactor)
352 NodeSUnit->isScheduleLow = true;
354 // If there are glue operands involved, N is now the bottom-most node
355 // of the sequence of nodes that are glued together.
357 NodeSUnit->setNode(N);
358 assert(N->getNodeId() == -1 && "Node already inserted!");
359 N->setNodeId(NodeSUnit->NodeNum);
361 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
362 InitNumRegDefsLeft(NodeSUnit);
364 // Assign the Latency field of NodeSUnit using target-provided information.
365 ComputeLatency(NodeSUnit);
368 // Find all call operands.
369 while (!CallSUnits.empty()) {
370 SUnit *SU = CallSUnits.pop_back_val();
371 for (const SDNode *SUNode = SU->getNode(); SUNode;
372 SUNode = SUNode->getGluedNode()) {
373 if (SUNode->getOpcode() != ISD::CopyToReg)
375 SDNode *SrcN = SUNode->getOperand(2).getNode();
376 if (isPassiveNode(SrcN)) continue; // Not scheduled.
377 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
378 SrcSU->isCallOp = true;
383 void ScheduleDAGSDNodes::AddSchedEdges() {
384 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
386 // Check to see if the scheduler cares about latencies.
387 bool UnitLatencies = ForceUnitLatencies();
389 // Pass 2: add the preds, succs, etc.
390 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
391 SUnit *SU = &SUnits[su];
392 SDNode *MainNode = SU->getNode();
394 if (MainNode->isMachineOpcode()) {
395 unsigned Opc = MainNode->getMachineOpcode();
396 const MCInstrDesc &MCID = TII->get(Opc);
397 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
398 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
399 SU->isTwoAddress = true;
403 if (MCID.isCommutable())
404 SU->isCommutable = true;
407 // Find all predecessors and successors of the group.
408 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
409 if (N->isMachineOpcode() &&
410 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
411 SU->hasPhysRegClobbers = true;
412 unsigned NumUsed = InstrEmitter::CountResults(N);
413 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
414 --NumUsed; // Skip over unused values at the end.
415 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
416 SU->hasPhysRegDefs = true;
419 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
420 SDNode *OpN = N->getOperand(i).getNode();
421 if (isPassiveNode(OpN)) continue; // Not scheduled.
422 SUnit *OpSU = &SUnits[OpN->getNodeId()];
423 assert(OpSU && "Node has no SUnit!");
424 if (OpSU == SU) continue; // In the same group.
426 EVT OpVT = N->getOperand(i).getValueType();
427 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
428 bool isChain = OpVT == MVT::Other;
430 unsigned PhysReg = 0;
432 // Determine if this is a physical register dependency.
433 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
434 assert((PhysReg == 0 || !isChain) &&
435 "Chain dependence via physreg data?");
436 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
437 // emits a copy from the physical register to a virtual register unless
438 // it requires a cross class copy (cost < 0). That means we are only
439 // treating "expensive to copy" register dependency as physical register
440 // dependency. This may change in the future though.
441 if (Cost >= 0 && !StressSched)
444 // If this is a ctrl dep, latency is 1.
445 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
446 // Special-case TokenFactor chains as zero-latency.
447 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
450 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
452 if (!isChain && !UnitLatencies) {
453 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
454 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
457 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
458 // Multiple register uses are combined in the same SUnit. For example,
459 // we could have a set of glued nodes with all their defs consumed by
460 // another set of glued nodes. Register pressure tracking sees this as
461 // a single use, so to keep pressure balanced we reduce the defs.
463 // We can't tell (without more book-keeping) if this results from
464 // glued nodes or duplicate operands. As long as we don't reduce
465 // NumRegDefsLeft to zero, we handle the common cases well.
466 --OpSU->NumRegDefsLeft;
473 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
474 /// are input. This SUnit graph is similar to the SelectionDAG, but
475 /// excludes nodes that aren't interesting to scheduling, and represents
476 /// glued together nodes with a single SUnit.
477 void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
478 // Cluster certain nodes which should be scheduled together.
480 // Populate the SUnits array.
482 // Compute all the scheduling dependencies between nodes.
486 // Initialize NumNodeDefs for the current Node's opcode.
487 void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
488 // Check for phys reg copy.
492 if (!Node->isMachineOpcode()) {
493 if (Node->getOpcode() == ISD::CopyFromReg)
499 unsigned POpc = Node->getMachineOpcode();
500 if (POpc == TargetOpcode::IMPLICIT_DEF) {
501 // No register need be allocated for this.
505 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
506 // Some instructions define regs that are not represented in the selection DAG
507 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
508 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
512 // Construct a RegDefIter for this SUnit and find the first valid value.
513 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
514 const ScheduleDAGSDNodes *SD)
515 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
520 // Advance to the next valid value defined by the SUnit.
521 void ScheduleDAGSDNodes::RegDefIter::Advance() {
522 for (;Node;) { // Visit all glued nodes.
523 for (;DefIdx < NodeNumDefs; ++DefIdx) {
524 if (!Node->hasAnyUseOfValue(DefIdx))
526 ValueType = Node->getValueType(DefIdx);
528 return; // Found a normal regdef.
530 Node = Node->getGluedNode();
532 return; // No values left to visit.
538 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
539 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
540 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
541 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
542 ++SU->NumRegDefsLeft;
546 void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
547 SDNode *N = SU->getNode();
549 // TokenFactor operands are considered zero latency, and some schedulers
550 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
551 // whenever node latency is nonzero.
552 if (N && N->getOpcode() == ISD::TokenFactor) {
557 // Check to see if the scheduler cares about latencies.
558 if (ForceUnitLatencies()) {
563 if (!InstrItins || InstrItins->isEmpty()) {
564 if (N && N->isMachineOpcode() &&
565 TII->isHighLatencyDef(N->getMachineOpcode()))
566 SU->Latency = HighLatencyCycles;
572 // Compute the latency for the node. We use the sum of the latencies for
573 // all nodes glued together into this SUnit.
575 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
576 if (N->isMachineOpcode())
577 SU->Latency += TII->getInstrLatency(InstrItins, N);
580 void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
581 unsigned OpIdx, SDep& dep) const{
582 // Check to see if the scheduler cares about latencies.
583 if (ForceUnitLatencies())
586 if (dep.getKind() != SDep::Data)
589 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
590 if (Use->isMachineOpcode())
591 // Adjust the use operand index by num of defs.
592 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
593 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
594 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
596 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
597 if (TargetRegisterInfo::isVirtualRegister(Reg))
598 // This copy is a liveout value. It is likely coalesced, so reduce the
599 // latency so not to penalize the def.
600 // FIXME: need target specific adjustment here?
601 Latency = (Latency > 1) ? Latency - 1 : 1;
604 dep.setLatency(Latency);
607 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
608 if (!SU->getNode()) {
609 dbgs() << "PHYS REG COPY\n";
613 SU->getNode()->dump(DAG);
615 SmallVector<SDNode *, 4> GluedNodes;
616 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
617 GluedNodes.push_back(N);
618 while (!GluedNodes.empty()) {
620 GluedNodes.back()->dump(DAG);
622 GluedNodes.pop_back();
626 void ScheduleDAGSDNodes::dumpSchedule() const {
627 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
628 if (SUnit *SU = Sequence[i])
631 dbgs() << "**** NOOP ****\n";
636 /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
637 /// their state is consistent with the nodes listed in Sequence.
639 void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
640 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
642 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
645 assert(Sequence.size() - Noops == ScheduledNodes &&
646 "The number of nodes scheduled doesn't match the expected number!");
652 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
653 const std::pair<unsigned, MachineInstr*> &B) {
654 return A.first < B.first;
659 /// ProcessSDDbgValues - Process SDDbgValues associated with this node.
660 static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
661 InstrEmitter &Emitter,
662 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
663 DenseMap<SDValue, unsigned> &VRBaseMap,
665 if (!N->getHasDebugValue())
668 // Opportunistically insert immediate dbg_value uses, i.e. those with source
669 // order number right after the N.
670 MachineBasicBlock *BB = Emitter.getBlock();
671 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
672 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
673 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
674 if (DVs[i]->isInvalidated())
676 unsigned DVOrder = DVs[i]->getOrder();
677 if (!Order || DVOrder == ++Order) {
678 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
680 Orders.push_back(std::make_pair(DVOrder, DbgMI));
681 BB->insert(InsertPos, DbgMI);
683 DVs[i]->setIsInvalidated();
688 // ProcessSourceNode - Process nodes with source order numbers. These are added
689 // to a vector which EmitSchedule uses to determine how to insert dbg_value
690 // instructions in the right order.
691 static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
692 InstrEmitter &Emitter,
693 DenseMap<SDValue, unsigned> &VRBaseMap,
694 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
695 SmallSet<unsigned, 8> &Seen) {
696 unsigned Order = DAG->GetOrdering(N);
697 if (!Order || !Seen.insert(Order)) {
698 // Process any valid SDDbgValues even if node does not have any order
700 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
704 MachineBasicBlock *BB = Emitter.getBlock();
705 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
706 // Did not insert any instruction.
707 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
711 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
712 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
715 void ScheduleDAGSDNodes::
716 EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
717 MachineBasicBlock::iterator InsertPos) {
718 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
720 if (I->isCtrl()) continue; // ignore chain preds
721 if (I->getSUnit()->CopyDstRC) {
722 // Copy to physical register.
723 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
724 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
725 // Find the destination physical register.
727 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
728 EE = SU->Succs.end(); II != EE; ++II) {
729 if (II->isCtrl()) continue; // ignore chain preds
735 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
736 .addReg(VRI->second);
738 // Copy from physical register.
739 assert(I->getReg() && "Unknown physical register!");
740 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
741 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
742 (void)isNew; // Silence compiler warning.
743 assert(isNew && "Node emitted out of order - early");
744 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
745 .addReg(I->getReg());
751 /// EmitSchedule - Emit the machine code in scheduled order. Return the new
752 /// InsertPos and MachineBasicBlock that contains this insertion
753 /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
754 /// not necessarily refer to returned BB. The emitter may split blocks.
755 MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
756 InstrEmitter Emitter(BB, InsertPos);
757 DenseMap<SDValue, unsigned> VRBaseMap;
758 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
759 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
760 SmallSet<unsigned, 8> Seen;
761 bool HasDbg = DAG->hasDebugValues();
763 // If this is the first BB, emit byval parameter dbg_value's.
764 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
765 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
766 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
767 for (; PDI != PDE; ++PDI) {
768 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
770 BB->insert(InsertPos, DbgMI);
774 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
775 SUnit *SU = Sequence[i];
777 // Null SUnit* is a noop.
778 TII->insertNoop(*Emitter.getBlock(), InsertPos);
782 // For pre-regalloc scheduling, create instructions corresponding to the
783 // SDNode and any glued SDNodes and append them to the block.
784 if (!SU->getNode()) {
786 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
790 SmallVector<SDNode *, 4> GluedNodes;
791 for (SDNode *N = SU->getNode()->getGluedNode(); N;
792 N = N->getGluedNode())
793 GluedNodes.push_back(N);
794 while (!GluedNodes.empty()) {
795 SDNode *N = GluedNodes.back();
796 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
798 // Remember the source order of the inserted instruction.
800 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
801 GluedNodes.pop_back();
803 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
805 // Remember the source order of the inserted instruction.
807 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
811 // Insert all the dbg_values which have not already been inserted in source
814 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
816 // Sort the source order instructions and use the order to insert debug
818 std::sort(Orders.begin(), Orders.end(), OrderSorter());
820 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
821 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
822 // Now emit the rest according to source order.
823 unsigned LastOrder = 0;
824 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
825 unsigned Order = Orders[i].first;
826 MachineInstr *MI = Orders[i].second;
827 // Insert all SDDbgValue's whose order(s) are before "Order".
831 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
832 if ((*DI)->isInvalidated())
834 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
837 // Insert to start of the BB (after PHIs).
838 BB->insert(BBBegin, DbgMI);
840 // Insert at the instruction, which may be in a different
841 // block, if the block was split by a custom inserter.
842 MachineBasicBlock::iterator Pos = MI;
843 MI->getParent()->insert(llvm::next(Pos), DbgMI);
849 // Add trailing DbgValue's before the terminator. FIXME: May want to add
850 // some of them before one or more conditional branches?
852 MachineBasicBlock *InsertBB = Emitter.getBlock();
853 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
854 if (!(*DI)->isInvalidated()) {
855 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
857 InsertBB->insert(Pos, DbgMI);
863 BB = Emitter.getBlock();
864 InsertPos = Emitter.getInsertPos();
868 /// Return the basic block label.
869 std::string ScheduleDAGSDNodes::getDAGName() const {
870 return "sunit-dag." + BB->getFullName();