blob: b45c28f4be41e1011bbea90e353cd95b5b989169 [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 =
104 TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
105 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;
113 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
114 VTs.push_back(N->getValueType(i));
115 if (AddFlag)
116 VTs.push_back(MVT::Flag);
117 SmallVector<SDValue, 4> Ops;
118 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
119 Ops.push_back(N->getOperand(i));
120 if (Flag.getNode())
121 Ops.push_back(Flag);
122 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
123 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
124}
125
126/// ClusterNeighboringLoads - Force nearby loads together by "flagging" them.
127/// This function finds loads of the same base and different offsets. If the
128/// offsets are not far apart (target specific), it add MVT::Flag inputs and
129/// outputs to ensure they are scheduled together and in order. This
130/// optimization may benefit some targets by improving cache locality.
131void ScheduleDAGSDNodes::ClusterNeighboringLoads() {
132 SmallPtrSet<SDNode*, 16> Visited;
133 SmallVector<int64_t, 4> Offsets;
134 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
135 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
136 E = DAG->allnodes_end(); NI != E; ++NI) {
137 SDNode *Node = &*NI;
138 if (!Node || !Node->isMachineOpcode())
139 continue;
140
141 unsigned Opc = Node->getMachineOpcode();
142 const TargetInstrDesc &TID = TII->get(Opc);
143 if (!TID.mayLoad())
144 continue;
145
146 SDNode *Chain = 0;
147 unsigned NumOps = Node->getNumOperands();
148 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
149 Chain = Node->getOperand(NumOps-1).getNode();
150 if (!Chain)
151 continue;
152
153 // Look for other loads of the same chain. Find loads that are loading from
154 // the same base pointer and different offsets.
155 Visited.clear();
156 Offsets.clear();
157 O2SMap.clear();
158 bool Cluster = false;
159 SDNode *Base = Node;
160 int64_t BaseOffset;
161 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
162 I != E; ++I) {
163 SDNode *User = *I;
164 if (User == Node || !Visited.insert(User))
165 continue;
166 int64_t Offset1, Offset2;
167 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
168 Offset1 == Offset2)
169 // FIXME: Should be ok if they addresses are identical. But earlier
170 // optimizations really should have eliminated one of the loads.
171 continue;
172 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
173 Offsets.push_back(Offset1);
174 O2SMap.insert(std::make_pair(Offset2, User));
175 Offsets.push_back(Offset2);
176 if (Offset2 < Offset1) {
177 Base = User;
178 BaseOffset = Offset2;
179 } else {
180 BaseOffset = Offset1;
181 }
182 Cluster = true;
183 }
184
185 if (!Cluster)
186 continue;
187
188 // Sort them in increasing order.
189 std::sort(Offsets.begin(), Offsets.end());
190
191 // Check if the loads are close enough.
192 SmallVector<SDNode*, 4> Loads;
193 unsigned NumLoads = 0;
194 int64_t BaseOff = Offsets[0];
195 SDNode *BaseLoad = O2SMap[BaseOff];
196 Loads.push_back(BaseLoad);
197 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
198 int64_t Offset = Offsets[i];
199 SDNode *Load = O2SMap[Offset];
200 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,
201 NumLoads))
202 break; // Stop right here. Ignore loads that are further away.
203 Loads.push_back(Load);
204 ++NumLoads;
205 }
206
207 if (NumLoads == 0)
208 continue;
209
210 // Cluster loads by adding MVT::Flag outputs and inputs. This also
211 // ensure they are scheduled in order of increasing addresses.
212 SDNode *Lead = Loads[0];
213 AddFlags(Lead, SDValue(0,0), true, DAG);
214 SDValue InFlag = SDValue(Lead, Lead->getNumValues()-1);
215 for (unsigned i = 1, e = Loads.size(); i != e; ++i) {
216 bool OutFlag = i < e-1;
217 SDNode *Load = Loads[i];
218 AddFlags(Load, InFlag, OutFlag, DAG);
219 if (OutFlag)
220 InFlag = SDValue(Load, Load->getNumValues()-1);
221 ++LoadsClustered;
222 }
223 }
224}
225
Dan Gohman343f0c02008-11-19 23:18:57 +0000226void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000227 // During scheduling, the NodeId field of SDNode is used to map SDNodes
228 // to their associated SUnits by holding SUnits table indices. A value
229 // of -1 means the SDNode does not yet have an associated SUnit.
230 unsigned NumNodes = 0;
231 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
232 E = DAG->allnodes_end(); NI != E; ++NI) {
233 NI->setNodeId(-1);
234 ++NumNodes;
235 }
236
Dan Gohman343f0c02008-11-19 23:18:57 +0000237 // Reserve entries in the vector for each of the SUnits we are creating. This
238 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
239 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000240 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
241 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000242 SUnits.reserve(NumNodes * 2);
Dan Gohman343f0c02008-11-19 23:18:57 +0000243
Chris Lattner736a6ea2010-02-24 06:11:37 +0000244 // Add all nodes in depth first order.
245 SmallVector<SDNode*, 64> Worklist;
246 SmallPtrSet<SDNode*, 64> Visited;
247 Worklist.push_back(DAG->getRoot().getNode());
248 Visited.insert(DAG->getRoot().getNode());
249
250 while (!Worklist.empty()) {
251 SDNode *NI = Worklist.pop_back_val();
252
253 // Add all operands to the worklist unless they've already been added.
254 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
255 if (Visited.insert(NI->getOperand(i).getNode()))
256 Worklist.push_back(NI->getOperand(i).getNode());
257
Dan Gohman343f0c02008-11-19 23:18:57 +0000258 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
259 continue;
260
261 // If this node has already been processed, stop now.
262 if (NI->getNodeId() != -1) continue;
263
264 SUnit *NodeSUnit = NewSUnit(NI);
265
266 // See if anything is flagged to this node, if so, add them to flagged
267 // nodes. Nodes can have at most one flag input and one flag output. Flags
Dan Gohmandb95fa12009-03-20 20:42:23 +0000268 // are required to be the last operand and result of a node.
Dan Gohman343f0c02008-11-19 23:18:57 +0000269
270 // Scan up to find flagged preds.
271 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000272 while (N->getNumOperands() &&
Owen Anderson825b72b2009-08-11 20:47:22 +0000273 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000274 N = N->getOperand(N->getNumOperands()-1).getNode();
275 assert(N->getNodeId() == -1 && "Node already inserted!");
276 N->setNodeId(NodeSUnit->NodeNum);
Dan Gohman343f0c02008-11-19 23:18:57 +0000277 }
278
279 // Scan down to find any flagged succs.
280 N = NI;
Owen Anderson825b72b2009-08-11 20:47:22 +0000281 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000282 SDValue FlagVal(N, N->getNumValues()-1);
283
284 // There are either zero or one users of the Flag result.
285 bool HasFlagUse = false;
286 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
287 UI != E; ++UI)
288 if (FlagVal.isOperandOf(*UI)) {
289 HasFlagUse = true;
290 assert(N->getNodeId() == -1 && "Node already inserted!");
291 N->setNodeId(NodeSUnit->NodeNum);
292 N = *UI;
293 break;
294 }
295 if (!HasFlagUse) break;
296 }
297
298 // If there are flag operands involved, N is now the bottom-most node
299 // of the sequence of nodes that are flagged together.
300 // Update the SUnit.
301 NodeSUnit->setNode(N);
302 assert(N->getNodeId() == -1 && "Node already inserted!");
303 N->setNodeId(NodeSUnit->NodeNum);
304
Dan Gohman787782f2008-11-21 01:44:51 +0000305 // Assign the Latency field of NodeSUnit using target-provided information.
Evan Chenge1631682010-05-19 22:42:23 +0000306 ComputeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000307 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000308}
309
310void ScheduleDAGSDNodes::AddSchedEdges() {
David Goodwin71046162009-08-13 16:05:04 +0000311 const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
312
David Goodwindc4bdcd2009-08-19 16:08:58 +0000313 // Check to see if the scheduler cares about latencies.
314 bool UnitLatencies = ForceUnitLatencies();
315
Dan Gohman343f0c02008-11-19 23:18:57 +0000316 // Pass 2: add the preds, succs, etc.
317 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
318 SUnit *SU = &SUnits[su];
319 SDNode *MainNode = SU->getNode();
320
321 if (MainNode->isMachineOpcode()) {
322 unsigned Opc = MainNode->getMachineOpcode();
323 const TargetInstrDesc &TID = TII->get(Opc);
324 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
325 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
326 SU->isTwoAddress = true;
327 break;
328 }
329 }
330 if (TID.isCommutable())
331 SU->isCommutable = true;
332 }
333
334 // Find all predecessors and successors of the group.
335 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode()) {
336 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000337 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
338 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000339 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000340 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
341 --NumUsed; // Skip over unused values at the end.
342 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000343 SU->hasPhysRegDefs = true;
344 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000345
346 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
347 SDNode *OpN = N->getOperand(i).getNode();
348 if (isPassiveNode(OpN)) continue; // Not scheduled.
349 SUnit *OpSU = &SUnits[OpN->getNodeId()];
350 assert(OpSU && "Node has no SUnit!");
351 if (OpSU == SU) continue; // In the same group.
352
Owen Andersone50ed302009-08-10 22:56:29 +0000353 EVT OpVT = N->getOperand(i).getValueType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000354 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
355 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000356
357 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000358 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000359 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000360 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000361 assert((PhysReg == 0 || !isChain) &&
362 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000363 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
364 // emits a copy from the physical register to a virtual register unless
365 // it requires a cross class copy (cost < 0). That means we are only
366 // treating "expensive to copy" register dependency as physical register
367 // dependency. This may change in the future though.
368 if (Cost >= 0)
369 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000370
Evan Cheng046fa3f2010-05-28 23:26:21 +0000371 // If this is a ctrl dep, latency is 1.
372 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
373 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
374 OpLatency, PhysReg);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000375 if (!isChain && !UnitLatencies) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000376 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
Dan Gohman3fb150a2010-04-17 17:42:52 +0000377 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
David Goodwindc4bdcd2009-08-19 16:08:58 +0000378 }
David Goodwin71046162009-08-13 16:05:04 +0000379
380 SU->addPred(dep);
Dan Gohman343f0c02008-11-19 23:18:57 +0000381 }
382 }
383 }
384}
385
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000386/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
387/// are input. This SUnit graph is similar to the SelectionDAG, but
388/// excludes nodes that aren't interesting to scheduling, and represents
389/// flagged together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000390void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Chengc589e032010-01-22 03:36:51 +0000391 // Cluster loads from "near" addresses into combined SUnits.
Evan Cheng42dae2d2010-01-22 23:49:45 +0000392 ClusterNeighboringLoads();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000393 // Populate the SUnits array.
394 BuildSchedUnits();
395 // Compute all the scheduling dependencies between nodes.
396 AddSchedEdges();
397}
398
Dan Gohman343f0c02008-11-19 23:18:57 +0000399void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
Evan Chenge1631682010-05-19 22:42:23 +0000400 // Check to see if the scheduler cares about latencies.
401 if (ForceUnitLatencies()) {
402 SU->Latency = 1;
403 return;
404 }
405
Dan Gohman343f0c02008-11-19 23:18:57 +0000406 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
Evan Cheng15a16de2010-05-20 06:13:19 +0000407 if (InstrItins.isEmpty()) {
408 SU->Latency = 1;
409 return;
410 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000411
412 // Compute the latency for the node. We use the sum of the latencies for
413 // all nodes flagged together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000414 SU->Latency = 0;
Dan Gohmanc8c28272008-11-21 00:12:10 +0000415 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())
Dan Gohman343f0c02008-11-19 23:18:57 +0000416 if (N->isMachineOpcode()) {
David Goodwindc4bdcd2009-08-19 16:08:58 +0000417 SU->Latency += InstrItins.
418 getStageLatency(TII->get(N->getMachineOpcode()).getSchedClass());
Dan Gohman343f0c02008-11-19 23:18:57 +0000419 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000420}
421
Evan Cheng15a16de2010-05-20 06:13:19 +0000422void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
423 unsigned OpIdx, SDep& dep) const{
424 // Check to see if the scheduler cares about latencies.
425 if (ForceUnitLatencies())
426 return;
427
428 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
429 if (InstrItins.isEmpty())
430 return;
431
432 if (dep.getKind() != SDep::Data)
433 return;
434
435 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng046fa3f2010-05-28 23:26:21 +0000436 if (Def->isMachineOpcode()) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000437 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
438 if (DefIdx >= II.getNumDefs())
439 return;
440 int DefCycle = InstrItins.getOperandCycle(II.getSchedClass(), DefIdx);
441 if (DefCycle < 0)
442 return;
Evan Cheng046fa3f2010-05-28 23:26:21 +0000443 int UseCycle = 1;
444 if (Use->isMachineOpcode()) {
445 const unsigned UseClass = TII->get(Use->getMachineOpcode()).getSchedClass();
446 UseCycle = InstrItins.getOperandCycle(UseClass, OpIdx);
447 }
Evan Cheng15a16de2010-05-20 06:13:19 +0000448 if (UseCycle >= 0) {
449 int Latency = DefCycle - UseCycle + 1;
450 if (Latency >= 0)
451 dep.setLatency(Latency);
452 }
453 }
454}
455
Dan Gohman343f0c02008-11-19 23:18:57 +0000456void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Evan Chengc29a56d2009-01-12 03:19:55 +0000457 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000458 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000459 return;
460 }
461
462 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000463 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000464 SmallVector<SDNode *, 4> FlaggedNodes;
465 for (SDNode *N = SU->getNode()->getFlaggedNode(); N; N = N->getFlaggedNode())
466 FlaggedNodes.push_back(N);
467 while (!FlaggedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000468 dbgs() << " ";
Dan Gohman343f0c02008-11-19 23:18:57 +0000469 FlaggedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000470 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000471 FlaggedNodes.pop_back();
472 }
473}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000474
Evan Chengbfcb3052010-03-25 01:38:16 +0000475namespace {
476 struct OrderSorter {
477 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
478 const std::pair<unsigned, MachineInstr*> &B) {
479 return A.first < B.first;
480 }
481 };
482}
483
484// ProcessSourceNode - Process nodes with source order numbers. These are added
485// to a vector which EmitSchedule use to determine how to insert dbg_value
486// instructions in the right order.
487static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
488 InstrEmitter &Emitter,
Evan Chengbfcb3052010-03-25 01:38:16 +0000489 DenseMap<SDValue, unsigned> &VRBaseMap,
490 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
491 SmallSet<unsigned, 8> &Seen) {
492 unsigned Order = DAG->GetOrdering(N);
493 if (!Order || !Seen.insert(Order))
494 return;
495
496 MachineBasicBlock *BB = Emitter.getBlock();
497 if (BB->empty() || BB->back().isPHI()) {
498 // Did not insert any instruction.
499 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
500 return;
501 }
502
503 Orders.push_back(std::make_pair(Order, &BB->back()));
504 if (!N->getHasDebugValue())
505 return;
506 // Opportunistically insert immediate dbg_value uses, i.e. those with source
507 // order number right after the N.
508 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
509 SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N);
510 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
511 if (DVs[i]->isInvalidated())
512 continue;
513 unsigned DVOrder = DVs[i]->getOrder();
514 if (DVOrder == ++Order) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000515 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000516 if (DbgMI) {
517 Orders.push_back(std::make_pair(DVOrder, DbgMI));
518 BB->insert(InsertPos, DbgMI);
519 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000520 DVs[i]->setIsInvalidated();
521 }
522 }
523}
524
525
Dan Gohmanbcea8592009-10-10 01:32:21 +0000526/// EmitSchedule - Emit the machine code in scheduled order.
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000527MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000528 InstrEmitter Emitter(BB, InsertPos);
529 DenseMap<SDValue, unsigned> VRBaseMap;
530 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000531 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
532 SmallSet<unsigned, 8> Seen;
533 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000534
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000535 // If this is the first BB, emit byval parameter dbg_value's.
536 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
537 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
538 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
539 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000540 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000541 if (DbgMI)
542 BB->insert(BB->end(), DbgMI);
543 }
544 }
545
Dan Gohmanbcea8592009-10-10 01:32:21 +0000546 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
547 SUnit *SU = Sequence[i];
548 if (!SU) {
549 // Null SUnit* is a noop.
550 EmitNoop();
551 continue;
552 }
553
554 // For pre-regalloc scheduling, create instructions corresponding to the
555 // SDNode and any flagged SDNodes and append them to the block.
556 if (!SU->getNode()) {
557 // Emit a copy.
558 EmitPhysRegCopy(SU, CopyVRBaseMap);
559 continue;
560 }
561
562 SmallVector<SDNode *, 4> FlaggedNodes;
563 for (SDNode *N = SU->getNode()->getFlaggedNode(); N;
564 N = N->getFlaggedNode())
565 FlaggedNodes.push_back(N);
566 while (!FlaggedNodes.empty()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000567 SDNode *N = FlaggedNodes.back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000568 Emitter.EmitNode(FlaggedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000569 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000570 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000571 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000572 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000573 FlaggedNodes.pop_back();
574 }
575 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000576 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000577 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000578 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000579 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000580 Seen);
581 }
582
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000583 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000584 // order sequence.
585 if (HasDbg) {
586 MachineBasicBlock::iterator BBBegin = BB->empty() ? BB->end() : BB->begin();
587 while (BBBegin != BB->end() && BBBegin->isPHI())
588 ++BBBegin;
589
590 // Sort the source order instructions and use the order to insert debug
591 // values.
592 std::sort(Orders.begin(), Orders.end(), OrderSorter());
593
594 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
595 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
596 // Now emit the rest according to source order.
597 unsigned LastOrder = 0;
598 MachineInstr *LastMI = 0;
599 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
600 unsigned Order = Orders[i].first;
601 MachineInstr *MI = Orders[i].second;
602 // Insert all SDDbgValue's whose order(s) are before "Order".
603 if (!MI)
604 continue;
605 MachineBasicBlock *MIBB = MI->getParent();
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000606#ifndef NDEBUG
607 unsigned LastDIOrder = 0;
608#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000609 for (; DI != DE &&
610 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000611#ifndef NDEBUG
612 assert((*DI)->getOrder() >= LastDIOrder &&
613 "SDDbgValue nodes must be in source order!");
614 LastDIOrder = (*DI)->getOrder();
615#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000616 if ((*DI)->isInvalidated())
617 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000618 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000619 if (DbgMI) {
620 if (!LastOrder)
621 // Insert to start of the BB (after PHIs).
622 BB->insert(BBBegin, DbgMI);
623 else {
624 MachineBasicBlock::iterator Pos = MI;
625 MIBB->insert(llvm::next(Pos), DbgMI);
626 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000627 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000628 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000629 LastOrder = Order;
630 LastMI = MI;
631 }
632 // Add trailing DbgValue's before the terminator. FIXME: May want to add
633 // some of them before one or more conditional branches?
634 while (DI != DE) {
635 MachineBasicBlock *InsertBB = Emitter.getBlock();
636 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
637 if (!(*DI)->isInvalidated()) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000638 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000639 if (DbgMI)
640 InsertBB->insert(Pos, DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000641 }
642 ++DI;
643 }
Dan Gohmanbcea8592009-10-10 01:32:21 +0000644 }
645
646 BB = Emitter.getBlock();
647 InsertPos = Emitter.getInsertPos();
648 return BB;
649}