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