ScheduleDAGInstrs.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. //===- ScheduleDAGInstrs.h - MachineInstr Scheduling ------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file Implements the ScheduleDAGInstrs class, which implements scheduling
  10. /// for a MachineInstr-based dependency graph.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
  14. #define LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/PointerIntPair.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/SparseMultiSet.h"
  20. #include "llvm/ADT/SparseSet.h"
  21. #include "llvm/CodeGen/LivePhysRegs.h"
  22. #include "llvm/CodeGen/MachineBasicBlock.h"
  23. #include "llvm/CodeGen/ScheduleDAG.h"
  24. #include "llvm/CodeGen/TargetRegisterInfo.h"
  25. #include "llvm/CodeGen/TargetSchedule.h"
  26. #include "llvm/MC/LaneBitmask.h"
  27. #include <cassert>
  28. #include <cstdint>
  29. #include <list>
  30. #include <utility>
  31. #include <vector>
  32. namespace llvm {
  33. class AAResults;
  34. class LiveIntervals;
  35. class MachineFrameInfo;
  36. class MachineFunction;
  37. class MachineInstr;
  38. class MachineLoopInfo;
  39. class MachineOperand;
  40. struct MCSchedClassDesc;
  41. class PressureDiffs;
  42. class PseudoSourceValue;
  43. class RegPressureTracker;
  44. class UndefValue;
  45. class Value;
  46. /// An individual mapping from virtual register number to SUnit.
  47. struct VReg2SUnit {
  48. unsigned VirtReg;
  49. LaneBitmask LaneMask;
  50. SUnit *SU;
  51. VReg2SUnit(unsigned VReg, LaneBitmask LaneMask, SUnit *SU)
  52. : VirtReg(VReg), LaneMask(LaneMask), SU(SU) {}
  53. unsigned getSparseSetIndex() const {
  54. return Register::virtReg2Index(VirtReg);
  55. }
  56. };
  57. /// Mapping from virtual register to SUnit including an operand index.
  58. struct VReg2SUnitOperIdx : public VReg2SUnit {
  59. unsigned OperandIndex;
  60. VReg2SUnitOperIdx(unsigned VReg, LaneBitmask LaneMask,
  61. unsigned OperandIndex, SUnit *SU)
  62. : VReg2SUnit(VReg, LaneMask, SU), OperandIndex(OperandIndex) {}
  63. };
  64. /// Record a physical register access.
  65. /// For non-data-dependent uses, OpIdx == -1.
  66. struct PhysRegSUOper {
  67. SUnit *SU;
  68. int OpIdx;
  69. unsigned Reg;
  70. PhysRegSUOper(SUnit *su, int op, unsigned R): SU(su), OpIdx(op), Reg(R) {}
  71. unsigned getSparseSetIndex() const { return Reg; }
  72. };
  73. /// Use a SparseMultiSet to track physical registers. Storage is only
  74. /// allocated once for the pass. It can be cleared in constant time and reused
  75. /// without any frees.
  76. using Reg2SUnitsMap =
  77. SparseMultiSet<PhysRegSUOper, identity<unsigned>, uint16_t>;
  78. /// Use SparseSet as a SparseMap by relying on the fact that it never
  79. /// compares ValueT's, only unsigned keys. This allows the set to be cleared
  80. /// between scheduling regions in constant time as long as ValueT does not
  81. /// require a destructor.
  82. using VReg2SUnitMap = SparseSet<VReg2SUnit, VirtReg2IndexFunctor>;
  83. /// Track local uses of virtual registers. These uses are gathered by the DAG
  84. /// builder and may be consulted by the scheduler to avoid iterating an entire
  85. /// vreg use list.
  86. using VReg2SUnitMultiMap = SparseMultiSet<VReg2SUnit, VirtReg2IndexFunctor>;
  87. using VReg2SUnitOperIdxMultiMap =
  88. SparseMultiSet<VReg2SUnitOperIdx, VirtReg2IndexFunctor>;
  89. using ValueType = PointerUnion<const Value *, const PseudoSourceValue *>;
  90. struct UnderlyingObject : PointerIntPair<ValueType, 1, bool> {
  91. UnderlyingObject(ValueType V, bool MayAlias)
  92. : PointerIntPair<ValueType, 1, bool>(V, MayAlias) {}
  93. ValueType getValue() const { return getPointer(); }
  94. bool mayAlias() const { return getInt(); }
  95. };
  96. using UnderlyingObjectsVector = SmallVector<UnderlyingObject, 4>;
  97. /// A ScheduleDAG for scheduling lists of MachineInstr.
  98. class ScheduleDAGInstrs : public ScheduleDAG {
  99. protected:
  100. const MachineLoopInfo *MLI;
  101. const MachineFrameInfo &MFI;
  102. /// TargetSchedModel provides an interface to the machine model.
  103. TargetSchedModel SchedModel;
  104. /// True if the DAG builder should remove kill flags (in preparation for
  105. /// rescheduling).
  106. bool RemoveKillFlags;
  107. /// The standard DAG builder does not normally include terminators as DAG
  108. /// nodes because it does not create the necessary dependencies to prevent
  109. /// reordering. A specialized scheduler can override
  110. /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
  111. /// it has taken responsibility for scheduling the terminator correctly.
  112. bool CanHandleTerminators = false;
  113. /// Whether lane masks should get tracked.
  114. bool TrackLaneMasks = false;
  115. // State specific to the current scheduling region.
  116. // ------------------------------------------------
  117. /// The block in which to insert instructions
  118. MachineBasicBlock *BB;
  119. /// The beginning of the range to be scheduled.
  120. MachineBasicBlock::iterator RegionBegin;
  121. /// The end of the range to be scheduled.
  122. MachineBasicBlock::iterator RegionEnd;
  123. /// Instructions in this region (distance(RegionBegin, RegionEnd)).
  124. unsigned NumRegionInstrs;
  125. /// After calling BuildSchedGraph, each machine instruction in the current
  126. /// scheduling region is mapped to an SUnit.
  127. DenseMap<MachineInstr*, SUnit*> MISUnitMap;
  128. // State internal to DAG building.
  129. // -------------------------------
  130. /// Defs, Uses - Remember where defs and uses of each register are as we
  131. /// iterate upward through the instructions. This is allocated here instead
  132. /// of inside BuildSchedGraph to avoid the need for it to be initialized and
  133. /// destructed for each block.
  134. Reg2SUnitsMap Defs;
  135. Reg2SUnitsMap Uses;
  136. /// Tracks the last instruction(s) in this region defining each virtual
  137. /// register. There may be multiple current definitions for a register with
  138. /// disjunct lanemasks.
  139. VReg2SUnitMultiMap CurrentVRegDefs;
  140. /// Tracks the last instructions in this region using each virtual register.
  141. VReg2SUnitOperIdxMultiMap CurrentVRegUses;
  142. AAResults *AAForDep = nullptr;
  143. /// Remember a generic side-effecting instruction as we proceed.
  144. /// No other SU ever gets scheduled around it (except in the special
  145. /// case of a huge region that gets reduced).
  146. SUnit *BarrierChain = nullptr;
  147. public:
  148. /// A list of SUnits, used in Value2SUsMap, during DAG construction.
  149. /// Note: to gain speed it might be worth investigating an optimized
  150. /// implementation of this data structure, such as a singly linked list
  151. /// with a memory pool (SmallVector was tried but slow and SparseSet is not
  152. /// applicable).
  153. using SUList = std::list<SUnit *>;
  154. protected:
  155. /// A map from ValueType to SUList, used during DAG construction, as
  156. /// a means of remembering which SUs depend on which memory locations.
  157. class Value2SUsMap;
  158. /// Reduces maps in FIFO order, by N SUs. This is better than turning
  159. /// every Nth memory SU into BarrierChain in buildSchedGraph(), since
  160. /// it avoids unnecessary edges between seen SUs above the new BarrierChain,
  161. /// and those below it.
  162. void reduceHugeMemNodeMaps(Value2SUsMap &stores,
  163. Value2SUsMap &loads, unsigned N);
  164. /// Adds a chain edge between SUa and SUb, but only if both
  165. /// AAResults and Target fail to deny the dependency.
  166. void addChainDependency(SUnit *SUa, SUnit *SUb,
  167. unsigned Latency = 0);
  168. /// Adds dependencies as needed from all SUs in list to SU.
  169. void addChainDependencies(SUnit *SU, SUList &SUs, unsigned Latency) {
  170. for (SUnit *Entry : SUs)
  171. addChainDependency(SU, Entry, Latency);
  172. }
  173. /// Adds dependencies as needed from all SUs in map, to SU.
  174. void addChainDependencies(SUnit *SU, Value2SUsMap &Val2SUsMap);
  175. /// Adds dependencies as needed to SU, from all SUs mapped to V.
  176. void addChainDependencies(SUnit *SU, Value2SUsMap &Val2SUsMap,
  177. ValueType V);
  178. /// Adds barrier chain edges from all SUs in map, and then clear the map.
  179. /// This is equivalent to insertBarrierChain(), but optimized for the common
  180. /// case where the new BarrierChain (a global memory object) has a higher
  181. /// NodeNum than all SUs in map. It is assumed BarrierChain has been set
  182. /// before calling this.
  183. void addBarrierChain(Value2SUsMap &map);
  184. /// Inserts a barrier chain in a huge region, far below current SU.
  185. /// Adds barrier chain edges from all SUs in map with higher NodeNums than
  186. /// this new BarrierChain, and remove them from map. It is assumed
  187. /// BarrierChain has been set before calling this.
  188. void insertBarrierChain(Value2SUsMap &map);
  189. /// For an unanalyzable memory access, this Value is used in maps.
  190. UndefValue *UnknownValue;
  191. /// Topo - A topological ordering for SUnits which permits fast IsReachable
  192. /// and similar queries.
  193. ScheduleDAGTopologicalSort Topo;
  194. using DbgValueVector =
  195. std::vector<std::pair<MachineInstr *, MachineInstr *>>;
  196. /// Remember instruction that precedes DBG_VALUE.
  197. /// These are generated by buildSchedGraph but persist so they can be
  198. /// referenced when emitting the final schedule.
  199. DbgValueVector DbgValues;
  200. MachineInstr *FirstDbgValue = nullptr;
  201. /// Set of live physical registers for updating kill flags.
  202. LivePhysRegs LiveRegs;
  203. public:
  204. explicit ScheduleDAGInstrs(MachineFunction &mf,
  205. const MachineLoopInfo *mli,
  206. bool RemoveKillFlags = false);
  207. ~ScheduleDAGInstrs() override = default;
  208. /// Gets the machine model for instruction scheduling.
  209. const TargetSchedModel *getSchedModel() const { return &SchedModel; }
  210. /// Resolves and cache a resolved scheduling class for an SUnit.
  211. const MCSchedClassDesc *getSchedClass(SUnit *SU) const {
  212. if (!SU->SchedClass && SchedModel.hasInstrSchedModel())
  213. SU->SchedClass = SchedModel.resolveSchedClass(SU->getInstr());
  214. return SU->SchedClass;
  215. }
  216. /// IsReachable - Checks if SU is reachable from TargetSU.
  217. bool IsReachable(SUnit *SU, SUnit *TargetSU) {
  218. return Topo.IsReachable(SU, TargetSU);
  219. }
  220. /// Returns an iterator to the top of the current scheduling region.
  221. MachineBasicBlock::iterator begin() const { return RegionBegin; }
  222. /// Returns an iterator to the bottom of the current scheduling region.
  223. MachineBasicBlock::iterator end() const { return RegionEnd; }
  224. /// Creates a new SUnit and return a ptr to it.
  225. SUnit *newSUnit(MachineInstr *MI);
  226. /// Returns an existing SUnit for this MI, or nullptr.
  227. SUnit *getSUnit(MachineInstr *MI) const;
  228. /// If this method returns true, handling of the scheduling regions
  229. /// themselves (in case of a scheduling boundary in MBB) will be done
  230. /// beginning with the topmost region of MBB.
  231. virtual bool doMBBSchedRegionsTopDown() const { return false; }
  232. /// Prepares to perform scheduling in the given block.
  233. virtual void startBlock(MachineBasicBlock *BB);
  234. /// Cleans up after scheduling in the given block.
  235. virtual void finishBlock();
  236. /// Initialize the DAG and common scheduler state for a new
  237. /// scheduling region. This does not actually create the DAG, only clears
  238. /// it. The scheduling driver may call BuildSchedGraph multiple times per
  239. /// scheduling region.
  240. virtual void enterRegion(MachineBasicBlock *bb,
  241. MachineBasicBlock::iterator begin,
  242. MachineBasicBlock::iterator end,
  243. unsigned regioninstrs);
  244. /// Called when the scheduler has finished scheduling the current region.
  245. virtual void exitRegion();
  246. /// Builds SUnits for the current region.
  247. /// If \p RPTracker is non-null, compute register pressure as a side effect.
  248. /// The DAG builder is an efficient place to do it because it already visits
  249. /// operands.
  250. void buildSchedGraph(AAResults *AA,
  251. RegPressureTracker *RPTracker = nullptr,
  252. PressureDiffs *PDiffs = nullptr,
  253. LiveIntervals *LIS = nullptr,
  254. bool TrackLaneMasks = false);
  255. /// Adds dependencies from instructions in the current list of
  256. /// instructions being scheduled to scheduling barrier. We want to make sure
  257. /// instructions which define registers that are either used by the
  258. /// terminator or are live-out are properly scheduled. This is especially
  259. /// important when the definition latency of the return value(s) are too
  260. /// high to be hidden by the branch or when the liveout registers used by
  261. /// instructions in the fallthrough block.
  262. void addSchedBarrierDeps();
  263. /// Orders nodes according to selected style.
  264. ///
  265. /// Typically, a scheduling algorithm will implement schedule() without
  266. /// overriding enterRegion() or exitRegion().
  267. virtual void schedule() = 0;
  268. /// Allow targets to perform final scheduling actions at the level of the
  269. /// whole MachineFunction. By default does nothing.
  270. virtual void finalizeSchedule() {}
  271. void dumpNode(const SUnit &SU) const override;
  272. void dump() const override;
  273. /// Returns a label for a DAG node that points to an instruction.
  274. std::string getGraphNodeLabel(const SUnit *SU) const override;
  275. /// Returns a label for the region of code covered by the DAG.
  276. std::string getDAGName() const override;
  277. /// Fixes register kill flags that scheduling has made invalid.
  278. void fixupKills(MachineBasicBlock &MBB);
  279. /// True if an edge can be added from PredSU to SuccSU without creating
  280. /// a cycle.
  281. bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
  282. /// Add a DAG edge to the given SU with the given predecessor
  283. /// dependence data.
  284. ///
  285. /// \returns true if the edge may be added without creating a cycle OR if an
  286. /// equivalent edge already existed (false indicates failure).
  287. bool addEdge(SUnit *SuccSU, const SDep &PredDep);
  288. protected:
  289. void initSUnits();
  290. void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
  291. void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
  292. void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
  293. void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
  294. /// Returns a mask for which lanes get read/written by the given (register)
  295. /// machine operand.
  296. LaneBitmask getLaneMaskForMO(const MachineOperand &MO) const;
  297. /// Returns true if the def register in \p MO has no uses.
  298. bool deadDefHasNoUse(const MachineOperand &MO);
  299. };
  300. /// Creates a new SUnit and return a ptr to it.
  301. inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
  302. #ifndef NDEBUG
  303. const SUnit *Addr = SUnits.empty() ? nullptr : &SUnits[0];
  304. #endif
  305. SUnits.emplace_back(MI, (unsigned)SUnits.size());
  306. assert((Addr == nullptr || Addr == &SUnits[0]) &&
  307. "SUnits std::vector reallocated on the fly!");
  308. return &SUnits.back();
  309. }
  310. /// Returns an existing SUnit for this MI, or nullptr.
  311. inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const {
  312. return MISUnitMap.lookup(MI);
  313. }
  314. } // end namespace llvm
  315. #endif // LLVM_CODEGEN_SCHEDULEDAGINSTRS_H