ScheduleDAG.h revision b1e07ec6a43383ce0baa42e2f139550cc540f631
1//===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===// 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 file implements the ScheduleDAG class, which is used as the common 11// base class for SelectionDAG-based instruction scheduler. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_CODEGEN_SCHEDULEDAG_H 16#define LLVM_CODEGEN_SCHEDULEDAG_H 17 18#include "llvm/CodeGen/MachineBasicBlock.h" 19#include "llvm/CodeGen/SelectionDAG.h" 20#include "llvm/ADT/BitVector.h" 21#include "llvm/ADT/DenseMap.h" 22#include "llvm/ADT/GraphTraits.h" 23#include "llvm/ADT/SmallSet.h" 24 25namespace llvm { 26 struct InstrStage; 27 struct SUnit; 28 class MachineConstantPool; 29 class MachineFunction; 30 class MachineModuleInfo; 31 class MachineRegisterInfo; 32 class MachineInstr; 33 class TargetRegisterInfo; 34 class SelectionDAG; 35 class SelectionDAGISel; 36 class TargetInstrInfo; 37 class TargetInstrDesc; 38 class TargetLowering; 39 class TargetMachine; 40 class TargetRegisterClass; 41 42 /// HazardRecognizer - This determines whether or not an instruction can be 43 /// issued this cycle, and whether or not a noop needs to be inserted to handle 44 /// the hazard. 45 class HazardRecognizer { 46 public: 47 virtual ~HazardRecognizer(); 48 49 enum HazardType { 50 NoHazard, // This instruction can be emitted at this cycle. 51 Hazard, // This instruction can't be emitted at this cycle. 52 NoopHazard // This instruction can't be emitted, and needs noops. 53 }; 54 55 /// getHazardType - Return the hazard type of emitting this node. There are 56 /// three possible results. Either: 57 /// * NoHazard: it is legal to issue this instruction on this cycle. 58 /// * Hazard: issuing this instruction would stall the machine. If some 59 /// other instruction is available, issue it first. 60 /// * NoopHazard: issuing this instruction would break the program. If 61 /// some other instruction can be issued, do so, otherwise issue a noop. 62 virtual HazardType getHazardType(SDNode *Node) { 63 return NoHazard; 64 } 65 66 /// EmitInstruction - This callback is invoked when an instruction is 67 /// emitted, to advance the hazard state. 68 virtual void EmitInstruction(SDNode *Node) { 69 } 70 71 /// AdvanceCycle - This callback is invoked when no instructions can be 72 /// issued on this cycle without a hazard. This should increment the 73 /// internal state of the hazard recognizer so that previously "Hazard" 74 /// instructions will now not be hazards. 75 virtual void AdvanceCycle() { 76 } 77 78 /// EmitNoop - This callback is invoked when a noop was added to the 79 /// instruction stream. 80 virtual void EmitNoop() { 81 } 82 }; 83 84 /// SDep - Scheduling dependency. It keeps track of dependent nodes, 85 /// cost of the depdenency, etc. 86 struct SDep { 87 SUnit *Dep; // Dependent - either a predecessor or a successor. 88 unsigned Reg; // If non-zero, this dep is a phy register dependency. 89 int Cost; // Cost of the dependency. 90 bool isCtrl : 1; // True iff it's a control dependency. 91 bool isSpecial : 1; // True iff it's a special ctrl dep added during sched. 92 SDep(SUnit *d, unsigned r, int t, bool c, bool s) 93 : Dep(d), Reg(r), Cost(t), isCtrl(c), isSpecial(s) {} 94 }; 95 96 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or 97 /// a group of nodes flagged together. 98 struct SUnit { 99 SDNode *Node; // Representative node. 100 SmallVector<SDNode*,4> FlaggedNodes;// All nodes flagged to Node. 101 unsigned InstanceNo; // Instance#. One SDNode can be multiple 102 // SUnit due to cloning. 103 104 // Preds/Succs - The SUnits before/after us in the graph. The boolean value 105 // is true if the edge is a token chain edge, false if it is a value edge. 106 SmallVector<SDep, 4> Preds; // All sunit predecessors. 107 SmallVector<SDep, 4> Succs; // All sunit successors. 108 109 typedef SmallVector<SDep, 4>::iterator pred_iterator; 110 typedef SmallVector<SDep, 4>::iterator succ_iterator; 111 typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator; 112 typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator; 113 114 unsigned NodeNum; // Entry # of node in the node vector. 115 unsigned short Latency; // Node latency. 116 short NumPreds; // # of preds. 117 short NumSuccs; // # of sucss. 118 short NumPredsLeft; // # of preds not scheduled. 119 short NumSuccsLeft; // # of succs not scheduled. 120 bool isTwoAddress : 1; // Is a two-address instruction. 121 bool isCommutable : 1; // Is a commutable instruction. 122 bool hasPhysRegDefs : 1; // Has physreg defs that are being used. 123 bool isPending : 1; // True once pending. 124 bool isAvailable : 1; // True once available. 125 bool isScheduled : 1; // True once scheduled. 126 unsigned CycleBound; // Upper/lower cycle to be scheduled at. 127 unsigned Cycle; // Once scheduled, the cycle of the op. 128 unsigned Depth; // Node depth; 129 unsigned Height; // Node height; 130 const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null. 131 const TargetRegisterClass *CopySrcRC; 132 133 SUnit(SDNode *node, unsigned nodenum) 134 : Node(node), InstanceNo(0), NodeNum(nodenum), Latency(0), 135 NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0), 136 isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false), 137 isPending(false), isAvailable(false), isScheduled(false), 138 CycleBound(0), Cycle(0), Depth(0), Height(0), 139 CopyDstRC(NULL), CopySrcRC(NULL) {} 140 141 /// addPred - This adds the specified node as a pred of the current node if 142 /// not already. This returns true if this is a new pred. 143 bool addPred(SUnit *N, bool isCtrl, bool isSpecial, 144 unsigned PhyReg = 0, int Cost = 1) { 145 for (unsigned i = 0, e = Preds.size(); i != e; ++i) 146 if (Preds[i].Dep == N && 147 Preds[i].isCtrl == isCtrl && Preds[i].isSpecial == isSpecial) 148 return false; 149 Preds.push_back(SDep(N, PhyReg, Cost, isCtrl, isSpecial)); 150 N->Succs.push_back(SDep(this, PhyReg, Cost, isCtrl, isSpecial)); 151 if (!isCtrl) { 152 ++NumPreds; 153 ++N->NumSuccs; 154 } 155 if (!N->isScheduled) 156 ++NumPredsLeft; 157 if (!isScheduled) 158 ++N->NumSuccsLeft; 159 return true; 160 } 161 162 bool removePred(SUnit *N, bool isCtrl, bool isSpecial) { 163 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end(); 164 I != E; ++I) 165 if (I->Dep == N && I->isCtrl == isCtrl && I->isSpecial == isSpecial) { 166 bool FoundSucc = false; 167 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(), 168 EE = N->Succs.end(); II != EE; ++II) 169 if (II->Dep == this && 170 II->isCtrl == isCtrl && II->isSpecial == isSpecial) { 171 FoundSucc = true; 172 N->Succs.erase(II); 173 break; 174 } 175 assert(FoundSucc && "Mismatching preds / succs lists!"); 176 Preds.erase(I); 177 if (!isCtrl) { 178 --NumPreds; 179 --N->NumSuccs; 180 } 181 if (!N->isScheduled) 182 --NumPredsLeft; 183 if (!isScheduled) 184 --N->NumSuccsLeft; 185 return true; 186 } 187 return false; 188 } 189 190 bool isPred(SUnit *N) { 191 for (unsigned i = 0, e = Preds.size(); i != e; ++i) 192 if (Preds[i].Dep == N) 193 return true; 194 return false; 195 } 196 197 bool isSucc(SUnit *N) { 198 for (unsigned i = 0, e = Succs.size(); i != e; ++i) 199 if (Succs[i].Dep == N) 200 return true; 201 return false; 202 } 203 204 void dump(const SelectionDAG *G) const; 205 void dumpAll(const SelectionDAG *G) const; 206 }; 207 208 //===--------------------------------------------------------------------===// 209 /// SchedulingPriorityQueue - This interface is used to plug different 210 /// priorities computation algorithms into the list scheduler. It implements 211 /// the interface of a standard priority queue, where nodes are inserted in 212 /// arbitrary order and returned in priority order. The computation of the 213 /// priority and the representation of the queue are totally up to the 214 /// implementation to decide. 215 /// 216 class SchedulingPriorityQueue { 217 public: 218 virtual ~SchedulingPriorityQueue() {} 219 220 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &SUMap, 221 std::vector<SUnit> &SUnits) = 0; 222 virtual void addNode(const SUnit *SU) = 0; 223 virtual void updateNode(const SUnit *SU) = 0; 224 virtual void releaseState() = 0; 225 226 virtual unsigned size() const = 0; 227 virtual bool empty() const = 0; 228 virtual void push(SUnit *U) = 0; 229 230 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0; 231 virtual SUnit *pop() = 0; 232 233 virtual void remove(SUnit *SU) = 0; 234 235 /// ScheduledNode - As each node is scheduled, this method is invoked. This 236 /// allows the priority function to adjust the priority of node that have 237 /// already been emitted. 238 virtual void ScheduledNode(SUnit *Node) {} 239 240 virtual void UnscheduledNode(SUnit *Node) {} 241 }; 242 243 class ScheduleDAG { 244 public: 245 SelectionDAG &DAG; // DAG of the current basic block 246 MachineBasicBlock *BB; // Current basic block 247 const TargetMachine &TM; // Target processor 248 const TargetInstrInfo *TII; // Target instruction information 249 const TargetRegisterInfo *TRI; // Target processor register info 250 TargetLowering *TLI; // Target lowering info 251 MachineFunction *MF; // Machine function 252 MachineRegisterInfo &MRI; // Virtual/real register map 253 MachineConstantPool *ConstPool; // Target constant pool 254 std::vector<SUnit*> Sequence; // The schedule. Null SUnit*'s 255 // represent noop instructions. 256 DenseMap<SDNode*, std::vector<SUnit*> > SUnitMap; 257 // SDNode to SUnit mapping (n -> n). 258 std::vector<SUnit> SUnits; // The scheduling units. 259 SmallSet<SDNode*, 16> CommuteSet; // Nodes that should be commuted. 260 261 ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb, 262 const TargetMachine &tm); 263 264 virtual ~ScheduleDAG() {} 265 266 /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered 267 /// using 'dot'. 268 /// 269 void viewGraph(); 270 271 /// Run - perform scheduling. 272 /// 273 MachineBasicBlock *Run(); 274 275 /// isPassiveNode - Return true if the node is a non-scheduled leaf. 276 /// 277 static bool isPassiveNode(SDNode *Node) { 278 if (isa<ConstantSDNode>(Node)) return true; 279 if (isa<ConstantFPSDNode>(Node)) return true; 280 if (isa<RegisterSDNode>(Node)) return true; 281 if (isa<GlobalAddressSDNode>(Node)) return true; 282 if (isa<BasicBlockSDNode>(Node)) return true; 283 if (isa<FrameIndexSDNode>(Node)) return true; 284 if (isa<ConstantPoolSDNode>(Node)) return true; 285 if (isa<JumpTableSDNode>(Node)) return true; 286 if (isa<ExternalSymbolSDNode>(Node)) return true; 287 if (isa<MemOperandSDNode>(Node)) return true; 288 return false; 289 } 290 291 /// NewSUnit - Creates a new SUnit and return a ptr to it. 292 /// 293 SUnit *NewSUnit(SDNode *N) { 294 SUnits.push_back(SUnit(N, SUnits.size())); 295 return &SUnits.back(); 296 } 297 298 /// Clone - Creates a clone of the specified SUnit. It does not copy the 299 /// predecessors / successors info nor the temporary scheduling states. 300 SUnit *Clone(SUnit *N); 301 302 /// BuildSchedUnits - Build SUnits from the selection dag that we are input. 303 /// This SUnit graph is similar to the SelectionDAG, but represents flagged 304 /// together nodes with a single SUnit. 305 void BuildSchedUnits(); 306 307 /// ComputeLatency - Compute node latency. 308 /// 309 void ComputeLatency(SUnit *SU); 310 311 /// CalculateDepths, CalculateHeights - Calculate node depth / height. 312 /// 313 void CalculateDepths(); 314 void CalculateHeights(); 315 316 /// CountResults - The results of target nodes have register or immediate 317 /// operands first, then an optional chain, and optional flag operands 318 /// (which do not go into the machine instrs.) 319 static unsigned CountResults(SDNode *Node); 320 321 /// CountOperands - The inputs to target nodes have any actual inputs first, 322 /// followed by special operands that describe memory references, then an 323 /// optional chain operand, then flag operands. Compute the number of 324 /// actual operands that will go into the resulting MachineInstr. 325 static unsigned CountOperands(SDNode *Node); 326 327 /// ComputeMemOperandsEnd - Find the index one past the last 328 /// MemOperandSDNode operand 329 static unsigned ComputeMemOperandsEnd(SDNode *Node); 330 331 /// EmitNode - Generate machine code for an node and needed dependencies. 332 /// VRBaseMap contains, for each already emitted node, the first virtual 333 /// register number for the results of the node. 334 /// 335 void EmitNode(SDNode *Node, unsigned InstNo, 336 DenseMap<SDOperandImpl, unsigned> &VRBaseMap); 337 338 /// EmitNoop - Emit a noop instruction. 339 /// 340 void EmitNoop(); 341 342 void EmitSchedule(); 343 344 void dumpSchedule() const; 345 346 /// Schedule - Order nodes according to selected style. 347 /// 348 virtual void Schedule() {} 349 350 private: 351 /// EmitSubregNode - Generate machine code for subreg nodes. 352 /// 353 void EmitSubregNode(SDNode *Node, 354 DenseMap<SDOperandImpl, unsigned> &VRBaseMap); 355 356 /// getVR - Return the virtual register corresponding to the specified result 357 /// of the specified node. 358 unsigned getVR(SDOperand Op, DenseMap<SDOperandImpl, unsigned> &VRBaseMap); 359 360 /// getDstOfCopyToRegUse - If the only use of the specified result number of 361 /// node is a CopyToReg, return its destination register. Return 0 otherwise. 362 unsigned getDstOfOnlyCopyToRegUse(SDNode *Node, unsigned ResNo) const; 363 364 void AddOperand(MachineInstr *MI, SDOperand Op, unsigned IIOpNum, 365 const TargetInstrDesc *II, 366 DenseMap<SDOperandImpl, unsigned> &VRBaseMap); 367 368 void AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO); 369 370 void EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap); 371 372 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an 373 /// implicit physical register output. 374 void EmitCopyFromReg(SDNode *Node, unsigned ResNo, unsigned InstNo, 375 unsigned SrcReg, 376 DenseMap<SDOperandImpl, unsigned> &VRBaseMap); 377 378 void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI, 379 const TargetInstrDesc &II, 380 DenseMap<SDOperandImpl, unsigned> &VRBaseMap); 381 382 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the 383 /// physical register has only a single copy use, then coalesced the copy 384 /// if possible. 385 void EmitLiveInCopy(MachineBasicBlock *MBB, 386 MachineBasicBlock::iterator &InsertPos, 387 unsigned VirtReg, unsigned PhysReg, 388 const TargetRegisterClass *RC, 389 DenseMap<MachineInstr*, unsigned> &CopyRegMap); 390 391 /// EmitLiveInCopies - If this is the first basic block in the function, 392 /// and if it has live ins that need to be copied into vregs, emit the 393 /// copies into the top of the block. 394 void EmitLiveInCopies(MachineBasicBlock *MBB); 395 }; 396 397 /// createBURRListDAGScheduler - This creates a bottom up register usage 398 /// reduction list scheduler. 399 ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS, 400 SelectionDAG *DAG, 401 MachineBasicBlock *BB); 402 403 /// createTDRRListDAGScheduler - This creates a top down register usage 404 /// reduction list scheduler. 405 ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS, 406 SelectionDAG *DAG, 407 MachineBasicBlock *BB); 408 409 /// createTDListDAGScheduler - This creates a top-down list scheduler with 410 /// a hazard recognizer. 411 ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS, 412 SelectionDAG *DAG, 413 MachineBasicBlock *BB); 414 415 /// createDefaultScheduler - This creates an instruction scheduler appropriate 416 /// for the target. 417 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS, 418 SelectionDAG *DAG, 419 MachineBasicBlock *BB); 420 421 class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> { 422 SUnit *Node; 423 unsigned Operand; 424 425 SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {} 426 public: 427 bool operator==(const SUnitIterator& x) const { 428 return Operand == x.Operand; 429 } 430 bool operator!=(const SUnitIterator& x) const { return !operator==(x); } 431 432 const SUnitIterator &operator=(const SUnitIterator &I) { 433 assert(I.Node == Node && "Cannot assign iterators to two different nodes!"); 434 Operand = I.Operand; 435 return *this; 436 } 437 438 pointer operator*() const { 439 return Node->Preds[Operand].Dep; 440 } 441 pointer operator->() const { return operator*(); } 442 443 SUnitIterator& operator++() { // Preincrement 444 ++Operand; 445 return *this; 446 } 447 SUnitIterator operator++(int) { // Postincrement 448 SUnitIterator tmp = *this; ++*this; return tmp; 449 } 450 451 static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); } 452 static SUnitIterator end (SUnit *N) { 453 return SUnitIterator(N, N->Preds.size()); 454 } 455 456 unsigned getOperand() const { return Operand; } 457 const SUnit *getNode() const { return Node; } 458 bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; } 459 }; 460 461 template <> struct GraphTraits<SUnit*> { 462 typedef SUnit NodeType; 463 typedef SUnitIterator ChildIteratorType; 464 static inline NodeType *getEntryNode(SUnit *N) { return N; } 465 static inline ChildIteratorType child_begin(NodeType *N) { 466 return SUnitIterator::begin(N); 467 } 468 static inline ChildIteratorType child_end(NodeType *N) { 469 return SUnitIterator::end(N); 470 } 471 }; 472 473 template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> { 474 typedef std::vector<SUnit>::iterator nodes_iterator; 475 static nodes_iterator nodes_begin(ScheduleDAG *G) { 476 return G->SUnits.begin(); 477 } 478 static nodes_iterator nodes_end(ScheduleDAG *G) { 479 return G->SUnits.end(); 480 } 481 }; 482} 483 484#endif 485