ScheduleDAGSDNodes.cpp revision 218893
1//===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This implements the ScheduleDAG class, which is a base class used by 11// scheduling implementation classes. 12// 13//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "pre-RA-sched" 16#include "SDNodeDbgValue.h" 17#include "ScheduleDAGSDNodes.h" 18#include "InstrEmitter.h" 19#include "llvm/CodeGen/SelectionDAG.h" 20#include "llvm/Target/TargetMachine.h" 21#include "llvm/Target/TargetInstrInfo.h" 22#include "llvm/Target/TargetLowering.h" 23#include "llvm/Target/TargetRegisterInfo.h" 24#include "llvm/Target/TargetSubtarget.h" 25#include "llvm/ADT/DenseMap.h" 26#include "llvm/ADT/SmallPtrSet.h" 27#include "llvm/ADT/SmallSet.h" 28#include "llvm/ADT/SmallVector.h" 29#include "llvm/ADT/Statistic.h" 30#include "llvm/Support/Debug.h" 31#include "llvm/Support/raw_ostream.h" 32using namespace llvm; 33 34STATISTIC(LoadsClustered, "Number of loads clustered together"); 35 36ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf) 37 : ScheduleDAG(mf), 38 InstrItins(mf.getTarget().getInstrItineraryData()) {} 39 40/// Run - perform scheduling. 41/// 42void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb, 43 MachineBasicBlock::iterator insertPos) { 44 DAG = dag; 45 ScheduleDAG::Run(bb, insertPos); 46} 47 48/// NewSUnit - Creates a new SUnit and return a ptr to it. 49/// 50SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) { 51#ifndef NDEBUG 52 const SUnit *Addr = 0; 53 if (!SUnits.empty()) 54 Addr = &SUnits[0]; 55#endif 56 SUnits.push_back(SUnit(N, (unsigned)SUnits.size())); 57 assert((Addr == 0 || Addr == &SUnits[0]) && 58 "SUnits std::vector reallocated on the fly!"); 59 SUnits.back().OrigNode = &SUnits.back(); 60 SUnit *SU = &SUnits.back(); 61 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 62 if (!N || 63 (N->isMachineOpcode() && 64 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF)) 65 SU->SchedulingPref = Sched::None; 66 else 67 SU->SchedulingPref = TLI.getSchedulingPreference(N); 68 return SU; 69} 70 71SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) { 72 SUnit *SU = NewSUnit(Old->getNode()); 73 SU->OrigNode = Old->OrigNode; 74 SU->Latency = Old->Latency; 75 SU->isCall = Old->isCall; 76 SU->isTwoAddress = Old->isTwoAddress; 77 SU->isCommutable = Old->isCommutable; 78 SU->hasPhysRegDefs = Old->hasPhysRegDefs; 79 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers; 80 SU->SchedulingPref = Old->SchedulingPref; 81 Old->isCloned = true; 82 return SU; 83} 84 85/// CheckForPhysRegDependency - Check if the dependency between def and use of 86/// a specified operand is a physical register dependency. If so, returns the 87/// register and the cost of copying the register. 88static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op, 89 const TargetRegisterInfo *TRI, 90 const TargetInstrInfo *TII, 91 unsigned &PhysReg, int &Cost) { 92 if (Op != 2 || User->getOpcode() != ISD::CopyToReg) 93 return; 94 95 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg(); 96 if (TargetRegisterInfo::isVirtualRegister(Reg)) 97 return; 98 99 unsigned ResNo = User->getOperand(2).getResNo(); 100 if (Def->isMachineOpcode()) { 101 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode()); 102 if (ResNo >= II.getNumDefs() && 103 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) { 104 PhysReg = Reg; 105 const TargetRegisterClass *RC = 106 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo)); 107 Cost = RC->getCopyCost(); 108 } 109 } 110} 111 112static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) { 113 SmallVector<EVT, 4> VTs; 114 SDNode *GlueDestNode = Glue.getNode(); 115 116 // Don't add glue from a node to itself. 117 if (GlueDestNode == N) return; 118 119 // Don't add glue to something which already has glue. 120 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return; 121 122 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 123 VTs.push_back(N->getValueType(I)); 124 125 if (AddGlue) 126 VTs.push_back(MVT::Glue); 127 128 SmallVector<SDValue, 4> Ops; 129 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I) 130 Ops.push_back(N->getOperand(I)); 131 132 if (GlueDestNode) 133 Ops.push_back(Glue); 134 135 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size()); 136 MachineSDNode::mmo_iterator Begin = 0, End = 0; 137 MachineSDNode *MN = dyn_cast<MachineSDNode>(N); 138 139 // Store memory references. 140 if (MN) { 141 Begin = MN->memoperands_begin(); 142 End = MN->memoperands_end(); 143 } 144 145 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size()); 146 147 // Reset the memory references 148 if (MN) 149 MN->setMemRefs(Begin, End); 150} 151 152/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them. 153/// This function finds loads of the same base and different offsets. If the 154/// offsets are not far apart (target specific), it add MVT::Glue inputs and 155/// outputs to ensure they are scheduled together and in order. This 156/// optimization may benefit some targets by improving cache locality. 157void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) { 158 SDNode *Chain = 0; 159 unsigned NumOps = Node->getNumOperands(); 160 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other) 161 Chain = Node->getOperand(NumOps-1).getNode(); 162 if (!Chain) 163 return; 164 165 // Look for other loads of the same chain. Find loads that are loading from 166 // the same base pointer and different offsets. 167 SmallPtrSet<SDNode*, 16> Visited; 168 SmallVector<int64_t, 4> Offsets; 169 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode. 170 bool Cluster = false; 171 SDNode *Base = Node; 172 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end(); 173 I != E; ++I) { 174 SDNode *User = *I; 175 if (User == Node || !Visited.insert(User)) 176 continue; 177 int64_t Offset1, Offset2; 178 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) || 179 Offset1 == Offset2) 180 // FIXME: Should be ok if they addresses are identical. But earlier 181 // optimizations really should have eliminated one of the loads. 182 continue; 183 if (O2SMap.insert(std::make_pair(Offset1, Base)).second) 184 Offsets.push_back(Offset1); 185 O2SMap.insert(std::make_pair(Offset2, User)); 186 Offsets.push_back(Offset2); 187 if (Offset2 < Offset1) 188 Base = User; 189 Cluster = true; 190 } 191 192 if (!Cluster) 193 return; 194 195 // Sort them in increasing order. 196 std::sort(Offsets.begin(), Offsets.end()); 197 198 // Check if the loads are close enough. 199 SmallVector<SDNode*, 4> Loads; 200 unsigned NumLoads = 0; 201 int64_t BaseOff = Offsets[0]; 202 SDNode *BaseLoad = O2SMap[BaseOff]; 203 Loads.push_back(BaseLoad); 204 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) { 205 int64_t Offset = Offsets[i]; 206 SDNode *Load = O2SMap[Offset]; 207 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads)) 208 break; // Stop right here. Ignore loads that are further away. 209 Loads.push_back(Load); 210 ++NumLoads; 211 } 212 213 if (NumLoads == 0) 214 return; 215 216 // Cluster loads by adding MVT::Glue outputs and inputs. This also 217 // ensure they are scheduled in order of increasing addresses. 218 SDNode *Lead = Loads[0]; 219 AddGlue(Lead, SDValue(0, 0), true, DAG); 220 221 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1); 222 for (unsigned I = 1, E = Loads.size(); I != E; ++I) { 223 bool OutGlue = I < E - 1; 224 SDNode *Load = Loads[I]; 225 226 AddGlue(Load, InGlue, OutGlue, DAG); 227 228 if (OutGlue) 229 InGlue = SDValue(Load, Load->getNumValues() - 1); 230 231 ++LoadsClustered; 232 } 233} 234 235/// ClusterNodes - Cluster certain nodes which should be scheduled together. 236/// 237void ScheduleDAGSDNodes::ClusterNodes() { 238 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(), 239 E = DAG->allnodes_end(); NI != E; ++NI) { 240 SDNode *Node = &*NI; 241 if (!Node || !Node->isMachineOpcode()) 242 continue; 243 244 unsigned Opc = Node->getMachineOpcode(); 245 const TargetInstrDesc &TID = TII->get(Opc); 246 if (TID.mayLoad()) 247 // Cluster loads from "near" addresses into combined SUnits. 248 ClusterNeighboringLoads(Node); 249 } 250} 251 252void ScheduleDAGSDNodes::BuildSchedUnits() { 253 // During scheduling, the NodeId field of SDNode is used to map SDNodes 254 // to their associated SUnits by holding SUnits table indices. A value 255 // of -1 means the SDNode does not yet have an associated SUnit. 256 unsigned NumNodes = 0; 257 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(), 258 E = DAG->allnodes_end(); NI != E; ++NI) { 259 NI->setNodeId(-1); 260 ++NumNodes; 261 } 262 263 // Reserve entries in the vector for each of the SUnits we are creating. This 264 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get 265 // invalidated. 266 // FIXME: Multiply by 2 because we may clone nodes during scheduling. 267 // This is a temporary workaround. 268 SUnits.reserve(NumNodes * 2); 269 270 // Add all nodes in depth first order. 271 SmallVector<SDNode*, 64> Worklist; 272 SmallPtrSet<SDNode*, 64> Visited; 273 Worklist.push_back(DAG->getRoot().getNode()); 274 Visited.insert(DAG->getRoot().getNode()); 275 276 while (!Worklist.empty()) { 277 SDNode *NI = Worklist.pop_back_val(); 278 279 // Add all operands to the worklist unless they've already been added. 280 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i) 281 if (Visited.insert(NI->getOperand(i).getNode())) 282 Worklist.push_back(NI->getOperand(i).getNode()); 283 284 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate. 285 continue; 286 287 // If this node has already been processed, stop now. 288 if (NI->getNodeId() != -1) continue; 289 290 SUnit *NodeSUnit = NewSUnit(NI); 291 292 // See if anything is glued to this node, if so, add them to glued 293 // nodes. Nodes can have at most one glue input and one glue output. Glue 294 // is required to be the last operand and result of a node. 295 296 // Scan up to find glued preds. 297 SDNode *N = NI; 298 while (N->getNumOperands() && 299 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) { 300 N = N->getOperand(N->getNumOperands()-1).getNode(); 301 assert(N->getNodeId() == -1 && "Node already inserted!"); 302 N->setNodeId(NodeSUnit->NodeNum); 303 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall()) 304 NodeSUnit->isCall = true; 305 } 306 307 // Scan down to find any glued succs. 308 N = NI; 309 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) { 310 SDValue GlueVal(N, N->getNumValues()-1); 311 312 // There are either zero or one users of the Glue result. 313 bool HasGlueUse = false; 314 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 315 UI != E; ++UI) 316 if (GlueVal.isOperandOf(*UI)) { 317 HasGlueUse = true; 318 assert(N->getNodeId() == -1 && "Node already inserted!"); 319 N->setNodeId(NodeSUnit->NodeNum); 320 N = *UI; 321 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall()) 322 NodeSUnit->isCall = true; 323 break; 324 } 325 if (!HasGlueUse) break; 326 } 327 328 // If there are glue operands involved, N is now the bottom-most node 329 // of the sequence of nodes that are glued together. 330 // Update the SUnit. 331 NodeSUnit->setNode(N); 332 assert(N->getNodeId() == -1 && "Node already inserted!"); 333 N->setNodeId(NodeSUnit->NodeNum); 334 335 // Compute NumRegDefsLeft. This must be done before AddSchedEdges. 336 InitNumRegDefsLeft(NodeSUnit); 337 338 // Assign the Latency field of NodeSUnit using target-provided information. 339 ComputeLatency(NodeSUnit); 340 } 341} 342 343void ScheduleDAGSDNodes::AddSchedEdges() { 344 const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>(); 345 346 // Check to see if the scheduler cares about latencies. 347 bool UnitLatencies = ForceUnitLatencies(); 348 349 // Pass 2: add the preds, succs, etc. 350 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) { 351 SUnit *SU = &SUnits[su]; 352 SDNode *MainNode = SU->getNode(); 353 354 if (MainNode->isMachineOpcode()) { 355 unsigned Opc = MainNode->getMachineOpcode(); 356 const TargetInstrDesc &TID = TII->get(Opc); 357 for (unsigned i = 0; i != TID.getNumOperands(); ++i) { 358 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) { 359 SU->isTwoAddress = true; 360 break; 361 } 362 } 363 if (TID.isCommutable()) 364 SU->isCommutable = true; 365 } 366 367 // Find all predecessors and successors of the group. 368 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) { 369 if (N->isMachineOpcode() && 370 TII->get(N->getMachineOpcode()).getImplicitDefs()) { 371 SU->hasPhysRegClobbers = true; 372 unsigned NumUsed = InstrEmitter::CountResults(N); 373 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1)) 374 --NumUsed; // Skip over unused values at the end. 375 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs()) 376 SU->hasPhysRegDefs = true; 377 } 378 379 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 380 SDNode *OpN = N->getOperand(i).getNode(); 381 if (isPassiveNode(OpN)) continue; // Not scheduled. 382 SUnit *OpSU = &SUnits[OpN->getNodeId()]; 383 assert(OpSU && "Node has no SUnit!"); 384 if (OpSU == SU) continue; // In the same group. 385 386 EVT OpVT = N->getOperand(i).getValueType(); 387 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!"); 388 bool isChain = OpVT == MVT::Other; 389 390 unsigned PhysReg = 0; 391 int Cost = 1; 392 // Determine if this is a physical register dependency. 393 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost); 394 assert((PhysReg == 0 || !isChain) && 395 "Chain dependence via physreg data?"); 396 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler 397 // emits a copy from the physical register to a virtual register unless 398 // it requires a cross class copy (cost < 0). That means we are only 399 // treating "expensive to copy" register dependency as physical register 400 // dependency. This may change in the future though. 401 if (Cost >= 0) 402 PhysReg = 0; 403 404 // If this is a ctrl dep, latency is 1. 405 unsigned OpLatency = isChain ? 1 : OpSU->Latency; 406 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data, 407 OpLatency, PhysReg); 408 if (!isChain && !UnitLatencies) { 409 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep)); 410 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep)); 411 } 412 413 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 0) { 414 // Multiple register uses are combined in the same SUnit. For example, 415 // we could have a set of glued nodes with all their defs consumed by 416 // another set of glued nodes. Register pressure tracking sees this as 417 // a single use, so to keep pressure balanced we reduce the defs. 418 --OpSU->NumRegDefsLeft; 419 } 420 } 421 } 422 } 423} 424 425/// BuildSchedGraph - Build the SUnit graph from the selection dag that we 426/// are input. This SUnit graph is similar to the SelectionDAG, but 427/// excludes nodes that aren't interesting to scheduling, and represents 428/// glued together nodes with a single SUnit. 429void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) { 430 // Cluster certain nodes which should be scheduled together. 431 ClusterNodes(); 432 // Populate the SUnits array. 433 BuildSchedUnits(); 434 // Compute all the scheduling dependencies between nodes. 435 AddSchedEdges(); 436} 437 438// Initialize NumNodeDefs for the current Node's opcode. 439void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() { 440 if (!Node->isMachineOpcode()) { 441 if (Node->getOpcode() == ISD::CopyFromReg) 442 NodeNumDefs = 1; 443 else 444 NodeNumDefs = 0; 445 return; 446 } 447 unsigned POpc = Node->getMachineOpcode(); 448 if (POpc == TargetOpcode::IMPLICIT_DEF) { 449 // No register need be allocated for this. 450 NodeNumDefs = 0; 451 return; 452 } 453 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs(); 454 // Some instructions define regs that are not represented in the selection DAG 455 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues. 456 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs); 457 DefIdx = 0; 458} 459 460// Construct a RegDefIter for this SUnit and find the first valid value. 461ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU, 462 const ScheduleDAGSDNodes *SD) 463 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) { 464 InitNodeNumDefs(); 465 Advance(); 466} 467 468// Advance to the next valid value defined by the SUnit. 469void ScheduleDAGSDNodes::RegDefIter::Advance() { 470 for (;Node;) { // Visit all glued nodes. 471 for (;DefIdx < NodeNumDefs; ++DefIdx) { 472 if (!Node->hasAnyUseOfValue(DefIdx)) 473 continue; 474 if (Node->isMachineOpcode() && 475 Node->getMachineOpcode() == TargetOpcode::EXTRACT_SUBREG) { 476 // Propagate the incoming (full-register) type. I doubt it's needed. 477 ValueType = Node->getOperand(0).getValueType(); 478 } 479 else { 480 ValueType = Node->getValueType(DefIdx); 481 } 482 ++DefIdx; 483 return; // Found a normal regdef. 484 } 485 Node = Node->getGluedNode(); 486 if (Node == NULL) { 487 return; // No values left to visit. 488 } 489 InitNodeNumDefs(); 490 } 491} 492 493void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) { 494 assert(SU->NumRegDefsLeft == 0 && "expect a new node"); 495 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) { 496 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected"); 497 ++SU->NumRegDefsLeft; 498 } 499} 500 501void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) { 502 // Check to see if the scheduler cares about latencies. 503 if (ForceUnitLatencies()) { 504 SU->Latency = 1; 505 return; 506 } 507 508 if (!InstrItins || InstrItins->isEmpty()) { 509 SU->Latency = 1; 510 return; 511 } 512 513 // Compute the latency for the node. We use the sum of the latencies for 514 // all nodes glued together into this SUnit. 515 SU->Latency = 0; 516 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) 517 if (N->isMachineOpcode()) 518 SU->Latency += TII->getInstrLatency(InstrItins, N); 519} 520 521void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use, 522 unsigned OpIdx, SDep& dep) const{ 523 // Check to see if the scheduler cares about latencies. 524 if (ForceUnitLatencies()) 525 return; 526 527 if (dep.getKind() != SDep::Data) 528 return; 529 530 unsigned DefIdx = Use->getOperand(OpIdx).getResNo(); 531 if (Use->isMachineOpcode()) 532 // Adjust the use operand index by num of defs. 533 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs(); 534 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx); 535 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg && 536 !BB->succ_empty()) { 537 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg(); 538 if (TargetRegisterInfo::isVirtualRegister(Reg)) 539 // This copy is a liveout value. It is likely coalesced, so reduce the 540 // latency so not to penalize the def. 541 // FIXME: need target specific adjustment here? 542 Latency = (Latency > 1) ? Latency - 1 : 1; 543 } 544 if (Latency >= 0) 545 dep.setLatency(Latency); 546} 547 548void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const { 549 if (!SU->getNode()) { 550 dbgs() << "PHYS REG COPY\n"; 551 return; 552 } 553 554 SU->getNode()->dump(DAG); 555 dbgs() << "\n"; 556 SmallVector<SDNode *, 4> GluedNodes; 557 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode()) 558 GluedNodes.push_back(N); 559 while (!GluedNodes.empty()) { 560 dbgs() << " "; 561 GluedNodes.back()->dump(DAG); 562 dbgs() << "\n"; 563 GluedNodes.pop_back(); 564 } 565} 566 567namespace { 568 struct OrderSorter { 569 bool operator()(const std::pair<unsigned, MachineInstr*> &A, 570 const std::pair<unsigned, MachineInstr*> &B) { 571 return A.first < B.first; 572 } 573 }; 574} 575 576/// ProcessSDDbgValues - Process SDDbgValues assoicated with this node. 577static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, 578 InstrEmitter &Emitter, 579 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders, 580 DenseMap<SDValue, unsigned> &VRBaseMap, 581 unsigned Order) { 582 if (!N->getHasDebugValue()) 583 return; 584 585 // Opportunistically insert immediate dbg_value uses, i.e. those with source 586 // order number right after the N. 587 MachineBasicBlock *BB = Emitter.getBlock(); 588 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos(); 589 SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N); 590 for (unsigned i = 0, e = DVs.size(); i != e; ++i) { 591 if (DVs[i]->isInvalidated()) 592 continue; 593 unsigned DVOrder = DVs[i]->getOrder(); 594 if (!Order || DVOrder == ++Order) { 595 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap); 596 if (DbgMI) { 597 Orders.push_back(std::make_pair(DVOrder, DbgMI)); 598 BB->insert(InsertPos, DbgMI); 599 } 600 DVs[i]->setIsInvalidated(); 601 } 602 } 603} 604 605// ProcessSourceNode - Process nodes with source order numbers. These are added 606// to a vector which EmitSchedule uses to determine how to insert dbg_value 607// instructions in the right order. 608static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG, 609 InstrEmitter &Emitter, 610 DenseMap<SDValue, unsigned> &VRBaseMap, 611 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders, 612 SmallSet<unsigned, 8> &Seen) { 613 unsigned Order = DAG->GetOrdering(N); 614 if (!Order || !Seen.insert(Order)) { 615 // Process any valid SDDbgValues even if node does not have any order 616 // assigned. 617 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0); 618 return; 619 } 620 621 MachineBasicBlock *BB = Emitter.getBlock(); 622 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) { 623 // Did not insert any instruction. 624 Orders.push_back(std::make_pair(Order, (MachineInstr*)0)); 625 return; 626 } 627 628 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos()))); 629 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order); 630} 631 632 633/// EmitSchedule - Emit the machine code in scheduled order. 634MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() { 635 InstrEmitter Emitter(BB, InsertPos); 636 DenseMap<SDValue, unsigned> VRBaseMap; 637 DenseMap<SUnit*, unsigned> CopyVRBaseMap; 638 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders; 639 SmallSet<unsigned, 8> Seen; 640 bool HasDbg = DAG->hasDebugValues(); 641 642 // If this is the first BB, emit byval parameter dbg_value's. 643 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) { 644 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin(); 645 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd(); 646 for (; PDI != PDE; ++PDI) { 647 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap); 648 if (DbgMI) 649 BB->insert(InsertPos, DbgMI); 650 } 651 } 652 653 for (unsigned i = 0, e = Sequence.size(); i != e; i++) { 654 SUnit *SU = Sequence[i]; 655 if (!SU) { 656 // Null SUnit* is a noop. 657 EmitNoop(); 658 continue; 659 } 660 661 // For pre-regalloc scheduling, create instructions corresponding to the 662 // SDNode and any glued SDNodes and append them to the block. 663 if (!SU->getNode()) { 664 // Emit a copy. 665 EmitPhysRegCopy(SU, CopyVRBaseMap); 666 continue; 667 } 668 669 SmallVector<SDNode *, 4> GluedNodes; 670 for (SDNode *N = SU->getNode()->getGluedNode(); N; 671 N = N->getGluedNode()) 672 GluedNodes.push_back(N); 673 while (!GluedNodes.empty()) { 674 SDNode *N = GluedNodes.back(); 675 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned, 676 VRBaseMap); 677 // Remember the source order of the inserted instruction. 678 if (HasDbg) 679 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen); 680 GluedNodes.pop_back(); 681 } 682 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned, 683 VRBaseMap); 684 // Remember the source order of the inserted instruction. 685 if (HasDbg) 686 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders, 687 Seen); 688 } 689 690 // Insert all the dbg_values which have not already been inserted in source 691 // order sequence. 692 if (HasDbg) { 693 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI(); 694 695 // Sort the source order instructions and use the order to insert debug 696 // values. 697 std::sort(Orders.begin(), Orders.end(), OrderSorter()); 698 699 SDDbgInfo::DbgIterator DI = DAG->DbgBegin(); 700 SDDbgInfo::DbgIterator DE = DAG->DbgEnd(); 701 // Now emit the rest according to source order. 702 unsigned LastOrder = 0; 703 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) { 704 unsigned Order = Orders[i].first; 705 MachineInstr *MI = Orders[i].second; 706 // Insert all SDDbgValue's whose order(s) are before "Order". 707 if (!MI) 708 continue; 709 for (; DI != DE && 710 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) { 711 if ((*DI)->isInvalidated()) 712 continue; 713 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap); 714 if (DbgMI) { 715 if (!LastOrder) 716 // Insert to start of the BB (after PHIs). 717 BB->insert(BBBegin, DbgMI); 718 else { 719 // Insert at the instruction, which may be in a different 720 // block, if the block was split by a custom inserter. 721 MachineBasicBlock::iterator Pos = MI; 722 MI->getParent()->insert(llvm::next(Pos), DbgMI); 723 } 724 } 725 } 726 LastOrder = Order; 727 } 728 // Add trailing DbgValue's before the terminator. FIXME: May want to add 729 // some of them before one or more conditional branches? 730 while (DI != DE) { 731 MachineBasicBlock *InsertBB = Emitter.getBlock(); 732 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator(); 733 if (!(*DI)->isInvalidated()) { 734 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap); 735 if (DbgMI) 736 InsertBB->insert(Pos, DbgMI); 737 } 738 ++DI; 739 } 740 } 741 742 BB = Emitter.getBlock(); 743 InsertPos = Emitter.getInsertPos(); 744 return BB; 745} 746