ScheduleDAG.cpp revision 5c982949bf87ffda129fb7fe372e414e255f4630
1//===---- ScheduleDAG.cpp - Implement the ScheduleDAG 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 "llvm/CodeGen/ScheduleDAG.h" 17#include "llvm/CodeGen/ScheduleHazardRecognizer.h" 18#include "llvm/Target/TargetMachine.h" 19#include "llvm/Target/TargetInstrInfo.h" 20#include "llvm/Target/TargetRegisterInfo.h" 21#include "llvm/Support/Debug.h" 22#include "llvm/Support/raw_ostream.h" 23#include <climits> 24using namespace llvm; 25 26ScheduleDAG::ScheduleDAG(MachineFunction &mf) 27 : TM(mf.getTarget()), 28 TII(TM.getInstrInfo()), 29 TRI(TM.getRegisterInfo()), 30 TLI(TM.getTargetLowering()), 31 MF(mf), MRI(mf.getRegInfo()), 32 EntrySU(), ExitSU() { 33} 34 35ScheduleDAG::~ScheduleDAG() {} 36 37/// dump - dump the schedule. 38void ScheduleDAG::dumpSchedule() const { 39 for (unsigned i = 0, e = Sequence.size(); i != e; i++) { 40 if (SUnit *SU = Sequence[i]) 41 SU->dump(this); 42 else 43 dbgs() << "**** NOOP ****\n"; 44 } 45} 46 47 48/// Run - perform scheduling. 49/// 50void ScheduleDAG::Run(MachineBasicBlock *bb, 51 MachineBasicBlock::iterator insertPos) { 52 BB = bb; 53 InsertPos = insertPos; 54 55 SUnits.clear(); 56 Sequence.clear(); 57 EntrySU = SUnit(); 58 ExitSU = SUnit(); 59 60 Schedule(); 61 62 DEBUG({ 63 dbgs() << "*** Final schedule ***\n"; 64 dumpSchedule(); 65 dbgs() << '\n'; 66 }); 67} 68 69/// addPred - This adds the specified edge as a pred of the current node if 70/// not already. It also adds the current node as a successor of the 71/// specified node. 72void SUnit::addPred(const SDep &D) { 73 // If this node already has this depenence, don't add a redundant one. 74 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end(); 75 I != E; ++I) 76 if (*I == D) 77 return; 78 // Now add a corresponding succ to N. 79 SDep P = D; 80 P.setSUnit(this); 81 SUnit *N = D.getSUnit(); 82 // Update the bookkeeping. 83 if (D.getKind() == SDep::Data) { 84 assert(NumPreds < UINT_MAX && "NumPreds will overflow!"); 85 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!"); 86 ++NumPreds; 87 ++N->NumSuccs; 88 } 89 if (!N->isScheduled) { 90 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!"); 91 ++NumPredsLeft; 92 } 93 if (!isScheduled) { 94 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!"); 95 ++N->NumSuccsLeft; 96 } 97 Preds.push_back(D); 98 N->Succs.push_back(P); 99 if (P.getLatency() != 0) { 100 this->setDepthDirty(); 101 N->setHeightDirty(); 102 } 103} 104 105/// removePred - This removes the specified edge as a pred of the current 106/// node if it exists. It also removes the current node as a successor of 107/// the specified node. 108void SUnit::removePred(const SDep &D) { 109 // Find the matching predecessor. 110 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end(); 111 I != E; ++I) 112 if (*I == D) { 113 bool FoundSucc = false; 114 // Find the corresponding successor in N. 115 SDep P = D; 116 P.setSUnit(this); 117 SUnit *N = D.getSUnit(); 118 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(), 119 EE = N->Succs.end(); II != EE; ++II) 120 if (*II == P) { 121 FoundSucc = true; 122 N->Succs.erase(II); 123 break; 124 } 125 assert(FoundSucc && "Mismatching preds / succs lists!"); 126 Preds.erase(I); 127 // Update the bookkeeping. 128 if (P.getKind() == SDep::Data) { 129 assert(NumPreds > 0 && "NumPreds will underflow!"); 130 assert(N->NumSuccs > 0 && "NumSuccs will underflow!"); 131 --NumPreds; 132 --N->NumSuccs; 133 } 134 if (!N->isScheduled) { 135 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!"); 136 --NumPredsLeft; 137 } 138 if (!isScheduled) { 139 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!"); 140 --N->NumSuccsLeft; 141 } 142 if (P.getLatency() != 0) { 143 this->setDepthDirty(); 144 N->setHeightDirty(); 145 } 146 return; 147 } 148} 149 150void SUnit::setDepthDirty() { 151 if (!isDepthCurrent) return; 152 SmallVector<SUnit*, 8> WorkList; 153 WorkList.push_back(this); 154 do { 155 SUnit *SU = WorkList.pop_back_val(); 156 SU->isDepthCurrent = false; 157 for (SUnit::const_succ_iterator I = SU->Succs.begin(), 158 E = SU->Succs.end(); I != E; ++I) { 159 SUnit *SuccSU = I->getSUnit(); 160 if (SuccSU->isDepthCurrent) 161 WorkList.push_back(SuccSU); 162 } 163 } while (!WorkList.empty()); 164} 165 166void SUnit::setHeightDirty() { 167 if (!isHeightCurrent) return; 168 SmallVector<SUnit*, 8> WorkList; 169 WorkList.push_back(this); 170 do { 171 SUnit *SU = WorkList.pop_back_val(); 172 SU->isHeightCurrent = false; 173 for (SUnit::const_pred_iterator I = SU->Preds.begin(), 174 E = SU->Preds.end(); I != E; ++I) { 175 SUnit *PredSU = I->getSUnit(); 176 if (PredSU->isHeightCurrent) 177 WorkList.push_back(PredSU); 178 } 179 } while (!WorkList.empty()); 180} 181 182/// setDepthToAtLeast - Update this node's successors to reflect the 183/// fact that this node's depth just increased. 184/// 185void SUnit::setDepthToAtLeast(unsigned NewDepth) { 186 if (NewDepth <= getDepth()) 187 return; 188 setDepthDirty(); 189 Depth = NewDepth; 190 isDepthCurrent = true; 191} 192 193/// setHeightToAtLeast - Update this node's predecessors to reflect the 194/// fact that this node's height just increased. 195/// 196void SUnit::setHeightToAtLeast(unsigned NewHeight) { 197 if (NewHeight <= getHeight()) 198 return; 199 setHeightDirty(); 200 Height = NewHeight; 201 isHeightCurrent = true; 202} 203 204/// ComputeDepth - Calculate the maximal path from the node to the exit. 205/// 206void SUnit::ComputeDepth() { 207 SmallVector<SUnit*, 8> WorkList; 208 WorkList.push_back(this); 209 do { 210 SUnit *Cur = WorkList.back(); 211 212 bool Done = true; 213 unsigned MaxPredDepth = 0; 214 for (SUnit::const_pred_iterator I = Cur->Preds.begin(), 215 E = Cur->Preds.end(); I != E; ++I) { 216 SUnit *PredSU = I->getSUnit(); 217 if (PredSU->isDepthCurrent) 218 MaxPredDepth = std::max(MaxPredDepth, 219 PredSU->Depth + I->getLatency()); 220 else { 221 Done = false; 222 WorkList.push_back(PredSU); 223 } 224 } 225 226 if (Done) { 227 WorkList.pop_back(); 228 if (MaxPredDepth != Cur->Depth) { 229 Cur->setDepthDirty(); 230 Cur->Depth = MaxPredDepth; 231 } 232 Cur->isDepthCurrent = true; 233 } 234 } while (!WorkList.empty()); 235} 236 237/// ComputeHeight - Calculate the maximal path from the node to the entry. 238/// 239void SUnit::ComputeHeight() { 240 SmallVector<SUnit*, 8> WorkList; 241 WorkList.push_back(this); 242 do { 243 SUnit *Cur = WorkList.back(); 244 245 bool Done = true; 246 unsigned MaxSuccHeight = 0; 247 for (SUnit::const_succ_iterator I = Cur->Succs.begin(), 248 E = Cur->Succs.end(); I != E; ++I) { 249 SUnit *SuccSU = I->getSUnit(); 250 if (SuccSU->isHeightCurrent) 251 MaxSuccHeight = std::max(MaxSuccHeight, 252 SuccSU->Height + I->getLatency()); 253 else { 254 Done = false; 255 WorkList.push_back(SuccSU); 256 } 257 } 258 259 if (Done) { 260 WorkList.pop_back(); 261 if (MaxSuccHeight != Cur->Height) { 262 Cur->setHeightDirty(); 263 Cur->Height = MaxSuccHeight; 264 } 265 Cur->isHeightCurrent = true; 266 } 267 } while (!WorkList.empty()); 268} 269 270/// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or 271/// a group of nodes flagged together. 272void SUnit::dump(const ScheduleDAG *G) const { 273 dbgs() << "SU(" << NodeNum << "): "; 274 G->dumpNode(this); 275} 276 277void SUnit::dumpAll(const ScheduleDAG *G) const { 278 dump(G); 279 280 dbgs() << " # preds left : " << NumPredsLeft << "\n"; 281 dbgs() << " # succs left : " << NumSuccsLeft << "\n"; 282 dbgs() << " Latency : " << Latency << "\n"; 283 dbgs() << " Depth : " << Depth << "\n"; 284 dbgs() << " Height : " << Height << "\n"; 285 286 if (Preds.size() != 0) { 287 dbgs() << " Predecessors:\n"; 288 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end(); 289 I != E; ++I) { 290 dbgs() << " "; 291 switch (I->getKind()) { 292 case SDep::Data: dbgs() << "val "; break; 293 case SDep::Anti: dbgs() << "anti"; break; 294 case SDep::Output: dbgs() << "out "; break; 295 case SDep::Order: dbgs() << "ch "; break; 296 } 297 dbgs() << "#"; 298 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")"; 299 if (I->isArtificial()) 300 dbgs() << " *"; 301 dbgs() << ": Latency=" << I->getLatency(); 302 dbgs() << "\n"; 303 } 304 } 305 if (Succs.size() != 0) { 306 dbgs() << " Successors:\n"; 307 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end(); 308 I != E; ++I) { 309 dbgs() << " "; 310 switch (I->getKind()) { 311 case SDep::Data: dbgs() << "val "; break; 312 case SDep::Anti: dbgs() << "anti"; break; 313 case SDep::Output: dbgs() << "out "; break; 314 case SDep::Order: dbgs() << "ch "; break; 315 } 316 dbgs() << "#"; 317 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")"; 318 if (I->isArtificial()) 319 dbgs() << " *"; 320 dbgs() << ": Latency=" << I->getLatency(); 321 dbgs() << "\n"; 322 } 323 } 324 dbgs() << "\n"; 325} 326 327#ifndef NDEBUG 328/// VerifySchedule - Verify that all SUnits were scheduled and that 329/// their state is consistent. 330/// 331void ScheduleDAG::VerifySchedule(bool isBottomUp) { 332 bool AnyNotSched = false; 333 unsigned DeadNodes = 0; 334 unsigned Noops = 0; 335 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 336 if (!SUnits[i].isScheduled) { 337 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) { 338 ++DeadNodes; 339 continue; 340 } 341 if (!AnyNotSched) 342 dbgs() << "*** Scheduling failed! ***\n"; 343 SUnits[i].dump(this); 344 dbgs() << "has not been scheduled!\n"; 345 AnyNotSched = true; 346 } 347 if (SUnits[i].isScheduled && 348 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) > 349 unsigned(INT_MAX)) { 350 if (!AnyNotSched) 351 dbgs() << "*** Scheduling failed! ***\n"; 352 SUnits[i].dump(this); 353 dbgs() << "has an unexpected " 354 << (isBottomUp ? "Height" : "Depth") << " value!\n"; 355 AnyNotSched = true; 356 } 357 if (isBottomUp) { 358 if (SUnits[i].NumSuccsLeft != 0) { 359 if (!AnyNotSched) 360 dbgs() << "*** Scheduling failed! ***\n"; 361 SUnits[i].dump(this); 362 dbgs() << "has successors left!\n"; 363 AnyNotSched = true; 364 } 365 } else { 366 if (SUnits[i].NumPredsLeft != 0) { 367 if (!AnyNotSched) 368 dbgs() << "*** Scheduling failed! ***\n"; 369 SUnits[i].dump(this); 370 dbgs() << "has predecessors left!\n"; 371 AnyNotSched = true; 372 } 373 } 374 } 375 for (unsigned i = 0, e = Sequence.size(); i != e; ++i) 376 if (!Sequence[i]) 377 ++Noops; 378 assert(!AnyNotSched); 379 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() && 380 "The number of nodes scheduled doesn't match the expected number!"); 381} 382#endif 383 384/// InitDAGTopologicalSorting - create the initial topological 385/// ordering from the DAG to be scheduled. 386/// 387/// The idea of the algorithm is taken from 388/// "Online algorithms for managing the topological order of 389/// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly 390/// This is the MNR algorithm, which was first introduced by 391/// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in 392/// "Maintaining a topological order under edge insertions". 393/// 394/// Short description of the algorithm: 395/// 396/// Topological ordering, ord, of a DAG maps each node to a topological 397/// index so that for all edges X->Y it is the case that ord(X) < ord(Y). 398/// 399/// This means that if there is a path from the node X to the node Z, 400/// then ord(X) < ord(Z). 401/// 402/// This property can be used to check for reachability of nodes: 403/// if Z is reachable from X, then an insertion of the edge Z->X would 404/// create a cycle. 405/// 406/// The algorithm first computes a topological ordering for the DAG by 407/// initializing the Index2Node and Node2Index arrays and then tries to keep 408/// the ordering up-to-date after edge insertions by reordering the DAG. 409/// 410/// On insertion of the edge X->Y, the algorithm first marks by calling DFS 411/// the nodes reachable from Y, and then shifts them using Shift to lie 412/// immediately after X in Index2Node. 413void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() { 414 unsigned DAGSize = SUnits.size(); 415 std::vector<SUnit*> WorkList; 416 WorkList.reserve(DAGSize); 417 418 Index2Node.resize(DAGSize); 419 Node2Index.resize(DAGSize); 420 421 // Initialize the data structures. 422 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 423 SUnit *SU = &SUnits[i]; 424 int NodeNum = SU->NodeNum; 425 unsigned Degree = SU->Succs.size(); 426 // Temporarily use the Node2Index array as scratch space for degree counts. 427 Node2Index[NodeNum] = Degree; 428 429 // Is it a node without dependencies? 430 if (Degree == 0) { 431 assert(SU->Succs.empty() && "SUnit should have no successors"); 432 // Collect leaf nodes. 433 WorkList.push_back(SU); 434 } 435 } 436 437 int Id = DAGSize; 438 while (!WorkList.empty()) { 439 SUnit *SU = WorkList.back(); 440 WorkList.pop_back(); 441 Allocate(SU->NodeNum, --Id); 442 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 443 I != E; ++I) { 444 SUnit *SU = I->getSUnit(); 445 if (!--Node2Index[SU->NodeNum]) 446 // If all dependencies of the node are processed already, 447 // then the node can be computed now. 448 WorkList.push_back(SU); 449 } 450 } 451 452 Visited.resize(DAGSize); 453 454#ifndef NDEBUG 455 // Check correctness of the ordering 456 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 457 SUnit *SU = &SUnits[i]; 458 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 459 I != E; ++I) { 460 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] && 461 "Wrong topological sorting"); 462 } 463 } 464#endif 465} 466 467/// AddPred - Updates the topological ordering to accomodate an edge 468/// to be added from SUnit X to SUnit Y. 469void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) { 470 int UpperBound, LowerBound; 471 LowerBound = Node2Index[Y->NodeNum]; 472 UpperBound = Node2Index[X->NodeNum]; 473 bool HasLoop = false; 474 // Is Ord(X) < Ord(Y) ? 475 if (LowerBound < UpperBound) { 476 // Update the topological order. 477 Visited.reset(); 478 DFS(Y, UpperBound, HasLoop); 479 assert(!HasLoop && "Inserted edge creates a loop!"); 480 // Recompute topological indexes. 481 Shift(Visited, LowerBound, UpperBound); 482 } 483} 484 485/// RemovePred - Updates the topological ordering to accomodate an 486/// an edge to be removed from the specified node N from the predecessors 487/// of the current node M. 488void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) { 489 // InitDAGTopologicalSorting(); 490} 491 492/// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark 493/// all nodes affected by the edge insertion. These nodes will later get new 494/// topological indexes by means of the Shift method. 495void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound, 496 bool& HasLoop) { 497 std::vector<const SUnit*> WorkList; 498 WorkList.reserve(SUnits.size()); 499 500 WorkList.push_back(SU); 501 do { 502 SU = WorkList.back(); 503 WorkList.pop_back(); 504 Visited.set(SU->NodeNum); 505 for (int I = SU->Succs.size()-1; I >= 0; --I) { 506 int s = SU->Succs[I].getSUnit()->NodeNum; 507 if (Node2Index[s] == UpperBound) { 508 HasLoop = true; 509 return; 510 } 511 // Visit successors if not already and in affected region. 512 if (!Visited.test(s) && Node2Index[s] < UpperBound) { 513 WorkList.push_back(SU->Succs[I].getSUnit()); 514 } 515 } 516 } while (!WorkList.empty()); 517} 518 519/// Shift - Renumber the nodes so that the topological ordering is 520/// preserved. 521void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound, 522 int UpperBound) { 523 std::vector<int> L; 524 int shift = 0; 525 int i; 526 527 for (i = LowerBound; i <= UpperBound; ++i) { 528 // w is node at topological index i. 529 int w = Index2Node[i]; 530 if (Visited.test(w)) { 531 // Unmark. 532 Visited.reset(w); 533 L.push_back(w); 534 shift = shift + 1; 535 } else { 536 Allocate(w, i - shift); 537 } 538 } 539 540 for (unsigned j = 0; j < L.size(); ++j) { 541 Allocate(L[j], i - shift); 542 i = i + 1; 543 } 544} 545 546 547/// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will 548/// create a cycle. 549bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) { 550 if (IsReachable(TargetSU, SU)) 551 return true; 552 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 553 I != E; ++I) 554 if (I->isAssignedRegDep() && 555 IsReachable(TargetSU, I->getSUnit())) 556 return true; 557 return false; 558} 559 560/// IsReachable - Checks if SU is reachable from TargetSU. 561bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU, 562 const SUnit *TargetSU) { 563 // If insertion of the edge SU->TargetSU would create a cycle 564 // then there is a path from TargetSU to SU. 565 int UpperBound, LowerBound; 566 LowerBound = Node2Index[TargetSU->NodeNum]; 567 UpperBound = Node2Index[SU->NodeNum]; 568 bool HasLoop = false; 569 // Is Ord(TargetSU) < Ord(SU) ? 570 if (LowerBound < UpperBound) { 571 Visited.reset(); 572 // There may be a path from TargetSU to SU. Check for it. 573 DFS(TargetSU, UpperBound, HasLoop); 574 } 575 return HasLoop; 576} 577 578/// Allocate - assign the topological index to the node n. 579void ScheduleDAGTopologicalSort::Allocate(int n, int index) { 580 Node2Index[n] = index; 581 Index2Node[index] = n; 582} 583 584ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort( 585 std::vector<SUnit> &sunits) 586 : SUnits(sunits) {} 587 588ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {} 589