ScheduleDAGSDNodes.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. //===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
  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. // This implements the ScheduleDAG class, which is a base class used by
  10. // scheduling implementation classes.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ScheduleDAGSDNodes.h"
  14. #include "InstrEmitter.h"
  15. #include "SDNodeDbgValue.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/CodeGen/MachineInstrBuilder.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/CodeGen/SelectionDAG.h"
  24. #include "llvm/CodeGen/TargetInstrInfo.h"
  25. #include "llvm/CodeGen/TargetLowering.h"
  26. #include "llvm/CodeGen/TargetRegisterInfo.h"
  27. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  28. #include "llvm/Config/llvm-config.h"
  29. #include "llvm/MC/MCInstrItineraries.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. using namespace llvm;
  34. #define DEBUG_TYPE "pre-RA-sched"
  35. STATISTIC(LoadsClustered, "Number of loads clustered together");
  36. // This allows the latency-based scheduler to notice high latency instructions
  37. // without a target itinerary. The choice of number here has more to do with
  38. // balancing scheduler heuristics than with the actual machine latency.
  39. static cl::opt<int> HighLatencyCycles(
  40. "sched-high-latency-cycles", cl::Hidden, cl::init(10),
  41. cl::desc("Roughly estimate the number of cycles that 'long latency'"
  42. "instructions take for targets with no itinerary"));
  43. ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
  44. : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
  45. InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
  46. /// Run - perform scheduling.
  47. ///
  48. void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
  49. BB = bb;
  50. DAG = dag;
  51. // Clear the scheduler's SUnit DAG.
  52. ScheduleDAG::clearDAG();
  53. Sequence.clear();
  54. // Invoke the target's selection of scheduler.
  55. Schedule();
  56. }
  57. /// NewSUnit - Creates a new SUnit and return a ptr to it.
  58. ///
  59. SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
  60. #ifndef NDEBUG
  61. const SUnit *Addr = nullptr;
  62. if (!SUnits.empty())
  63. Addr = &SUnits[0];
  64. #endif
  65. SUnits.emplace_back(N, (unsigned)SUnits.size());
  66. assert((Addr == nullptr || Addr == &SUnits[0]) &&
  67. "SUnits std::vector reallocated on the fly!");
  68. SUnits.back().OrigNode = &SUnits.back();
  69. SUnit *SU = &SUnits.back();
  70. const TargetLowering &TLI = DAG->getTargetLoweringInfo();
  71. if (!N ||
  72. (N->isMachineOpcode() &&
  73. N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
  74. SU->SchedulingPref = Sched::None;
  75. else
  76. SU->SchedulingPref = TLI.getSchedulingPreference(N);
  77. return SU;
  78. }
  79. SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
  80. SUnit *SU = newSUnit(Old->getNode());
  81. SU->OrigNode = Old->OrigNode;
  82. SU->Latency = Old->Latency;
  83. SU->isVRegCycle = Old->isVRegCycle;
  84. SU->isCall = Old->isCall;
  85. SU->isCallOp = Old->isCallOp;
  86. SU->isTwoAddress = Old->isTwoAddress;
  87. SU->isCommutable = Old->isCommutable;
  88. SU->hasPhysRegDefs = Old->hasPhysRegDefs;
  89. SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
  90. SU->isScheduleHigh = Old->isScheduleHigh;
  91. SU->isScheduleLow = Old->isScheduleLow;
  92. SU->SchedulingPref = Old->SchedulingPref;
  93. Old->isCloned = true;
  94. return SU;
  95. }
  96. /// CheckForPhysRegDependency - Check if the dependency between def and use of
  97. /// a specified operand is a physical register dependency. If so, returns the
  98. /// register and the cost of copying the register.
  99. static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
  100. const TargetRegisterInfo *TRI,
  101. const TargetInstrInfo *TII,
  102. unsigned &PhysReg, int &Cost) {
  103. if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
  104. return;
  105. unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  106. if (Register::isVirtualRegister(Reg))
  107. return;
  108. unsigned ResNo = User->getOperand(2).getResNo();
  109. if (Def->getOpcode() == ISD::CopyFromReg &&
  110. cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
  111. PhysReg = Reg;
  112. } else if (Def->isMachineOpcode()) {
  113. const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
  114. if (ResNo >= II.getNumDefs() &&
  115. II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg)
  116. PhysReg = Reg;
  117. }
  118. if (PhysReg != 0) {
  119. const TargetRegisterClass *RC =
  120. TRI->getMinimalPhysRegClass(Reg, Def->getSimpleValueType(ResNo));
  121. Cost = RC->getCopyCost();
  122. }
  123. }
  124. // Helper for AddGlue to clone node operands.
  125. static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG, ArrayRef<EVT> VTs,
  126. SDValue ExtraOper = SDValue()) {
  127. SmallVector<SDValue, 8> Ops(N->op_begin(), N->op_end());
  128. if (ExtraOper.getNode())
  129. Ops.push_back(ExtraOper);
  130. SDVTList VTList = DAG->getVTList(VTs);
  131. MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
  132. // Store memory references.
  133. SmallVector<MachineMemOperand *, 2> MMOs;
  134. if (MN)
  135. MMOs.assign(MN->memoperands_begin(), MN->memoperands_end());
  136. DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
  137. // Reset the memory references
  138. if (MN)
  139. DAG->setNodeMemRefs(MN, MMOs);
  140. }
  141. static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
  142. SDNode *GlueDestNode = Glue.getNode();
  143. // Don't add glue from a node to itself.
  144. if (GlueDestNode == N) return false;
  145. // Don't add a glue operand to something that already uses glue.
  146. if (GlueDestNode &&
  147. N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
  148. return false;
  149. }
  150. // Don't add glue to something that already has a glue value.
  151. if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
  152. SmallVector<EVT, 4> VTs(N->value_begin(), N->value_end());
  153. if (AddGlue)
  154. VTs.push_back(MVT::Glue);
  155. CloneNodeWithValues(N, DAG, VTs, Glue);
  156. return true;
  157. }
  158. // Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
  159. // node even though simply shrinking the value list is sufficient.
  160. static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
  161. assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
  162. !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
  163. "expected an unused glue value");
  164. CloneNodeWithValues(N, DAG,
  165. makeArrayRef(N->value_begin(), N->getNumValues() - 1));
  166. }
  167. /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
  168. /// This function finds loads of the same base and different offsets. If the
  169. /// offsets are not far apart (target specific), it add MVT::Glue inputs and
  170. /// outputs to ensure they are scheduled together and in order. This
  171. /// optimization may benefit some targets by improving cache locality.
  172. void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
  173. SDNode *Chain = nullptr;
  174. unsigned NumOps = Node->getNumOperands();
  175. if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
  176. Chain = Node->getOperand(NumOps-1).getNode();
  177. if (!Chain)
  178. return;
  179. // Skip any load instruction that has a tied input. There may be an additional
  180. // dependency requiring a different order than by increasing offsets, and the
  181. // added glue may introduce a cycle.
  182. auto hasTiedInput = [this](const SDNode *N) {
  183. const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
  184. for (unsigned I = 0; I != MCID.getNumOperands(); ++I) {
  185. if (MCID.getOperandConstraint(I, MCOI::TIED_TO) != -1)
  186. return true;
  187. }
  188. return false;
  189. };
  190. // Look for other loads of the same chain. Find loads that are loading from
  191. // the same base pointer and different offsets.
  192. SmallPtrSet<SDNode*, 16> Visited;
  193. SmallVector<int64_t, 4> Offsets;
  194. DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
  195. bool Cluster = false;
  196. SDNode *Base = Node;
  197. if (hasTiedInput(Base))
  198. return;
  199. // This algorithm requires a reasonably low use count before finding a match
  200. // to avoid uselessly blowing up compile time in large blocks.
  201. unsigned UseCount = 0;
  202. for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
  203. I != E && UseCount < 100; ++I, ++UseCount) {
  204. SDNode *User = *I;
  205. if (User == Node || !Visited.insert(User).second)
  206. continue;
  207. int64_t Offset1, Offset2;
  208. if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
  209. Offset1 == Offset2 ||
  210. hasTiedInput(User)) {
  211. // FIXME: Should be ok if they addresses are identical. But earlier
  212. // optimizations really should have eliminated one of the loads.
  213. continue;
  214. }
  215. if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
  216. Offsets.push_back(Offset1);
  217. O2SMap.insert(std::make_pair(Offset2, User));
  218. Offsets.push_back(Offset2);
  219. if (Offset2 < Offset1)
  220. Base = User;
  221. Cluster = true;
  222. // Reset UseCount to allow more matches.
  223. UseCount = 0;
  224. }
  225. if (!Cluster)
  226. return;
  227. // Sort them in increasing order.
  228. llvm::sort(Offsets);
  229. // Check if the loads are close enough.
  230. SmallVector<SDNode*, 4> Loads;
  231. unsigned NumLoads = 0;
  232. int64_t BaseOff = Offsets[0];
  233. SDNode *BaseLoad = O2SMap[BaseOff];
  234. Loads.push_back(BaseLoad);
  235. for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
  236. int64_t Offset = Offsets[i];
  237. SDNode *Load = O2SMap[Offset];
  238. if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
  239. break; // Stop right here. Ignore loads that are further away.
  240. Loads.push_back(Load);
  241. ++NumLoads;
  242. }
  243. if (NumLoads == 0)
  244. return;
  245. // Cluster loads by adding MVT::Glue outputs and inputs. This also
  246. // ensure they are scheduled in order of increasing addresses.
  247. SDNode *Lead = Loads[0];
  248. SDValue InGlue = SDValue(nullptr, 0);
  249. if (AddGlue(Lead, InGlue, true, DAG))
  250. InGlue = SDValue(Lead, Lead->getNumValues() - 1);
  251. for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
  252. bool OutGlue = I < E - 1;
  253. SDNode *Load = Loads[I];
  254. // If AddGlue fails, we could leave an unsused glue value. This should not
  255. // cause any
  256. if (AddGlue(Load, InGlue, OutGlue, DAG)) {
  257. if (OutGlue)
  258. InGlue = SDValue(Load, Load->getNumValues() - 1);
  259. ++LoadsClustered;
  260. }
  261. else if (!OutGlue && InGlue.getNode())
  262. RemoveUnusedGlue(InGlue.getNode(), DAG);
  263. }
  264. }
  265. /// ClusterNodes - Cluster certain nodes which should be scheduled together.
  266. ///
  267. void ScheduleDAGSDNodes::ClusterNodes() {
  268. for (SDNode &NI : DAG->allnodes()) {
  269. SDNode *Node = &NI;
  270. if (!Node || !Node->isMachineOpcode())
  271. continue;
  272. unsigned Opc = Node->getMachineOpcode();
  273. const MCInstrDesc &MCID = TII->get(Opc);
  274. if (MCID.mayLoad())
  275. // Cluster loads from "near" addresses into combined SUnits.
  276. ClusterNeighboringLoads(Node);
  277. }
  278. }
  279. void ScheduleDAGSDNodes::BuildSchedUnits() {
  280. // During scheduling, the NodeId field of SDNode is used to map SDNodes
  281. // to their associated SUnits by holding SUnits table indices. A value
  282. // of -1 means the SDNode does not yet have an associated SUnit.
  283. unsigned NumNodes = 0;
  284. for (SDNode &NI : DAG->allnodes()) {
  285. NI.setNodeId(-1);
  286. ++NumNodes;
  287. }
  288. // Reserve entries in the vector for each of the SUnits we are creating. This
  289. // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
  290. // invalidated.
  291. // FIXME: Multiply by 2 because we may clone nodes during scheduling.
  292. // This is a temporary workaround.
  293. SUnits.reserve(NumNodes * 2);
  294. // Add all nodes in depth first order.
  295. SmallVector<SDNode*, 64> Worklist;
  296. SmallPtrSet<SDNode*, 32> Visited;
  297. Worklist.push_back(DAG->getRoot().getNode());
  298. Visited.insert(DAG->getRoot().getNode());
  299. SmallVector<SUnit*, 8> CallSUnits;
  300. while (!Worklist.empty()) {
  301. SDNode *NI = Worklist.pop_back_val();
  302. // Add all operands to the worklist unless they've already been added.
  303. for (const SDValue &Op : NI->op_values())
  304. if (Visited.insert(Op.getNode()).second)
  305. Worklist.push_back(Op.getNode());
  306. if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
  307. continue;
  308. // If this node has already been processed, stop now.
  309. if (NI->getNodeId() != -1) continue;
  310. SUnit *NodeSUnit = newSUnit(NI);
  311. // See if anything is glued to this node, if so, add them to glued
  312. // nodes. Nodes can have at most one glue input and one glue output. Glue
  313. // is required to be the last operand and result of a node.
  314. // Scan up to find glued preds.
  315. SDNode *N = NI;
  316. while (N->getNumOperands() &&
  317. N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
  318. N = N->getOperand(N->getNumOperands()-1).getNode();
  319. assert(N->getNodeId() == -1 && "Node already inserted!");
  320. N->setNodeId(NodeSUnit->NodeNum);
  321. if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
  322. NodeSUnit->isCall = true;
  323. }
  324. // Scan down to find any glued succs.
  325. N = NI;
  326. while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
  327. SDValue GlueVal(N, N->getNumValues()-1);
  328. // There are either zero or one users of the Glue result.
  329. bool HasGlueUse = false;
  330. for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
  331. UI != E; ++UI)
  332. if (GlueVal.isOperandOf(*UI)) {
  333. HasGlueUse = true;
  334. assert(N->getNodeId() == -1 && "Node already inserted!");
  335. N->setNodeId(NodeSUnit->NodeNum);
  336. N = *UI;
  337. if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
  338. NodeSUnit->isCall = true;
  339. break;
  340. }
  341. if (!HasGlueUse) break;
  342. }
  343. if (NodeSUnit->isCall)
  344. CallSUnits.push_back(NodeSUnit);
  345. // Schedule zero-latency TokenFactor below any nodes that may increase the
  346. // schedule height. Otherwise, ancestors of the TokenFactor may appear to
  347. // have false stalls.
  348. if (NI->getOpcode() == ISD::TokenFactor)
  349. NodeSUnit->isScheduleLow = true;
  350. // If there are glue operands involved, N is now the bottom-most node
  351. // of the sequence of nodes that are glued together.
  352. // Update the SUnit.
  353. NodeSUnit->setNode(N);
  354. assert(N->getNodeId() == -1 && "Node already inserted!");
  355. N->setNodeId(NodeSUnit->NodeNum);
  356. // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
  357. InitNumRegDefsLeft(NodeSUnit);
  358. // Assign the Latency field of NodeSUnit using target-provided information.
  359. computeLatency(NodeSUnit);
  360. }
  361. // Find all call operands.
  362. while (!CallSUnits.empty()) {
  363. SUnit *SU = CallSUnits.pop_back_val();
  364. for (const SDNode *SUNode = SU->getNode(); SUNode;
  365. SUNode = SUNode->getGluedNode()) {
  366. if (SUNode->getOpcode() != ISD::CopyToReg)
  367. continue;
  368. SDNode *SrcN = SUNode->getOperand(2).getNode();
  369. if (isPassiveNode(SrcN)) continue; // Not scheduled.
  370. SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
  371. SrcSU->isCallOp = true;
  372. }
  373. }
  374. }
  375. void ScheduleDAGSDNodes::AddSchedEdges() {
  376. const TargetSubtargetInfo &ST = MF.getSubtarget();
  377. // Check to see if the scheduler cares about latencies.
  378. bool UnitLatencies = forceUnitLatencies();
  379. // Pass 2: add the preds, succs, etc.
  380. for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
  381. SUnit *SU = &SUnits[su];
  382. SDNode *MainNode = SU->getNode();
  383. if (MainNode->isMachineOpcode()) {
  384. unsigned Opc = MainNode->getMachineOpcode();
  385. const MCInstrDesc &MCID = TII->get(Opc);
  386. for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
  387. if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
  388. SU->isTwoAddress = true;
  389. break;
  390. }
  391. }
  392. if (MCID.isCommutable())
  393. SU->isCommutable = true;
  394. }
  395. // Find all predecessors and successors of the group.
  396. for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
  397. if (N->isMachineOpcode() &&
  398. TII->get(N->getMachineOpcode()).getImplicitDefs()) {
  399. SU->hasPhysRegClobbers = true;
  400. unsigned NumUsed = InstrEmitter::CountResults(N);
  401. while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
  402. --NumUsed; // Skip over unused values at the end.
  403. if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
  404. SU->hasPhysRegDefs = true;
  405. }
  406. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  407. SDNode *OpN = N->getOperand(i).getNode();
  408. if (isPassiveNode(OpN)) continue; // Not scheduled.
  409. SUnit *OpSU = &SUnits[OpN->getNodeId()];
  410. assert(OpSU && "Node has no SUnit!");
  411. if (OpSU == SU) continue; // In the same group.
  412. EVT OpVT = N->getOperand(i).getValueType();
  413. assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
  414. bool isChain = OpVT == MVT::Other;
  415. unsigned PhysReg = 0;
  416. int Cost = 1;
  417. // Determine if this is a physical register dependency.
  418. CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
  419. assert((PhysReg == 0 || !isChain) &&
  420. "Chain dependence via physreg data?");
  421. // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
  422. // emits a copy from the physical register to a virtual register unless
  423. // it requires a cross class copy (cost < 0). That means we are only
  424. // treating "expensive to copy" register dependency as physical register
  425. // dependency. This may change in the future though.
  426. if (Cost >= 0 && !StressSched)
  427. PhysReg = 0;
  428. // If this is a ctrl dep, latency is 1.
  429. unsigned OpLatency = isChain ? 1 : OpSU->Latency;
  430. // Special-case TokenFactor chains as zero-latency.
  431. if(isChain && OpN->getOpcode() == ISD::TokenFactor)
  432. OpLatency = 0;
  433. SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
  434. : SDep(OpSU, SDep::Data, PhysReg);
  435. Dep.setLatency(OpLatency);
  436. if (!isChain && !UnitLatencies) {
  437. computeOperandLatency(OpN, N, i, Dep);
  438. ST.adjustSchedDependency(OpSU, SU, Dep);
  439. }
  440. if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
  441. // Multiple register uses are combined in the same SUnit. For example,
  442. // we could have a set of glued nodes with all their defs consumed by
  443. // another set of glued nodes. Register pressure tracking sees this as
  444. // a single use, so to keep pressure balanced we reduce the defs.
  445. //
  446. // We can't tell (without more book-keeping) if this results from
  447. // glued nodes or duplicate operands. As long as we don't reduce
  448. // NumRegDefsLeft to zero, we handle the common cases well.
  449. --OpSU->NumRegDefsLeft;
  450. }
  451. }
  452. }
  453. }
  454. }
  455. /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
  456. /// are input. This SUnit graph is similar to the SelectionDAG, but
  457. /// excludes nodes that aren't interesting to scheduling, and represents
  458. /// glued together nodes with a single SUnit.
  459. void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
  460. // Cluster certain nodes which should be scheduled together.
  461. ClusterNodes();
  462. // Populate the SUnits array.
  463. BuildSchedUnits();
  464. // Compute all the scheduling dependencies between nodes.
  465. AddSchedEdges();
  466. }
  467. // Initialize NumNodeDefs for the current Node's opcode.
  468. void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
  469. // Check for phys reg copy.
  470. if (!Node)
  471. return;
  472. if (!Node->isMachineOpcode()) {
  473. if (Node->getOpcode() == ISD::CopyFromReg)
  474. NodeNumDefs = 1;
  475. else
  476. NodeNumDefs = 0;
  477. return;
  478. }
  479. unsigned POpc = Node->getMachineOpcode();
  480. if (POpc == TargetOpcode::IMPLICIT_DEF) {
  481. // No register need be allocated for this.
  482. NodeNumDefs = 0;
  483. return;
  484. }
  485. if (POpc == TargetOpcode::PATCHPOINT &&
  486. Node->getValueType(0) == MVT::Other) {
  487. // PATCHPOINT is defined to have one result, but it might really have none
  488. // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
  489. // real definition.
  490. NodeNumDefs = 0;
  491. return;
  492. }
  493. unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
  494. // Some instructions define regs that are not represented in the selection DAG
  495. // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
  496. NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
  497. DefIdx = 0;
  498. }
  499. // Construct a RegDefIter for this SUnit and find the first valid value.
  500. ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
  501. const ScheduleDAGSDNodes *SD)
  502. : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
  503. InitNodeNumDefs();
  504. Advance();
  505. }
  506. // Advance to the next valid value defined by the SUnit.
  507. void ScheduleDAGSDNodes::RegDefIter::Advance() {
  508. for (;Node;) { // Visit all glued nodes.
  509. for (;DefIdx < NodeNumDefs; ++DefIdx) {
  510. if (!Node->hasAnyUseOfValue(DefIdx))
  511. continue;
  512. ValueType = Node->getSimpleValueType(DefIdx);
  513. ++DefIdx;
  514. return; // Found a normal regdef.
  515. }
  516. Node = Node->getGluedNode();
  517. if (!Node) {
  518. return; // No values left to visit.
  519. }
  520. InitNodeNumDefs();
  521. }
  522. }
  523. void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
  524. assert(SU->NumRegDefsLeft == 0 && "expect a new node");
  525. for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
  526. assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
  527. ++SU->NumRegDefsLeft;
  528. }
  529. }
  530. void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
  531. SDNode *N = SU->getNode();
  532. // TokenFactor operands are considered zero latency, and some schedulers
  533. // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
  534. // whenever node latency is nonzero.
  535. if (N && N->getOpcode() == ISD::TokenFactor) {
  536. SU->Latency = 0;
  537. return;
  538. }
  539. // Check to see if the scheduler cares about latencies.
  540. if (forceUnitLatencies()) {
  541. SU->Latency = 1;
  542. return;
  543. }
  544. if (!InstrItins || InstrItins->isEmpty()) {
  545. if (N && N->isMachineOpcode() &&
  546. TII->isHighLatencyDef(N->getMachineOpcode()))
  547. SU->Latency = HighLatencyCycles;
  548. else
  549. SU->Latency = 1;
  550. return;
  551. }
  552. // Compute the latency for the node. We use the sum of the latencies for
  553. // all nodes glued together into this SUnit.
  554. SU->Latency = 0;
  555. for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
  556. if (N->isMachineOpcode())
  557. SU->Latency += TII->getInstrLatency(InstrItins, N);
  558. }
  559. void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
  560. unsigned OpIdx, SDep& dep) const{
  561. // Check to see if the scheduler cares about latencies.
  562. if (forceUnitLatencies())
  563. return;
  564. if (dep.getKind() != SDep::Data)
  565. return;
  566. unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
  567. if (Use->isMachineOpcode())
  568. // Adjust the use operand index by num of defs.
  569. OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
  570. int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
  571. if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
  572. !BB->succ_empty()) {
  573. unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
  574. if (Register::isVirtualRegister(Reg))
  575. // This copy is a liveout value. It is likely coalesced, so reduce the
  576. // latency so not to penalize the def.
  577. // FIXME: need target specific adjustment here?
  578. Latency = (Latency > 1) ? Latency - 1 : 1;
  579. }
  580. if (Latency >= 0)
  581. dep.setLatency(Latency);
  582. }
  583. void ScheduleDAGSDNodes::dumpNode(const SUnit &SU) const {
  584. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  585. dumpNodeName(SU);
  586. dbgs() << ": ";
  587. if (!SU.getNode()) {
  588. dbgs() << "PHYS REG COPY\n";
  589. return;
  590. }
  591. SU.getNode()->dump(DAG);
  592. dbgs() << "\n";
  593. SmallVector<SDNode *, 4> GluedNodes;
  594. for (SDNode *N = SU.getNode()->getGluedNode(); N; N = N->getGluedNode())
  595. GluedNodes.push_back(N);
  596. while (!GluedNodes.empty()) {
  597. dbgs() << " ";
  598. GluedNodes.back()->dump(DAG);
  599. dbgs() << "\n";
  600. GluedNodes.pop_back();
  601. }
  602. #endif
  603. }
  604. void ScheduleDAGSDNodes::dump() const {
  605. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  606. if (EntrySU.getNode() != nullptr)
  607. dumpNodeAll(EntrySU);
  608. for (const SUnit &SU : SUnits)
  609. dumpNodeAll(SU);
  610. if (ExitSU.getNode() != nullptr)
  611. dumpNodeAll(ExitSU);
  612. #endif
  613. }
  614. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  615. void ScheduleDAGSDNodes::dumpSchedule() const {
  616. for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
  617. if (SUnit *SU = Sequence[i])
  618. dumpNode(*SU);
  619. else
  620. dbgs() << "**** NOOP ****\n";
  621. }
  622. }
  623. #endif
  624. #ifndef NDEBUG
  625. /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
  626. /// their state is consistent with the nodes listed in Sequence.
  627. ///
  628. void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
  629. unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
  630. unsigned Noops = 0;
  631. for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
  632. if (!Sequence[i])
  633. ++Noops;
  634. assert(Sequence.size() - Noops == ScheduledNodes &&
  635. "The number of nodes scheduled doesn't match the expected number!");
  636. }
  637. #endif // NDEBUG
  638. /// ProcessSDDbgValues - Process SDDbgValues associated with this node.
  639. static void
  640. ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
  641. SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
  642. DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
  643. if (!N->getHasDebugValue())
  644. return;
  645. // Opportunistically insert immediate dbg_value uses, i.e. those with the same
  646. // source order number as N.
  647. MachineBasicBlock *BB = Emitter.getBlock();
  648. MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
  649. for (auto DV : DAG->GetDbgValues(N)) {
  650. if (DV->isEmitted())
  651. continue;
  652. unsigned DVOrder = DV->getOrder();
  653. if (!Order || DVOrder == Order) {
  654. MachineInstr *DbgMI = Emitter.EmitDbgValue(DV, VRBaseMap);
  655. if (DbgMI) {
  656. Orders.push_back({DVOrder, DbgMI});
  657. BB->insert(InsertPos, DbgMI);
  658. }
  659. }
  660. }
  661. }
  662. // ProcessSourceNode - Process nodes with source order numbers. These are added
  663. // to a vector which EmitSchedule uses to determine how to insert dbg_value
  664. // instructions in the right order.
  665. static void
  666. ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
  667. DenseMap<SDValue, unsigned> &VRBaseMap,
  668. SmallVectorImpl<std::pair<unsigned, MachineInstr *>> &Orders,
  669. SmallSet<unsigned, 8> &Seen, MachineInstr *NewInsn) {
  670. unsigned Order = N->getIROrder();
  671. if (!Order || Seen.count(Order)) {
  672. // Process any valid SDDbgValues even if node does not have any order
  673. // assigned.
  674. ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
  675. return;
  676. }
  677. // If a new instruction was generated for this Order number, record it.
  678. // Otherwise, leave this order number unseen: we will either find later
  679. // instructions for it, or leave it unseen if there were no instructions at
  680. // all.
  681. if (NewInsn) {
  682. Seen.insert(Order);
  683. Orders.push_back({Order, NewInsn});
  684. }
  685. // Even if no instruction was generated, a Value may have become defined via
  686. // earlier nodes. Try to process them now.
  687. ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
  688. }
  689. void ScheduleDAGSDNodes::
  690. EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
  691. MachineBasicBlock::iterator InsertPos) {
  692. for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
  693. I != E; ++I) {
  694. if (I->isCtrl()) continue; // ignore chain preds
  695. if (I->getSUnit()->CopyDstRC) {
  696. // Copy to physical register.
  697. DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
  698. assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
  699. // Find the destination physical register.
  700. unsigned Reg = 0;
  701. for (SUnit::const_succ_iterator II = SU->Succs.begin(),
  702. EE = SU->Succs.end(); II != EE; ++II) {
  703. if (II->isCtrl()) continue; // ignore chain preds
  704. if (II->getReg()) {
  705. Reg = II->getReg();
  706. break;
  707. }
  708. }
  709. BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
  710. .addReg(VRI->second);
  711. } else {
  712. // Copy from physical register.
  713. assert(I->getReg() && "Unknown physical register!");
  714. Register VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
  715. bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
  716. (void)isNew; // Silence compiler warning.
  717. assert(isNew && "Node emitted out of order - early");
  718. BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
  719. .addReg(I->getReg());
  720. }
  721. break;
  722. }
  723. }
  724. /// EmitSchedule - Emit the machine code in scheduled order. Return the new
  725. /// InsertPos and MachineBasicBlock that contains this insertion
  726. /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
  727. /// not necessarily refer to returned BB. The emitter may split blocks.
  728. MachineBasicBlock *ScheduleDAGSDNodes::
  729. EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
  730. InstrEmitter Emitter(BB, InsertPos);
  731. DenseMap<SDValue, unsigned> VRBaseMap;
  732. DenseMap<SUnit*, unsigned> CopyVRBaseMap;
  733. SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
  734. SmallSet<unsigned, 8> Seen;
  735. bool HasDbg = DAG->hasDebugValues();
  736. // Emit a node, and determine where its first instruction is for debuginfo.
  737. // Zero, one, or multiple instructions can be created when emitting a node.
  738. auto EmitNode =
  739. [&](SDNode *Node, bool IsClone, bool IsCloned,
  740. DenseMap<SDValue, unsigned> &VRBaseMap) -> MachineInstr * {
  741. // Fetch instruction prior to this, or end() if nonexistant.
  742. auto GetPrevInsn = [&](MachineBasicBlock::iterator I) {
  743. if (I == BB->begin())
  744. return BB->end();
  745. else
  746. return std::prev(Emitter.getInsertPos());
  747. };
  748. MachineBasicBlock::iterator Before = GetPrevInsn(Emitter.getInsertPos());
  749. Emitter.EmitNode(Node, IsClone, IsCloned, VRBaseMap);
  750. MachineBasicBlock::iterator After = GetPrevInsn(Emitter.getInsertPos());
  751. // If the iterator did not change, no instructions were inserted.
  752. if (Before == After)
  753. return nullptr;
  754. MachineInstr *MI;
  755. if (Before == BB->end()) {
  756. // There were no prior instructions; the new ones must start at the
  757. // beginning of the block.
  758. MI = &Emitter.getBlock()->instr_front();
  759. } else {
  760. // Return first instruction after the pre-existing instructions.
  761. MI = &*std::next(Before);
  762. }
  763. if (MI->isCall() && DAG->getTarget().Options.EnableDebugEntryValues)
  764. MF.addCallArgsForwardingRegs(MI, DAG->getSDCallSiteInfo(Node));
  765. return MI;
  766. };
  767. // If this is the first BB, emit byval parameter dbg_value's.
  768. if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
  769. SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
  770. SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
  771. for (; PDI != PDE; ++PDI) {
  772. MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
  773. if (DbgMI) {
  774. BB->insert(InsertPos, DbgMI);
  775. // We re-emit the dbg_value closer to its use, too, after instructions
  776. // are emitted to the BB.
  777. (*PDI)->clearIsEmitted();
  778. }
  779. }
  780. }
  781. for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
  782. SUnit *SU = Sequence[i];
  783. if (!SU) {
  784. // Null SUnit* is a noop.
  785. TII->insertNoop(*Emitter.getBlock(), InsertPos);
  786. continue;
  787. }
  788. // For pre-regalloc scheduling, create instructions corresponding to the
  789. // SDNode and any glued SDNodes and append them to the block.
  790. if (!SU->getNode()) {
  791. // Emit a copy.
  792. EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
  793. continue;
  794. }
  795. SmallVector<SDNode *, 4> GluedNodes;
  796. for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
  797. GluedNodes.push_back(N);
  798. while (!GluedNodes.empty()) {
  799. SDNode *N = GluedNodes.back();
  800. auto NewInsn = EmitNode(N, SU->OrigNode != SU, SU->isCloned, VRBaseMap);
  801. // Remember the source order of the inserted instruction.
  802. if (HasDbg)
  803. ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen, NewInsn);
  804. if (MDNode *MD = DAG->getHeapAllocSite(N)) {
  805. if (NewInsn && NewInsn->isCall())
  806. MF.addCodeViewHeapAllocSite(NewInsn, MD);
  807. }
  808. GluedNodes.pop_back();
  809. }
  810. auto NewInsn =
  811. EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned, VRBaseMap);
  812. // Remember the source order of the inserted instruction.
  813. if (HasDbg)
  814. ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders, Seen,
  815. NewInsn);
  816. if (MDNode *MD = DAG->getHeapAllocSite(SU->getNode())) {
  817. if (NewInsn && NewInsn->isCall())
  818. MF.addCodeViewHeapAllocSite(NewInsn, MD);
  819. }
  820. }
  821. // Insert all the dbg_values which have not already been inserted in source
  822. // order sequence.
  823. if (HasDbg) {
  824. MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
  825. // Sort the source order instructions and use the order to insert debug
  826. // values. Use stable_sort so that DBG_VALUEs are inserted in the same order
  827. // regardless of the host's implementation fo std::sort.
  828. llvm::stable_sort(Orders, less_first());
  829. std::stable_sort(DAG->DbgBegin(), DAG->DbgEnd(),
  830. [](const SDDbgValue *LHS, const SDDbgValue *RHS) {
  831. return LHS->getOrder() < RHS->getOrder();
  832. });
  833. SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
  834. SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
  835. // Now emit the rest according to source order.
  836. unsigned LastOrder = 0;
  837. for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
  838. unsigned Order = Orders[i].first;
  839. MachineInstr *MI = Orders[i].second;
  840. // Insert all SDDbgValue's whose order(s) are before "Order".
  841. assert(MI);
  842. for (; DI != DE; ++DI) {
  843. if ((*DI)->getOrder() < LastOrder || (*DI)->getOrder() >= Order)
  844. break;
  845. if ((*DI)->isEmitted())
  846. continue;
  847. MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
  848. if (DbgMI) {
  849. if (!LastOrder)
  850. // Insert to start of the BB (after PHIs).
  851. BB->insert(BBBegin, DbgMI);
  852. else {
  853. // Insert at the instruction, which may be in a different
  854. // block, if the block was split by a custom inserter.
  855. MachineBasicBlock::iterator Pos = MI;
  856. MI->getParent()->insert(Pos, DbgMI);
  857. }
  858. }
  859. }
  860. LastOrder = Order;
  861. }
  862. // Add trailing DbgValue's before the terminator. FIXME: May want to add
  863. // some of them before one or more conditional branches?
  864. SmallVector<MachineInstr*, 8> DbgMIs;
  865. for (; DI != DE; ++DI) {
  866. if ((*DI)->isEmitted())
  867. continue;
  868. assert((*DI)->getOrder() >= LastOrder &&
  869. "emitting DBG_VALUE out of order");
  870. if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
  871. DbgMIs.push_back(DbgMI);
  872. }
  873. MachineBasicBlock *InsertBB = Emitter.getBlock();
  874. MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
  875. InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
  876. SDDbgInfo::DbgLabelIterator DLI = DAG->DbgLabelBegin();
  877. SDDbgInfo::DbgLabelIterator DLE = DAG->DbgLabelEnd();
  878. // Now emit the rest according to source order.
  879. LastOrder = 0;
  880. for (const auto &InstrOrder : Orders) {
  881. unsigned Order = InstrOrder.first;
  882. MachineInstr *MI = InstrOrder.second;
  883. if (!MI)
  884. continue;
  885. // Insert all SDDbgLabel's whose order(s) are before "Order".
  886. for (; DLI != DLE &&
  887. (*DLI)->getOrder() >= LastOrder && (*DLI)->getOrder() < Order;
  888. ++DLI) {
  889. MachineInstr *DbgMI = Emitter.EmitDbgLabel(*DLI);
  890. if (DbgMI) {
  891. if (!LastOrder)
  892. // Insert to start of the BB (after PHIs).
  893. BB->insert(BBBegin, DbgMI);
  894. else {
  895. // Insert at the instruction, which may be in a different
  896. // block, if the block was split by a custom inserter.
  897. MachineBasicBlock::iterator Pos = MI;
  898. MI->getParent()->insert(Pos, DbgMI);
  899. }
  900. }
  901. }
  902. if (DLI == DLE)
  903. break;
  904. LastOrder = Order;
  905. }
  906. }
  907. InsertPos = Emitter.getInsertPos();
  908. return Emitter.getBlock();
  909. }
  910. /// Return the basic block label.
  911. std::string ScheduleDAGSDNodes::getDAGName() const {
  912. return "sunit-dag." + BB->getFullName();
  913. }