1 //===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ScheduleDAG class, which is used as the common
11 // base class for SelectionDAG-based instruction scheduler.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_SCHEDULEDAG_H
16 #define LLVM_CODEGEN_SCHEDULEDAG_H
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/GraphTraits.h"
22 #include "llvm/ADT/SmallSet.h"
26 class MachineConstantPool;
27 class MachineFunction;
28 class MachineModuleInfo;
29 class MachineRegisterInfo;
31 class TargetRegisterInfo;
34 class SelectionDAGISel;
35 class TargetInstrInfo;
36 class TargetInstrDesc;
39 class TargetRegisterClass;
41 /// HazardRecognizer - This determines whether or not an instruction can be
42 /// issued this cycle, and whether or not a noop needs to be inserted to handle
44 class HazardRecognizer {
46 virtual ~HazardRecognizer();
49 NoHazard, // This instruction can be emitted at this cycle.
50 Hazard, // This instruction can't be emitted at this cycle.
51 NoopHazard // This instruction can't be emitted, and needs noops.
54 /// getHazardType - Return the hazard type of emitting this node. There are
55 /// three possible results. Either:
56 /// * NoHazard: it is legal to issue this instruction on this cycle.
57 /// * Hazard: issuing this instruction would stall the machine. If some
58 /// other instruction is available, issue it first.
59 /// * NoopHazard: issuing this instruction would break the program. If
60 /// some other instruction can be issued, do so, otherwise issue a noop.
61 virtual HazardType getHazardType(SDNode *) {
65 /// EmitInstruction - This callback is invoked when an instruction is
66 /// emitted, to advance the hazard state.
67 virtual void EmitInstruction(SDNode *) {}
69 /// AdvanceCycle - This callback is invoked when no instructions can be
70 /// issued on this cycle without a hazard. This should increment the
71 /// internal state of the hazard recognizer so that previously "Hazard"
72 /// instructions will now not be hazards.
73 virtual void AdvanceCycle() {}
75 /// EmitNoop - This callback is invoked when a noop was added to the
76 /// instruction stream.
77 virtual void EmitNoop() {}
80 /// SDep - Scheduling dependency. It keeps track of dependent nodes,
81 /// cost of the depdenency, etc.
83 SUnit *Dep; // Dependent - either a predecessor or a successor.
84 unsigned Reg; // If non-zero, this dep is a phy register dependency.
85 int Cost; // Cost of the dependency.
86 bool isCtrl : 1; // True iff it's a control dependency.
87 bool isSpecial : 1; // True iff it's a special ctrl dep added during sched.
88 SDep(SUnit *d, unsigned r, int t, bool c, bool s)
89 : Dep(d), Reg(r), Cost(t), isCtrl(c), isSpecial(s) {}
92 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
93 /// a group of nodes flagged together.
96 SDNode *Node; // Representative node.
97 MachineInstr *Instr; // Alternatively, a MachineInstr.
99 SUnit *OrigNode; // If not this, the node from which
100 // this node was cloned.
102 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
103 // is true if the edge is a token chain edge, false if it is a value edge.
104 SmallVector<SDep, 4> Preds; // All sunit predecessors.
105 SmallVector<SDep, 4> Succs; // All sunit successors.
107 typedef SmallVector<SDep, 4>::iterator pred_iterator;
108 typedef SmallVector<SDep, 4>::iterator succ_iterator;
109 typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
110 typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
112 unsigned NodeNum; // Entry # of node in the node vector.
113 unsigned NodeQueueId; // Queue id of node.
114 unsigned short Latency; // Node latency.
115 short NumPreds; // # of non-control preds.
116 short NumSuccs; // # of non-control sucss.
117 short NumPredsLeft; // # of preds not scheduled.
118 short NumSuccsLeft; // # of succs not scheduled.
119 bool isTwoAddress : 1; // Is a two-address instruction.
120 bool isCommutable : 1; // Is a commutable instruction.
121 bool hasPhysRegDefs : 1; // Has physreg defs that are being used.
122 bool isPending : 1; // True once pending.
123 bool isAvailable : 1; // True once available.
124 bool isScheduled : 1; // True once scheduled.
125 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
126 unsigned Cycle; // Once scheduled, the cycle of the op.
127 unsigned Depth; // Node depth;
128 unsigned Height; // Node height;
129 const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
130 const TargetRegisterClass *CopySrcRC;
132 /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
133 /// an SDNode and any nodes flagged to it.
134 SUnit(SDNode *node, unsigned nodenum)
135 : Node(node), Instr(0), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
136 Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
137 isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
138 isPending(false), isAvailable(false), isScheduled(false),
139 CycleBound(0), Cycle(0), Depth(0), Height(0),
140 CopyDstRC(NULL), CopySrcRC(NULL) {}
142 /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
144 SUnit(MachineInstr *instr, unsigned nodenum)
145 : Node(0), Instr(instr), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
146 Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
147 isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
148 isPending(false), isAvailable(false), isScheduled(false),
149 CycleBound(0), Cycle(0), Depth(0), Height(0),
150 CopyDstRC(NULL), CopySrcRC(NULL) {}
152 /// setNode - Assign the representative SDNode for this SUnit.
153 /// This may be used during pre-regalloc scheduling.
154 void setNode(SDNode *N) {
155 assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
159 /// getNode - Return the representative SDNode for this SUnit.
160 /// This may be used during pre-regalloc scheduling.
161 SDNode *getNode() const {
162 assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
166 /// setInstr - Assign the instruction for the SUnit.
167 /// This may be used during post-regalloc scheduling.
168 void setInstr(MachineInstr *MI) {
169 assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
173 /// getInstr - Return the representative MachineInstr for this SUnit.
174 /// This may be used during post-regalloc scheduling.
175 MachineInstr *getInstr() const {
176 assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
180 /// addPred - This adds the specified node as a pred of the current node if
181 /// not already. This returns true if this is a new pred.
182 bool addPred(SUnit *N, bool isCtrl, bool isSpecial,
183 unsigned PhyReg = 0, int Cost = 1) {
184 for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
185 if (Preds[i].Dep == N &&
186 Preds[i].isCtrl == isCtrl && Preds[i].isSpecial == isSpecial)
188 Preds.push_back(SDep(N, PhyReg, Cost, isCtrl, isSpecial));
189 N->Succs.push_back(SDep(this, PhyReg, Cost, isCtrl, isSpecial));
201 bool removePred(SUnit *N, bool isCtrl, bool isSpecial) {
202 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
204 if (I->Dep == N && I->isCtrl == isCtrl && I->isSpecial == isSpecial) {
205 bool FoundSucc = false;
206 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
207 EE = N->Succs.end(); II != EE; ++II)
208 if (II->Dep == this &&
209 II->isCtrl == isCtrl && II->isSpecial == isSpecial) {
214 assert(FoundSucc && "Mismatching preds / succs lists!");
229 bool isPred(SUnit *N) {
230 for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
231 if (Preds[i].Dep == N)
236 bool isSucc(SUnit *N) {
237 for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
238 if (Succs[i].Dep == N)
243 void dump(const ScheduleDAG *G) const;
244 void dumpAll(const ScheduleDAG *G) const;
247 //===--------------------------------------------------------------------===//
248 /// SchedulingPriorityQueue - This interface is used to plug different
249 /// priorities computation algorithms into the list scheduler. It implements
250 /// the interface of a standard priority queue, where nodes are inserted in
251 /// arbitrary order and returned in priority order. The computation of the
252 /// priority and the representation of the queue are totally up to the
253 /// implementation to decide.
255 class SchedulingPriorityQueue {
257 virtual ~SchedulingPriorityQueue() {}
259 virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
260 virtual void addNode(const SUnit *SU) = 0;
261 virtual void updateNode(const SUnit *SU) = 0;
262 virtual void releaseState() = 0;
264 virtual unsigned size() const = 0;
265 virtual bool empty() const = 0;
266 virtual void push(SUnit *U) = 0;
268 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
269 virtual SUnit *pop() = 0;
271 virtual void remove(SUnit *SU) = 0;
273 /// ScheduledNode - As each node is scheduled, this method is invoked. This
274 /// allows the priority function to adjust the priority of related
275 /// unscheduled nodes, for example.
277 virtual void ScheduledNode(SUnit *) {}
279 virtual void UnscheduledNode(SUnit *) {}
284 SelectionDAG *DAG; // DAG of the current basic block
285 MachineBasicBlock *BB; // Current basic block
286 const TargetMachine &TM; // Target processor
287 const TargetInstrInfo *TII; // Target instruction information
288 const TargetRegisterInfo *TRI; // Target processor register info
289 TargetLowering *TLI; // Target lowering info
290 MachineFunction *MF; // Machine function
291 MachineRegisterInfo &MRI; // Virtual/real register map
292 MachineConstantPool *ConstPool; // Target constant pool
293 std::vector<SUnit*> Sequence; // The schedule. Null SUnit*'s
294 // represent noop instructions.
295 std::vector<SUnit> SUnits; // The scheduling units.
296 SmallSet<SDNode*, 16> CommuteSet; // Nodes that should be commuted.
298 ScheduleDAG(SelectionDAG *dag, MachineBasicBlock *bb,
299 const TargetMachine &tm);
301 virtual ~ScheduleDAG() {}
303 /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
308 /// Run - perform scheduling.
312 /// isPassiveNode - Return true if the node is a non-scheduled leaf.
314 static bool isPassiveNode(SDNode *Node) {
315 if (isa<ConstantSDNode>(Node)) return true;
316 if (isa<ConstantFPSDNode>(Node)) return true;
317 if (isa<RegisterSDNode>(Node)) return true;
318 if (isa<GlobalAddressSDNode>(Node)) return true;
319 if (isa<BasicBlockSDNode>(Node)) return true;
320 if (isa<FrameIndexSDNode>(Node)) return true;
321 if (isa<ConstantPoolSDNode>(Node)) return true;
322 if (isa<JumpTableSDNode>(Node)) return true;
323 if (isa<ExternalSymbolSDNode>(Node)) return true;
324 if (isa<MemOperandSDNode>(Node)) return true;
325 if (Node->getOpcode() == ISD::EntryToken) return true;
329 /// NewSUnit - Creates a new SUnit and return a ptr to it.
331 SUnit *NewSUnit(SDNode *N) {
332 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
333 SUnits.back().OrigNode = &SUnits.back();
334 return &SUnits.back();
337 /// NewSUnit - Creates a new SUnit and return a ptr to it.
339 SUnit *NewSUnit(MachineInstr *MI) {
340 SUnits.push_back(SUnit(MI, (unsigned)SUnits.size()));
341 SUnits.back().OrigNode = &SUnits.back();
342 return &SUnits.back();
345 /// Clone - Creates a clone of the specified SUnit. It does not copy the
346 /// predecessors / successors info nor the temporary scheduling states.
347 SUnit *Clone(SUnit *N);
349 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
350 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
351 /// together nodes with a single SUnit.
352 void BuildSchedUnits();
354 /// ComputeLatency - Compute node latency.
356 void ComputeLatency(SUnit *SU);
358 /// CalculateDepths, CalculateHeights - Calculate node depth / height.
360 void CalculateDepths();
361 void CalculateHeights();
363 /// CountResults - The results of target nodes have register or immediate
364 /// operands first, then an optional chain, and optional flag operands
365 /// (which do not go into the machine instrs.)
366 static unsigned CountResults(SDNode *Node);
368 /// CountOperands - The inputs to target nodes have any actual inputs first,
369 /// followed by special operands that describe memory references, then an
370 /// optional chain operand, then flag operands. Compute the number of
371 /// actual operands that will go into the resulting MachineInstr.
372 static unsigned CountOperands(SDNode *Node);
374 /// ComputeMemOperandsEnd - Find the index one past the last
375 /// MemOperandSDNode operand
376 static unsigned ComputeMemOperandsEnd(SDNode *Node);
378 /// EmitNode - Generate machine code for an node and needed dependencies.
379 /// VRBaseMap contains, for each already emitted node, the first virtual
380 /// register number for the results of the node.
382 void EmitNode(SDNode *Node, bool IsClone,
383 DenseMap<SDValue, unsigned> &VRBaseMap);
385 /// EmitNoop - Emit a noop instruction.
389 MachineBasicBlock *EmitSchedule();
391 void dumpSchedule() const;
393 /// Schedule - Order nodes according to selected style, filling
394 /// in the Sequence member.
396 virtual void Schedule() = 0;
399 /// EmitSubregNode - Generate machine code for subreg nodes.
401 void EmitSubregNode(SDNode *Node,
402 DenseMap<SDValue, unsigned> &VRBaseMap);
404 /// getVR - Return the virtual register corresponding to the specified result
405 /// of the specified node.
406 unsigned getVR(SDValue Op, DenseMap<SDValue, unsigned> &VRBaseMap);
408 /// getDstOfCopyToRegUse - If the only use of the specified result number of
409 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
410 unsigned getDstOfOnlyCopyToRegUse(SDNode *Node, unsigned ResNo) const;
412 void AddOperand(MachineInstr *MI, SDValue Op, unsigned IIOpNum,
413 const TargetInstrDesc *II,
414 DenseMap<SDValue, unsigned> &VRBaseMap);
415 void AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO);
417 void EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
419 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
420 /// implicit physical register output.
421 void EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone,
423 DenseMap<SDValue, unsigned> &VRBaseMap);
425 void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
426 const TargetInstrDesc &II,
427 DenseMap<SDValue, unsigned> &VRBaseMap);
429 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
430 /// physical register has only a single copy use, then coalesced the copy
432 void EmitLiveInCopy(MachineBasicBlock *MBB,
433 MachineBasicBlock::iterator &InsertPos,
434 unsigned VirtReg, unsigned PhysReg,
435 const TargetRegisterClass *RC,
436 DenseMap<MachineInstr*, unsigned> &CopyRegMap);
438 /// EmitLiveInCopies - If this is the first basic block in the function,
439 /// and if it has live ins that need to be copied into vregs, emit the
440 /// copies into the top of the block.
441 void EmitLiveInCopies(MachineBasicBlock *MBB);
443 /// BuildSchedUnitsFromMBB - Build SUnits from the MachineBasicBlock.
444 /// This SUnit graph is similar to the pre-regalloc SUnit graph, but represents
445 /// MachineInstrs directly instead of SDNodes.
446 void BuildSchedUnitsFromMBB();
449 /// createBURRListDAGScheduler - This creates a bottom up register usage
450 /// reduction list scheduler.
451 ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
453 const TargetMachine *TM,
454 MachineBasicBlock *BB,
457 /// createTDRRListDAGScheduler - This creates a top down register usage
458 /// reduction list scheduler.
459 ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
461 const TargetMachine *TM,
462 MachineBasicBlock *BB,
465 /// createTDListDAGScheduler - This creates a top-down list scheduler with
466 /// a hazard recognizer.
467 ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
469 const TargetMachine *TM,
470 MachineBasicBlock *BB,
473 /// createFastDAGScheduler - This creates a "fast" scheduler.
475 ScheduleDAG *createFastDAGScheduler(SelectionDAGISel *IS,
477 const TargetMachine *TM,
478 MachineBasicBlock *BB,
481 /// createDefaultScheduler - This creates an instruction scheduler appropriate
483 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
485 const TargetMachine *TM,
486 MachineBasicBlock *BB,
489 class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
493 SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
495 bool operator==(const SUnitIterator& x) const {
496 return Operand == x.Operand;
498 bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
500 const SUnitIterator &operator=(const SUnitIterator &I) {
501 assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
506 pointer operator*() const {
507 return Node->Preds[Operand].Dep;
509 pointer operator->() const { return operator*(); }
511 SUnitIterator& operator++() { // Preincrement
515 SUnitIterator operator++(int) { // Postincrement
516 SUnitIterator tmp = *this; ++*this; return tmp;
519 static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
520 static SUnitIterator end (SUnit *N) {
521 return SUnitIterator(N, (unsigned)N->Preds.size());
524 unsigned getOperand() const { return Operand; }
525 const SUnit *getNode() const { return Node; }
526 bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
527 bool isSpecialDep() const { return Node->Preds[Operand].isSpecial; }
530 template <> struct GraphTraits<SUnit*> {
531 typedef SUnit NodeType;
532 typedef SUnitIterator ChildIteratorType;
533 static inline NodeType *getEntryNode(SUnit *N) { return N; }
534 static inline ChildIteratorType child_begin(NodeType *N) {
535 return SUnitIterator::begin(N);
537 static inline ChildIteratorType child_end(NodeType *N) {
538 return SUnitIterator::end(N);
542 template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
543 typedef std::vector<SUnit>::iterator nodes_iterator;
544 static nodes_iterator nodes_begin(ScheduleDAG *G) {
545 return G->SUnits.begin();
547 static nodes_iterator nodes_end(ScheduleDAG *G) {
548 return G->SUnits.end();