ScheduleDAGSDNodes.cpp revision 276479
1130561Sobrien//===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
2130561Sobrien//
3130561Sobrien//                     The LLVM Compiler Infrastructure
4130561Sobrien//
5130561Sobrien// This file is distributed under the University of Illinois Open Source
6130561Sobrien// License. See LICENSE.TXT for details.
7130561Sobrien//
8130561Sobrien//===----------------------------------------------------------------------===//
9130561Sobrien//
10130561Sobrien// This implements the ScheduleDAG class, which is a base class used by
11130561Sobrien// scheduling implementation classes.
12130561Sobrien//
13130561Sobrien//===----------------------------------------------------------------------===//
14130561Sobrien
15130561Sobrien#include "ScheduleDAGSDNodes.h"
16130561Sobrien#include "InstrEmitter.h"
17130561Sobrien#include "SDNodeDbgValue.h"
18218822Sdim#include "llvm/ADT/DenseMap.h"
19130561Sobrien#include "llvm/ADT/SmallPtrSet.h"
20130561Sobrien#include "llvm/ADT/SmallSet.h"
21130561Sobrien#include "llvm/ADT/SmallVector.h"
22130561Sobrien#include "llvm/ADT/Statistic.h"
23130561Sobrien#include "llvm/CodeGen/MachineInstrBuilder.h"
24130561Sobrien#include "llvm/CodeGen/MachineRegisterInfo.h"
25130561Sobrien#include "llvm/CodeGen/SelectionDAG.h"
26130561Sobrien#include "llvm/MC/MCInstrItineraries.h"
27130561Sobrien#include "llvm/Support/CommandLine.h"
28130561Sobrien#include "llvm/Support/Debug.h"
29130561Sobrien#include "llvm/Support/raw_ostream.h"
30130561Sobrien#include "llvm/Target/TargetInstrInfo.h"
31130561Sobrien#include "llvm/Target/TargetLowering.h"
32130561Sobrien#include "llvm/Target/TargetMachine.h"
33130561Sobrien#include "llvm/Target/TargetRegisterInfo.h"
34130561Sobrien#include "llvm/Target/TargetSubtargetInfo.h"
35130561Sobrienusing namespace llvm;
36130561Sobrien
37130561Sobrien#define DEBUG_TYPE "pre-RA-sched"
38130561Sobrien
39130561SobrienSTATISTIC(LoadsClustered, "Number of loads clustered together");
40130561Sobrien
41130561Sobrien// This allows latency based scheduler to notice high latency instructions
42130561Sobrien// without a target itinerary. The choise if number here has more to do with
43130561Sobrien// balancing scheduler heursitics than with the actual machine latency.
44130561Sobrienstatic cl::opt<int> HighLatencyCycles(
45130561Sobrien  "sched-high-latency-cycles", cl::Hidden, cl::init(10),
46130561Sobrien  cl::desc("Roughly estimate the number of cycles that 'long latency'"
47130561Sobrien           "instructions take for targets with no itinerary"));
48130561Sobrien
49130561SobrienScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
50130561Sobrien  : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
51130561Sobrien    InstrItins(mf.getTarget().getInstrItineraryData()) {}
52130561Sobrien
53130561Sobrien/// Run - perform scheduling.
54130561Sobrien///
55130561Sobrienvoid ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
56130561Sobrien  BB = bb;
57130561Sobrien  DAG = dag;
58130561Sobrien
59130561Sobrien  // Clear the scheduler's SUnit DAG.
60130561Sobrien  ScheduleDAG::clearDAG();
61130561Sobrien  Sequence.clear();
62130561Sobrien
63130561Sobrien  // Invoke the target's selection of scheduler.
64130561Sobrien  Schedule();
65130561Sobrien}
66130561Sobrien
67130561Sobrien/// NewSUnit - Creates a new SUnit and return a ptr to it.
68130561Sobrien///
69130561SobrienSUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
70130561Sobrien#ifndef NDEBUG
71130561Sobrien  const SUnit *Addr = nullptr;
72130561Sobrien  if (!SUnits.empty())
73130561Sobrien    Addr = &SUnits[0];
74130561Sobrien#endif
75130561Sobrien  SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
76130561Sobrien  assert((Addr == nullptr || Addr == &SUnits[0]) &&
77130561Sobrien         "SUnits std::vector reallocated on the fly!");
78130561Sobrien  SUnits.back().OrigNode = &SUnits.back();
79130561Sobrien  SUnit *SU = &SUnits.back();
80130561Sobrien  const TargetLowering &TLI = DAG->getTargetLoweringInfo();
81130561Sobrien  if (!N ||
82130561Sobrien      (N->isMachineOpcode() &&
83130561Sobrien       N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
84130561Sobrien    SU->SchedulingPref = Sched::None;
85130561Sobrien  else
86130561Sobrien    SU->SchedulingPref = TLI.getSchedulingPreference(N);
87130561Sobrien  return SU;
88130561Sobrien}
89130561Sobrien
90130561SobrienSUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
91130561Sobrien  SUnit *SU = newSUnit(Old->getNode());
92130561Sobrien  SU->OrigNode = Old->OrigNode;
93130561Sobrien  SU->Latency = Old->Latency;
94130561Sobrien  SU->isVRegCycle = Old->isVRegCycle;
95130561Sobrien  SU->isCall = Old->isCall;
96130561Sobrien  SU->isCallOp = Old->isCallOp;
97130561Sobrien  SU->isTwoAddress = Old->isTwoAddress;
98130561Sobrien  SU->isCommutable = Old->isCommutable;
99130561Sobrien  SU->hasPhysRegDefs = Old->hasPhysRegDefs;
100130561Sobrien  SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
101130561Sobrien  SU->isScheduleHigh = Old->isScheduleHigh;
102130561Sobrien  SU->isScheduleLow = Old->isScheduleLow;
103130561Sobrien  SU->SchedulingPref = Old->SchedulingPref;
104130561Sobrien  Old->isCloned = true;
105130561Sobrien  return SU;
106130561Sobrien}
107130561Sobrien
108130561Sobrien/// CheckForPhysRegDependency - Check if the dependency between def and use of
109130561Sobrien/// a specified operand is a physical register dependency. If so, returns the
110130561Sobrien/// register and the cost of copying the register.
111130561Sobrienstatic void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
112130561Sobrien                                      const TargetRegisterInfo *TRI,
113130561Sobrien                                      const TargetInstrInfo *TII,
114130561Sobrien                                      unsigned &PhysReg, int &Cost) {
115130561Sobrien  if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
116130561Sobrien    return;
117130561Sobrien
118130561Sobrien  unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
119130561Sobrien  if (TargetRegisterInfo::isVirtualRegister(Reg))
120130561Sobrien    return;
121130561Sobrien
122130561Sobrien  unsigned ResNo = User->getOperand(2).getResNo();
123130561Sobrien  if (Def->isMachineOpcode()) {
124130561Sobrien    const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
125130561Sobrien    if (ResNo >= II.getNumDefs() &&
126130561Sobrien        II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
127130561Sobrien      PhysReg = Reg;
128130561Sobrien      const TargetRegisterClass *RC =
129130561Sobrien        TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
130130561Sobrien      Cost = RC->getCopyCost();
131130561Sobrien    }
132130561Sobrien  }
133130561Sobrien}
134130561Sobrien
135130561Sobrien// Helper for AddGlue to clone node operands.
136130561Sobrienstatic void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG,
137130561Sobrien                                SmallVectorImpl<EVT> &VTs,
138130561Sobrien                                SDValue ExtraOper = SDValue()) {
139130561Sobrien  SmallVector<SDValue, 4> Ops;
140130561Sobrien  for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
141130561Sobrien    Ops.push_back(N->getOperand(I));
142130561Sobrien
143130561Sobrien  if (ExtraOper.getNode())
144130561Sobrien    Ops.push_back(ExtraOper);
145130561Sobrien
146130561Sobrien  SDVTList VTList = DAG->getVTList(VTs);
147130561Sobrien  MachineSDNode::mmo_iterator Begin = nullptr, End = nullptr;
148130561Sobrien  MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
149130561Sobrien
150130561Sobrien  // Store memory references.
151130561Sobrien  if (MN) {
152130561Sobrien    Begin = MN->memoperands_begin();
153130561Sobrien    End = MN->memoperands_end();
154130561Sobrien  }
155130561Sobrien
156130561Sobrien  DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
157130561Sobrien
158130561Sobrien  // Reset the memory references
159130561Sobrien  if (MN)
160130561Sobrien    MN->setMemRefs(Begin, End);
161130561Sobrien}
162130561Sobrien
163130561Sobrienstatic bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
164130561Sobrien  SmallVector<EVT, 4> VTs;
165130561Sobrien  SDNode *GlueDestNode = Glue.getNode();
166130561Sobrien
167130561Sobrien  // Don't add glue from a node to itself.
168130561Sobrien  if (GlueDestNode == N) return false;
169130561Sobrien
170130561Sobrien  // Don't add a glue operand to something that already uses glue.
171130561Sobrien  if (GlueDestNode &&
172130561Sobrien      N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
173130561Sobrien    return false;
174130561Sobrien  }
175130561Sobrien  // Don't add glue to something that already has a glue value.
176130561Sobrien  if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
177130561Sobrien
178130561Sobrien  for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
179130561Sobrien    VTs.push_back(N->getValueType(I));
180130561Sobrien
181130561Sobrien  if (AddGlue)
182130561Sobrien    VTs.push_back(MVT::Glue);
183130561Sobrien
184130561Sobrien  CloneNodeWithValues(N, DAG, VTs, Glue);
185130561Sobrien
186130561Sobrien  return true;
187130561Sobrien}
188130561Sobrien
189130561Sobrien// Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
190130561Sobrien// node even though simply shrinking the value list is sufficient.
191130561Sobrienstatic void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
192130561Sobrien  assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
193130561Sobrien          !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
194130561Sobrien         "expected an unused glue value");
195130561Sobrien
196130561Sobrien  SmallVector<EVT, 4> VTs;
197130561Sobrien  for (unsigned I = 0, E = N->getNumValues()-1; I != E; ++I)
198130561Sobrien    VTs.push_back(N->getValueType(I));
199130561Sobrien
200130561Sobrien  CloneNodeWithValues(N, DAG, VTs);
201130561Sobrien}
202130561Sobrien
203130561Sobrien/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
204130561Sobrien/// This function finds loads of the same base and different offsets. If the
205130561Sobrien/// offsets are not far apart (target specific), it add MVT::Glue inputs and
206130561Sobrien/// outputs to ensure they are scheduled together and in order. This
207130561Sobrien/// optimization may benefit some targets by improving cache locality.
208130561Sobrienvoid ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
209130561Sobrien  SDNode *Chain = nullptr;
210130561Sobrien  unsigned NumOps = Node->getNumOperands();
211130561Sobrien  if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
212130561Sobrien    Chain = Node->getOperand(NumOps-1).getNode();
213130561Sobrien  if (!Chain)
214130561Sobrien    return;
215130561Sobrien
216130561Sobrien  // Look for other loads of the same chain. Find loads that are loading from
217130561Sobrien  // the same base pointer and different offsets.
218130561Sobrien  SmallPtrSet<SDNode*, 16> Visited;
219130561Sobrien  SmallVector<int64_t, 4> Offsets;
220130561Sobrien  DenseMap<long long, SDNode*> O2SMap;  // Map from offset to SDNode.
221130561Sobrien  bool Cluster = false;
222130561Sobrien  SDNode *Base = Node;
223130561Sobrien  // This algorithm requires a reasonably low use count before finding a match
224130561Sobrien  // to avoid uselessly blowing up compile time in large blocks.
225130561Sobrien  unsigned UseCount = 0;
226130561Sobrien  for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
227130561Sobrien       I != E && UseCount < 100; ++I, ++UseCount) {
228130561Sobrien    SDNode *User = *I;
229130561Sobrien    if (User == Node || !Visited.insert(User))
230130561Sobrien      continue;
231130561Sobrien    int64_t Offset1, Offset2;
232130561Sobrien    if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
233130561Sobrien        Offset1 == Offset2)
234130561Sobrien      // FIXME: Should be ok if they addresses are identical. But earlier
235130561Sobrien      // optimizations really should have eliminated one of the loads.
236130561Sobrien      continue;
237130561Sobrien    if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
238130561Sobrien      Offsets.push_back(Offset1);
239130561Sobrien    O2SMap.insert(std::make_pair(Offset2, User));
240130561Sobrien    Offsets.push_back(Offset2);
241130561Sobrien    if (Offset2 < Offset1)
242130561Sobrien      Base = User;
243130561Sobrien    Cluster = true;
244130561Sobrien    // Reset UseCount to allow more matches.
245130561Sobrien    UseCount = 0;
246130561Sobrien  }
247130561Sobrien
248130561Sobrien  if (!Cluster)
249130561Sobrien    return;
250130561Sobrien
251130561Sobrien  // Sort them in increasing order.
252130561Sobrien  std::sort(Offsets.begin(), Offsets.end());
253130561Sobrien
254130561Sobrien  // Check if the loads are close enough.
255130561Sobrien  SmallVector<SDNode*, 4> Loads;
256130561Sobrien  unsigned NumLoads = 0;
257130561Sobrien  int64_t BaseOff = Offsets[0];
258130561Sobrien  SDNode *BaseLoad = O2SMap[BaseOff];
259130561Sobrien  Loads.push_back(BaseLoad);
260130561Sobrien  for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
261130561Sobrien    int64_t Offset = Offsets[i];
262130561Sobrien    SDNode *Load = O2SMap[Offset];
263130561Sobrien    if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
264130561Sobrien      break; // Stop right here. Ignore loads that are further away.
265130561Sobrien    Loads.push_back(Load);
266130561Sobrien    ++NumLoads;
267130561Sobrien  }
268130561Sobrien
269130561Sobrien  if (NumLoads == 0)
270130561Sobrien    return;
271130561Sobrien
272130561Sobrien  // Cluster loads by adding MVT::Glue outputs and inputs. This also
273130561Sobrien  // ensure they are scheduled in order of increasing addresses.
274130561Sobrien  SDNode *Lead = Loads[0];
275130561Sobrien  SDValue InGlue = SDValue(nullptr, 0);
276130561Sobrien  if (AddGlue(Lead, InGlue, true, DAG))
277130561Sobrien    InGlue = SDValue(Lead, Lead->getNumValues() - 1);
278130561Sobrien  for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
279130561Sobrien    bool OutGlue = I < E - 1;
280130561Sobrien    SDNode *Load = Loads[I];
281130561Sobrien
282130561Sobrien    // If AddGlue fails, we could leave an unsused glue value. This should not
283130561Sobrien    // cause any
284130561Sobrien    if (AddGlue(Load, InGlue, OutGlue, DAG)) {
285130561Sobrien      if (OutGlue)
286130561Sobrien        InGlue = SDValue(Load, Load->getNumValues() - 1);
287130561Sobrien
288130561Sobrien      ++LoadsClustered;
289130561Sobrien    }
290130561Sobrien    else if (!OutGlue && InGlue.getNode())
291130561Sobrien      RemoveUnusedGlue(InGlue.getNode(), DAG);
292130561Sobrien  }
293130561Sobrien}
294130561Sobrien
295130561Sobrien/// ClusterNodes - Cluster certain nodes which should be scheduled together.
296130561Sobrien///
297130561Sobrienvoid ScheduleDAGSDNodes::ClusterNodes() {
298130561Sobrien  for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
299130561Sobrien       E = DAG->allnodes_end(); NI != E; ++NI) {
300130561Sobrien    SDNode *Node = &*NI;
301130561Sobrien    if (!Node || !Node->isMachineOpcode())
302130561Sobrien      continue;
303130561Sobrien
304130561Sobrien    unsigned Opc = Node->getMachineOpcode();
305130561Sobrien    const MCInstrDesc &MCID = TII->get(Opc);
306130561Sobrien    if (MCID.mayLoad())
307130561Sobrien      // Cluster loads from "near" addresses into combined SUnits.
308130561Sobrien      ClusterNeighboringLoads(Node);
309130561Sobrien  }
310130561Sobrien}
311130561Sobrien
312130561Sobrienvoid ScheduleDAGSDNodes::BuildSchedUnits() {
313130561Sobrien  // During scheduling, the NodeId field of SDNode is used to map SDNodes
314130561Sobrien  // to their associated SUnits by holding SUnits table indices. A value
315130561Sobrien  // of -1 means the SDNode does not yet have an associated SUnit.
316130561Sobrien  unsigned NumNodes = 0;
317130561Sobrien  for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
318130561Sobrien       E = DAG->allnodes_end(); NI != E; ++NI) {
319130561Sobrien    NI->setNodeId(-1);
320130561Sobrien    ++NumNodes;
321130561Sobrien  }
322130561Sobrien
323130561Sobrien  // Reserve entries in the vector for each of the SUnits we are creating.  This
324130561Sobrien  // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
325130561Sobrien  // invalidated.
326130561Sobrien  // FIXME: Multiply by 2 because we may clone nodes during scheduling.
327130561Sobrien  // This is a temporary workaround.
328130561Sobrien  SUnits.reserve(NumNodes * 2);
329130561Sobrien
330130561Sobrien  // Add all nodes in depth first order.
331130561Sobrien  SmallVector<SDNode*, 64> Worklist;
332130561Sobrien  SmallPtrSet<SDNode*, 64> Visited;
333130561Sobrien  Worklist.push_back(DAG->getRoot().getNode());
334130561Sobrien  Visited.insert(DAG->getRoot().getNode());
335130561Sobrien
336130561Sobrien  SmallVector<SUnit*, 8> CallSUnits;
337130561Sobrien  while (!Worklist.empty()) {
338130561Sobrien    SDNode *NI = Worklist.pop_back_val();
339130561Sobrien
340130561Sobrien    // Add all operands to the worklist unless they've already been added.
341130561Sobrien    for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
342130561Sobrien      if (Visited.insert(NI->getOperand(i).getNode()))
343130561Sobrien        Worklist.push_back(NI->getOperand(i).getNode());
344130561Sobrien
345130561Sobrien    if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
346130561Sobrien      continue;
347130561Sobrien
348130561Sobrien    // If this node has already been processed, stop now.
349130561Sobrien    if (NI->getNodeId() != -1) continue;
350130561Sobrien
351130561Sobrien    SUnit *NodeSUnit = newSUnit(NI);
352130561Sobrien
353130561Sobrien    // See if anything is glued to this node, if so, add them to glued
354130561Sobrien    // nodes.  Nodes can have at most one glue input and one glue output.  Glue
355130561Sobrien    // is required to be the last operand and result of a node.
356130561Sobrien
357130561Sobrien    // Scan up to find glued preds.
358130561Sobrien    SDNode *N = NI;
359130561Sobrien    while (N->getNumOperands() &&
360130561Sobrien           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
361130561Sobrien      N = N->getOperand(N->getNumOperands()-1).getNode();
362130561Sobrien      assert(N->getNodeId() == -1 && "Node already inserted!");
363130561Sobrien      N->setNodeId(NodeSUnit->NodeNum);
364130561Sobrien      if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
365130561Sobrien        NodeSUnit->isCall = true;
366130561Sobrien    }
367130561Sobrien
368130561Sobrien    // Scan down to find any glued succs.
369130561Sobrien    N = NI;
370130561Sobrien    while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
371130561Sobrien      SDValue GlueVal(N, N->getNumValues()-1);
372130561Sobrien
373130561Sobrien      // There are either zero or one users of the Glue result.
374130561Sobrien      bool HasGlueUse = false;
375130561Sobrien      for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
376130561Sobrien           UI != E; ++UI)
377130561Sobrien        if (GlueVal.isOperandOf(*UI)) {
378130561Sobrien          HasGlueUse = true;
379130561Sobrien          assert(N->getNodeId() == -1 && "Node already inserted!");
380130561Sobrien          N->setNodeId(NodeSUnit->NodeNum);
381130561Sobrien          N = *UI;
382130561Sobrien          if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
383130561Sobrien            NodeSUnit->isCall = true;
384130561Sobrien          break;
385130561Sobrien        }
386130561Sobrien      if (!HasGlueUse) break;
387130561Sobrien    }
388130561Sobrien
389130561Sobrien    if (NodeSUnit->isCall)
390130561Sobrien      CallSUnits.push_back(NodeSUnit);
391130561Sobrien
392130561Sobrien    // Schedule zero-latency TokenFactor below any nodes that may increase the
393130561Sobrien    // schedule height. Otherwise, ancestors of the TokenFactor may appear to
394130561Sobrien    // have false stalls.
395130561Sobrien    if (NI->getOpcode() == ISD::TokenFactor)
396130561Sobrien      NodeSUnit->isScheduleLow = true;
397130561Sobrien
398130561Sobrien    // If there are glue operands involved, N is now the bottom-most node
399130561Sobrien    // of the sequence of nodes that are glued together.
400130561Sobrien    // Update the SUnit.
401130561Sobrien    NodeSUnit->setNode(N);
402130561Sobrien    assert(N->getNodeId() == -1 && "Node already inserted!");
403130561Sobrien    N->setNodeId(NodeSUnit->NodeNum);
404130561Sobrien
405130561Sobrien    // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
406130561Sobrien    InitNumRegDefsLeft(NodeSUnit);
407130561Sobrien
408130561Sobrien    // Assign the Latency field of NodeSUnit using target-provided information.
409130561Sobrien    computeLatency(NodeSUnit);
410130561Sobrien  }
411130561Sobrien
412130561Sobrien  // Find all call operands.
413130561Sobrien  while (!CallSUnits.empty()) {
414130561Sobrien    SUnit *SU = CallSUnits.pop_back_val();
415130561Sobrien    for (const SDNode *SUNode = SU->getNode(); SUNode;
416130561Sobrien         SUNode = SUNode->getGluedNode()) {
417130561Sobrien      if (SUNode->getOpcode() != ISD::CopyToReg)
418130561Sobrien        continue;
419130561Sobrien      SDNode *SrcN = SUNode->getOperand(2).getNode();
420130561Sobrien      if (isPassiveNode(SrcN)) continue;   // Not scheduled.
421130561Sobrien      SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
422130561Sobrien      SrcSU->isCallOp = true;
423    }
424  }
425}
426
427void ScheduleDAGSDNodes::AddSchedEdges() {
428  const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
429
430  // Check to see if the scheduler cares about latencies.
431  bool UnitLatencies = forceUnitLatencies();
432
433  // Pass 2: add the preds, succs, etc.
434  for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
435    SUnit *SU = &SUnits[su];
436    SDNode *MainNode = SU->getNode();
437
438    if (MainNode->isMachineOpcode()) {
439      unsigned Opc = MainNode->getMachineOpcode();
440      const MCInstrDesc &MCID = TII->get(Opc);
441      for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
442        if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
443          SU->isTwoAddress = true;
444          break;
445        }
446      }
447      if (MCID.isCommutable())
448        SU->isCommutable = true;
449    }
450
451    // Find all predecessors and successors of the group.
452    for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
453      if (N->isMachineOpcode() &&
454          TII->get(N->getMachineOpcode()).getImplicitDefs()) {
455        SU->hasPhysRegClobbers = true;
456        unsigned NumUsed = InstrEmitter::CountResults(N);
457        while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
458          --NumUsed;    // Skip over unused values at the end.
459        if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
460          SU->hasPhysRegDefs = true;
461      }
462
463      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
464        SDNode *OpN = N->getOperand(i).getNode();
465        if (isPassiveNode(OpN)) continue;   // Not scheduled.
466        SUnit *OpSU = &SUnits[OpN->getNodeId()];
467        assert(OpSU && "Node has no SUnit!");
468        if (OpSU == SU) continue;           // In the same group.
469
470        EVT OpVT = N->getOperand(i).getValueType();
471        assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
472        bool isChain = OpVT == MVT::Other;
473
474        unsigned PhysReg = 0;
475        int Cost = 1;
476        // Determine if this is a physical register dependency.
477        CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
478        assert((PhysReg == 0 || !isChain) &&
479               "Chain dependence via physreg data?");
480        // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
481        // emits a copy from the physical register to a virtual register unless
482        // it requires a cross class copy (cost < 0). That means we are only
483        // treating "expensive to copy" register dependency as physical register
484        // dependency. This may change in the future though.
485        if (Cost >= 0 && !StressSched)
486          PhysReg = 0;
487
488        // If this is a ctrl dep, latency is 1.
489        unsigned OpLatency = isChain ? 1 : OpSU->Latency;
490        // Special-case TokenFactor chains as zero-latency.
491        if(isChain && OpN->getOpcode() == ISD::TokenFactor)
492          OpLatency = 0;
493
494        SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
495          : SDep(OpSU, SDep::Data, PhysReg);
496        Dep.setLatency(OpLatency);
497        if (!isChain && !UnitLatencies) {
498          computeOperandLatency(OpN, N, i, Dep);
499          ST.adjustSchedDependency(OpSU, SU, Dep);
500        }
501
502        if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
503          // Multiple register uses are combined in the same SUnit. For example,
504          // we could have a set of glued nodes with all their defs consumed by
505          // another set of glued nodes. Register pressure tracking sees this as
506          // a single use, so to keep pressure balanced we reduce the defs.
507          //
508          // We can't tell (without more book-keeping) if this results from
509          // glued nodes or duplicate operands. As long as we don't reduce
510          // NumRegDefsLeft to zero, we handle the common cases well.
511          --OpSU->NumRegDefsLeft;
512        }
513      }
514    }
515  }
516}
517
518/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
519/// are input.  This SUnit graph is similar to the SelectionDAG, but
520/// excludes nodes that aren't interesting to scheduling, and represents
521/// glued together nodes with a single SUnit.
522void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
523  // Cluster certain nodes which should be scheduled together.
524  ClusterNodes();
525  // Populate the SUnits array.
526  BuildSchedUnits();
527  // Compute all the scheduling dependencies between nodes.
528  AddSchedEdges();
529}
530
531// Initialize NumNodeDefs for the current Node's opcode.
532void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
533  // Check for phys reg copy.
534  if (!Node)
535    return;
536
537  if (!Node->isMachineOpcode()) {
538    if (Node->getOpcode() == ISD::CopyFromReg)
539      NodeNumDefs = 1;
540    else
541      NodeNumDefs = 0;
542    return;
543  }
544  unsigned POpc = Node->getMachineOpcode();
545  if (POpc == TargetOpcode::IMPLICIT_DEF) {
546    // No register need be allocated for this.
547    NodeNumDefs = 0;
548    return;
549  }
550  unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
551  // Some instructions define regs that are not represented in the selection DAG
552  // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
553  NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
554  DefIdx = 0;
555}
556
557// Construct a RegDefIter for this SUnit and find the first valid value.
558ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
559                                           const ScheduleDAGSDNodes *SD)
560  : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
561  InitNodeNumDefs();
562  Advance();
563}
564
565// Advance to the next valid value defined by the SUnit.
566void ScheduleDAGSDNodes::RegDefIter::Advance() {
567  for (;Node;) { // Visit all glued nodes.
568    for (;DefIdx < NodeNumDefs; ++DefIdx) {
569      if (!Node->hasAnyUseOfValue(DefIdx))
570        continue;
571      ValueType = Node->getSimpleValueType(DefIdx);
572      ++DefIdx;
573      return; // Found a normal regdef.
574    }
575    Node = Node->getGluedNode();
576    if (!Node) {
577      return; // No values left to visit.
578    }
579    InitNodeNumDefs();
580  }
581}
582
583void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
584  assert(SU->NumRegDefsLeft == 0 && "expect a new node");
585  for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
586    assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
587    ++SU->NumRegDefsLeft;
588  }
589}
590
591void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
592  SDNode *N = SU->getNode();
593
594  // TokenFactor operands are considered zero latency, and some schedulers
595  // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
596  // whenever node latency is nonzero.
597  if (N && N->getOpcode() == ISD::TokenFactor) {
598    SU->Latency = 0;
599    return;
600  }
601
602  // Check to see if the scheduler cares about latencies.
603  if (forceUnitLatencies()) {
604    SU->Latency = 1;
605    return;
606  }
607
608  if (!InstrItins || InstrItins->isEmpty()) {
609    if (N && N->isMachineOpcode() &&
610        TII->isHighLatencyDef(N->getMachineOpcode()))
611      SU->Latency = HighLatencyCycles;
612    else
613      SU->Latency = 1;
614    return;
615  }
616
617  // Compute the latency for the node.  We use the sum of the latencies for
618  // all nodes glued together into this SUnit.
619  SU->Latency = 0;
620  for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
621    if (N->isMachineOpcode())
622      SU->Latency += TII->getInstrLatency(InstrItins, N);
623}
624
625void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
626                                               unsigned OpIdx, SDep& dep) const{
627  // Check to see if the scheduler cares about latencies.
628  if (forceUnitLatencies())
629    return;
630
631  if (dep.getKind() != SDep::Data)
632    return;
633
634  unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
635  if (Use->isMachineOpcode())
636    // Adjust the use operand index by num of defs.
637    OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
638  int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
639  if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
640      !BB->succ_empty()) {
641    unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
642    if (TargetRegisterInfo::isVirtualRegister(Reg))
643      // This copy is a liveout value. It is likely coalesced, so reduce the
644      // latency so not to penalize the def.
645      // FIXME: need target specific adjustment here?
646      Latency = (Latency > 1) ? Latency - 1 : 1;
647  }
648  if (Latency >= 0)
649    dep.setLatency(Latency);
650}
651
652void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
653#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
654  if (!SU->getNode()) {
655    dbgs() << "PHYS REG COPY\n";
656    return;
657  }
658
659  SU->getNode()->dump(DAG);
660  dbgs() << "\n";
661  SmallVector<SDNode *, 4> GluedNodes;
662  for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
663    GluedNodes.push_back(N);
664  while (!GluedNodes.empty()) {
665    dbgs() << "    ";
666    GluedNodes.back()->dump(DAG);
667    dbgs() << "\n";
668    GluedNodes.pop_back();
669  }
670#endif
671}
672
673#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
674void ScheduleDAGSDNodes::dumpSchedule() const {
675  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
676    if (SUnit *SU = Sequence[i])
677      SU->dump(this);
678    else
679      dbgs() << "**** NOOP ****\n";
680  }
681}
682#endif
683
684#ifndef NDEBUG
685/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
686/// their state is consistent with the nodes listed in Sequence.
687///
688void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
689  unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
690  unsigned Noops = 0;
691  for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
692    if (!Sequence[i])
693      ++Noops;
694  assert(Sequence.size() - Noops == ScheduledNodes &&
695         "The number of nodes scheduled doesn't match the expected number!");
696}
697#endif // NDEBUG
698
699/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
700static void
701ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
702                   SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
703                   DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
704  if (!N->getHasDebugValue())
705    return;
706
707  // Opportunistically insert immediate dbg_value uses, i.e. those with source
708  // order number right after the N.
709  MachineBasicBlock *BB = Emitter.getBlock();
710  MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
711  ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
712  for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
713    if (DVs[i]->isInvalidated())
714      continue;
715    unsigned DVOrder = DVs[i]->getOrder();
716    if (!Order || DVOrder == ++Order) {
717      MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
718      if (DbgMI) {
719        Orders.push_back(std::make_pair(DVOrder, DbgMI));
720        BB->insert(InsertPos, DbgMI);
721      }
722      DVs[i]->setIsInvalidated();
723    }
724  }
725}
726
727// ProcessSourceNode - Process nodes with source order numbers. These are added
728// to a vector which EmitSchedule uses to determine how to insert dbg_value
729// instructions in the right order.
730static void
731ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
732                  DenseMap<SDValue, unsigned> &VRBaseMap,
733                  SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
734                  SmallSet<unsigned, 8> &Seen) {
735  unsigned Order = N->getIROrder();
736  if (!Order || !Seen.insert(Order)) {
737    // Process any valid SDDbgValues even if node does not have any order
738    // assigned.
739    ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
740    return;
741  }
742
743  MachineBasicBlock *BB = Emitter.getBlock();
744  if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI() ||
745      // Fast-isel may have inserted some instructions, in which case the
746      // BB->back().isPHI() test will not fire when we want it to.
747      std::prev(Emitter.getInsertPos())->isPHI()) {
748    // Did not insert any instruction.
749    Orders.push_back(std::make_pair(Order, (MachineInstr*)nullptr));
750    return;
751  }
752
753  Orders.push_back(std::make_pair(Order, std::prev(Emitter.getInsertPos())));
754  ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
755}
756
757void ScheduleDAGSDNodes::
758EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
759                MachineBasicBlock::iterator InsertPos) {
760  for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
761       I != E; ++I) {
762    if (I->isCtrl()) continue;  // ignore chain preds
763    if (I->getSUnit()->CopyDstRC) {
764      // Copy to physical register.
765      DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
766      assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
767      // Find the destination physical register.
768      unsigned Reg = 0;
769      for (SUnit::const_succ_iterator II = SU->Succs.begin(),
770             EE = SU->Succs.end(); II != EE; ++II) {
771        if (II->isCtrl()) continue;  // ignore chain preds
772        if (II->getReg()) {
773          Reg = II->getReg();
774          break;
775        }
776      }
777      BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
778        .addReg(VRI->second);
779    } else {
780      // Copy from physical register.
781      assert(I->getReg() && "Unknown physical register!");
782      unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
783      bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
784      (void)isNew; // Silence compiler warning.
785      assert(isNew && "Node emitted out of order - early");
786      BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
787        .addReg(I->getReg());
788    }
789    break;
790  }
791}
792
793/// EmitSchedule - Emit the machine code in scheduled order. Return the new
794/// InsertPos and MachineBasicBlock that contains this insertion
795/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
796/// not necessarily refer to returned BB. The emitter may split blocks.
797MachineBasicBlock *ScheduleDAGSDNodes::
798EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
799  InstrEmitter Emitter(BB, InsertPos);
800  DenseMap<SDValue, unsigned> VRBaseMap;
801  DenseMap<SUnit*, unsigned> CopyVRBaseMap;
802  SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
803  SmallSet<unsigned, 8> Seen;
804  bool HasDbg = DAG->hasDebugValues();
805
806  // If this is the first BB, emit byval parameter dbg_value's.
807  if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
808    SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
809    SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
810    for (; PDI != PDE; ++PDI) {
811      MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
812      if (DbgMI)
813        BB->insert(InsertPos, DbgMI);
814    }
815  }
816
817  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
818    SUnit *SU = Sequence[i];
819    if (!SU) {
820      // Null SUnit* is a noop.
821      TII->insertNoop(*Emitter.getBlock(), InsertPos);
822      continue;
823    }
824
825    // For pre-regalloc scheduling, create instructions corresponding to the
826    // SDNode and any glued SDNodes and append them to the block.
827    if (!SU->getNode()) {
828      // Emit a copy.
829      EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
830      continue;
831    }
832
833    SmallVector<SDNode *, 4> GluedNodes;
834    for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
835      GluedNodes.push_back(N);
836    while (!GluedNodes.empty()) {
837      SDNode *N = GluedNodes.back();
838      Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
839                       VRBaseMap);
840      // Remember the source order of the inserted instruction.
841      if (HasDbg)
842        ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
843      GluedNodes.pop_back();
844    }
845    Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
846                     VRBaseMap);
847    // Remember the source order of the inserted instruction.
848    if (HasDbg)
849      ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
850                        Seen);
851  }
852
853  // Insert all the dbg_values which have not already been inserted in source
854  // order sequence.
855  if (HasDbg) {
856    MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
857
858    // Sort the source order instructions and use the order to insert debug
859    // values.
860    std::sort(Orders.begin(), Orders.end(), less_first());
861
862    SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
863    SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
864    // Now emit the rest according to source order.
865    unsigned LastOrder = 0;
866    for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
867      unsigned Order = Orders[i].first;
868      MachineInstr *MI = Orders[i].second;
869      // Insert all SDDbgValue's whose order(s) are before "Order".
870      if (!MI)
871        continue;
872      for (; DI != DE &&
873             (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
874        if ((*DI)->isInvalidated())
875          continue;
876        MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
877        if (DbgMI) {
878          if (!LastOrder)
879            // Insert to start of the BB (after PHIs).
880            BB->insert(BBBegin, DbgMI);
881          else {
882            // Insert at the instruction, which may be in a different
883            // block, if the block was split by a custom inserter.
884            MachineBasicBlock::iterator Pos = MI;
885            MI->getParent()->insert(Pos, DbgMI);
886          }
887        }
888      }
889      LastOrder = Order;
890    }
891    // Add trailing DbgValue's before the terminator. FIXME: May want to add
892    // some of them before one or more conditional branches?
893    SmallVector<MachineInstr*, 8> DbgMIs;
894    while (DI != DE) {
895      if (!(*DI)->isInvalidated())
896        if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
897          DbgMIs.push_back(DbgMI);
898      ++DI;
899    }
900
901    MachineBasicBlock *InsertBB = Emitter.getBlock();
902    MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
903    InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
904  }
905
906  InsertPos = Emitter.getInsertPos();
907  return Emitter.getBlock();
908}
909
910/// Return the basic block label.
911std::string ScheduleDAGSDNodes::getDAGName() const {
912  return "sunit-dag." + BB->getFullName();
913}
914