blob: ebc76e9b36321f19f8d3a53b8d8df33c1c1cc155 [file] [log] [blame]
Dan Gohman343f0c02008-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
15#define DEBUG_TYPE "pre-RA-sched"
Evan Chenga8efe282010-03-14 19:56:39 +000016#include "SDNodeDbgValue.h"
Dan Gohman84fbac52009-02-06 17:22:58 +000017#include "ScheduleDAGSDNodes.h"
Dan Gohmanbcea8592009-10-10 01:32:21 +000018#include "InstrEmitter.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000019#include "llvm/CodeGen/SelectionDAG.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng1cc39842010-05-20 23:26:43 +000022#include "llvm/Target/TargetLowering.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000023#include "llvm/Target/TargetRegisterInfo.h"
David Goodwin71046162009-08-13 16:05:04 +000024#include "llvm/Target/TargetSubtarget.h"
Evan Chengc589e032010-01-22 03:36:51 +000025#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/SmallPtrSet.h"
Evan Chengbfcb3052010-03-25 01:38:16 +000027#include "llvm/ADT/SmallSet.h"
Evan Chengc589e032010-01-22 03:36:51 +000028#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/Statistic.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000030#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32using namespace llvm;
33
Evan Chengc589e032010-01-22 03:36:51 +000034STATISTIC(LoadsClustered, "Number of loads clustered together");
35
Dan Gohman79ce2762009-01-15 19:20:50 +000036ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
37 : ScheduleDAG(mf) {
Dan Gohman343f0c02008-11-19 23:18:57 +000038}
39
Dan Gohman47ac0f02009-02-11 04:27:20 +000040/// Run - perform scheduling.
41///
42void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
43 MachineBasicBlock::iterator insertPos) {
44 DAG = dag;
45 ScheduleDAG::Run(bb, insertPos);
46}
47
Evan Cheng1cc39842010-05-20 23:26:43 +000048/// NewSUnit - Creates a new SUnit and return a ptr to it.
49///
50SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) {
51#ifndef NDEBUG
52 const SUnit *Addr = 0;
53 if (!SUnits.empty())
54 Addr = &SUnits[0];
55#endif
56 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
57 assert((Addr == 0 || Addr == &SUnits[0]) &&
58 "SUnits std::vector reallocated on the fly!");
59 SUnits.back().OrigNode = &SUnits.back();
60 SUnit *SU = &SUnits.back();
61 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
Evan Cheng046fa3f2010-05-28 23:26:21 +000062 if (N->isMachineOpcode() &&
63 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF)
64 SU->SchedulingPref = Sched::None;
65 else
66 SU->SchedulingPref = TLI.getSchedulingPreference(N);
Evan Cheng1cc39842010-05-20 23:26:43 +000067 return SU;
68}
69
Dan Gohman343f0c02008-11-19 23:18:57 +000070SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
71 SUnit *SU = NewSUnit(Old->getNode());
72 SU->OrigNode = Old->OrigNode;
73 SU->Latency = Old->Latency;
74 SU->isTwoAddress = Old->isTwoAddress;
75 SU->isCommutable = Old->isCommutable;
76 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
Dan Gohman39746672009-03-23 16:10:52 +000077 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
Evan Cheng1cc39842010-05-20 23:26:43 +000078 SU->SchedulingPref = Old->SchedulingPref;
Evan Chenge57187c2009-01-16 20:57:18 +000079 Old->isCloned = true;
Dan Gohman343f0c02008-11-19 23:18:57 +000080 return SU;
81}
82
83/// CheckForPhysRegDependency - Check if the dependency between def and use of
84/// a specified operand is a physical register dependency. If so, returns the
Evan Chengc29a56d2009-01-12 03:19:55 +000085/// register and the cost of copying the register.
Dan Gohman343f0c02008-11-19 23:18:57 +000086static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
87 const TargetRegisterInfo *TRI,
88 const TargetInstrInfo *TII,
Evan Chengc29a56d2009-01-12 03:19:55 +000089 unsigned &PhysReg, int &Cost) {
Dan Gohman343f0c02008-11-19 23:18:57 +000090 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
91 return;
92
93 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
94 if (TargetRegisterInfo::isVirtualRegister(Reg))
95 return;
96
97 unsigned ResNo = User->getOperand(2).getResNo();
98 if (Def->isMachineOpcode()) {
99 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
100 if (ResNo >= II.getNumDefs() &&
Evan Chengc29a56d2009-01-12 03:19:55 +0000101 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000102 PhysReg = Reg;
Evan Chengc29a56d2009-01-12 03:19:55 +0000103 const TargetRegisterClass *RC =
Rafael Espindolad31f9722010-06-29 14:02:34 +0000104 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
Evan Chengc29a56d2009-01-12 03:19:55 +0000105 Cost = RC->getCopyCost();
106 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000107 }
108}
109
Evan Chengc589e032010-01-22 03:36:51 +0000110static void AddFlags(SDNode *N, SDValue Flag, bool AddFlag,
111 SelectionDAG *DAG) {
112 SmallVector<EVT, 4> VTs;
Bill Wendling10707f32010-06-24 22:00:37 +0000113 SDNode *FlagDestNode = Flag.getNode();
Bill Wendling151d26d2010-06-23 18:16:24 +0000114
Bill Wendling10707f32010-06-24 22:00:37 +0000115 // Don't add a flag from a node to itself.
116 if (FlagDestNode == N) return;
117
118 // Don't add a flag to something which already has a flag.
119 if (N->getValueType(N->getNumValues() - 1) == MVT::Flag) return;
120
121 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
122 VTs.push_back(N->getValueType(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000123
Evan Chengc589e032010-01-22 03:36:51 +0000124 if (AddFlag)
125 VTs.push_back(MVT::Flag);
Bill Wendling151d26d2010-06-23 18:16:24 +0000126
Evan Chengc589e032010-01-22 03:36:51 +0000127 SmallVector<SDValue, 4> Ops;
Bill Wendling10707f32010-06-24 22:00:37 +0000128 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
129 Ops.push_back(N->getOperand(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000130
Bill Wendling10707f32010-06-24 22:00:37 +0000131 if (FlagDestNode)
Evan Chengc589e032010-01-22 03:36:51 +0000132 Ops.push_back(Flag);
Bill Wendling151d26d2010-06-23 18:16:24 +0000133
Evan Chengc589e032010-01-22 03:36:51 +0000134 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000135 MachineSDNode::mmo_iterator Begin = 0, End = 0;
136 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
137
138 // Store memory references.
139 if (MN) {
140 Begin = MN->memoperands_begin();
141 End = MN->memoperands_end();
142 }
143
Evan Chengc589e032010-01-22 03:36:51 +0000144 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000145
146 // Reset the memory references
147 if (MN)
148 MN->setMemRefs(Begin, End);
Evan Chengc589e032010-01-22 03:36:51 +0000149}
150
151/// ClusterNeighboringLoads - Force nearby loads together by "flagging" them.
152/// This function finds loads of the same base and different offsets. If the
153/// offsets are not far apart (target specific), it add MVT::Flag inputs and
154/// outputs to ensure they are scheduled together and in order. This
155/// optimization may benefit some targets by improving cache locality.
Evan Cheng302ef832010-06-10 02:09:31 +0000156void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
157 SDNode *Chain = 0;
158 unsigned NumOps = Node->getNumOperands();
159 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
160 Chain = Node->getOperand(NumOps-1).getNode();
161 if (!Chain)
162 return;
163
164 // Look for other loads of the same chain. Find loads that are loading from
165 // the same base pointer and different offsets.
Evan Chengc589e032010-01-22 03:36:51 +0000166 SmallPtrSet<SDNode*, 16> Visited;
167 SmallVector<int64_t, 4> Offsets;
168 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng302ef832010-06-10 02:09:31 +0000169 bool Cluster = false;
170 SDNode *Base = Node;
Evan Cheng302ef832010-06-10 02:09:31 +0000171 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
172 I != E; ++I) {
173 SDNode *User = *I;
174 if (User == Node || !Visited.insert(User))
175 continue;
176 int64_t Offset1, Offset2;
177 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
178 Offset1 == Offset2)
179 // FIXME: Should be ok if they addresses are identical. But earlier
180 // optimizations really should have eliminated one of the loads.
181 continue;
182 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
183 Offsets.push_back(Offset1);
184 O2SMap.insert(std::make_pair(Offset2, User));
185 Offsets.push_back(Offset2);
Duncan Sandsb447c4e2010-06-25 14:48:39 +0000186 if (Offset2 < Offset1)
Evan Cheng302ef832010-06-10 02:09:31 +0000187 Base = User;
Evan Cheng302ef832010-06-10 02:09:31 +0000188 Cluster = true;
189 }
190
191 if (!Cluster)
192 return;
193
194 // Sort them in increasing order.
195 std::sort(Offsets.begin(), Offsets.end());
196
197 // Check if the loads are close enough.
198 SmallVector<SDNode*, 4> Loads;
199 unsigned NumLoads = 0;
200 int64_t BaseOff = Offsets[0];
201 SDNode *BaseLoad = O2SMap[BaseOff];
202 Loads.push_back(BaseLoad);
203 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
204 int64_t Offset = Offsets[i];
205 SDNode *Load = O2SMap[Offset];
206 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
207 break; // Stop right here. Ignore loads that are further away.
208 Loads.push_back(Load);
209 ++NumLoads;
210 }
211
212 if (NumLoads == 0)
213 return;
214
215 // Cluster loads by adding MVT::Flag outputs and inputs. This also
216 // ensure they are scheduled in order of increasing addresses.
217 SDNode *Lead = Loads[0];
Bill Wendling10707f32010-06-24 22:00:37 +0000218 AddFlags(Lead, SDValue(0, 0), true, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000219
Bill Wendling10707f32010-06-24 22:00:37 +0000220 SDValue InFlag = SDValue(Lead, Lead->getNumValues() - 1);
221 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
222 bool OutFlag = I < E - 1;
223 SDNode *Load = Loads[I];
224
Evan Cheng302ef832010-06-10 02:09:31 +0000225 AddFlags(Load, InFlag, OutFlag, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000226
Evan Cheng302ef832010-06-10 02:09:31 +0000227 if (OutFlag)
Bill Wendling10707f32010-06-24 22:00:37 +0000228 InFlag = SDValue(Load, Load->getNumValues() - 1);
Bill Wendling151d26d2010-06-23 18:16:24 +0000229
Evan Cheng302ef832010-06-10 02:09:31 +0000230 ++LoadsClustered;
231 }
232}
233
234/// ClusterNodes - Cluster certain nodes which should be scheduled together.
235///
236void ScheduleDAGSDNodes::ClusterNodes() {
Evan Chengc589e032010-01-22 03:36:51 +0000237 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
238 E = DAG->allnodes_end(); NI != E; ++NI) {
239 SDNode *Node = &*NI;
240 if (!Node || !Node->isMachineOpcode())
241 continue;
242
243 unsigned Opc = Node->getMachineOpcode();
244 const TargetInstrDesc &TID = TII->get(Opc);
Evan Cheng302ef832010-06-10 02:09:31 +0000245 if (TID.mayLoad())
246 // Cluster loads from "near" addresses into combined SUnits.
247 ClusterNeighboringLoads(Node);
Evan Chengc589e032010-01-22 03:36:51 +0000248 }
249}
250
Dan Gohman343f0c02008-11-19 23:18:57 +0000251void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000252 // During scheduling, the NodeId field of SDNode is used to map SDNodes
253 // to their associated SUnits by holding SUnits table indices. A value
254 // of -1 means the SDNode does not yet have an associated SUnit.
255 unsigned NumNodes = 0;
256 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
257 E = DAG->allnodes_end(); NI != E; ++NI) {
258 NI->setNodeId(-1);
259 ++NumNodes;
260 }
261
Dan Gohman343f0c02008-11-19 23:18:57 +0000262 // Reserve entries in the vector for each of the SUnits we are creating. This
263 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
264 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000265 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
266 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000267 SUnits.reserve(NumNodes * 2);
Dan Gohman343f0c02008-11-19 23:18:57 +0000268
Chris Lattner736a6ea2010-02-24 06:11:37 +0000269 // Add all nodes in depth first order.
270 SmallVector<SDNode*, 64> Worklist;
271 SmallPtrSet<SDNode*, 64> Visited;
272 Worklist.push_back(DAG->getRoot().getNode());
273 Visited.insert(DAG->getRoot().getNode());
274
275 while (!Worklist.empty()) {
276 SDNode *NI = Worklist.pop_back_val();
277
278 // Add all operands to the worklist unless they've already been added.
279 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
280 if (Visited.insert(NI->getOperand(i).getNode()))
281 Worklist.push_back(NI->getOperand(i).getNode());
282
Dan Gohman343f0c02008-11-19 23:18:57 +0000283 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
284 continue;
285
286 // If this node has already been processed, stop now.
287 if (NI->getNodeId() != -1) continue;
288
289 SUnit *NodeSUnit = NewSUnit(NI);
290
291 // See if anything is flagged to this node, if so, add them to flagged
292 // nodes. Nodes can have at most one flag input and one flag output. Flags
Dan Gohmandb95fa12009-03-20 20:42:23 +0000293 // are required to be the last operand and result of a node.
Dan Gohman343f0c02008-11-19 23:18:57 +0000294
295 // Scan up to find flagged preds.
296 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000297 while (N->getNumOperands() &&
Owen Anderson825b72b2009-08-11 20:47:22 +0000298 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000299 N = N->getOperand(N->getNumOperands()-1).getNode();
300 assert(N->getNodeId() == -1 && "Node already inserted!");
301 N->setNodeId(NodeSUnit->NodeNum);
Dan Gohman343f0c02008-11-19 23:18:57 +0000302 }
303
304 // Scan down to find any flagged succs.
305 N = NI;
Owen Anderson825b72b2009-08-11 20:47:22 +0000306 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000307 SDValue FlagVal(N, N->getNumValues()-1);
308
309 // There are either zero or one users of the Flag result.
310 bool HasFlagUse = false;
311 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
312 UI != E; ++UI)
313 if (FlagVal.isOperandOf(*UI)) {
314 HasFlagUse = true;
315 assert(N->getNodeId() == -1 && "Node already inserted!");
316 N->setNodeId(NodeSUnit->NodeNum);
317 N = *UI;
318 break;
319 }
320 if (!HasFlagUse) break;
321 }
322
323 // If there are flag operands involved, N is now the bottom-most node
324 // of the sequence of nodes that are flagged together.
325 // Update the SUnit.
326 NodeSUnit->setNode(N);
327 assert(N->getNodeId() == -1 && "Node already inserted!");
328 N->setNodeId(NodeSUnit->NodeNum);
329
Dan Gohman787782f2008-11-21 01:44:51 +0000330 // Assign the Latency field of NodeSUnit using target-provided information.
Evan Chenge1631682010-05-19 22:42:23 +0000331 ComputeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000332 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000333}
334
335void ScheduleDAGSDNodes::AddSchedEdges() {
David Goodwin71046162009-08-13 16:05:04 +0000336 const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
337
David Goodwindc4bdcd2009-08-19 16:08:58 +0000338 // Check to see if the scheduler cares about latencies.
339 bool UnitLatencies = ForceUnitLatencies();
340
Dan Gohman343f0c02008-11-19 23:18:57 +0000341 // Pass 2: add the preds, succs, etc.
342 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
343 SUnit *SU = &SUnits[su];
344 SDNode *MainNode = SU->getNode();
345
346 if (MainNode->isMachineOpcode()) {
347 unsigned Opc = MainNode->getMachineOpcode();
348 const TargetInstrDesc &TID = TII->get(Opc);
349 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
350 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
351 SU->isTwoAddress = true;
352 break;
353 }
354 }
355 if (TID.isCommutable())
356 SU->isCommutable = true;
357 }
358
359 // Find all predecessors and successors of the group.
360 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode()) {
361 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000362 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
363 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000364 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000365 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
366 --NumUsed; // Skip over unused values at the end.
367 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000368 SU->hasPhysRegDefs = true;
369 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000370
371 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
372 SDNode *OpN = N->getOperand(i).getNode();
373 if (isPassiveNode(OpN)) continue; // Not scheduled.
374 SUnit *OpSU = &SUnits[OpN->getNodeId()];
375 assert(OpSU && "Node has no SUnit!");
376 if (OpSU == SU) continue; // In the same group.
377
Owen Andersone50ed302009-08-10 22:56:29 +0000378 EVT OpVT = N->getOperand(i).getValueType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000379 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
380 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000381
382 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000383 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000384 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000385 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000386 assert((PhysReg == 0 || !isChain) &&
387 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000388 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
389 // emits a copy from the physical register to a virtual register unless
390 // it requires a cross class copy (cost < 0). That means we are only
391 // treating "expensive to copy" register dependency as physical register
392 // dependency. This may change in the future though.
393 if (Cost >= 0)
394 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000395
Evan Cheng046fa3f2010-05-28 23:26:21 +0000396 // If this is a ctrl dep, latency is 1.
397 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
398 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
399 OpLatency, PhysReg);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000400 if (!isChain && !UnitLatencies) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000401 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
Dan Gohman3fb150a2010-04-17 17:42:52 +0000402 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
David Goodwindc4bdcd2009-08-19 16:08:58 +0000403 }
David Goodwin71046162009-08-13 16:05:04 +0000404
405 SU->addPred(dep);
Dan Gohman343f0c02008-11-19 23:18:57 +0000406 }
407 }
408 }
409}
410
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000411/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
412/// are input. This SUnit graph is similar to the SelectionDAG, but
413/// excludes nodes that aren't interesting to scheduling, and represents
414/// flagged together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000415void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng302ef832010-06-10 02:09:31 +0000416 // Cluster certain nodes which should be scheduled together.
417 ClusterNodes();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000418 // Populate the SUnits array.
419 BuildSchedUnits();
420 // Compute all the scheduling dependencies between nodes.
421 AddSchedEdges();
422}
423
Dan Gohman343f0c02008-11-19 23:18:57 +0000424void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
Evan Chenge1631682010-05-19 22:42:23 +0000425 // Check to see if the scheduler cares about latencies.
426 if (ForceUnitLatencies()) {
427 SU->Latency = 1;
428 return;
429 }
430
Dan Gohman343f0c02008-11-19 23:18:57 +0000431 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
Evan Cheng15a16de2010-05-20 06:13:19 +0000432 if (InstrItins.isEmpty()) {
433 SU->Latency = 1;
434 return;
435 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000436
437 // Compute the latency for the node. We use the sum of the latencies for
438 // all nodes flagged together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000439 SU->Latency = 0;
Dan Gohmanc8c28272008-11-21 00:12:10 +0000440 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())
Dan Gohman343f0c02008-11-19 23:18:57 +0000441 if (N->isMachineOpcode()) {
David Goodwindc4bdcd2009-08-19 16:08:58 +0000442 SU->Latency += InstrItins.
443 getStageLatency(TII->get(N->getMachineOpcode()).getSchedClass());
Dan Gohman343f0c02008-11-19 23:18:57 +0000444 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000445}
446
Evan Cheng15a16de2010-05-20 06:13:19 +0000447void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
448 unsigned OpIdx, SDep& dep) const{
449 // Check to see if the scheduler cares about latencies.
450 if (ForceUnitLatencies())
451 return;
452
453 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
454 if (InstrItins.isEmpty())
455 return;
456
457 if (dep.getKind() != SDep::Data)
458 return;
459
460 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng046fa3f2010-05-28 23:26:21 +0000461 if (Def->isMachineOpcode()) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000462 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
463 if (DefIdx >= II.getNumDefs())
464 return;
465 int DefCycle = InstrItins.getOperandCycle(II.getSchedClass(), DefIdx);
466 if (DefCycle < 0)
467 return;
Evan Cheng046fa3f2010-05-28 23:26:21 +0000468 int UseCycle = 1;
469 if (Use->isMachineOpcode()) {
470 const unsigned UseClass = TII->get(Use->getMachineOpcode()).getSchedClass();
471 UseCycle = InstrItins.getOperandCycle(UseClass, OpIdx);
472 }
Evan Cheng15a16de2010-05-20 06:13:19 +0000473 if (UseCycle >= 0) {
474 int Latency = DefCycle - UseCycle + 1;
475 if (Latency >= 0)
476 dep.setLatency(Latency);
477 }
478 }
479}
480
Dan Gohman343f0c02008-11-19 23:18:57 +0000481void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Evan Chengc29a56d2009-01-12 03:19:55 +0000482 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000483 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000484 return;
485 }
486
487 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000488 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000489 SmallVector<SDNode *, 4> FlaggedNodes;
490 for (SDNode *N = SU->getNode()->getFlaggedNode(); N; N = N->getFlaggedNode())
491 FlaggedNodes.push_back(N);
492 while (!FlaggedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000493 dbgs() << " ";
Dan Gohman343f0c02008-11-19 23:18:57 +0000494 FlaggedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000495 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000496 FlaggedNodes.pop_back();
497 }
498}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000499
Evan Chengbfcb3052010-03-25 01:38:16 +0000500namespace {
501 struct OrderSorter {
502 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
503 const std::pair<unsigned, MachineInstr*> &B) {
504 return A.first < B.first;
505 }
506 };
507}
508
509// ProcessSourceNode - Process nodes with source order numbers. These are added
510// to a vector which EmitSchedule use to determine how to insert dbg_value
511// instructions in the right order.
512static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
513 InstrEmitter &Emitter,
Evan Chengbfcb3052010-03-25 01:38:16 +0000514 DenseMap<SDValue, unsigned> &VRBaseMap,
515 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
516 SmallSet<unsigned, 8> &Seen) {
517 unsigned Order = DAG->GetOrdering(N);
518 if (!Order || !Seen.insert(Order))
519 return;
520
521 MachineBasicBlock *BB = Emitter.getBlock();
522 if (BB->empty() || BB->back().isPHI()) {
523 // Did not insert any instruction.
524 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
525 return;
526 }
527
528 Orders.push_back(std::make_pair(Order, &BB->back()));
529 if (!N->getHasDebugValue())
530 return;
531 // Opportunistically insert immediate dbg_value uses, i.e. those with source
532 // order number right after the N.
533 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
534 SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N);
535 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
536 if (DVs[i]->isInvalidated())
537 continue;
538 unsigned DVOrder = DVs[i]->getOrder();
539 if (DVOrder == ++Order) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000540 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000541 if (DbgMI) {
542 Orders.push_back(std::make_pair(DVOrder, DbgMI));
543 BB->insert(InsertPos, DbgMI);
544 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000545 DVs[i]->setIsInvalidated();
546 }
547 }
548}
549
550
Dan Gohmanbcea8592009-10-10 01:32:21 +0000551/// EmitSchedule - Emit the machine code in scheduled order.
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000552MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000553 InstrEmitter Emitter(BB, InsertPos);
554 DenseMap<SDValue, unsigned> VRBaseMap;
555 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000556 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
557 SmallSet<unsigned, 8> Seen;
558 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000559
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000560 // If this is the first BB, emit byval parameter dbg_value's.
561 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
562 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
563 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
564 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000565 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000566 if (DbgMI)
Dan Gohman403a8cd2010-06-21 19:47:52 +0000567 BB->push_back(DbgMI);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000568 }
569 }
570
Dan Gohmanbcea8592009-10-10 01:32:21 +0000571 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
572 SUnit *SU = Sequence[i];
573 if (!SU) {
574 // Null SUnit* is a noop.
575 EmitNoop();
576 continue;
577 }
578
579 // For pre-regalloc scheduling, create instructions corresponding to the
580 // SDNode and any flagged SDNodes and append them to the block.
581 if (!SU->getNode()) {
582 // Emit a copy.
583 EmitPhysRegCopy(SU, CopyVRBaseMap);
584 continue;
585 }
586
587 SmallVector<SDNode *, 4> FlaggedNodes;
588 for (SDNode *N = SU->getNode()->getFlaggedNode(); N;
589 N = N->getFlaggedNode())
590 FlaggedNodes.push_back(N);
591 while (!FlaggedNodes.empty()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000592 SDNode *N = FlaggedNodes.back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000593 Emitter.EmitNode(FlaggedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000594 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000595 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000596 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000597 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000598 FlaggedNodes.pop_back();
599 }
600 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000601 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000602 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000603 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000604 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000605 Seen);
606 }
607
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000608 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000609 // order sequence.
610 if (HasDbg) {
611 MachineBasicBlock::iterator BBBegin = BB->empty() ? BB->end() : BB->begin();
612 while (BBBegin != BB->end() && BBBegin->isPHI())
613 ++BBBegin;
614
615 // Sort the source order instructions and use the order to insert debug
616 // values.
617 std::sort(Orders.begin(), Orders.end(), OrderSorter());
618
619 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
620 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
621 // Now emit the rest according to source order.
622 unsigned LastOrder = 0;
Evan Chengbfcb3052010-03-25 01:38:16 +0000623 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
624 unsigned Order = Orders[i].first;
625 MachineInstr *MI = Orders[i].second;
626 // Insert all SDDbgValue's whose order(s) are before "Order".
627 if (!MI)
628 continue;
629 MachineBasicBlock *MIBB = MI->getParent();
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000630#ifndef NDEBUG
631 unsigned LastDIOrder = 0;
632#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000633 for (; DI != DE &&
634 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000635#ifndef NDEBUG
636 assert((*DI)->getOrder() >= LastDIOrder &&
637 "SDDbgValue nodes must be in source order!");
638 LastDIOrder = (*DI)->getOrder();
639#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000640 if ((*DI)->isInvalidated())
641 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000642 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000643 if (DbgMI) {
644 if (!LastOrder)
645 // Insert to start of the BB (after PHIs).
646 BB->insert(BBBegin, DbgMI);
647 else {
648 MachineBasicBlock::iterator Pos = MI;
649 MIBB->insert(llvm::next(Pos), DbgMI);
650 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000651 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000652 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000653 LastOrder = Order;
Evan Chengbfcb3052010-03-25 01:38:16 +0000654 }
655 // Add trailing DbgValue's before the terminator. FIXME: May want to add
656 // some of them before one or more conditional branches?
657 while (DI != DE) {
658 MachineBasicBlock *InsertBB = Emitter.getBlock();
659 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
660 if (!(*DI)->isInvalidated()) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000661 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000662 if (DbgMI)
663 InsertBB->insert(Pos, DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000664 }
665 ++DI;
666 }
Dan Gohmanbcea8592009-10-10 01:32:21 +0000667 }
668
669 BB = Emitter.getBlock();
670 InsertPos = Emitter.getInsertPos();
671 return BB;
672}