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