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