Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

759 lines
29 KiB

  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 instruction schedulers. This encapsulates the scheduling DAG,
  12. // which is shared between SelectionDAG and MachineInstr scheduling.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_CODEGEN_SCHEDULEDAG_H
  16. #define LLVM_CODEGEN_SCHEDULEDAG_H
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/GraphTraits.h"
  19. #include "llvm/ADT/PointerIntPair.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/CodeGen/MachineInstr.h"
  22. #include "llvm/Target/TargetLowering.h"
  23. namespace llvm {
  24. class AliasAnalysis;
  25. class SUnit;
  26. class MachineConstantPool;
  27. class MachineFunction;
  28. class MachineRegisterInfo;
  29. class MachineInstr;
  30. struct MCSchedClassDesc;
  31. class TargetRegisterInfo;
  32. class ScheduleDAG;
  33. class SDNode;
  34. class TargetInstrInfo;
  35. class MCInstrDesc;
  36. class TargetMachine;
  37. class TargetRegisterClass;
  38. template<class Graph> class GraphWriter;
  39. /// SDep - Scheduling dependency. This represents one direction of an
  40. /// edge in the scheduling DAG.
  41. class SDep {
  42. public:
  43. /// Kind - These are the different kinds of scheduling dependencies.
  44. enum Kind {
  45. Data, ///< Regular data dependence (aka true-dependence).
  46. Anti, ///< A register anti-dependedence (aka WAR).
  47. Output, ///< A register output-dependence (aka WAW).
  48. Order ///< Any other ordering dependency.
  49. };
  50. // Strong dependencies must be respected by the scheduler. Artificial
  51. // dependencies may be removed only if they are redundant with another
  52. // strong depedence.
  53. //
  54. // Weak dependencies may be violated by the scheduling strategy, but only if
  55. // the strategy can prove it is correct to do so.
  56. //
  57. // Strong OrderKinds must occur before "Weak".
  58. // Weak OrderKinds must occur after "Weak".
  59. enum OrderKind {
  60. Barrier, ///< An unknown scheduling barrier.
  61. MayAliasMem, ///< Nonvolatile load/Store instructions that may alias.
  62. MustAliasMem, ///< Nonvolatile load/Store instructions that must alias.
  63. Artificial, ///< Arbitrary strong DAG edge (no real dependence).
  64. Weak, ///< Arbitrary weak DAG edge.
  65. Cluster ///< Weak DAG edge linking a chain of clustered instrs.
  66. };
  67. private:
  68. /// Dep - A pointer to the depending/depended-on SUnit, and an enum
  69. /// indicating the kind of the dependency.
  70. PointerIntPair<SUnit *, 2, Kind> Dep;
  71. /// Contents - A union discriminated by the dependence kind.
  72. union {
  73. /// Reg - For Data, Anti, and Output dependencies, the associated
  74. /// register. For Data dependencies that don't currently have a register
  75. /// assigned, this is set to zero.
  76. unsigned Reg;
  77. /// Order - Additional information about Order dependencies.
  78. unsigned OrdKind; // enum OrderKind
  79. } Contents;
  80. /// Latency - The time associated with this edge. Often this is just
  81. /// the value of the Latency field of the predecessor, however advanced
  82. /// models may provide additional information about specific edges.
  83. unsigned Latency;
  84. /// Record MinLatency seperately from "expected" Latency.
  85. ///
  86. /// FIXME: this field is not packed on LP64. Convert to 16-bit DAG edge
  87. /// latency after introducing saturating truncation.
  88. unsigned MinLatency;
  89. public:
  90. /// SDep - Construct a null SDep. This is only for use by container
  91. /// classes which require default constructors. SUnits may not
  92. /// have null SDep edges.
  93. SDep() : Dep(0, Data) {}
  94. /// SDep - Construct an SDep with the specified values.
  95. SDep(SUnit *S, Kind kind, unsigned Reg)
  96. : Dep(S, kind), Contents() {
  97. switch (kind) {
  98. default:
  99. llvm_unreachable("Reg given for non-register dependence!");
  100. case Anti:
  101. case Output:
  102. assert(Reg != 0 &&
  103. "SDep::Anti and SDep::Output must use a non-zero Reg!");
  104. Contents.Reg = Reg;
  105. Latency = 0;
  106. break;
  107. case Data:
  108. Contents.Reg = Reg;
  109. Latency = 1;
  110. break;
  111. }
  112. MinLatency = Latency;
  113. }
  114. SDep(SUnit *S, OrderKind kind)
  115. : Dep(S, Order), Contents(), Latency(0), MinLatency(0) {
  116. Contents.OrdKind = kind;
  117. }
  118. /// Return true if the specified SDep is equivalent except for latency.
  119. bool overlaps(const SDep &Other) const {
  120. if (Dep != Other.Dep) return false;
  121. switch (Dep.getInt()) {
  122. case Data:
  123. case Anti:
  124. case Output:
  125. return Contents.Reg == Other.Contents.Reg;
  126. case Order:
  127. return Contents.OrdKind == Other.Contents.OrdKind;
  128. }
  129. llvm_unreachable("Invalid dependency kind!");
  130. }
  131. bool operator==(const SDep &Other) const {
  132. return overlaps(Other)
  133. && Latency == Other.Latency && MinLatency == Other.MinLatency;
  134. }
  135. bool operator!=(const SDep &Other) const {
  136. return !operator==(Other);
  137. }
  138. /// getLatency - Return the latency value for this edge, which roughly
  139. /// means the minimum number of cycles that must elapse between the
  140. /// predecessor and the successor, given that they have this edge
  141. /// between them.
  142. unsigned getLatency() const {
  143. return Latency;
  144. }
  145. /// setLatency - Set the latency for this edge.
  146. void setLatency(unsigned Lat) {
  147. Latency = Lat;
  148. }
  149. /// getMinLatency - Return the minimum latency for this edge. Minimum
  150. /// latency is used for scheduling groups, while normal (expected) latency
  151. /// is for instruction cost and critical path.
  152. unsigned getMinLatency() const {
  153. return MinLatency;
  154. }
  155. /// setMinLatency - Set the minimum latency for this edge.
  156. void setMinLatency(unsigned Lat) {
  157. MinLatency = Lat;
  158. }
  159. //// getSUnit - Return the SUnit to which this edge points.
  160. SUnit *getSUnit() const {
  161. return Dep.getPointer();
  162. }
  163. //// setSUnit - Assign the SUnit to which this edge points.
  164. void setSUnit(SUnit *SU) {
  165. Dep.setPointer(SU);
  166. }
  167. /// getKind - Return an enum value representing the kind of the dependence.
  168. Kind getKind() const {
  169. return Dep.getInt();
  170. }
  171. /// isCtrl - Shorthand for getKind() != SDep::Data.
  172. bool isCtrl() const {
  173. return getKind() != Data;
  174. }
  175. /// isNormalMemory - Test if this is an Order dependence between two
  176. /// memory accesses where both sides of the dependence access memory
  177. /// in non-volatile and fully modeled ways.
  178. bool isNormalMemory() const {
  179. return getKind() == Order && (Contents.OrdKind == MayAliasMem
  180. || Contents.OrdKind == MustAliasMem);
  181. }
  182. /// isMustAlias - Test if this is an Order dependence that is marked
  183. /// as "must alias", meaning that the SUnits at either end of the edge
  184. /// have a memory dependence on a known memory location.
  185. bool isMustAlias() const {
  186. return getKind() == Order && Contents.OrdKind == MustAliasMem;
  187. }
  188. /// isWeak - Test if this a weak dependence. Weak dependencies are
  189. /// considered DAG edges for height computation and other heuristics, but do
  190. /// not force ordering. Breaking a weak edge may require the scheduler to
  191. /// compensate, for example by inserting a copy.
  192. bool isWeak() const {
  193. return getKind() == Order && Contents.OrdKind >= Weak;
  194. }
  195. /// isArtificial - Test if this is an Order dependence that is marked
  196. /// as "artificial", meaning it isn't necessary for correctness.
  197. bool isArtificial() const {
  198. return getKind() == Order && Contents.OrdKind == Artificial;
  199. }
  200. /// isCluster - Test if this is an Order dependence that is marked
  201. /// as "cluster", meaning it is artificial and wants to be adjacent.
  202. bool isCluster() const {
  203. return getKind() == Order && Contents.OrdKind == Cluster;
  204. }
  205. /// isAssignedRegDep - Test if this is a Data dependence that is
  206. /// associated with a register.
  207. bool isAssignedRegDep() const {
  208. return getKind() == Data && Contents.Reg != 0;
  209. }
  210. /// getReg - Return the register associated with this edge. This is
  211. /// only valid on Data, Anti, and Output edges. On Data edges, this
  212. /// value may be zero, meaning there is no associated register.
  213. unsigned getReg() const {
  214. assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
  215. "getReg called on non-register dependence edge!");
  216. return Contents.Reg;
  217. }
  218. /// setReg - Assign the associated register for this edge. This is
  219. /// only valid on Data, Anti, and Output edges. On Anti and Output
  220. /// edges, this value must not be zero. On Data edges, the value may
  221. /// be zero, which would mean that no specific register is associated
  222. /// with this edge.
  223. void setReg(unsigned Reg) {
  224. assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
  225. "setReg called on non-register dependence edge!");
  226. assert((getKind() != Anti || Reg != 0) &&
  227. "SDep::Anti edge cannot use the zero register!");
  228. assert((getKind() != Output || Reg != 0) &&
  229. "SDep::Output edge cannot use the zero register!");
  230. Contents.Reg = Reg;
  231. }
  232. };
  233. template <>
  234. struct isPodLike<SDep> { static const bool value = true; };
  235. /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
  236. class SUnit {
  237. private:
  238. enum { BoundaryID = ~0u };
  239. SDNode *Node; // Representative node.
  240. MachineInstr *Instr; // Alternatively, a MachineInstr.
  241. public:
  242. SUnit *OrigNode; // If not this, the node from which
  243. // this node was cloned.
  244. // (SD scheduling only)
  245. const MCSchedClassDesc *SchedClass; // NULL or resolved SchedClass.
  246. // Preds/Succs - The SUnits before/after us in the graph.
  247. SmallVector<SDep, 4> Preds; // All sunit predecessors.
  248. SmallVector<SDep, 4> Succs; // All sunit successors.
  249. typedef SmallVector<SDep, 4>::iterator pred_iterator;
  250. typedef SmallVector<SDep, 4>::iterator succ_iterator;
  251. typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
  252. typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
  253. unsigned NodeNum; // Entry # of node in the node vector.
  254. unsigned NodeQueueId; // Queue id of node.
  255. unsigned NumPreds; // # of SDep::Data preds.
  256. unsigned NumSuccs; // # of SDep::Data sucss.
  257. unsigned NumPredsLeft; // # of preds not scheduled.
  258. unsigned NumSuccsLeft; // # of succs not scheduled.
  259. unsigned WeakPredsLeft; // # of weak preds not scheduled.
  260. unsigned WeakSuccsLeft; // # of weak succs not scheduled.
  261. unsigned short NumRegDefsLeft; // # of reg defs with no scheduled use.
  262. unsigned short Latency; // Node latency.
  263. bool isVRegCycle : 1; // May use and def the same vreg.
  264. bool isCall : 1; // Is a function call.
  265. bool isCallOp : 1; // Is a function call operand.
  266. bool isTwoAddress : 1; // Is a two-address instruction.
  267. bool isCommutable : 1; // Is a commutable instruction.
  268. bool hasPhysRegUses : 1; // Has physreg uses.
  269. bool hasPhysRegDefs : 1; // Has physreg defs that are being used.
  270. bool hasPhysRegClobbers : 1; // Has any physreg defs, used or not.
  271. bool isPending : 1; // True once pending.
  272. bool isAvailable : 1; // True once available.
  273. bool isScheduled : 1; // True once scheduled.
  274. bool isScheduleHigh : 1; // True if preferable to schedule high.
  275. bool isScheduleLow : 1; // True if preferable to schedule low.
  276. bool isCloned : 1; // True if this node has been cloned.
  277. Sched::Preference SchedulingPref; // Scheduling preference.
  278. private:
  279. bool isDepthCurrent : 1; // True if Depth is current.
  280. bool isHeightCurrent : 1; // True if Height is current.
  281. unsigned Depth; // Node depth.
  282. unsigned Height; // Node height.
  283. public:
  284. unsigned TopReadyCycle; // Cycle relative to start when node is ready.
  285. unsigned BotReadyCycle; // Cycle relative to end when node is ready.
  286. const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
  287. const TargetRegisterClass *CopySrcRC;
  288. /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
  289. /// an SDNode and any nodes flagged to it.
  290. SUnit(SDNode *node, unsigned nodenum)
  291. : Node(node), Instr(0), OrigNode(0), SchedClass(0), NodeNum(nodenum),
  292. NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
  293. NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0), NumRegDefsLeft(0),
  294. Latency(0), isVRegCycle(false), isCall(false), isCallOp(false),
  295. isTwoAddress(false), isCommutable(false), hasPhysRegUses(false),
  296. hasPhysRegDefs(false), hasPhysRegClobbers(false), isPending(false),
  297. isAvailable(false), isScheduled(false), isScheduleHigh(false),
  298. isScheduleLow(false), isCloned(false), SchedulingPref(Sched::None),
  299. isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
  300. TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(NULL), CopySrcRC(NULL) {}
  301. /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
  302. /// a MachineInstr.
  303. SUnit(MachineInstr *instr, unsigned nodenum)
  304. : Node(0), Instr(instr), OrigNode(0), SchedClass(0), NodeNum(nodenum),
  305. NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
  306. NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0), NumRegDefsLeft(0),
  307. Latency(0), isVRegCycle(false), isCall(false), isCallOp(false),
  308. isTwoAddress(false), isCommutable(false), hasPhysRegUses(false),
  309. hasPhysRegDefs(false), hasPhysRegClobbers(false), isPending(false),
  310. isAvailable(false), isScheduled(false), isScheduleHigh(false),
  311. isScheduleLow(false), isCloned(false), SchedulingPref(Sched::None),
  312. isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
  313. TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(NULL), CopySrcRC(NULL) {}
  314. /// SUnit - Construct a placeholder SUnit.
  315. SUnit()
  316. : Node(0), Instr(0), OrigNode(0), SchedClass(0), NodeNum(BoundaryID),
  317. NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
  318. NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0), NumRegDefsLeft(0),
  319. Latency(0), isVRegCycle(false), isCall(false), isCallOp(false),
  320. isTwoAddress(false), isCommutable(false), hasPhysRegUses(false),
  321. hasPhysRegDefs(false), hasPhysRegClobbers(false), isPending(false),
  322. isAvailable(false), isScheduled(false), isScheduleHigh(false),
  323. isScheduleLow(false), isCloned(false), SchedulingPref(Sched::None),
  324. isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
  325. TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(NULL), CopySrcRC(NULL) {}
  326. /// \brief Boundary nodes are placeholders for the boundary of the
  327. /// scheduling region.
  328. ///
  329. /// BoundaryNodes can have DAG edges, including Data edges, but they do not
  330. /// correspond to schedulable entities (e.g. instructions) and do not have a
  331. /// valid ID. Consequently, always check for boundary nodes before accessing
  332. /// an assoicative data structure keyed on node ID.
  333. bool isBoundaryNode() const { return NodeNum == BoundaryID; };
  334. /// setNode - Assign the representative SDNode for this SUnit.
  335. /// This may be used during pre-regalloc scheduling.
  336. void setNode(SDNode *N) {
  337. assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
  338. Node = N;
  339. }
  340. /// getNode - Return the representative SDNode for this SUnit.
  341. /// This may be used during pre-regalloc scheduling.
  342. SDNode *getNode() const {
  343. assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
  344. return Node;
  345. }
  346. /// isInstr - Return true if this SUnit refers to a machine instruction as
  347. /// opposed to an SDNode.
  348. bool isInstr() const { return Instr; }
  349. /// setInstr - Assign the instruction for the SUnit.
  350. /// This may be used during post-regalloc scheduling.
  351. void setInstr(MachineInstr *MI) {
  352. assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
  353. Instr = MI;
  354. }
  355. /// getInstr - Return the representative MachineInstr for this SUnit.
  356. /// This may be used during post-regalloc scheduling.
  357. MachineInstr *getInstr() const {
  358. assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
  359. return Instr;
  360. }
  361. /// addPred - This adds the specified edge as a pred of the current node if
  362. /// not already. It also adds the current node as a successor of the
  363. /// specified node.
  364. bool addPred(const SDep &D, bool Required = true);
  365. /// removePred - This removes the specified edge as a pred of the current
  366. /// node if it exists. It also removes the current node as a successor of
  367. /// the specified node.
  368. void removePred(const SDep &D);
  369. /// getDepth - Return the depth of this node, which is the length of the
  370. /// maximum path up to any node which has no predecessors.
  371. unsigned getDepth() const {
  372. if (!isDepthCurrent)
  373. const_cast<SUnit *>(this)->ComputeDepth();
  374. return Depth;
  375. }
  376. /// getHeight - Return the height of this node, which is the length of the
  377. /// maximum path down to any node which has no successors.
  378. unsigned getHeight() const {
  379. if (!isHeightCurrent)
  380. const_cast<SUnit *>(this)->ComputeHeight();
  381. return Height;
  382. }
  383. /// setDepthToAtLeast - If NewDepth is greater than this node's
  384. /// depth value, set it to be the new depth value. This also
  385. /// recursively marks successor nodes dirty.
  386. void setDepthToAtLeast(unsigned NewDepth);
  387. /// setDepthToAtLeast - If NewDepth is greater than this node's
  388. /// depth value, set it to be the new height value. This also
  389. /// recursively marks predecessor nodes dirty.
  390. void setHeightToAtLeast(unsigned NewHeight);
  391. /// setDepthDirty - Set a flag in this node to indicate that its
  392. /// stored Depth value will require recomputation the next time
  393. /// getDepth() is called.
  394. void setDepthDirty();
  395. /// setHeightDirty - Set a flag in this node to indicate that its
  396. /// stored Height value will require recomputation the next time
  397. /// getHeight() is called.
  398. void setHeightDirty();
  399. /// isPred - Test if node N is a predecessor of this node.
  400. bool isPred(SUnit *N) {
  401. for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
  402. if (Preds[i].getSUnit() == N)
  403. return true;
  404. return false;
  405. }
  406. /// isSucc - Test if node N is a successor of this node.
  407. bool isSucc(SUnit *N) {
  408. for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
  409. if (Succs[i].getSUnit() == N)
  410. return true;
  411. return false;
  412. }
  413. bool isTopReady() const {
  414. return NumPredsLeft == 0;
  415. }
  416. bool isBottomReady() const {
  417. return NumSuccsLeft == 0;
  418. }
  419. /// \brief Order this node's predecessor edges such that the critical path
  420. /// edge occurs first.
  421. void biasCriticalPath();
  422. void dump(const ScheduleDAG *G) const;
  423. void dumpAll(const ScheduleDAG *G) const;
  424. void print(raw_ostream &O, const ScheduleDAG *G) const;
  425. private:
  426. void ComputeDepth();
  427. void ComputeHeight();
  428. };
  429. //===--------------------------------------------------------------------===//
  430. /// SchedulingPriorityQueue - This interface is used to plug different
  431. /// priorities computation algorithms into the list scheduler. It implements
  432. /// the interface of a standard priority queue, where nodes are inserted in
  433. /// arbitrary order and returned in priority order. The computation of the
  434. /// priority and the representation of the queue are totally up to the
  435. /// implementation to decide.
  436. ///
  437. class SchedulingPriorityQueue {
  438. virtual void anchor();
  439. unsigned CurCycle;
  440. bool HasReadyFilter;
  441. public:
  442. SchedulingPriorityQueue(bool rf = false):
  443. CurCycle(0), HasReadyFilter(rf) {}
  444. virtual ~SchedulingPriorityQueue() {}
  445. virtual bool isBottomUp() const = 0;
  446. virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
  447. virtual void addNode(const SUnit *SU) = 0;
  448. virtual void updateNode(const SUnit *SU) = 0;
  449. virtual void releaseState() = 0;
  450. virtual bool empty() const = 0;
  451. bool hasReadyFilter() const { return HasReadyFilter; }
  452. virtual bool tracksRegPressure() const { return false; }
  453. virtual bool isReady(SUnit *) const {
  454. assert(!HasReadyFilter && "The ready filter must override isReady()");
  455. return true;
  456. }
  457. virtual void push(SUnit *U) = 0;
  458. void push_all(const std::vector<SUnit *> &Nodes) {
  459. for (std::vector<SUnit *>::const_iterator I = Nodes.begin(),
  460. E = Nodes.end(); I != E; ++I)
  461. push(*I);
  462. }
  463. virtual SUnit *pop() = 0;
  464. virtual void remove(SUnit *SU) = 0;
  465. virtual void dump(ScheduleDAG *) const {}
  466. /// scheduledNode - As each node is scheduled, this method is invoked. This
  467. /// allows the priority function to adjust the priority of related
  468. /// unscheduled nodes, for example.
  469. ///
  470. virtual void scheduledNode(SUnit *) {}
  471. virtual void unscheduledNode(SUnit *) {}
  472. void setCurCycle(unsigned Cycle) {
  473. CurCycle = Cycle;
  474. }
  475. unsigned getCurCycle() const {
  476. return CurCycle;
  477. }
  478. };
  479. class ScheduleDAG {
  480. public:
  481. const TargetMachine &TM; // Target processor
  482. const TargetInstrInfo *TII; // Target instruction information
  483. const TargetRegisterInfo *TRI; // Target processor register info
  484. MachineFunction &MF; // Machine function
  485. MachineRegisterInfo &MRI; // Virtual/real register map
  486. std::vector<SUnit> SUnits; // The scheduling units.
  487. SUnit EntrySU; // Special node for the region entry.
  488. SUnit ExitSU; // Special node for the region exit.
  489. #ifdef NDEBUG
  490. static const bool StressSched = false;
  491. #else
  492. bool StressSched;
  493. #endif
  494. explicit ScheduleDAG(MachineFunction &mf);
  495. virtual ~ScheduleDAG();
  496. /// clearDAG - clear the DAG state (between regions).
  497. void clearDAG();
  498. /// getInstrDesc - Return the MCInstrDesc of this SUnit.
  499. /// Return NULL for SDNodes without a machine opcode.
  500. const MCInstrDesc *getInstrDesc(const SUnit *SU) const {
  501. if (SU->isInstr()) return &SU->getInstr()->getDesc();
  502. return getNodeDesc(SU->getNode());
  503. }
  504. /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
  505. /// using 'dot'.
  506. ///
  507. virtual void viewGraph(const Twine &Name, const Twine &Title);
  508. virtual void viewGraph();
  509. virtual void dumpNode(const SUnit *SU) const = 0;
  510. /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
  511. /// of the ScheduleDAG.
  512. virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
  513. /// getDAGLabel - Return a label for the region of code covered by the DAG.
  514. virtual std::string getDAGName() const = 0;
  515. /// addCustomGraphFeatures - Add custom features for a visualization of
  516. /// the ScheduleDAG.
  517. virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
  518. #ifndef NDEBUG
  519. /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
  520. /// their state is consistent. Return the number of scheduled SUnits.
  521. unsigned VerifyScheduledDAG(bool isBottomUp);
  522. #endif
  523. private:
  524. // Return the MCInstrDesc of this SDNode or NULL.
  525. const MCInstrDesc *getNodeDesc(const SDNode *Node) const;
  526. };
  527. class SUnitIterator : public std::iterator<std::forward_iterator_tag,
  528. SUnit, ptrdiff_t> {
  529. SUnit *Node;
  530. unsigned Operand;
  531. SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
  532. public:
  533. bool operator==(const SUnitIterator& x) const {
  534. return Operand == x.Operand;
  535. }
  536. bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
  537. const SUnitIterator &operator=(const SUnitIterator &I) {
  538. assert(I.Node==Node && "Cannot assign iterators to two different nodes!");
  539. Operand = I.Operand;
  540. return *this;
  541. }
  542. pointer operator*() const {
  543. return Node->Preds[Operand].getSUnit();
  544. }
  545. pointer operator->() const { return operator*(); }
  546. SUnitIterator& operator++() { // Preincrement
  547. ++Operand;
  548. return *this;
  549. }
  550. SUnitIterator operator++(int) { // Postincrement
  551. SUnitIterator tmp = *this; ++*this; return tmp;
  552. }
  553. static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
  554. static SUnitIterator end (SUnit *N) {
  555. return SUnitIterator(N, (unsigned)N->Preds.size());
  556. }
  557. unsigned getOperand() const { return Operand; }
  558. const SUnit *getNode() const { return Node; }
  559. /// isCtrlDep - Test if this is not an SDep::Data dependence.
  560. bool isCtrlDep() const {
  561. return getSDep().isCtrl();
  562. }
  563. bool isArtificialDep() const {
  564. return getSDep().isArtificial();
  565. }
  566. const SDep &getSDep() const {
  567. return Node->Preds[Operand];
  568. }
  569. };
  570. template <> struct GraphTraits<SUnit*> {
  571. typedef SUnit NodeType;
  572. typedef SUnitIterator ChildIteratorType;
  573. static inline NodeType *getEntryNode(SUnit *N) { return N; }
  574. static inline ChildIteratorType child_begin(NodeType *N) {
  575. return SUnitIterator::begin(N);
  576. }
  577. static inline ChildIteratorType child_end(NodeType *N) {
  578. return SUnitIterator::end(N);
  579. }
  580. };
  581. template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
  582. typedef std::vector<SUnit>::iterator nodes_iterator;
  583. static nodes_iterator nodes_begin(ScheduleDAG *G) {
  584. return G->SUnits.begin();
  585. }
  586. static nodes_iterator nodes_end(ScheduleDAG *G) {
  587. return G->SUnits.end();
  588. }
  589. };
  590. /// ScheduleDAGTopologicalSort is a class that computes a topological
  591. /// ordering for SUnits and provides methods for dynamically updating
  592. /// the ordering as new edges are added.
  593. ///
  594. /// This allows a very fast implementation of IsReachable, for example.
  595. ///
  596. class ScheduleDAGTopologicalSort {
  597. /// SUnits - A reference to the ScheduleDAG's SUnits.
  598. std::vector<SUnit> &SUnits;
  599. SUnit *ExitSU;
  600. /// Index2Node - Maps topological index to the node number.
  601. std::vector<int> Index2Node;
  602. /// Node2Index - Maps the node number to its topological index.
  603. std::vector<int> Node2Index;
  604. /// Visited - a set of nodes visited during a DFS traversal.
  605. BitVector Visited;
  606. /// DFS - make a DFS traversal and mark all nodes affected by the
  607. /// edge insertion. These nodes will later get new topological indexes
  608. /// by means of the Shift method.
  609. void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
  610. /// Shift - reassign topological indexes for the nodes in the DAG
  611. /// to preserve the topological ordering.
  612. void Shift(BitVector& Visited, int LowerBound, int UpperBound);
  613. /// Allocate - assign the topological index to the node n.
  614. void Allocate(int n, int index);
  615. public:
  616. ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits, SUnit *ExitSU);
  617. /// InitDAGTopologicalSorting - create the initial topological
  618. /// ordering from the DAG to be scheduled.
  619. void InitDAGTopologicalSorting();
  620. /// IsReachable - Checks if SU is reachable from TargetSU.
  621. bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
  622. /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU
  623. /// will create a cycle.
  624. bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
  625. /// AddPred - Updates the topological ordering to accommodate an edge
  626. /// to be added from SUnit X to SUnit Y.
  627. void AddPred(SUnit *Y, SUnit *X);
  628. /// RemovePred - Updates the topological ordering to accommodate an
  629. /// an edge to be removed from the specified node N from the predecessors
  630. /// of the current node M.
  631. void RemovePred(SUnit *M, SUnit *N);
  632. typedef std::vector<int>::iterator iterator;
  633. typedef std::vector<int>::const_iterator const_iterator;
  634. iterator begin() { return Index2Node.begin(); }
  635. const_iterator begin() const { return Index2Node.begin(); }
  636. iterator end() { return Index2Node.end(); }
  637. const_iterator end() const { return Index2Node.end(); }
  638. typedef std::vector<int>::reverse_iterator reverse_iterator;
  639. typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
  640. reverse_iterator rbegin() { return Index2Node.rbegin(); }
  641. const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
  642. reverse_iterator rend() { return Index2Node.rend(); }
  643. const_reverse_iterator rend() const { return Index2Node.rend(); }
  644. };
  645. }
  646. #endif