blob: b22d6edd85af15ff27ad265638cbea98b6869072 [file] [log] [blame]
Dan Gohman60cb69e2008-11-19 23:18:57 +00001//===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the ScheduleDAG class, which is a base class used by
11// scheduling implementation classes.
12//
13//===----------------------------------------------------------------------===//
14
Dan Gohman483377c2009-02-06 17:22:58 +000015#include "ScheduleDAGSDNodes.h"
Dan Gohmanb8120772009-10-10 01:32:21 +000016#include "InstrEmitter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "SDNodeDbgValue.h"
Evan Cheng9d92aaa2010-01-22 03:36:51 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng563fe3c2010-03-25 01:38:16 +000020#include "llvm/ADT/SmallSet.h"
Evan Cheng9d92aaa2010-01-22 03:36:51 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/SelectionDAG.h"
26#include "llvm/MC/MCInstrItineraries.h"
Andrew Trick641e2d42011-03-05 08:00:22 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetRegisterInfo.h"
33#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000034using namespace llvm;
35
Chandler Carruth1b9dde02014-04-22 02:02:50 +000036#define DEBUG_TYPE "pre-RA-sched"
37
Evan Cheng9d92aaa2010-01-22 03:36:51 +000038STATISTIC(LoadsClustered, "Number of loads clustered together");
39
Sanjay Patel25d3c1c2014-10-07 17:38:33 +000040// This allows the latency-based scheduler to notice high latency instructions
Sanjay Pateleb0cc1b2014-10-07 17:36:50 +000041// without a target itinerary. The choice of number here has more to do with
Sanjay Patel25d3c1c2014-10-07 17:38:33 +000042// balancing scheduler heuristics than with the actual machine latency.
Andrew Trick641e2d42011-03-05 08:00:22 +000043static 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"));
47
Dan Gohman619ef482009-01-15 19:20:50 +000048ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
Eric Christopherd9134482014-08-04 21:25:23 +000049 : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
Eric Christopherfc6de422014-08-05 02:39:49 +000050 InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
Dan Gohman60cb69e2008-11-19 23:18:57 +000051
Dan Gohmandfaf6462009-02-11 04:27:20 +000052/// Run - perform scheduling.
53///
Andrew Trick60cf03e2012-03-07 05:21:52 +000054void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
55 BB = bb;
Dan Gohmandfaf6462009-02-11 04:27:20 +000056 DAG = dag;
Andrew Trick60cf03e2012-03-07 05:21:52 +000057
58 // Clear the scheduler's SUnit DAG.
59 ScheduleDAG::clearDAG();
60 Sequence.clear();
61
62 // Invoke the target's selection of scheduler.
63 Schedule();
Dan Gohmandfaf6462009-02-11 04:27:20 +000064}
65
Evan Cheng4401f882010-05-20 23:26:43 +000066/// NewSUnit - Creates a new SUnit and return a ptr to it.
67///
Andrew Trick52226d42012-03-07 23:00:49 +000068SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
Evan Cheng4401f882010-05-20 23:26:43 +000069#ifndef NDEBUG
Craig Topperc0196b12014-04-14 00:51:57 +000070 const SUnit *Addr = nullptr;
Evan Cheng4401f882010-05-20 23:26:43 +000071 if (!SUnits.empty())
72 Addr = &SUnits[0];
73#endif
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000074 SUnits.emplace_back(N, (unsigned)SUnits.size());
Craig Topperc0196b12014-04-14 00:51:57 +000075 assert((Addr == nullptr || Addr == &SUnits[0]) &&
Evan Cheng4401f882010-05-20 23:26:43 +000076 "SUnits std::vector reallocated on the fly!");
77 SUnits.back().OrigNode = &SUnits.back();
78 SUnit *SU = &SUnits.back();
79 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
Evan Cheng23ef8292010-08-10 02:39:45 +000080 if (!N ||
81 (N->isMachineOpcode() &&
82 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
Evan Chengcc2efe12010-05-28 23:26:21 +000083 SU->SchedulingPref = Sched::None;
84 else
85 SU->SchedulingPref = TLI.getSchedulingPreference(N);
Evan Cheng4401f882010-05-20 23:26:43 +000086 return SU;
87}
88
Dan Gohman60cb69e2008-11-19 23:18:57 +000089SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
Andrew Trick52226d42012-03-07 23:00:49 +000090 SUnit *SU = newSUnit(Old->getNode());
Dan Gohman60cb69e2008-11-19 23:18:57 +000091 SU->OrigNode = Old->OrigNode;
92 SU->Latency = Old->Latency;
Andrew Trick2ad0b372011-04-07 19:54:57 +000093 SU->isVRegCycle = Old->isVRegCycle;
Evan Chengdebf9c52010-11-03 00:45:17 +000094 SU->isCall = Old->isCall;
Evan Cheng1355bbd2011-04-26 21:31:35 +000095 SU->isCallOp = Old->isCallOp;
Dan Gohman60cb69e2008-11-19 23:18:57 +000096 SU->isTwoAddress = Old->isTwoAddress;
97 SU->isCommutable = Old->isCommutable;
98 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
Dan Gohman52c278e2009-03-23 16:10:52 +000099 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
Andrew Trickbfbd9722011-04-14 05:15:06 +0000100 SU->isScheduleHigh = Old->isScheduleHigh;
101 SU->isScheduleLow = Old->isScheduleLow;
Evan Cheng4401f882010-05-20 23:26:43 +0000102 SU->SchedulingPref = Old->SchedulingPref;
Evan Cheng968e2e72009-01-16 20:57:18 +0000103 Old->isCloned = true;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000104 return SU;
105}
106
107/// CheckForPhysRegDependency - Check if the dependency between def and use of
108/// a specified operand is a physical register dependency. If so, returns the
Evan Chengb2c42c62009-01-12 03:19:55 +0000109/// register and the cost of copying the register.
Dan Gohman60cb69e2008-11-19 23:18:57 +0000110static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
Andrew Trick3f924e42011-02-03 23:00:17 +0000111 const TargetRegisterInfo *TRI,
Dan Gohman60cb69e2008-11-19 23:18:57 +0000112 const TargetInstrInfo *TII,
Evan Chengb2c42c62009-01-12 03:19:55 +0000113 unsigned &PhysReg, int &Cost) {
Dan Gohman60cb69e2008-11-19 23:18:57 +0000114 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
115 return;
116
117 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
118 if (TargetRegisterInfo::isVirtualRegister(Reg))
119 return;
120
121 unsigned ResNo = User->getOperand(2).getResNo();
Tim Northovere4c7be52014-10-23 22:31:48 +0000122 if (Def->getOpcode() == ISD::CopyFromReg &&
123 cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
124 PhysReg = Reg;
125 } else if (Def->isMachineOpcode()) {
Evan Cheng6cc775f2011-06-28 19:10:37 +0000126 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
Dan Gohman60cb69e2008-11-19 23:18:57 +0000127 if (ResNo >= II.getNumDefs() &&
Tim Northovere4c7be52014-10-23 22:31:48 +0000128 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg)
Dan Gohman60cb69e2008-11-19 23:18:57 +0000129 PhysReg = Reg;
Tim Northovere4c7be52014-10-23 22:31:48 +0000130 }
131
132 if (PhysReg != 0) {
133 const TargetRegisterClass *RC =
Craig Topper7f416c82014-11-16 21:17:18 +0000134 TRI->getMinimalPhysRegClass(Reg, Def->getSimpleValueType(ResNo));
Tim Northovere4c7be52014-10-23 22:31:48 +0000135 Cost = RC->getCopyCost();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000136 }
137}
138
Andrew Trick833f0492012-04-28 01:03:23 +0000139// Helper for AddGlue to clone node operands.
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000140static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG, ArrayRef<EVT> VTs,
Andrew Trick833f0492012-04-28 01:03:23 +0000141 SDValue ExtraOper = SDValue()) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000142 SmallVector<SDValue, 8> Ops(N->op_begin(), N->op_end());
Andrew Trick833f0492012-04-28 01:03:23 +0000143 if (ExtraOper.getNode())
144 Ops.push_back(ExtraOper);
Bill Wendlinga1365212010-06-23 18:16:24 +0000145
Craig Topperabb4ac72014-04-16 06:10:51 +0000146 SDVTList VTList = DAG->getVTList(VTs);
Craig Topperc0196b12014-04-14 00:51:57 +0000147 MachineSDNode::mmo_iterator Begin = nullptr, End = nullptr;
Bill Wendlinga1365212010-06-23 18:16:24 +0000148 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
149
150 // Store memory references.
151 if (MN) {
152 Begin = MN->memoperands_begin();
153 End = MN->memoperands_end();
154 }
155
Craig Topper131de822014-04-27 19:21:16 +0000156 DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
Bill Wendlinga1365212010-06-23 18:16:24 +0000157
158 // Reset the memory references
159 if (MN)
160 MN->setMemRefs(Begin, End);
Evan Cheng9d92aaa2010-01-22 03:36:51 +0000161}
162
Andrew Trick833f0492012-04-28 01:03:23 +0000163static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
Andrew Trick833f0492012-04-28 01:03:23 +0000164 SDNode *GlueDestNode = Glue.getNode();
165
166 // Don't add glue from a node to itself.
167 if (GlueDestNode == N) return false;
168
169 // Don't add a glue operand to something that already uses glue.
170 if (GlueDestNode &&
171 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
172 return false;
173 }
174 // Don't add glue to something that already has a glue value.
175 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
176
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000177 SmallVector<EVT, 4> VTs(N->value_begin(), N->value_end());
Andrew Trick833f0492012-04-28 01:03:23 +0000178 if (AddGlue)
179 VTs.push_back(MVT::Glue);
180
181 CloneNodeWithValues(N, DAG, VTs, Glue);
182
183 return true;
184}
185
186// Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
187// node even though simply shrinking the value list is sufficient.
188static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
189 assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
190 !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
191 "expected an unused glue value");
192
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000193 CloneNodeWithValues(N, DAG,
194 makeArrayRef(N->value_begin(), N->getNumValues() - 1));
Andrew Trick833f0492012-04-28 01:03:23 +0000195}
196
Chris Lattner11a33812010-12-23 17:24:32 +0000197/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
Evan Cheng9d92aaa2010-01-22 03:36:51 +0000198/// This function finds loads of the same base and different offsets. If the
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000199/// offsets are not far apart (target specific), it add MVT::Glue inputs and
Evan Cheng9d92aaa2010-01-22 03:36:51 +0000200/// outputs to ensure they are scheduled together and in order. This
201/// optimization may benefit some targets by improving cache locality.
Evan Cheng38f65602010-06-10 02:09:31 +0000202void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
Craig Topperc0196b12014-04-14 00:51:57 +0000203 SDNode *Chain = nullptr;
Evan Cheng38f65602010-06-10 02:09:31 +0000204 unsigned NumOps = Node->getNumOperands();
205 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
206 Chain = Node->getOperand(NumOps-1).getNode();
207 if (!Chain)
208 return;
209
210 // Look for other loads of the same chain. Find loads that are loading from
211 // the same base pointer and different offsets.
Evan Cheng9d92aaa2010-01-22 03:36:51 +0000212 SmallPtrSet<SDNode*, 16> Visited;
213 SmallVector<int64_t, 4> Offsets;
214 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng38f65602010-06-10 02:09:31 +0000215 bool Cluster = false;
216 SDNode *Base = Node;
Andrew Trick8d007bb2014-04-07 21:29:22 +0000217 // This algorithm requires a reasonably low use count before finding a match
218 // to avoid uselessly blowing up compile time in large blocks.
219 unsigned UseCount = 0;
Evan Cheng38f65602010-06-10 02:09:31 +0000220 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
Andrew Trick8d007bb2014-04-07 21:29:22 +0000221 I != E && UseCount < 100; ++I, ++UseCount) {
Evan Cheng38f65602010-06-10 02:09:31 +0000222 SDNode *User = *I;
David Blaikie70573dc2014-11-19 07:49:26 +0000223 if (User == Node || !Visited.insert(User).second)
Evan Cheng38f65602010-06-10 02:09:31 +0000224 continue;
225 int64_t Offset1, Offset2;
226 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
227 Offset1 == Offset2)
228 // FIXME: Should be ok if they addresses are identical. But earlier
229 // optimizations really should have eliminated one of the loads.
230 continue;
231 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
232 Offsets.push_back(Offset1);
233 O2SMap.insert(std::make_pair(Offset2, User));
234 Offsets.push_back(Offset2);
Duncan Sands2dc70be2010-06-25 14:48:39 +0000235 if (Offset2 < Offset1)
Evan Cheng38f65602010-06-10 02:09:31 +0000236 Base = User;
Evan Cheng38f65602010-06-10 02:09:31 +0000237 Cluster = true;
Andrew Trick8d007bb2014-04-07 21:29:22 +0000238 // Reset UseCount to allow more matches.
239 UseCount = 0;
Evan Cheng38f65602010-06-10 02:09:31 +0000240 }
241
242 if (!Cluster)
243 return;
244
245 // Sort them in increasing order.
246 std::sort(Offsets.begin(), Offsets.end());
247
248 // Check if the loads are close enough.
249 SmallVector<SDNode*, 4> Loads;
250 unsigned NumLoads = 0;
251 int64_t BaseOff = Offsets[0];
252 SDNode *BaseLoad = O2SMap[BaseOff];
253 Loads.push_back(BaseLoad);
254 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
255 int64_t Offset = Offsets[i];
256 SDNode *Load = O2SMap[Offset];
257 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
258 break; // Stop right here. Ignore loads that are further away.
259 Loads.push_back(Load);
260 ++NumLoads;
261 }
262
263 if (NumLoads == 0)
264 return;
265
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000266 // Cluster loads by adding MVT::Glue outputs and inputs. This also
Evan Cheng38f65602010-06-10 02:09:31 +0000267 // ensure they are scheduled in order of increasing addresses.
268 SDNode *Lead = Loads[0];
Craig Topperc0196b12014-04-14 00:51:57 +0000269 SDValue InGlue = SDValue(nullptr, 0);
Andrew Trick833f0492012-04-28 01:03:23 +0000270 if (AddGlue(Lead, InGlue, true, DAG))
271 InGlue = SDValue(Lead, Lead->getNumValues() - 1);
Bill Wendling2d3c4902010-06-24 22:00:37 +0000272 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
Chris Lattner11a33812010-12-23 17:24:32 +0000273 bool OutGlue = I < E - 1;
Bill Wendling2d3c4902010-06-24 22:00:37 +0000274 SDNode *Load = Loads[I];
275
Andrew Trick833f0492012-04-28 01:03:23 +0000276 // If AddGlue fails, we could leave an unsused glue value. This should not
277 // cause any
278 if (AddGlue(Load, InGlue, OutGlue, DAG)) {
279 if (OutGlue)
280 InGlue = SDValue(Load, Load->getNumValues() - 1);
Bill Wendlinga1365212010-06-23 18:16:24 +0000281
Andrew Trick833f0492012-04-28 01:03:23 +0000282 ++LoadsClustered;
283 }
284 else if (!OutGlue && InGlue.getNode())
285 RemoveUnusedGlue(InGlue.getNode(), DAG);
Evan Cheng38f65602010-06-10 02:09:31 +0000286 }
287}
288
289/// ClusterNodes - Cluster certain nodes which should be scheduled together.
290///
291void ScheduleDAGSDNodes::ClusterNodes() {
Evan Cheng9d92aaa2010-01-22 03:36:51 +0000292 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
293 E = DAG->allnodes_end(); NI != E; ++NI) {
294 SDNode *Node = &*NI;
295 if (!Node || !Node->isMachineOpcode())
296 continue;
297
298 unsigned Opc = Node->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +0000299 const MCInstrDesc &MCID = TII->get(Opc);
300 if (MCID.mayLoad())
Evan Cheng38f65602010-06-10 02:09:31 +0000301 // Cluster loads from "near" addresses into combined SUnits.
302 ClusterNeighboringLoads(Node);
Evan Cheng9d92aaa2010-01-22 03:36:51 +0000303 }
304}
305
Dan Gohman60cb69e2008-11-19 23:18:57 +0000306void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohman92cf2802008-12-23 17:24:50 +0000307 // During scheduling, the NodeId field of SDNode is used to map SDNodes
308 // to their associated SUnits by holding SUnits table indices. A value
309 // of -1 means the SDNode does not yet have an associated SUnit.
310 unsigned NumNodes = 0;
311 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
312 E = DAG->allnodes_end(); NI != E; ++NI) {
313 NI->setNodeId(-1);
314 ++NumNodes;
315 }
316
Dan Gohman60cb69e2008-11-19 23:18:57 +0000317 // Reserve entries in the vector for each of the SUnits we are creating. This
318 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
319 // invalidated.
Dan Gohmance70fe22008-12-17 04:30:46 +0000320 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
321 // This is a temporary workaround.
Dan Gohman92cf2802008-12-23 17:24:50 +0000322 SUnits.reserve(NumNodes * 2);
Andrew Trick3f924e42011-02-03 23:00:17 +0000323
Chris Lattnerdf8a8a82010-02-24 06:11:37 +0000324 // Add all nodes in depth first order.
325 SmallVector<SDNode*, 64> Worklist;
326 SmallPtrSet<SDNode*, 64> Visited;
327 Worklist.push_back(DAG->getRoot().getNode());
328 Visited.insert(DAG->getRoot().getNode());
Andrew Trick3f924e42011-02-03 23:00:17 +0000329
Evan Cheng1355bbd2011-04-26 21:31:35 +0000330 SmallVector<SUnit*, 8> CallSUnits;
Chris Lattnerdf8a8a82010-02-24 06:11:37 +0000331 while (!Worklist.empty()) {
332 SDNode *NI = Worklist.pop_back_val();
Andrew Trick3f924e42011-02-03 23:00:17 +0000333
Chris Lattnerdf8a8a82010-02-24 06:11:37 +0000334 // Add all operands to the worklist unless they've already been added.
Pete Cooper9271ccc2015-06-26 19:18:49 +0000335 for (const SDValue &Op : NI->op_values())
336 if (Visited.insert(Op.getNode()).second)
337 Worklist.push_back(Op.getNode());
Andrew Trick3f924e42011-02-03 23:00:17 +0000338
Dan Gohman60cb69e2008-11-19 23:18:57 +0000339 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
340 continue;
Andrew Trick3f924e42011-02-03 23:00:17 +0000341
Dan Gohman60cb69e2008-11-19 23:18:57 +0000342 // If this node has already been processed, stop now.
343 if (NI->getNodeId() != -1) continue;
Andrew Trick3f924e42011-02-03 23:00:17 +0000344
Andrew Trick52226d42012-03-07 23:00:49 +0000345 SUnit *NodeSUnit = newSUnit(NI);
Andrew Trick3f924e42011-02-03 23:00:17 +0000346
Chris Lattner11a33812010-12-23 17:24:32 +0000347 // See if anything is glued to this node, if so, add them to glued
348 // nodes. Nodes can have at most one glue input and one glue output. Glue
349 // is required to be the last operand and result of a node.
Andrew Trick3f924e42011-02-03 23:00:17 +0000350
Chris Lattner11a33812010-12-23 17:24:32 +0000351 // Scan up to find glued preds.
Dan Gohman60cb69e2008-11-19 23:18:57 +0000352 SDNode *N = NI;
Dan Gohman3bdc4bd2009-03-20 20:42:23 +0000353 while (N->getNumOperands() &&
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000354 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
Dan Gohman3bdc4bd2009-03-20 20:42:23 +0000355 N = N->getOperand(N->getNumOperands()-1).getNode();
356 assert(N->getNodeId() == -1 && "Node already inserted!");
357 N->setNodeId(NodeSUnit->NodeNum);
Evan Chengdebf9c52010-11-03 00:45:17 +0000358 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
359 NodeSUnit->isCall = true;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000360 }
Andrew Trick3f924e42011-02-03 23:00:17 +0000361
Chris Lattner11a33812010-12-23 17:24:32 +0000362 // Scan down to find any glued succs.
Dan Gohman60cb69e2008-11-19 23:18:57 +0000363 N = NI;
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000364 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
Chris Lattner11a33812010-12-23 17:24:32 +0000365 SDValue GlueVal(N, N->getNumValues()-1);
Andrew Trick3f924e42011-02-03 23:00:17 +0000366
Chris Lattner11a33812010-12-23 17:24:32 +0000367 // There are either zero or one users of the Glue result.
368 bool HasGlueUse = false;
Andrew Trick3f924e42011-02-03 23:00:17 +0000369 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000370 UI != E; ++UI)
Chris Lattner11a33812010-12-23 17:24:32 +0000371 if (GlueVal.isOperandOf(*UI)) {
372 HasGlueUse = true;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000373 assert(N->getNodeId() == -1 && "Node already inserted!");
374 N->setNodeId(NodeSUnit->NodeNum);
375 N = *UI;
Evan Chengdebf9c52010-11-03 00:45:17 +0000376 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
377 NodeSUnit->isCall = true;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000378 break;
379 }
Chris Lattner11a33812010-12-23 17:24:32 +0000380 if (!HasGlueUse) break;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000381 }
Andrew Trick3f924e42011-02-03 23:00:17 +0000382
Evan Cheng1355bbd2011-04-26 21:31:35 +0000383 if (NodeSUnit->isCall)
384 CallSUnits.push_back(NodeSUnit);
385
Andrew Trickbfbd9722011-04-14 05:15:06 +0000386 // Schedule zero-latency TokenFactor below any nodes that may increase the
387 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
388 // have false stalls.
389 if (NI->getOpcode() == ISD::TokenFactor)
390 NodeSUnit->isScheduleLow = true;
391
Chris Lattner11a33812010-12-23 17:24:32 +0000392 // If there are glue operands involved, N is now the bottom-most node
393 // of the sequence of nodes that are glued together.
Dan Gohman60cb69e2008-11-19 23:18:57 +0000394 // Update the SUnit.
395 NodeSUnit->setNode(N);
396 assert(N->getNodeId() == -1 && "Node already inserted!");
397 N->setNodeId(NodeSUnit->NodeNum);
398
Andrew Trickd0548ae2011-02-04 03:18:17 +0000399 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
400 InitNumRegDefsLeft(NodeSUnit);
401
Dan Gohmand1f33e22008-11-21 01:44:51 +0000402 // Assign the Latency field of NodeSUnit using target-provided information.
Andrew Trick52226d42012-03-07 23:00:49 +0000403 computeLatency(NodeSUnit);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000404 }
Evan Cheng1355bbd2011-04-26 21:31:35 +0000405
406 // Find all call operands.
407 while (!CallSUnits.empty()) {
408 SUnit *SU = CallSUnits.pop_back_val();
409 for (const SDNode *SUNode = SU->getNode(); SUNode;
410 SUNode = SUNode->getGluedNode()) {
411 if (SUNode->getOpcode() != ISD::CopyToReg)
412 continue;
413 SDNode *SrcN = SUNode->getOperand(2).getNode();
414 if (isPassiveNode(SrcN)) continue; // Not scheduled.
415 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
416 SrcSU->isCallOp = true;
417 }
418 }
Dan Gohman04543e72008-12-23 18:36:58 +0000419}
420
421void ScheduleDAGSDNodes::AddSchedEdges() {
Eric Christopheredba30c2014-10-09 06:28:06 +0000422 const TargetSubtargetInfo &ST = MF.getSubtarget();
David Goodwin90e6b8b2009-08-13 16:05:04 +0000423
David Goodwin9b48cd42009-08-19 16:08:58 +0000424 // Check to see if the scheduler cares about latencies.
Andrew Trick52226d42012-03-07 23:00:49 +0000425 bool UnitLatencies = forceUnitLatencies();
David Goodwin9b48cd42009-08-19 16:08:58 +0000426
Dan Gohman60cb69e2008-11-19 23:18:57 +0000427 // Pass 2: add the preds, succs, etc.
428 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
429 SUnit *SU = &SUnits[su];
430 SDNode *MainNode = SU->getNode();
Andrew Trick3f924e42011-02-03 23:00:17 +0000431
Dan Gohman60cb69e2008-11-19 23:18:57 +0000432 if (MainNode->isMachineOpcode()) {
433 unsigned Opc = MainNode->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +0000434 const MCInstrDesc &MCID = TII->get(Opc);
435 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
436 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Dan Gohman60cb69e2008-11-19 23:18:57 +0000437 SU->isTwoAddress = true;
438 break;
439 }
440 }
Evan Cheng6cc775f2011-06-28 19:10:37 +0000441 if (MCID.isCommutable())
Dan Gohman60cb69e2008-11-19 23:18:57 +0000442 SU->isCommutable = true;
443 }
Andrew Trick3f924e42011-02-03 23:00:17 +0000444
Dan Gohman60cb69e2008-11-19 23:18:57 +0000445 // Find all predecessors and successors of the group.
Chris Lattner11a33812010-12-23 17:24:32 +0000446 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
Dan Gohman60cb69e2008-11-19 23:18:57 +0000447 if (N->isMachineOpcode() &&
Dan Gohman52c278e2009-03-23 16:10:52 +0000448 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
449 SU->hasPhysRegClobbers = true;
Dan Gohmanb8120772009-10-10 01:32:21 +0000450 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohmanf4772622009-03-23 17:39:36 +0000451 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
452 --NumUsed; // Skip over unused values at the end.
453 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman52c278e2009-03-23 16:10:52 +0000454 SU->hasPhysRegDefs = true;
455 }
Andrew Trick3f924e42011-02-03 23:00:17 +0000456
Dan Gohman60cb69e2008-11-19 23:18:57 +0000457 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
458 SDNode *OpN = N->getOperand(i).getNode();
459 if (isPassiveNode(OpN)) continue; // Not scheduled.
460 SUnit *OpSU = &SUnits[OpN->getNodeId()];
461 assert(OpSU && "Node has no SUnit!");
462 if (OpSU == SU) continue; // In the same group.
463
Owen Anderson53aa7a92009-08-10 22:56:29 +0000464 EVT OpVT = N->getOperand(i).getValueType();
Chris Lattner11a33812010-12-23 17:24:32 +0000465 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
Owen Anderson9f944592009-08-11 20:47:22 +0000466 bool isChain = OpVT == MVT::Other;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000467
468 unsigned PhysReg = 0;
Evan Chengb2c42c62009-01-12 03:19:55 +0000469 int Cost = 1;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000470 // Determine if this is a physical register dependency.
Evan Chengb2c42c62009-01-12 03:19:55 +0000471 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman2d170892008-12-09 22:54:47 +0000472 assert((PhysReg == 0 || !isChain) &&
473 "Chain dependence via physreg data?");
Evan Chengb2c42c62009-01-12 03:19:55 +0000474 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
475 // emits a copy from the physical register to a virtual register unless
476 // it requires a cross class copy (cost < 0). That means we are only
477 // treating "expensive to copy" register dependency as physical register
478 // dependency. This may change in the future though.
Andrew Trick3013b6a2011-06-15 17:16:12 +0000479 if (Cost >= 0 && !StressSched)
Evan Chengb2c42c62009-01-12 03:19:55 +0000480 PhysReg = 0;
David Goodwin90e6b8b2009-08-13 16:05:04 +0000481
Evan Chengcc2efe12010-05-28 23:26:21 +0000482 // If this is a ctrl dep, latency is 1.
Andrew Trick1b60ad62011-04-12 20:14:07 +0000483 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
Andrew Trickb53a00d2011-04-13 00:38:32 +0000484 // Special-case TokenFactor chains as zero-latency.
485 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
486 OpLatency = 0;
487
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000488 SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
489 : SDep(OpSU, SDep::Data, PhysReg);
490 Dep.setLatency(OpLatency);
David Goodwin9b48cd42009-08-19 16:08:58 +0000491 if (!isChain && !UnitLatencies) {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000492 computeOperandLatency(OpN, N, i, Dep);
493 ST.adjustSchedDependency(OpSU, SU, Dep);
David Goodwin9b48cd42009-08-19 16:08:58 +0000494 }
David Goodwin90e6b8b2009-08-13 16:05:04 +0000495
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000496 if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
Andrew Trickd0548ae2011-02-04 03:18:17 +0000497 // Multiple register uses are combined in the same SUnit. For example,
498 // we could have a set of glued nodes with all their defs consumed by
499 // another set of glued nodes. Register pressure tracking sees this as
500 // a single use, so to keep pressure balanced we reduce the defs.
Andrew Trick072ed2e2011-03-09 19:12:43 +0000501 //
502 // We can't tell (without more book-keeping) if this results from
503 // glued nodes or duplicate operands. As long as we don't reduce
504 // NumRegDefsLeft to zero, we handle the common cases well.
Andrew Trickd0548ae2011-02-04 03:18:17 +0000505 --OpSU->NumRegDefsLeft;
506 }
Dan Gohman60cb69e2008-11-19 23:18:57 +0000507 }
508 }
509 }
510}
511
Dan Gohman04543e72008-12-23 18:36:58 +0000512/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
513/// are input. This SUnit graph is similar to the SelectionDAG, but
514/// excludes nodes that aren't interesting to scheduling, and represents
Chris Lattner11a33812010-12-23 17:24:32 +0000515/// glued together nodes with a single SUnit.
Dan Gohman918ec532009-10-09 23:33:48 +0000516void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng38f65602010-06-10 02:09:31 +0000517 // Cluster certain nodes which should be scheduled together.
518 ClusterNodes();
Dan Gohman04543e72008-12-23 18:36:58 +0000519 // Populate the SUnits array.
520 BuildSchedUnits();
521 // Compute all the scheduling dependencies between nodes.
522 AddSchedEdges();
523}
524
Andrew Trickd0548ae2011-02-04 03:18:17 +0000525// Initialize NumNodeDefs for the current Node's opcode.
526void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
Eric Christopher7238cba2011-03-08 19:35:47 +0000527 // Check for phys reg copy.
528 if (!Node)
529 return;
530
Andrew Trickd0548ae2011-02-04 03:18:17 +0000531 if (!Node->isMachineOpcode()) {
532 if (Node->getOpcode() == ISD::CopyFromReg)
533 NodeNumDefs = 1;
534 else
535 NodeNumDefs = 0;
536 return;
537 }
538 unsigned POpc = Node->getMachineOpcode();
539 if (POpc == TargetOpcode::IMPLICIT_DEF) {
540 // No register need be allocated for this.
541 NodeNumDefs = 0;
542 return;
543 }
Hal Finkel665026832015-01-14 01:07:03 +0000544 if (POpc == TargetOpcode::PATCHPOINT &&
545 Node->getValueType(0) == MVT::Other) {
546 // PATCHPOINT is defined to have one result, but it might really have none
547 // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
548 // real definition.
549 NodeNumDefs = 0;
550 return;
551 }
Andrew Trickd0548ae2011-02-04 03:18:17 +0000552 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
553 // Some instructions define regs that are not represented in the selection DAG
554 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
555 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
556 DefIdx = 0;
557}
558
559// Construct a RegDefIter for this SUnit and find the first valid value.
560ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
561 const ScheduleDAGSDNodes *SD)
562 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
563 InitNodeNumDefs();
564 Advance();
565}
566
567// Advance to the next valid value defined by the SUnit.
568void ScheduleDAGSDNodes::RegDefIter::Advance() {
569 for (;Node;) { // Visit all glued nodes.
570 for (;DefIdx < NodeNumDefs; ++DefIdx) {
571 if (!Node->hasAnyUseOfValue(DefIdx))
572 continue;
Patrik Hagglund05394352012-12-13 18:45:35 +0000573 ValueType = Node->getSimpleValueType(DefIdx);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000574 ++DefIdx;
575 return; // Found a normal regdef.
576 }
577 Node = Node->getGluedNode();
Craig Topperc0196b12014-04-14 00:51:57 +0000578 if (!Node) {
Andrew Trickd0548ae2011-02-04 03:18:17 +0000579 return; // No values left to visit.
580 }
581 InitNodeNumDefs();
582 }
583}
584
585void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
586 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
587 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
588 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
589 ++SU->NumRegDefsLeft;
590 }
591}
592
Andrew Trick52226d42012-03-07 23:00:49 +0000593void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
Andrew Trickb53a00d2011-04-13 00:38:32 +0000594 SDNode *N = SU->getNode();
595
596 // TokenFactor operands are considered zero latency, and some schedulers
597 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
598 // whenever node latency is nonzero.
599 if (N && N->getOpcode() == ISD::TokenFactor) {
600 SU->Latency = 0;
601 return;
602 }
603
Evan Cheng70e506e2010-05-19 22:42:23 +0000604 // Check to see if the scheduler cares about latencies.
Andrew Trick52226d42012-03-07 23:00:49 +0000605 if (forceUnitLatencies()) {
Evan Cheng70e506e2010-05-19 22:42:23 +0000606 SU->Latency = 1;
607 return;
608 }
609
Evan Chengbf407072010-09-10 01:29:16 +0000610 if (!InstrItins || InstrItins->isEmpty()) {
Andrew Trickd7f4c212011-03-05 09:18:16 +0000611 if (N && N->isMachineOpcode() &&
612 TII->isHighLatencyDef(N->getMachineOpcode()))
Andrew Trick641e2d42011-03-05 08:00:22 +0000613 SU->Latency = HighLatencyCycles;
614 else
615 SU->Latency = 1;
Evan Chengbdd062d2010-05-20 06:13:19 +0000616 return;
617 }
Andrew Trick3f924e42011-02-03 23:00:17 +0000618
Dan Gohman60cb69e2008-11-19 23:18:57 +0000619 // Compute the latency for the node. We use the sum of the latencies for
Chris Lattner11a33812010-12-23 17:24:32 +0000620 // all nodes glued together into this SUnit.
Dan Gohman60cb69e2008-11-19 23:18:57 +0000621 SU->Latency = 0;
Chris Lattner11a33812010-12-23 17:24:32 +0000622 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
Evan Chengdebf9c52010-11-03 00:45:17 +0000623 if (N->isMachineOpcode())
624 SU->Latency += TII->getInstrLatency(InstrItins, N);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000625}
626
Andrew Trick52226d42012-03-07 23:00:49 +0000627void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
Evan Chengbdd062d2010-05-20 06:13:19 +0000628 unsigned OpIdx, SDep& dep) const{
629 // Check to see if the scheduler cares about latencies.
Andrew Trick52226d42012-03-07 23:00:49 +0000630 if (forceUnitLatencies())
Evan Chengbdd062d2010-05-20 06:13:19 +0000631 return;
632
Evan Chengbdd062d2010-05-20 06:13:19 +0000633 if (dep.getKind() != SDep::Data)
634 return;
635
636 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Chengff310732010-10-28 06:47:08 +0000637 if (Use->isMachineOpcode())
638 // Adjust the use operand index by num of defs.
639 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
Evan Cheng49d4c0b2010-10-06 06:27:31 +0000640 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
Evan Cheng6c1414f2010-10-29 18:09:28 +0000641 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
642 !BB->succ_empty()) {
643 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
644 if (TargetRegisterInfo::isVirtualRegister(Reg))
645 // This copy is a liveout value. It is likely coalesced, so reduce the
646 // latency so not to penalize the def.
647 // FIXME: need target specific adjustment here?
648 Latency = (Latency > 1) ? Latency - 1 : 1;
649 }
Evan Cheng4a010fd2010-09-29 22:42:35 +0000650 if (Latency >= 0)
651 dep.setLatency(Latency);
Evan Chengbdd062d2010-05-20 06:13:19 +0000652}
653
Dan Gohman60cb69e2008-11-19 23:18:57 +0000654void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Manman Ren19f49ac2012-09-11 22:23:19 +0000655#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Chengb2c42c62009-01-12 03:19:55 +0000656 if (!SU->getNode()) {
David Greene4eb5bed2010-01-05 01:25:11 +0000657 dbgs() << "PHYS REG COPY\n";
Evan Chengb2c42c62009-01-12 03:19:55 +0000658 return;
659 }
660
661 SU->getNode()->dump(DAG);
David Greene4eb5bed2010-01-05 01:25:11 +0000662 dbgs() << "\n";
Chris Lattner11a33812010-12-23 17:24:32 +0000663 SmallVector<SDNode *, 4> GluedNodes;
664 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
665 GluedNodes.push_back(N);
666 while (!GluedNodes.empty()) {
David Greene4eb5bed2010-01-05 01:25:11 +0000667 dbgs() << " ";
Chris Lattner11a33812010-12-23 17:24:32 +0000668 GluedNodes.back()->dump(DAG);
David Greene4eb5bed2010-01-05 01:25:11 +0000669 dbgs() << "\n";
Chris Lattner11a33812010-12-23 17:24:32 +0000670 GluedNodes.pop_back();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000671 }
Manman Ren742534c2012-09-06 19:06:06 +0000672#endif
Dan Gohman60cb69e2008-11-19 23:18:57 +0000673}
Dan Gohmanb8120772009-10-10 01:32:21 +0000674
Manman Ren19f49ac2012-09-11 22:23:19 +0000675#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickedee68c2012-03-07 05:21:40 +0000676void ScheduleDAGSDNodes::dumpSchedule() const {
677 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
678 if (SUnit *SU = Sequence[i])
679 SU->dump(this);
680 else
681 dbgs() << "**** NOOP ****\n";
682 }
683}
Manman Ren742534c2012-09-06 19:06:06 +0000684#endif
Andrew Trickedee68c2012-03-07 05:21:40 +0000685
Andrew Trick46a58662012-03-07 05:21:36 +0000686#ifndef NDEBUG
687/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
688/// their state is consistent with the nodes listed in Sequence.
689///
690void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
691 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
692 unsigned Noops = 0;
693 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
694 if (!Sequence[i])
695 ++Noops;
696 assert(Sequence.size() - Noops == ScheduledNodes &&
697 "The number of nodes scheduled doesn't match the expected number!");
698}
699#endif // NDEBUG
700
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000701/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
Craig Topperb94011f2013-07-14 04:42:23 +0000702static void
703ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
704 SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
705 DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
Devang Patel1448e7c2011-01-26 18:20:04 +0000706 if (!N->getHasDebugValue())
707 return;
708
709 // Opportunistically insert immediate dbg_value uses, i.e. those with source
710 // order number right after the N.
711 MachineBasicBlock *BB = Emitter.getBlock();
712 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
Benjamin Kramere1fc29b2011-06-18 13:13:44 +0000713 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
Devang Patel1448e7c2011-01-26 18:20:04 +0000714 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
715 if (DVs[i]->isInvalidated())
716 continue;
717 unsigned DVOrder = DVs[i]->getOrder();
718 if (!Order || DVOrder == ++Order) {
719 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
720 if (DbgMI) {
721 Orders.push_back(std::make_pair(DVOrder, DbgMI));
722 BB->insert(InsertPos, DbgMI);
723 }
724 DVs[i]->setIsInvalidated();
725 }
726 }
727}
728
Evan Cheng563fe3c2010-03-25 01:38:16 +0000729// ProcessSourceNode - Process nodes with source order numbers. These are added
Jim Grosbachcaf9b3a2010-06-30 21:27:56 +0000730// to a vector which EmitSchedule uses to determine how to insert dbg_value
Evan Cheng563fe3c2010-03-25 01:38:16 +0000731// instructions in the right order.
Craig Topperb94011f2013-07-14 04:42:23 +0000732static void
733ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
734 DenseMap<SDValue, unsigned> &VRBaseMap,
735 SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
736 SmallSet<unsigned, 8> &Seen) {
Andrew Tricke2431c62013-05-25 03:08:10 +0000737 unsigned Order = N->getIROrder();
David Blaikie70573dc2014-11-19 07:49:26 +0000738 if (!Order || !Seen.insert(Order).second) {
Devang Patel92b70772011-01-27 00:13:27 +0000739 // Process any valid SDDbgValues even if node does not have any order
740 // assigned.
741 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
Evan Cheng563fe3c2010-03-25 01:38:16 +0000742 return;
Devang Patel92b70772011-01-27 00:13:27 +0000743 }
Evan Cheng563fe3c2010-03-25 01:38:16 +0000744
745 MachineBasicBlock *BB = Emitter.getBlock();
Bill Schmidt3684fdd2013-10-18 14:20:11 +0000746 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI() ||
747 // Fast-isel may have inserted some instructions, in which case the
748 // BB->back().isPHI() test will not fire when we want it to.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000749 std::prev(Emitter.getInsertPos())->isPHI()) {
Evan Cheng563fe3c2010-03-25 01:38:16 +0000750 // Did not insert any instruction.
Craig Topperc0196b12014-04-14 00:51:57 +0000751 Orders.push_back(std::make_pair(Order, (MachineInstr*)nullptr));
Evan Cheng563fe3c2010-03-25 01:38:16 +0000752 return;
753 }
754
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000755 Orders.push_back(std::make_pair(Order, std::prev(Emitter.getInsertPos())));
Devang Patel1448e7c2011-01-26 18:20:04 +0000756 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
Evan Cheng563fe3c2010-03-25 01:38:16 +0000757}
758
Andrew Tricke932bb72012-03-07 05:21:44 +0000759void ScheduleDAGSDNodes::
760EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
761 MachineBasicBlock::iterator InsertPos) {
762 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
763 I != E; ++I) {
764 if (I->isCtrl()) continue; // ignore chain preds
765 if (I->getSUnit()->CopyDstRC) {
766 // Copy to physical register.
767 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
768 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
769 // Find the destination physical register.
770 unsigned Reg = 0;
771 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
772 EE = SU->Succs.end(); II != EE; ++II) {
773 if (II->isCtrl()) continue; // ignore chain preds
774 if (II->getReg()) {
775 Reg = II->getReg();
776 break;
777 }
778 }
779 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
780 .addReg(VRI->second);
781 } else {
782 // Copy from physical register.
783 assert(I->getReg() && "Unknown physical register!");
784 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
785 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
786 (void)isNew; // Silence compiler warning.
787 assert(isNew && "Node emitted out of order - early");
788 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
789 .addReg(I->getReg());
790 }
791 break;
792 }
793}
Evan Cheng563fe3c2010-03-25 01:38:16 +0000794
Andrew Tricke932bb72012-03-07 05:21:44 +0000795/// EmitSchedule - Emit the machine code in scheduled order. Return the new
796/// InsertPos and MachineBasicBlock that contains this insertion
797/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
798/// not necessarily refer to returned BB. The emitter may split blocks.
Andrew Trick60cf03e2012-03-07 05:21:52 +0000799MachineBasicBlock *ScheduleDAGSDNodes::
800EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
Dan Gohmanb8120772009-10-10 01:32:21 +0000801 InstrEmitter Emitter(BB, InsertPos);
802 DenseMap<SDValue, unsigned> VRBaseMap;
803 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Cheng563fe3c2010-03-25 01:38:16 +0000804 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
805 SmallSet<unsigned, 8> Seen;
806 bool HasDbg = DAG->hasDebugValues();
Dale Johannesen49de0602010-03-10 22:13:47 +0000807
Dale Johannesene0983522010-04-26 20:06:49 +0000808 // If this is the first BB, emit byval parameter dbg_value's.
809 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
810 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
811 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
812 for (; PDI != PDE; ++PDI) {
Dan Gohman8acc8f72010-04-30 19:35:33 +0000813 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesene0983522010-04-26 20:06:49 +0000814 if (DbgMI)
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000815 BB->insert(InsertPos, DbgMI);
Dale Johannesene0983522010-04-26 20:06:49 +0000816 }
817 }
818
Dan Gohmanb8120772009-10-10 01:32:21 +0000819 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
820 SUnit *SU = Sequence[i];
821 if (!SU) {
822 // Null SUnit* is a noop.
Andrew Tricke932bb72012-03-07 05:21:44 +0000823 TII->insertNoop(*Emitter.getBlock(), InsertPos);
Dan Gohmanb8120772009-10-10 01:32:21 +0000824 continue;
825 }
826
827 // For pre-regalloc scheduling, create instructions corresponding to the
Chris Lattner11a33812010-12-23 17:24:32 +0000828 // SDNode and any glued SDNodes and append them to the block.
Dan Gohmanb8120772009-10-10 01:32:21 +0000829 if (!SU->getNode()) {
830 // Emit a copy.
Andrew Tricke932bb72012-03-07 05:21:44 +0000831 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
Dan Gohmanb8120772009-10-10 01:32:21 +0000832 continue;
833 }
834
Chris Lattner11a33812010-12-23 17:24:32 +0000835 SmallVector<SDNode *, 4> GluedNodes;
Evan Cheng839fb652012-10-17 19:39:36 +0000836 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
Chris Lattner11a33812010-12-23 17:24:32 +0000837 GluedNodes.push_back(N);
838 while (!GluedNodes.empty()) {
839 SDNode *N = GluedNodes.back();
840 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohman25c16532010-05-01 00:01:06 +0000841 VRBaseMap);
Dale Johannesene0983522010-04-26 20:06:49 +0000842 // Remember the source order of the inserted instruction.
Evan Cheng563fe3c2010-03-25 01:38:16 +0000843 if (HasDbg)
Dan Gohman8acc8f72010-04-30 19:35:33 +0000844 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Chris Lattner11a33812010-12-23 17:24:32 +0000845 GluedNodes.pop_back();
Dan Gohmanb8120772009-10-10 01:32:21 +0000846 }
847 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohman25c16532010-05-01 00:01:06 +0000848 VRBaseMap);
Dale Johannesene0983522010-04-26 20:06:49 +0000849 // Remember the source order of the inserted instruction.
Evan Cheng563fe3c2010-03-25 01:38:16 +0000850 if (HasDbg)
Dan Gohman8acc8f72010-04-30 19:35:33 +0000851 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Cheng563fe3c2010-03-25 01:38:16 +0000852 Seen);
853 }
854
Dale Johannesene0983522010-04-26 20:06:49 +0000855 // Insert all the dbg_values which have not already been inserted in source
Evan Cheng563fe3c2010-03-25 01:38:16 +0000856 // order sequence.
857 if (HasDbg) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000858 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
Evan Cheng563fe3c2010-03-25 01:38:16 +0000859
860 // Sort the source order instructions and use the order to insert debug
861 // values.
Benjamin Kramerb12cf012013-08-24 12:54:27 +0000862 std::sort(Orders.begin(), Orders.end(), less_first());
Evan Cheng563fe3c2010-03-25 01:38:16 +0000863
864 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
865 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
866 // Now emit the rest according to source order.
867 unsigned LastOrder = 0;
Evan Cheng563fe3c2010-03-25 01:38:16 +0000868 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
869 unsigned Order = Orders[i].first;
870 MachineInstr *MI = Orders[i].second;
871 // Insert all SDDbgValue's whose order(s) are before "Order".
872 if (!MI)
873 continue;
Evan Cheng563fe3c2010-03-25 01:38:16 +0000874 for (; DI != DE &&
875 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
876 if ((*DI)->isInvalidated())
877 continue;
Dan Gohman8acc8f72010-04-30 19:35:33 +0000878 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Chenged69b382010-04-26 07:38:55 +0000879 if (DbgMI) {
880 if (!LastOrder)
881 // Insert to start of the BB (after PHIs).
882 BB->insert(BBBegin, DbgMI);
883 else {
Dan Gohmana64a3232010-07-10 22:42:31 +0000884 // Insert at the instruction, which may be in a different
885 // block, if the block was split by a custom inserter.
Evan Chenged69b382010-04-26 07:38:55 +0000886 MachineBasicBlock::iterator Pos = MI;
Andrew Trickc66d26a2013-05-26 08:58:50 +0000887 MI->getParent()->insert(Pos, DbgMI);
Evan Chenged69b382010-04-26 07:38:55 +0000888 }
Evan Cheng563fe3c2010-03-25 01:38:16 +0000889 }
Dale Johannesen49de0602010-03-10 22:13:47 +0000890 }
Evan Cheng563fe3c2010-03-25 01:38:16 +0000891 LastOrder = Order;
Evan Cheng563fe3c2010-03-25 01:38:16 +0000892 }
893 // Add trailing DbgValue's before the terminator. FIXME: May want to add
894 // some of them before one or more conditional branches?
Bill Wendling618d5732012-03-14 07:14:25 +0000895 SmallVector<MachineInstr*, 8> DbgMIs;
Evan Cheng563fe3c2010-03-25 01:38:16 +0000896 while (DI != DE) {
Bill Wendling618d5732012-03-14 07:14:25 +0000897 if (!(*DI)->isInvalidated())
898 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
899 DbgMIs.push_back(DbgMI);
Evan Cheng563fe3c2010-03-25 01:38:16 +0000900 ++DI;
901 }
Bill Wendling618d5732012-03-14 07:14:25 +0000902
903 MachineBasicBlock *InsertBB = Emitter.getBlock();
904 MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
905 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
Dan Gohmanb8120772009-10-10 01:32:21 +0000906 }
907
Dan Gohmanb8120772009-10-10 01:32:21 +0000908 InsertPos = Emitter.getInsertPos();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000909 return Emitter.getBlock();
Dan Gohmanb8120772009-10-10 01:32:21 +0000910}
Andrew Trick1b2324d2012-03-07 00:18:22 +0000911
912/// Return the basic block label.
913std::string ScheduleDAGSDNodes::getDAGName() const {
914 return "sunit-dag." + BB->getFullName();
915}