blob: 69dd813b24e0171b973f805b2de7d795cff154ed [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"
Andrew Trick84b454d2012-03-07 05:21:44 +000020#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chengab8be962011-06-29 01:14:12 +000022#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000023#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng1cc39842010-05-20 23:26:43 +000025#include "llvm/Target/TargetLowering.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000026#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng5b1b44892011-07-01 21:01:15 +000027#include "llvm/Target/TargetSubtargetInfo.h"
Evan Chengc589e032010-01-22 03:36:51 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/SmallPtrSet.h"
Evan Chengbfcb3052010-03-25 01:38:16 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc589e032010-01-22 03:36:51 +000031#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
Andrew Tricke0ef5092011-03-05 08:00:22 +000033#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
36using namespace llvm;
37
Evan Chengc589e032010-01-22 03:36:51 +000038STATISTIC(LoadsClustered, "Number of loads clustered together");
39
Andrew Tricke0ef5092011-03-05 08:00:22 +000040// This allows latency based scheduler to notice high latency instructions
41// without a target itinerary. The choise if number here has more to do with
42// balancing scheduler heursitics than with the actual machine latency.
43static 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 Gohman79ce2762009-01-15 19:20:50 +000048ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
Andrew Trick47c14452012-03-07 05:21:52 +000049 : ScheduleDAG(mf), BB(0), DAG(0),
Evan Cheng3ef1c872010-09-10 01:29:16 +000050 InstrItins(mf.getTarget().getInstrItineraryData()) {}
Dan Gohman343f0c02008-11-19 23:18:57 +000051
Dan Gohman47ac0f02009-02-11 04:27:20 +000052/// Run - perform scheduling.
53///
Andrew Trick47c14452012-03-07 05:21:52 +000054void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
55 BB = bb;
Dan Gohman47ac0f02009-02-11 04:27:20 +000056 DAG = dag;
Andrew Trick47c14452012-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 Gohman47ac0f02009-02-11 04:27:20 +000064}
65
Evan Cheng1cc39842010-05-20 23:26:43 +000066/// NewSUnit - Creates a new SUnit and return a ptr to it.
67///
Andrew Trick953be892012-03-07 23:00:49 +000068SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
Evan Cheng1cc39842010-05-20 23:26:43 +000069#ifndef NDEBUG
70 const SUnit *Addr = 0;
71 if (!SUnits.empty())
72 Addr = &SUnits[0];
73#endif
74 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
75 assert((Addr == 0 || Addr == &SUnits[0]) &&
76 "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 Chengc120af42010-08-10 02:39:45 +000080 if (!N ||
81 (N->isMachineOpcode() &&
82 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
Evan Cheng046fa3f2010-05-28 23:26:21 +000083 SU->SchedulingPref = Sched::None;
84 else
85 SU->SchedulingPref = TLI.getSchedulingPreference(N);
Evan Cheng1cc39842010-05-20 23:26:43 +000086 return SU;
87}
88
Dan Gohman343f0c02008-11-19 23:18:57 +000089SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
Andrew Trick953be892012-03-07 23:00:49 +000090 SUnit *SU = newSUnit(Old->getNode());
Dan Gohman343f0c02008-11-19 23:18:57 +000091 SU->OrigNode = Old->OrigNode;
92 SU->Latency = Old->Latency;
Andrew Trick54699762011-04-07 19:54:57 +000093 SU->isVRegCycle = Old->isVRegCycle;
Evan Cheng8239daf2010-11-03 00:45:17 +000094 SU->isCall = Old->isCall;
Evan Cheng554daa62011-04-26 21:31:35 +000095 SU->isCallOp = Old->isCallOp;
Dan Gohman343f0c02008-11-19 23:18:57 +000096 SU->isTwoAddress = Old->isTwoAddress;
97 SU->isCommutable = Old->isCommutable;
98 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
Dan Gohman39746672009-03-23 16:10:52 +000099 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
Andrew Trick12f0dc62011-04-14 05:15:06 +0000100 SU->isScheduleHigh = Old->isScheduleHigh;
101 SU->isScheduleLow = Old->isScheduleLow;
Evan Cheng1cc39842010-05-20 23:26:43 +0000102 SU->SchedulingPref = Old->SchedulingPref;
Evan Chenge57187c2009-01-16 20:57:18 +0000103 Old->isCloned = true;
Dan Gohman343f0c02008-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 Chengc29a56d2009-01-12 03:19:55 +0000109/// register and the cost of copying the register.
Dan Gohman343f0c02008-11-19 23:18:57 +0000110static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
Andrew Trickcd5af072011-02-03 23:00:17 +0000111 const TargetRegisterInfo *TRI,
Dan Gohman343f0c02008-11-19 23:18:57 +0000112 const TargetInstrInfo *TII,
Evan Chengc29a56d2009-01-12 03:19:55 +0000113 unsigned &PhysReg, int &Cost) {
Dan Gohman343f0c02008-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();
122 if (Def->isMachineOpcode()) {
Evan Chenge837dea2011-06-28 19:10:37 +0000123 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
Dan Gohman343f0c02008-11-19 23:18:57 +0000124 if (ResNo >= II.getNumDefs() &&
Evan Chengc29a56d2009-01-12 03:19:55 +0000125 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000126 PhysReg = Reg;
Evan Chengc29a56d2009-01-12 03:19:55 +0000127 const TargetRegisterClass *RC =
Rafael Espindolad31f9722010-06-29 14:02:34 +0000128 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
Evan Chengc29a56d2009-01-12 03:19:55 +0000129 Cost = RC->getCopyCost();
130 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000131 }
132}
133
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000134static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
Evan Chengc589e032010-01-22 03:36:51 +0000135 SmallVector<EVT, 4> VTs;
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000136 SDNode *GlueDestNode = Glue.getNode();
Bill Wendling151d26d2010-06-23 18:16:24 +0000137
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000138 // Don't add glue from a node to itself.
139 if (GlueDestNode == N) return;
Bill Wendling10707f32010-06-24 22:00:37 +0000140
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000141 // Don't add glue to something which already has glue.
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000142 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return;
Bill Wendling10707f32010-06-24 22:00:37 +0000143
144 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
145 VTs.push_back(N->getValueType(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000146
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000147 if (AddGlue)
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000148 VTs.push_back(MVT::Glue);
Bill Wendling151d26d2010-06-23 18:16:24 +0000149
Evan Chengc589e032010-01-22 03:36:51 +0000150 SmallVector<SDValue, 4> Ops;
Bill Wendling10707f32010-06-24 22:00:37 +0000151 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
152 Ops.push_back(N->getOperand(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000153
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000154 if (GlueDestNode)
155 Ops.push_back(Glue);
Bill Wendling151d26d2010-06-23 18:16:24 +0000156
Evan Chengc589e032010-01-22 03:36:51 +0000157 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000158 MachineSDNode::mmo_iterator Begin = 0, End = 0;
159 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
160
161 // Store memory references.
162 if (MN) {
163 Begin = MN->memoperands_begin();
164 End = MN->memoperands_end();
165 }
166
Evan Chengc589e032010-01-22 03:36:51 +0000167 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000168
169 // Reset the memory references
170 if (MN)
171 MN->setMemRefs(Begin, End);
Evan Chengc589e032010-01-22 03:36:51 +0000172}
173
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000174/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
Evan Chengc589e032010-01-22 03:36:51 +0000175/// This function finds loads of the same base and different offsets. If the
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000176/// offsets are not far apart (target specific), it add MVT::Glue inputs and
Evan Chengc589e032010-01-22 03:36:51 +0000177/// outputs to ensure they are scheduled together and in order. This
178/// optimization may benefit some targets by improving cache locality.
Evan Cheng302ef832010-06-10 02:09:31 +0000179void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
180 SDNode *Chain = 0;
181 unsigned NumOps = Node->getNumOperands();
182 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
183 Chain = Node->getOperand(NumOps-1).getNode();
184 if (!Chain)
185 return;
186
187 // Look for other loads of the same chain. Find loads that are loading from
188 // the same base pointer and different offsets.
Evan Chengc589e032010-01-22 03:36:51 +0000189 SmallPtrSet<SDNode*, 16> Visited;
190 SmallVector<int64_t, 4> Offsets;
191 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng302ef832010-06-10 02:09:31 +0000192 bool Cluster = false;
193 SDNode *Base = Node;
Evan Cheng302ef832010-06-10 02:09:31 +0000194 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
195 I != E; ++I) {
196 SDNode *User = *I;
197 if (User == Node || !Visited.insert(User))
198 continue;
199 int64_t Offset1, Offset2;
200 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
201 Offset1 == Offset2)
202 // FIXME: Should be ok if they addresses are identical. But earlier
203 // optimizations really should have eliminated one of the loads.
204 continue;
205 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
206 Offsets.push_back(Offset1);
207 O2SMap.insert(std::make_pair(Offset2, User));
208 Offsets.push_back(Offset2);
Duncan Sandsb447c4e2010-06-25 14:48:39 +0000209 if (Offset2 < Offset1)
Evan Cheng302ef832010-06-10 02:09:31 +0000210 Base = User;
Evan Cheng302ef832010-06-10 02:09:31 +0000211 Cluster = true;
212 }
213
214 if (!Cluster)
215 return;
216
217 // Sort them in increasing order.
218 std::sort(Offsets.begin(), Offsets.end());
219
220 // Check if the loads are close enough.
221 SmallVector<SDNode*, 4> Loads;
222 unsigned NumLoads = 0;
223 int64_t BaseOff = Offsets[0];
224 SDNode *BaseLoad = O2SMap[BaseOff];
225 Loads.push_back(BaseLoad);
226 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
227 int64_t Offset = Offsets[i];
228 SDNode *Load = O2SMap[Offset];
229 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
230 break; // Stop right here. Ignore loads that are further away.
231 Loads.push_back(Load);
232 ++NumLoads;
233 }
234
235 if (NumLoads == 0)
236 return;
237
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000238 // Cluster loads by adding MVT::Glue outputs and inputs. This also
Evan Cheng302ef832010-06-10 02:09:31 +0000239 // ensure they are scheduled in order of increasing addresses.
240 SDNode *Lead = Loads[0];
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000241 AddGlue(Lead, SDValue(0, 0), true, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000242
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000243 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1);
Bill Wendling10707f32010-06-24 22:00:37 +0000244 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000245 bool OutGlue = I < E - 1;
Bill Wendling10707f32010-06-24 22:00:37 +0000246 SDNode *Load = Loads[I];
247
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000248 AddGlue(Load, InGlue, OutGlue, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000249
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000250 if (OutGlue)
251 InGlue = SDValue(Load, Load->getNumValues() - 1);
Bill Wendling151d26d2010-06-23 18:16:24 +0000252
Evan Cheng302ef832010-06-10 02:09:31 +0000253 ++LoadsClustered;
254 }
255}
256
257/// ClusterNodes - Cluster certain nodes which should be scheduled together.
258///
259void ScheduleDAGSDNodes::ClusterNodes() {
Evan Chengc589e032010-01-22 03:36:51 +0000260 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
261 E = DAG->allnodes_end(); NI != E; ++NI) {
262 SDNode *Node = &*NI;
263 if (!Node || !Node->isMachineOpcode())
264 continue;
265
266 unsigned Opc = Node->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000267 const MCInstrDesc &MCID = TII->get(Opc);
268 if (MCID.mayLoad())
Evan Cheng302ef832010-06-10 02:09:31 +0000269 // Cluster loads from "near" addresses into combined SUnits.
270 ClusterNeighboringLoads(Node);
Evan Chengc589e032010-01-22 03:36:51 +0000271 }
272}
273
Dan Gohman343f0c02008-11-19 23:18:57 +0000274void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000275 // During scheduling, the NodeId field of SDNode is used to map SDNodes
276 // to their associated SUnits by holding SUnits table indices. A value
277 // of -1 means the SDNode does not yet have an associated SUnit.
278 unsigned NumNodes = 0;
279 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
280 E = DAG->allnodes_end(); NI != E; ++NI) {
281 NI->setNodeId(-1);
282 ++NumNodes;
283 }
284
Dan Gohman343f0c02008-11-19 23:18:57 +0000285 // Reserve entries in the vector for each of the SUnits we are creating. This
286 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
287 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000288 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
289 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000290 SUnits.reserve(NumNodes * 2);
Andrew Trickcd5af072011-02-03 23:00:17 +0000291
Chris Lattner736a6ea2010-02-24 06:11:37 +0000292 // Add all nodes in depth first order.
293 SmallVector<SDNode*, 64> Worklist;
294 SmallPtrSet<SDNode*, 64> Visited;
295 Worklist.push_back(DAG->getRoot().getNode());
296 Visited.insert(DAG->getRoot().getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000297
Evan Cheng554daa62011-04-26 21:31:35 +0000298 SmallVector<SUnit*, 8> CallSUnits;
Chris Lattner736a6ea2010-02-24 06:11:37 +0000299 while (!Worklist.empty()) {
300 SDNode *NI = Worklist.pop_back_val();
Andrew Trickcd5af072011-02-03 23:00:17 +0000301
Chris Lattner736a6ea2010-02-24 06:11:37 +0000302 // Add all operands to the worklist unless they've already been added.
303 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
304 if (Visited.insert(NI->getOperand(i).getNode()))
305 Worklist.push_back(NI->getOperand(i).getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000306
Dan Gohman343f0c02008-11-19 23:18:57 +0000307 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
308 continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000309
Dan Gohman343f0c02008-11-19 23:18:57 +0000310 // If this node has already been processed, stop now.
311 if (NI->getNodeId() != -1) continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000312
Andrew Trick953be892012-03-07 23:00:49 +0000313 SUnit *NodeSUnit = newSUnit(NI);
Andrew Trickcd5af072011-02-03 23:00:17 +0000314
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000315 // See if anything is glued to this node, if so, add them to glued
316 // nodes. Nodes can have at most one glue input and one glue output. Glue
317 // is required to be the last operand and result of a node.
Andrew Trickcd5af072011-02-03 23:00:17 +0000318
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000319 // Scan up to find glued preds.
Dan Gohman343f0c02008-11-19 23:18:57 +0000320 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000321 while (N->getNumOperands() &&
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000322 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000323 N = N->getOperand(N->getNumOperands()-1).getNode();
324 assert(N->getNodeId() == -1 && "Node already inserted!");
325 N->setNodeId(NodeSUnit->NodeNum);
Evan Cheng8239daf2010-11-03 00:45:17 +0000326 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
327 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000328 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000329
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000330 // Scan down to find any glued succs.
Dan Gohman343f0c02008-11-19 23:18:57 +0000331 N = NI;
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000332 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000333 SDValue GlueVal(N, N->getNumValues()-1);
Andrew Trickcd5af072011-02-03 23:00:17 +0000334
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000335 // There are either zero or one users of the Glue result.
336 bool HasGlueUse = false;
Andrew Trickcd5af072011-02-03 23:00:17 +0000337 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000338 UI != E; ++UI)
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000339 if (GlueVal.isOperandOf(*UI)) {
340 HasGlueUse = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000341 assert(N->getNodeId() == -1 && "Node already inserted!");
342 N->setNodeId(NodeSUnit->NodeNum);
343 N = *UI;
Evan Cheng8239daf2010-11-03 00:45:17 +0000344 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
345 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000346 break;
347 }
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000348 if (!HasGlueUse) break;
Dan Gohman343f0c02008-11-19 23:18:57 +0000349 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000350
Evan Cheng554daa62011-04-26 21:31:35 +0000351 if (NodeSUnit->isCall)
352 CallSUnits.push_back(NodeSUnit);
353
Andrew Trick12f0dc62011-04-14 05:15:06 +0000354 // Schedule zero-latency TokenFactor below any nodes that may increase the
355 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
356 // have false stalls.
357 if (NI->getOpcode() == ISD::TokenFactor)
358 NodeSUnit->isScheduleLow = true;
359
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000360 // If there are glue operands involved, N is now the bottom-most node
361 // of the sequence of nodes that are glued together.
Dan Gohman343f0c02008-11-19 23:18:57 +0000362 // Update the SUnit.
363 NodeSUnit->setNode(N);
364 assert(N->getNodeId() == -1 && "Node already inserted!");
365 N->setNodeId(NodeSUnit->NodeNum);
366
Andrew Trick92e94662011-02-04 03:18:17 +0000367 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
368 InitNumRegDefsLeft(NodeSUnit);
369
Dan Gohman787782f2008-11-21 01:44:51 +0000370 // Assign the Latency field of NodeSUnit using target-provided information.
Andrew Trick953be892012-03-07 23:00:49 +0000371 computeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000372 }
Evan Cheng554daa62011-04-26 21:31:35 +0000373
374 // Find all call operands.
375 while (!CallSUnits.empty()) {
376 SUnit *SU = CallSUnits.pop_back_val();
377 for (const SDNode *SUNode = SU->getNode(); SUNode;
378 SUNode = SUNode->getGluedNode()) {
379 if (SUNode->getOpcode() != ISD::CopyToReg)
380 continue;
381 SDNode *SrcN = SUNode->getOperand(2).getNode();
382 if (isPassiveNode(SrcN)) continue; // Not scheduled.
383 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
384 SrcSU->isCallOp = true;
385 }
386 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000387}
388
389void ScheduleDAGSDNodes::AddSchedEdges() {
Evan Cheng5b1b44892011-07-01 21:01:15 +0000390 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
David Goodwin71046162009-08-13 16:05:04 +0000391
David Goodwindc4bdcd2009-08-19 16:08:58 +0000392 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000393 bool UnitLatencies = forceUnitLatencies();
David Goodwindc4bdcd2009-08-19 16:08:58 +0000394
Dan Gohman343f0c02008-11-19 23:18:57 +0000395 // Pass 2: add the preds, succs, etc.
396 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
397 SUnit *SU = &SUnits[su];
398 SDNode *MainNode = SU->getNode();
Andrew Trickcd5af072011-02-03 23:00:17 +0000399
Dan Gohman343f0c02008-11-19 23:18:57 +0000400 if (MainNode->isMachineOpcode()) {
401 unsigned Opc = MainNode->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000402 const MCInstrDesc &MCID = TII->get(Opc);
403 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
404 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000405 SU->isTwoAddress = true;
406 break;
407 }
408 }
Evan Chenge837dea2011-06-28 19:10:37 +0000409 if (MCID.isCommutable())
Dan Gohman343f0c02008-11-19 23:18:57 +0000410 SU->isCommutable = true;
411 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000412
Dan Gohman343f0c02008-11-19 23:18:57 +0000413 // Find all predecessors and successors of the group.
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000414 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000415 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000416 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
417 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000418 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000419 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
420 --NumUsed; // Skip over unused values at the end.
421 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000422 SU->hasPhysRegDefs = true;
423 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000424
Dan Gohman343f0c02008-11-19 23:18:57 +0000425 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
426 SDNode *OpN = N->getOperand(i).getNode();
427 if (isPassiveNode(OpN)) continue; // Not scheduled.
428 SUnit *OpSU = &SUnits[OpN->getNodeId()];
429 assert(OpSU && "Node has no SUnit!");
430 if (OpSU == SU) continue; // In the same group.
431
Owen Andersone50ed302009-08-10 22:56:29 +0000432 EVT OpVT = N->getOperand(i).getValueType();
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000433 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000434 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000435
436 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000437 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000438 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000439 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000440 assert((PhysReg == 0 || !isChain) &&
441 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000442 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
443 // emits a copy from the physical register to a virtual register unless
444 // it requires a cross class copy (cost < 0). That means we are only
445 // treating "expensive to copy" register dependency as physical register
446 // dependency. This may change in the future though.
Andrew Trick4cb971c2011-06-15 17:16:12 +0000447 if (Cost >= 0 && !StressSched)
Evan Chengc29a56d2009-01-12 03:19:55 +0000448 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000449
Evan Cheng046fa3f2010-05-28 23:26:21 +0000450 // If this is a ctrl dep, latency is 1.
Andrew Trickc558bf32011-04-12 20:14:07 +0000451 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
Andrew Trick87896d92011-04-13 00:38:32 +0000452 // Special-case TokenFactor chains as zero-latency.
453 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
454 OpLatency = 0;
455
Evan Cheng046fa3f2010-05-28 23:26:21 +0000456 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
457 OpLatency, PhysReg);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000458 if (!isChain && !UnitLatencies) {
Andrew Trick953be892012-03-07 23:00:49 +0000459 computeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
Dan Gohman3fb150a2010-04-17 17:42:52 +0000460 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
David Goodwindc4bdcd2009-08-19 16:08:58 +0000461 }
David Goodwin71046162009-08-13 16:05:04 +0000462
Andrew Trick4bbf4672011-03-09 19:12:43 +0000463 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
Andrew Trick92e94662011-02-04 03:18:17 +0000464 // Multiple register uses are combined in the same SUnit. For example,
465 // we could have a set of glued nodes with all their defs consumed by
466 // another set of glued nodes. Register pressure tracking sees this as
467 // a single use, so to keep pressure balanced we reduce the defs.
Andrew Trick4bbf4672011-03-09 19:12:43 +0000468 //
469 // We can't tell (without more book-keeping) if this results from
470 // glued nodes or duplicate operands. As long as we don't reduce
471 // NumRegDefsLeft to zero, we handle the common cases well.
Andrew Trick92e94662011-02-04 03:18:17 +0000472 --OpSU->NumRegDefsLeft;
473 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000474 }
475 }
476 }
477}
478
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000479/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
480/// are input. This SUnit graph is similar to the SelectionDAG, but
481/// excludes nodes that aren't interesting to scheduling, and represents
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000482/// glued together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000483void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng302ef832010-06-10 02:09:31 +0000484 // Cluster certain nodes which should be scheduled together.
485 ClusterNodes();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000486 // Populate the SUnits array.
487 BuildSchedUnits();
488 // Compute all the scheduling dependencies between nodes.
489 AddSchedEdges();
490}
491
Andrew Trick92e94662011-02-04 03:18:17 +0000492// Initialize NumNodeDefs for the current Node's opcode.
493void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
Eric Christopher29449442011-03-08 19:35:47 +0000494 // Check for phys reg copy.
495 if (!Node)
496 return;
497
Andrew Trick92e94662011-02-04 03:18:17 +0000498 if (!Node->isMachineOpcode()) {
499 if (Node->getOpcode() == ISD::CopyFromReg)
500 NodeNumDefs = 1;
501 else
502 NodeNumDefs = 0;
503 return;
504 }
505 unsigned POpc = Node->getMachineOpcode();
506 if (POpc == TargetOpcode::IMPLICIT_DEF) {
507 // No register need be allocated for this.
508 NodeNumDefs = 0;
509 return;
510 }
511 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
512 // Some instructions define regs that are not represented in the selection DAG
513 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
514 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
515 DefIdx = 0;
516}
517
518// Construct a RegDefIter for this SUnit and find the first valid value.
519ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
520 const ScheduleDAGSDNodes *SD)
521 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
522 InitNodeNumDefs();
523 Advance();
524}
525
526// Advance to the next valid value defined by the SUnit.
527void ScheduleDAGSDNodes::RegDefIter::Advance() {
528 for (;Node;) { // Visit all glued nodes.
529 for (;DefIdx < NodeNumDefs; ++DefIdx) {
530 if (!Node->hasAnyUseOfValue(DefIdx))
531 continue;
Andrew Trick4ef4c172011-06-27 18:01:20 +0000532 ValueType = Node->getValueType(DefIdx);
Andrew Trick92e94662011-02-04 03:18:17 +0000533 ++DefIdx;
534 return; // Found a normal regdef.
535 }
536 Node = Node->getGluedNode();
537 if (Node == NULL) {
538 return; // No values left to visit.
539 }
540 InitNodeNumDefs();
541 }
542}
543
544void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
545 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
546 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
547 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
548 ++SU->NumRegDefsLeft;
549 }
550}
551
Andrew Trick953be892012-03-07 23:00:49 +0000552void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
Andrew Trick87896d92011-04-13 00:38:32 +0000553 SDNode *N = SU->getNode();
554
555 // TokenFactor operands are considered zero latency, and some schedulers
556 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
557 // whenever node latency is nonzero.
558 if (N && N->getOpcode() == ISD::TokenFactor) {
559 SU->Latency = 0;
560 return;
561 }
562
Evan Chenge1631682010-05-19 22:42:23 +0000563 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000564 if (forceUnitLatencies()) {
Evan Chenge1631682010-05-19 22:42:23 +0000565 SU->Latency = 1;
566 return;
567 }
568
Evan Cheng3ef1c872010-09-10 01:29:16 +0000569 if (!InstrItins || InstrItins->isEmpty()) {
Andrew Trick5e84e3c2011-03-05 09:18:16 +0000570 if (N && N->isMachineOpcode() &&
571 TII->isHighLatencyDef(N->getMachineOpcode()))
Andrew Tricke0ef5092011-03-05 08:00:22 +0000572 SU->Latency = HighLatencyCycles;
573 else
574 SU->Latency = 1;
Evan Cheng15a16de2010-05-20 06:13:19 +0000575 return;
576 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000577
Dan Gohman343f0c02008-11-19 23:18:57 +0000578 // Compute the latency for the node. We use the sum of the latencies for
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000579 // all nodes glued together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000580 SU->Latency = 0;
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000581 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
Evan Cheng8239daf2010-11-03 00:45:17 +0000582 if (N->isMachineOpcode())
583 SU->Latency += TII->getInstrLatency(InstrItins, N);
Dan Gohman343f0c02008-11-19 23:18:57 +0000584}
585
Andrew Trick953be892012-03-07 23:00:49 +0000586void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
Evan Cheng15a16de2010-05-20 06:13:19 +0000587 unsigned OpIdx, SDep& dep) const{
588 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000589 if (forceUnitLatencies())
Evan Cheng15a16de2010-05-20 06:13:19 +0000590 return;
591
Evan Cheng15a16de2010-05-20 06:13:19 +0000592 if (dep.getKind() != SDep::Data)
593 return;
594
595 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng7e2fe912010-10-28 06:47:08 +0000596 if (Use->isMachineOpcode())
597 // Adjust the use operand index by num of defs.
598 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
Evan Chenga0792de2010-10-06 06:27:31 +0000599 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
Evan Cheng08975152010-10-29 18:09:28 +0000600 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
601 !BB->succ_empty()) {
602 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
603 if (TargetRegisterInfo::isVirtualRegister(Reg))
604 // This copy is a liveout value. It is likely coalesced, so reduce the
605 // latency so not to penalize the def.
606 // FIXME: need target specific adjustment here?
607 Latency = (Latency > 1) ? Latency - 1 : 1;
608 }
Evan Cheng3881cb72010-09-29 22:42:35 +0000609 if (Latency >= 0)
610 dep.setLatency(Latency);
Evan Cheng15a16de2010-05-20 06:13:19 +0000611}
612
Dan Gohman343f0c02008-11-19 23:18:57 +0000613void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Evan Chengc29a56d2009-01-12 03:19:55 +0000614 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000615 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000616 return;
617 }
618
619 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000620 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000621 SmallVector<SDNode *, 4> GluedNodes;
622 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
623 GluedNodes.push_back(N);
624 while (!GluedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000625 dbgs() << " ";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000626 GluedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000627 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000628 GluedNodes.pop_back();
Dan Gohman343f0c02008-11-19 23:18:57 +0000629 }
630}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000631
Andrew Trick73ba69b2012-03-07 05:21:40 +0000632void ScheduleDAGSDNodes::dumpSchedule() const {
633 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
634 if (SUnit *SU = Sequence[i])
635 SU->dump(this);
636 else
637 dbgs() << "**** NOOP ****\n";
638 }
639}
640
Andrew Trick4c727202012-03-07 05:21:36 +0000641#ifndef NDEBUG
642/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
643/// their state is consistent with the nodes listed in Sequence.
644///
645void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
646 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
647 unsigned Noops = 0;
648 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
649 if (!Sequence[i])
650 ++Noops;
651 assert(Sequence.size() - Noops == ScheduledNodes &&
652 "The number of nodes scheduled doesn't match the expected number!");
653}
654#endif // NDEBUG
655
Evan Chengbfcb3052010-03-25 01:38:16 +0000656namespace {
657 struct OrderSorter {
658 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
659 const std::pair<unsigned, MachineInstr*> &B) {
660 return A.first < B.first;
661 }
662 };
663}
664
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000665/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
Andrew Trickcd5af072011-02-03 23:00:17 +0000666static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
Devang Patel55d20e82011-01-26 18:20:04 +0000667 InstrEmitter &Emitter,
668 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
669 DenseMap<SDValue, unsigned> &VRBaseMap,
670 unsigned Order) {
671 if (!N->getHasDebugValue())
672 return;
673
674 // Opportunistically insert immediate dbg_value uses, i.e. those with source
675 // order number right after the N.
676 MachineBasicBlock *BB = Emitter.getBlock();
677 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
Benjamin Kramer22a54c12011-06-18 13:13:44 +0000678 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
Devang Patel55d20e82011-01-26 18:20:04 +0000679 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
680 if (DVs[i]->isInvalidated())
681 continue;
682 unsigned DVOrder = DVs[i]->getOrder();
683 if (!Order || DVOrder == ++Order) {
684 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
685 if (DbgMI) {
686 Orders.push_back(std::make_pair(DVOrder, DbgMI));
687 BB->insert(InsertPos, DbgMI);
688 }
689 DVs[i]->setIsInvalidated();
690 }
691 }
692}
693
Evan Chengbfcb3052010-03-25 01:38:16 +0000694// ProcessSourceNode - Process nodes with source order numbers. These are added
Jim Grosbachd27946d2010-06-30 21:27:56 +0000695// to a vector which EmitSchedule uses to determine how to insert dbg_value
Evan Chengbfcb3052010-03-25 01:38:16 +0000696// instructions in the right order.
697static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
698 InstrEmitter &Emitter,
Evan Chengbfcb3052010-03-25 01:38:16 +0000699 DenseMap<SDValue, unsigned> &VRBaseMap,
700 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
701 SmallSet<unsigned, 8> &Seen) {
702 unsigned Order = DAG->GetOrdering(N);
Devang Patel39078a82011-01-27 00:13:27 +0000703 if (!Order || !Seen.insert(Order)) {
704 // Process any valid SDDbgValues even if node does not have any order
705 // assigned.
706 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
Evan Chengbfcb3052010-03-25 01:38:16 +0000707 return;
Devang Patel39078a82011-01-27 00:13:27 +0000708 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000709
710 MachineBasicBlock *BB = Emitter.getBlock();
Dan Gohman84023e02010-07-10 09:00:22 +0000711 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000712 // Did not insert any instruction.
713 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
714 return;
715 }
716
Dan Gohman84023e02010-07-10 09:00:22 +0000717 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
Devang Patel55d20e82011-01-26 18:20:04 +0000718 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
Evan Chengbfcb3052010-03-25 01:38:16 +0000719}
720
Andrew Trick84b454d2012-03-07 05:21:44 +0000721void ScheduleDAGSDNodes::
722EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
723 MachineBasicBlock::iterator InsertPos) {
724 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
725 I != E; ++I) {
726 if (I->isCtrl()) continue; // ignore chain preds
727 if (I->getSUnit()->CopyDstRC) {
728 // Copy to physical register.
729 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
730 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
731 // Find the destination physical register.
732 unsigned Reg = 0;
733 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
734 EE = SU->Succs.end(); II != EE; ++II) {
735 if (II->isCtrl()) continue; // ignore chain preds
736 if (II->getReg()) {
737 Reg = II->getReg();
738 break;
739 }
740 }
741 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
742 .addReg(VRI->second);
743 } else {
744 // Copy from physical register.
745 assert(I->getReg() && "Unknown physical register!");
746 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
747 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
748 (void)isNew; // Silence compiler warning.
749 assert(isNew && "Node emitted out of order - early");
750 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
751 .addReg(I->getReg());
752 }
753 break;
754 }
755}
Evan Chengbfcb3052010-03-25 01:38:16 +0000756
Andrew Trick84b454d2012-03-07 05:21:44 +0000757/// EmitSchedule - Emit the machine code in scheduled order. Return the new
758/// InsertPos and MachineBasicBlock that contains this insertion
759/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
760/// not necessarily refer to returned BB. The emitter may split blocks.
Andrew Trick47c14452012-03-07 05:21:52 +0000761MachineBasicBlock *ScheduleDAGSDNodes::
762EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000763 InstrEmitter Emitter(BB, InsertPos);
764 DenseMap<SDValue, unsigned> VRBaseMap;
765 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000766 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
767 SmallSet<unsigned, 8> Seen;
768 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000769
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000770 // If this is the first BB, emit byval parameter dbg_value's.
771 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
772 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
773 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
774 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000775 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000776 if (DbgMI)
Dan Gohman84023e02010-07-10 09:00:22 +0000777 BB->insert(InsertPos, DbgMI);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000778 }
779 }
780
Dan Gohmanbcea8592009-10-10 01:32:21 +0000781 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
782 SUnit *SU = Sequence[i];
783 if (!SU) {
784 // Null SUnit* is a noop.
Andrew Trick84b454d2012-03-07 05:21:44 +0000785 TII->insertNoop(*Emitter.getBlock(), InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000786 continue;
787 }
788
789 // For pre-regalloc scheduling, create instructions corresponding to the
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000790 // SDNode and any glued SDNodes and append them to the block.
Dan Gohmanbcea8592009-10-10 01:32:21 +0000791 if (!SU->getNode()) {
792 // Emit a copy.
Andrew Trick84b454d2012-03-07 05:21:44 +0000793 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000794 continue;
795 }
796
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000797 SmallVector<SDNode *, 4> GluedNodes;
798 for (SDNode *N = SU->getNode()->getGluedNode(); N;
799 N = N->getGluedNode())
800 GluedNodes.push_back(N);
801 while (!GluedNodes.empty()) {
802 SDNode *N = GluedNodes.back();
803 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000804 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000805 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000806 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000807 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000808 GluedNodes.pop_back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000809 }
810 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000811 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000812 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000813 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000814 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000815 Seen);
816 }
817
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000818 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000819 // order sequence.
820 if (HasDbg) {
Dan Gohman84023e02010-07-10 09:00:22 +0000821 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
Evan Chengbfcb3052010-03-25 01:38:16 +0000822
823 // Sort the source order instructions and use the order to insert debug
824 // values.
825 std::sort(Orders.begin(), Orders.end(), OrderSorter());
826
827 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
828 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
829 // Now emit the rest according to source order.
830 unsigned LastOrder = 0;
Evan Chengbfcb3052010-03-25 01:38:16 +0000831 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
832 unsigned Order = Orders[i].first;
833 MachineInstr *MI = Orders[i].second;
834 // Insert all SDDbgValue's whose order(s) are before "Order".
835 if (!MI)
836 continue;
Evan Chengbfcb3052010-03-25 01:38:16 +0000837 for (; DI != DE &&
838 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
839 if ((*DI)->isInvalidated())
840 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000841 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000842 if (DbgMI) {
843 if (!LastOrder)
844 // Insert to start of the BB (after PHIs).
845 BB->insert(BBBegin, DbgMI);
846 else {
Dan Gohmana8dab362010-07-10 22:42:31 +0000847 // Insert at the instruction, which may be in a different
848 // block, if the block was split by a custom inserter.
Evan Cheng962021b2010-04-26 07:38:55 +0000849 MachineBasicBlock::iterator Pos = MI;
Dan Gohmana8dab362010-07-10 22:42:31 +0000850 MI->getParent()->insert(llvm::next(Pos), DbgMI);
Evan Cheng962021b2010-04-26 07:38:55 +0000851 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000852 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000853 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000854 LastOrder = Order;
Evan Chengbfcb3052010-03-25 01:38:16 +0000855 }
856 // Add trailing DbgValue's before the terminator. FIXME: May want to add
857 // some of them before one or more conditional branches?
Bill Wendling7bf116a2012-03-14 07:14:25 +0000858 SmallVector<MachineInstr*, 8> DbgMIs;
Evan Chengbfcb3052010-03-25 01:38:16 +0000859 while (DI != DE) {
Bill Wendling7bf116a2012-03-14 07:14:25 +0000860 if (!(*DI)->isInvalidated())
861 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
862 DbgMIs.push_back(DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000863 ++DI;
864 }
Bill Wendling7bf116a2012-03-14 07:14:25 +0000865
866 MachineBasicBlock *InsertBB = Emitter.getBlock();
867 MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
868 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
Dan Gohmanbcea8592009-10-10 01:32:21 +0000869 }
870
Dan Gohmanbcea8592009-10-10 01:32:21 +0000871 InsertPos = Emitter.getInsertPos();
Andrew Trick47c14452012-03-07 05:21:52 +0000872 return Emitter.getBlock();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000873}
Andrew Trick56b94c52012-03-07 00:18:22 +0000874
875/// Return the basic block label.
876std::string ScheduleDAGSDNodes::getDAGName() const {
877 return "sunit-dag." + BB->getFullName();
878}