MachineScheduler.cpp 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  1. //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
  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. // MachineScheduler schedules machine instructions after phi elimination. It
  11. // preserves LiveIntervals so it can be invoked before register allocation.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #define DEBUG_TYPE "misched"
  15. #include "llvm/CodeGen/MachineScheduler.h"
  16. #include "llvm/ADT/OwningPtr.h"
  17. #include "llvm/ADT/PriorityQueue.h"
  18. #include "llvm/Analysis/AliasAnalysis.h"
  19. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  20. #include "llvm/CodeGen/MachineDominators.h"
  21. #include "llvm/CodeGen/MachineLoopInfo.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/CodeGen/Passes.h"
  24. #include "llvm/CodeGen/RegisterClassInfo.h"
  25. #include "llvm/CodeGen/ScheduleDFS.h"
  26. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/GraphWriter.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Target/TargetInstrInfo.h"
  33. #include <queue>
  34. using namespace llvm;
  35. namespace llvm {
  36. cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
  37. cl::desc("Force top-down list scheduling"));
  38. cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
  39. cl::desc("Force bottom-up list scheduling"));
  40. }
  41. #ifndef NDEBUG
  42. static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
  43. cl::desc("Pop up a window to show MISched dags after they are processed"));
  44. static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
  45. cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
  46. #else
  47. static bool ViewMISchedDAGs = false;
  48. #endif // NDEBUG
  49. static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
  50. cl::desc("Enable register pressure scheduling."), cl::init(true));
  51. static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
  52. cl::desc("Enable cyclic critical path analysis."), cl::init(false));
  53. static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
  54. cl::desc("Enable load clustering."), cl::init(true));
  55. // Experimental heuristics
  56. static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
  57. cl::desc("Enable scheduling for macro fusion."), cl::init(true));
  58. static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
  59. cl::desc("Verify machine instrs before and after machine scheduling"));
  60. // DAG subtrees must have at least this many nodes.
  61. static const unsigned MinSubtreeSize = 8;
  62. //===----------------------------------------------------------------------===//
  63. // Machine Instruction Scheduling Pass and Registry
  64. //===----------------------------------------------------------------------===//
  65. MachineSchedContext::MachineSchedContext():
  66. MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
  67. RegClassInfo = new RegisterClassInfo();
  68. }
  69. MachineSchedContext::~MachineSchedContext() {
  70. delete RegClassInfo;
  71. }
  72. namespace {
  73. /// MachineScheduler runs after coalescing and before register allocation.
  74. class MachineScheduler : public MachineSchedContext,
  75. public MachineFunctionPass {
  76. public:
  77. MachineScheduler();
  78. virtual void getAnalysisUsage(AnalysisUsage &AU) const;
  79. virtual void releaseMemory() {}
  80. virtual bool runOnMachineFunction(MachineFunction&);
  81. virtual void print(raw_ostream &O, const Module* = 0) const;
  82. static char ID; // Class identification, replacement for typeinfo
  83. };
  84. } // namespace
  85. char MachineScheduler::ID = 0;
  86. char &llvm::MachineSchedulerID = MachineScheduler::ID;
  87. INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
  88. "Machine Instruction Scheduler", false, false)
  89. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  90. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  91. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  92. INITIALIZE_PASS_END(MachineScheduler, "misched",
  93. "Machine Instruction Scheduler", false, false)
  94. MachineScheduler::MachineScheduler()
  95. : MachineFunctionPass(ID) {
  96. initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
  97. }
  98. void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
  99. AU.setPreservesCFG();
  100. AU.addRequiredID(MachineDominatorsID);
  101. AU.addRequired<MachineLoopInfo>();
  102. AU.addRequired<AliasAnalysis>();
  103. AU.addRequired<TargetPassConfig>();
  104. AU.addRequired<SlotIndexes>();
  105. AU.addPreserved<SlotIndexes>();
  106. AU.addRequired<LiveIntervals>();
  107. AU.addPreserved<LiveIntervals>();
  108. MachineFunctionPass::getAnalysisUsage(AU);
  109. }
  110. MachinePassRegistry MachineSchedRegistry::Registry;
  111. /// A dummy default scheduler factory indicates whether the scheduler
  112. /// is overridden on the command line.
  113. static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
  114. return 0;
  115. }
  116. /// MachineSchedOpt allows command line selection of the scheduler.
  117. static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
  118. RegisterPassParser<MachineSchedRegistry> >
  119. MachineSchedOpt("misched",
  120. cl::init(&useDefaultMachineSched), cl::Hidden,
  121. cl::desc("Machine instruction scheduler to use"));
  122. static MachineSchedRegistry
  123. DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
  124. useDefaultMachineSched);
  125. /// Forward declare the standard machine scheduler. This will be used as the
  126. /// default scheduler if the target does not set a default.
  127. static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
  128. /// Decrement this iterator until reaching the top or a non-debug instr.
  129. static MachineBasicBlock::const_iterator
  130. priorNonDebug(MachineBasicBlock::const_iterator I,
  131. MachineBasicBlock::const_iterator Beg) {
  132. assert(I != Beg && "reached the top of the region, cannot decrement");
  133. while (--I != Beg) {
  134. if (!I->isDebugValue())
  135. break;
  136. }
  137. return I;
  138. }
  139. /// Non-const version.
  140. static MachineBasicBlock::iterator
  141. priorNonDebug(MachineBasicBlock::iterator I,
  142. MachineBasicBlock::const_iterator Beg) {
  143. return const_cast<MachineInstr*>(
  144. &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
  145. }
  146. /// If this iterator is a debug value, increment until reaching the End or a
  147. /// non-debug instruction.
  148. static MachineBasicBlock::const_iterator
  149. nextIfDebug(MachineBasicBlock::const_iterator I,
  150. MachineBasicBlock::const_iterator End) {
  151. for(; I != End; ++I) {
  152. if (!I->isDebugValue())
  153. break;
  154. }
  155. return I;
  156. }
  157. /// Non-const version.
  158. static MachineBasicBlock::iterator
  159. nextIfDebug(MachineBasicBlock::iterator I,
  160. MachineBasicBlock::const_iterator End) {
  161. // Cast the return value to nonconst MachineInstr, then cast to an
  162. // instr_iterator, which does not check for null, finally return a
  163. // bundle_iterator.
  164. return MachineBasicBlock::instr_iterator(
  165. const_cast<MachineInstr*>(
  166. &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
  167. }
  168. /// Top-level MachineScheduler pass driver.
  169. ///
  170. /// Visit blocks in function order. Divide each block into scheduling regions
  171. /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
  172. /// consistent with the DAG builder, which traverses the interior of the
  173. /// scheduling regions bottom-up.
  174. ///
  175. /// This design avoids exposing scheduling boundaries to the DAG builder,
  176. /// simplifying the DAG builder's support for "special" target instructions.
  177. /// At the same time the design allows target schedulers to operate across
  178. /// scheduling boundaries, for example to bundle the boudary instructions
  179. /// without reordering them. This creates complexity, because the target
  180. /// scheduler must update the RegionBegin and RegionEnd positions cached by
  181. /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
  182. /// design would be to split blocks at scheduling boundaries, but LLVM has a
  183. /// general bias against block splitting purely for implementation simplicity.
  184. bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
  185. DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
  186. // Initialize the context of the pass.
  187. MF = &mf;
  188. MLI = &getAnalysis<MachineLoopInfo>();
  189. MDT = &getAnalysis<MachineDominatorTree>();
  190. PassConfig = &getAnalysis<TargetPassConfig>();
  191. AA = &getAnalysis<AliasAnalysis>();
  192. LIS = &getAnalysis<LiveIntervals>();
  193. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  194. if (VerifyScheduling) {
  195. DEBUG(LIS->dump());
  196. MF->verify(this, "Before machine scheduling.");
  197. }
  198. RegClassInfo->runOnMachineFunction(*MF);
  199. // Select the scheduler, or set the default.
  200. MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
  201. if (Ctor == useDefaultMachineSched) {
  202. // Get the default scheduler set by the target.
  203. Ctor = MachineSchedRegistry::getDefault();
  204. if (!Ctor) {
  205. Ctor = createConvergingSched;
  206. MachineSchedRegistry::setDefault(Ctor);
  207. }
  208. }
  209. // Instantiate the selected scheduler.
  210. OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
  211. // Visit all machine basic blocks.
  212. //
  213. // TODO: Visit blocks in global postorder or postorder within the bottom-up
  214. // loop tree. Then we can optionally compute global RegPressure.
  215. for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
  216. MBB != MBBEnd; ++MBB) {
  217. Scheduler->startBlock(MBB);
  218. // Break the block into scheduling regions [I, RegionEnd), and schedule each
  219. // region as soon as it is discovered. RegionEnd points the scheduling
  220. // boundary at the bottom of the region. The DAG does not include RegionEnd,
  221. // but the region does (i.e. the next RegionEnd is above the previous
  222. // RegionBegin). If the current block has no terminator then RegionEnd ==
  223. // MBB->end() for the bottom region.
  224. //
  225. // The Scheduler may insert instructions during either schedule() or
  226. // exitRegion(), even for empty regions. So the local iterators 'I' and
  227. // 'RegionEnd' are invalid across these calls.
  228. unsigned RemainingInstrs = MBB->size();
  229. for(MachineBasicBlock::iterator RegionEnd = MBB->end();
  230. RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
  231. // Avoid decrementing RegionEnd for blocks with no terminator.
  232. if (RegionEnd != MBB->end()
  233. || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
  234. --RegionEnd;
  235. // Count the boundary instruction.
  236. --RemainingInstrs;
  237. }
  238. // The next region starts above the previous region. Look backward in the
  239. // instruction stream until we find the nearest boundary.
  240. unsigned NumRegionInstrs = 0;
  241. MachineBasicBlock::iterator I = RegionEnd;
  242. for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
  243. if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
  244. break;
  245. }
  246. // Notify the scheduler of the region, even if we may skip scheduling
  247. // it. Perhaps it still needs to be bundled.
  248. Scheduler->enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
  249. // Skip empty scheduling regions (0 or 1 schedulable instructions).
  250. if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
  251. // Close the current region. Bundle the terminator if needed.
  252. // This invalidates 'RegionEnd' and 'I'.
  253. Scheduler->exitRegion();
  254. continue;
  255. }
  256. DEBUG(dbgs() << "********** MI Scheduling **********\n");
  257. DEBUG(dbgs() << MF->getName()
  258. << ":BB#" << MBB->getNumber() << " " << MBB->getName()
  259. << "\n From: " << *I << " To: ";
  260. if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
  261. else dbgs() << "End";
  262. dbgs() << " RegionInstrs: " << NumRegionInstrs
  263. << " Remaining: " << RemainingInstrs << "\n");
  264. // Schedule a region: possibly reorder instructions.
  265. // This invalidates 'RegionEnd' and 'I'.
  266. Scheduler->schedule();
  267. // Close the current region.
  268. Scheduler->exitRegion();
  269. // Scheduling has invalidated the current iterator 'I'. Ask the
  270. // scheduler for the top of it's scheduled region.
  271. RegionEnd = Scheduler->begin();
  272. }
  273. assert(RemainingInstrs == 0 && "Instruction count mismatch!");
  274. Scheduler->finishBlock();
  275. }
  276. Scheduler->finalizeSchedule();
  277. DEBUG(LIS->dump());
  278. if (VerifyScheduling)
  279. MF->verify(this, "After machine scheduling.");
  280. return true;
  281. }
  282. void MachineScheduler::print(raw_ostream &O, const Module* m) const {
  283. // unimplemented
  284. }
  285. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  286. void ReadyQueue::dump() {
  287. dbgs() << Name << ": ";
  288. for (unsigned i = 0, e = Queue.size(); i < e; ++i)
  289. dbgs() << Queue[i]->NodeNum << " ";
  290. dbgs() << "\n";
  291. }
  292. #endif
  293. //===----------------------------------------------------------------------===//
  294. // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
  295. // preservation.
  296. //===----------------------------------------------------------------------===//
  297. ScheduleDAGMI::~ScheduleDAGMI() {
  298. delete DFSResult;
  299. DeleteContainerPointers(Mutations);
  300. delete SchedImpl;
  301. }
  302. bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
  303. return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
  304. }
  305. bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
  306. if (SuccSU != &ExitSU) {
  307. // Do not use WillCreateCycle, it assumes SD scheduling.
  308. // If Pred is reachable from Succ, then the edge creates a cycle.
  309. if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
  310. return false;
  311. Topo.AddPred(SuccSU, PredDep.getSUnit());
  312. }
  313. SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
  314. // Return true regardless of whether a new edge needed to be inserted.
  315. return true;
  316. }
  317. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
  318. /// NumPredsLeft reaches zero, release the successor node.
  319. ///
  320. /// FIXME: Adjust SuccSU height based on MinLatency.
  321. void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
  322. SUnit *SuccSU = SuccEdge->getSUnit();
  323. if (SuccEdge->isWeak()) {
  324. --SuccSU->WeakPredsLeft;
  325. if (SuccEdge->isCluster())
  326. NextClusterSucc = SuccSU;
  327. return;
  328. }
  329. #ifndef NDEBUG
  330. if (SuccSU->NumPredsLeft == 0) {
  331. dbgs() << "*** Scheduling failed! ***\n";
  332. SuccSU->dump(this);
  333. dbgs() << " has been released too many times!\n";
  334. llvm_unreachable(0);
  335. }
  336. #endif
  337. --SuccSU->NumPredsLeft;
  338. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  339. SchedImpl->releaseTopNode(SuccSU);
  340. }
  341. /// releaseSuccessors - Call releaseSucc on each of SU's successors.
  342. void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
  343. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  344. I != E; ++I) {
  345. releaseSucc(SU, &*I);
  346. }
  347. }
  348. /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
  349. /// NumSuccsLeft reaches zero, release the predecessor node.
  350. ///
  351. /// FIXME: Adjust PredSU height based on MinLatency.
  352. void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
  353. SUnit *PredSU = PredEdge->getSUnit();
  354. if (PredEdge->isWeak()) {
  355. --PredSU->WeakSuccsLeft;
  356. if (PredEdge->isCluster())
  357. NextClusterPred = PredSU;
  358. return;
  359. }
  360. #ifndef NDEBUG
  361. if (PredSU->NumSuccsLeft == 0) {
  362. dbgs() << "*** Scheduling failed! ***\n";
  363. PredSU->dump(this);
  364. dbgs() << " has been released too many times!\n";
  365. llvm_unreachable(0);
  366. }
  367. #endif
  368. --PredSU->NumSuccsLeft;
  369. if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
  370. SchedImpl->releaseBottomNode(PredSU);
  371. }
  372. /// releasePredecessors - Call releasePred on each of SU's predecessors.
  373. void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
  374. for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
  375. I != E; ++I) {
  376. releasePred(SU, &*I);
  377. }
  378. }
  379. /// This is normally called from the main scheduler loop but may also be invoked
  380. /// by the scheduling strategy to perform additional code motion.
  381. void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
  382. MachineBasicBlock::iterator InsertPos) {
  383. // Advance RegionBegin if the first instruction moves down.
  384. if (&*RegionBegin == MI)
  385. ++RegionBegin;
  386. // Update the instruction stream.
  387. BB->splice(InsertPos, BB, MI);
  388. // Update LiveIntervals
  389. LIS->handleMove(MI, /*UpdateFlags=*/true);
  390. // Recede RegionBegin if an instruction moves above the first.
  391. if (RegionBegin == InsertPos)
  392. RegionBegin = MI;
  393. }
  394. bool ScheduleDAGMI::checkSchedLimit() {
  395. #ifndef NDEBUG
  396. if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
  397. CurrentTop = CurrentBottom;
  398. return false;
  399. }
  400. ++NumInstrsScheduled;
  401. #endif
  402. return true;
  403. }
  404. /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
  405. /// crossing a scheduling boundary. [begin, end) includes all instructions in
  406. /// the region, including the boundary itself and single-instruction regions
  407. /// that don't get scheduled.
  408. void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
  409. MachineBasicBlock::iterator begin,
  410. MachineBasicBlock::iterator end,
  411. unsigned regioninstrs)
  412. {
  413. ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
  414. // For convenience remember the end of the liveness region.
  415. LiveRegionEnd =
  416. (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
  417. SchedImpl->initPolicy(begin, end, regioninstrs);
  418. ShouldTrackPressure = SchedImpl->shouldTrackPressure();
  419. }
  420. // Setup the register pressure trackers for the top scheduled top and bottom
  421. // scheduled regions.
  422. void ScheduleDAGMI::initRegPressure() {
  423. TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
  424. BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
  425. // Close the RPTracker to finalize live ins.
  426. RPTracker.closeRegion();
  427. DEBUG(RPTracker.dump());
  428. // Initialize the live ins and live outs.
  429. TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
  430. BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
  431. // Close one end of the tracker so we can call
  432. // getMaxUpward/DownwardPressureDelta before advancing across any
  433. // instructions. This converts currently live regs into live ins/outs.
  434. TopRPTracker.closeTop();
  435. BotRPTracker.closeBottom();
  436. BotRPTracker.initLiveThru(RPTracker);
  437. if (!BotRPTracker.getLiveThru().empty()) {
  438. TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
  439. DEBUG(dbgs() << "Live Thru: ";
  440. dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
  441. };
  442. // For each live out vreg reduce the pressure change associated with other
  443. // uses of the same vreg below the live-out reaching def.
  444. updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
  445. // Account for liveness generated by the region boundary.
  446. if (LiveRegionEnd != RegionEnd) {
  447. SmallVector<unsigned, 8> LiveUses;
  448. BotRPTracker.recede(&LiveUses);
  449. updatePressureDiffs(LiveUses);
  450. }
  451. assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
  452. // Cache the list of excess pressure sets in this region. This will also track
  453. // the max pressure in the scheduled code for these sets.
  454. RegionCriticalPSets.clear();
  455. const std::vector<unsigned> &RegionPressure =
  456. RPTracker.getPressure().MaxSetPressure;
  457. for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
  458. unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
  459. if (RegionPressure[i] > Limit) {
  460. DEBUG(dbgs() << TRI->getRegPressureSetName(i)
  461. << " Limit " << Limit
  462. << " Actual " << RegionPressure[i] << "\n");
  463. RegionCriticalPSets.push_back(PressureChange(i));
  464. }
  465. }
  466. DEBUG(dbgs() << "Excess PSets: ";
  467. for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
  468. dbgs() << TRI->getRegPressureSetName(
  469. RegionCriticalPSets[i].getPSet()) << " ";
  470. dbgs() << "\n");
  471. }
  472. // FIXME: When the pressure tracker deals in pressure differences then we won't
  473. // iterate over all RegionCriticalPSets[i].
  474. void ScheduleDAGMI::
  475. updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
  476. for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
  477. unsigned ID = RegionCriticalPSets[i].getPSet();
  478. if ((int)NewMaxPressure[ID] > RegionCriticalPSets[i].getUnitInc()
  479. && NewMaxPressure[ID] <= INT16_MAX)
  480. RegionCriticalPSets[i].setUnitInc(NewMaxPressure[ID]);
  481. }
  482. DEBUG(
  483. for (unsigned i = 0, e = NewMaxPressure.size(); i < e; ++i) {
  484. unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
  485. if (NewMaxPressure[i] > Limit ) {
  486. dbgs() << " " << TRI->getRegPressureSetName(i) << ": "
  487. << NewMaxPressure[i] << " > " << Limit << "\n";
  488. }
  489. });
  490. }
  491. /// Update the PressureDiff array for liveness after scheduling this
  492. /// instruction.
  493. void ScheduleDAGMI::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
  494. for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
  495. /// FIXME: Currently assuming single-use physregs.
  496. unsigned Reg = LiveUses[LUIdx];
  497. DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
  498. if (!TRI->isVirtualRegister(Reg))
  499. continue;
  500. // This may be called before CurrentBottom has been initialized. However,
  501. // BotRPTracker must have a valid position. We want the value live into the
  502. // instruction or live out of the block, so ask for the previous
  503. // instruction's live-out.
  504. const LiveInterval &LI = LIS->getInterval(Reg);
  505. VNInfo *VNI;
  506. MachineBasicBlock::const_iterator I =
  507. nextIfDebug(BotRPTracker.getPos(), BB->end());
  508. if (I == BB->end())
  509. VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
  510. else {
  511. LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(I));
  512. VNI = LRQ.valueIn();
  513. }
  514. // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
  515. assert(VNI && "No live value at use.");
  516. for (VReg2UseMap::iterator
  517. UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
  518. SUnit *SU = UI->SU;
  519. DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
  520. << *SU->getInstr());
  521. // If this use comes before the reaching def, it cannot be a last use, so
  522. // descrease its pressure change.
  523. if (!SU->isScheduled && SU != &ExitSU) {
  524. LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(SU->getInstr()));
  525. if (LRQ.valueIn() == VNI)
  526. getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
  527. }
  528. }
  529. }
  530. }
  531. /// schedule - Called back from MachineScheduler::runOnMachineFunction
  532. /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
  533. /// only includes instructions that have DAG nodes, not scheduling boundaries.
  534. ///
  535. /// This is a skeletal driver, with all the functionality pushed into helpers,
  536. /// so that it can be easilly extended by experimental schedulers. Generally,
  537. /// implementing MachineSchedStrategy should be sufficient to implement a new
  538. /// scheduling algorithm. However, if a scheduler further subclasses
  539. /// ScheduleDAGMI then it will want to override this virtual method in order to
  540. /// update any specialized state.
  541. void ScheduleDAGMI::schedule() {
  542. buildDAGWithRegPressure();
  543. Topo.InitDAGTopologicalSorting();
  544. postprocessDAG();
  545. SmallVector<SUnit*, 8> TopRoots, BotRoots;
  546. findRootsAndBiasEdges(TopRoots, BotRoots);
  547. // Initialize the strategy before modifying the DAG.
  548. // This may initialize a DFSResult to be used for queue priority.
  549. SchedImpl->initialize(this);
  550. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  551. SUnits[su].dumpAll(this));
  552. if (ViewMISchedDAGs) viewGraph();
  553. // Initialize ready queues now that the DAG and priority data are finalized.
  554. initQueues(TopRoots, BotRoots);
  555. bool IsTopNode = false;
  556. while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
  557. assert(!SU->isScheduled && "Node already scheduled");
  558. if (!checkSchedLimit())
  559. break;
  560. scheduleMI(SU, IsTopNode);
  561. updateQueues(SU, IsTopNode);
  562. }
  563. assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
  564. placeDebugValues();
  565. DEBUG({
  566. unsigned BBNum = begin()->getParent()->getNumber();
  567. dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
  568. dumpSchedule();
  569. dbgs() << '\n';
  570. });
  571. }
  572. /// Build the DAG and setup three register pressure trackers.
  573. void ScheduleDAGMI::buildDAGWithRegPressure() {
  574. if (!ShouldTrackPressure) {
  575. RPTracker.reset();
  576. RegionCriticalPSets.clear();
  577. buildSchedGraph(AA);
  578. return;
  579. }
  580. // Initialize the register pressure tracker used by buildSchedGraph.
  581. RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
  582. /*TrackUntiedDefs=*/true);
  583. // Account for liveness generate by the region boundary.
  584. if (LiveRegionEnd != RegionEnd)
  585. RPTracker.recede();
  586. // Build the DAG, and compute current register pressure.
  587. buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
  588. // Initialize top/bottom trackers after computing region pressure.
  589. initRegPressure();
  590. }
  591. /// Apply each ScheduleDAGMutation step in order.
  592. void ScheduleDAGMI::postprocessDAG() {
  593. for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
  594. Mutations[i]->apply(this);
  595. }
  596. }
  597. void ScheduleDAGMI::computeDFSResult() {
  598. if (!DFSResult)
  599. DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
  600. DFSResult->clear();
  601. ScheduledTrees.clear();
  602. DFSResult->resize(SUnits.size());
  603. DFSResult->compute(SUnits);
  604. ScheduledTrees.resize(DFSResult->getNumSubtrees());
  605. }
  606. void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
  607. SmallVectorImpl<SUnit*> &BotRoots) {
  608. for (std::vector<SUnit>::iterator
  609. I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
  610. SUnit *SU = &(*I);
  611. assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
  612. // Order predecessors so DFSResult follows the critical path.
  613. SU->biasCriticalPath();
  614. // A SUnit is ready to top schedule if it has no predecessors.
  615. if (!I->NumPredsLeft)
  616. TopRoots.push_back(SU);
  617. // A SUnit is ready to bottom schedule if it has no successors.
  618. if (!I->NumSuccsLeft)
  619. BotRoots.push_back(SU);
  620. }
  621. ExitSU.biasCriticalPath();
  622. }
  623. /// Compute the max cyclic critical path through the DAG. The scheduling DAG
  624. /// only provides the critical path for single block loops. To handle loops that
  625. /// span blocks, we could use the vreg path latencies provided by
  626. /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
  627. /// available for use in the scheduler.
  628. ///
  629. /// The cyclic path estimation identifies a def-use pair that crosses the back
  630. /// edge and considers the depth and height of the nodes. For example, consider
  631. /// the following instruction sequence where each instruction has unit latency
  632. /// and defines an epomymous virtual register:
  633. ///
  634. /// a->b(a,c)->c(b)->d(c)->exit
  635. ///
  636. /// The cyclic critical path is a two cycles: b->c->b
  637. /// The acyclic critical path is four cycles: a->b->c->d->exit
  638. /// LiveOutHeight = height(c) = len(c->d->exit) = 2
  639. /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
  640. /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
  641. /// LiveInDepth = depth(b) = len(a->b) = 1
  642. ///
  643. /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
  644. /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
  645. /// CyclicCriticalPath = min(2, 2) = 2
  646. unsigned ScheduleDAGMI::computeCyclicCriticalPath() {
  647. // This only applies to single block loop.
  648. if (!BB->isSuccessor(BB))
  649. return 0;
  650. unsigned MaxCyclicLatency = 0;
  651. // Visit each live out vreg def to find def/use pairs that cross iterations.
  652. ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
  653. for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
  654. RI != RE; ++RI) {
  655. unsigned Reg = *RI;
  656. if (!TRI->isVirtualRegister(Reg))
  657. continue;
  658. const LiveInterval &LI = LIS->getInterval(Reg);
  659. const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
  660. if (!DefVNI)
  661. continue;
  662. MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
  663. const SUnit *DefSU = getSUnit(DefMI);
  664. if (!DefSU)
  665. continue;
  666. unsigned LiveOutHeight = DefSU->getHeight();
  667. unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
  668. // Visit all local users of the vreg def.
  669. for (VReg2UseMap::iterator
  670. UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
  671. if (UI->SU == &ExitSU)
  672. continue;
  673. // Only consider uses of the phi.
  674. LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(UI->SU->getInstr()));
  675. if (!LRQ.valueIn()->isPHIDef())
  676. continue;
  677. // Assume that a path spanning two iterations is a cycle, which could
  678. // overestimate in strange cases. This allows cyclic latency to be
  679. // estimated as the minimum slack of the vreg's depth or height.
  680. unsigned CyclicLatency = 0;
  681. if (LiveOutDepth > UI->SU->getDepth())
  682. CyclicLatency = LiveOutDepth - UI->SU->getDepth();
  683. unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
  684. if (LiveInHeight > LiveOutHeight) {
  685. if (LiveInHeight - LiveOutHeight < CyclicLatency)
  686. CyclicLatency = LiveInHeight - LiveOutHeight;
  687. }
  688. else
  689. CyclicLatency = 0;
  690. DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
  691. << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
  692. if (CyclicLatency > MaxCyclicLatency)
  693. MaxCyclicLatency = CyclicLatency;
  694. }
  695. }
  696. DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
  697. return MaxCyclicLatency;
  698. }
  699. /// Identify DAG roots and setup scheduler queues.
  700. void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
  701. ArrayRef<SUnit*> BotRoots) {
  702. NextClusterSucc = NULL;
  703. NextClusterPred = NULL;
  704. // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
  705. //
  706. // Nodes with unreleased weak edges can still be roots.
  707. // Release top roots in forward order.
  708. for (SmallVectorImpl<SUnit*>::const_iterator
  709. I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
  710. SchedImpl->releaseTopNode(*I);
  711. }
  712. // Release bottom roots in reverse order so the higher priority nodes appear
  713. // first. This is more natural and slightly more efficient.
  714. for (SmallVectorImpl<SUnit*>::const_reverse_iterator
  715. I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
  716. SchedImpl->releaseBottomNode(*I);
  717. }
  718. releaseSuccessors(&EntrySU);
  719. releasePredecessors(&ExitSU);
  720. SchedImpl->registerRoots();
  721. // Advance past initial DebugValues.
  722. CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
  723. CurrentBottom = RegionEnd;
  724. if (ShouldTrackPressure) {
  725. assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
  726. TopRPTracker.setPos(CurrentTop);
  727. }
  728. }
  729. /// Move an instruction and update register pressure.
  730. void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
  731. // Move the instruction to its new location in the instruction stream.
  732. MachineInstr *MI = SU->getInstr();
  733. if (IsTopNode) {
  734. assert(SU->isTopReady() && "node still has unscheduled dependencies");
  735. if (&*CurrentTop == MI)
  736. CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
  737. else {
  738. moveInstruction(MI, CurrentTop);
  739. TopRPTracker.setPos(MI);
  740. }
  741. if (ShouldTrackPressure) {
  742. // Update top scheduled pressure.
  743. TopRPTracker.advance();
  744. assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
  745. updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
  746. }
  747. }
  748. else {
  749. assert(SU->isBottomReady() && "node still has unscheduled dependencies");
  750. MachineBasicBlock::iterator priorII =
  751. priorNonDebug(CurrentBottom, CurrentTop);
  752. if (&*priorII == MI)
  753. CurrentBottom = priorII;
  754. else {
  755. if (&*CurrentTop == MI) {
  756. CurrentTop = nextIfDebug(++CurrentTop, priorII);
  757. TopRPTracker.setPos(CurrentTop);
  758. }
  759. moveInstruction(MI, CurrentBottom);
  760. CurrentBottom = MI;
  761. }
  762. if (ShouldTrackPressure) {
  763. // Update bottom scheduled pressure.
  764. SmallVector<unsigned, 8> LiveUses;
  765. BotRPTracker.recede(&LiveUses);
  766. assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
  767. updatePressureDiffs(LiveUses);
  768. updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
  769. }
  770. }
  771. }
  772. /// Update scheduler queues after scheduling an instruction.
  773. void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
  774. // Release dependent instructions for scheduling.
  775. if (IsTopNode)
  776. releaseSuccessors(SU);
  777. else
  778. releasePredecessors(SU);
  779. SU->isScheduled = true;
  780. if (DFSResult) {
  781. unsigned SubtreeID = DFSResult->getSubtreeID(SU);
  782. if (!ScheduledTrees.test(SubtreeID)) {
  783. ScheduledTrees.set(SubtreeID);
  784. DFSResult->scheduleTree(SubtreeID);
  785. SchedImpl->scheduleTree(SubtreeID);
  786. }
  787. }
  788. // Notify the scheduling strategy after updating the DAG.
  789. SchedImpl->schedNode(SU, IsTopNode);
  790. }
  791. /// Reinsert any remaining debug_values, just like the PostRA scheduler.
  792. void ScheduleDAGMI::placeDebugValues() {
  793. // If first instruction was a DBG_VALUE then put it back.
  794. if (FirstDbgValue) {
  795. BB->splice(RegionBegin, BB, FirstDbgValue);
  796. RegionBegin = FirstDbgValue;
  797. }
  798. for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
  799. DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
  800. std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
  801. MachineInstr *DbgValue = P.first;
  802. MachineBasicBlock::iterator OrigPrevMI = P.second;
  803. if (&*RegionBegin == DbgValue)
  804. ++RegionBegin;
  805. BB->splice(++OrigPrevMI, BB, DbgValue);
  806. if (OrigPrevMI == llvm::prior(RegionEnd))
  807. RegionEnd = DbgValue;
  808. }
  809. DbgValues.clear();
  810. FirstDbgValue = NULL;
  811. }
  812. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  813. void ScheduleDAGMI::dumpSchedule() const {
  814. for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
  815. if (SUnit *SU = getSUnit(&(*MI)))
  816. SU->dump(this);
  817. else
  818. dbgs() << "Missing SUnit\n";
  819. }
  820. }
  821. #endif
  822. //===----------------------------------------------------------------------===//
  823. // LoadClusterMutation - DAG post-processing to cluster loads.
  824. //===----------------------------------------------------------------------===//
  825. namespace {
  826. /// \brief Post-process the DAG to create cluster edges between neighboring
  827. /// loads.
  828. class LoadClusterMutation : public ScheduleDAGMutation {
  829. struct LoadInfo {
  830. SUnit *SU;
  831. unsigned BaseReg;
  832. unsigned Offset;
  833. LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
  834. : SU(su), BaseReg(reg), Offset(ofs) {}
  835. };
  836. static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
  837. const LoadClusterMutation::LoadInfo &RHS);
  838. const TargetInstrInfo *TII;
  839. const TargetRegisterInfo *TRI;
  840. public:
  841. LoadClusterMutation(const TargetInstrInfo *tii,
  842. const TargetRegisterInfo *tri)
  843. : TII(tii), TRI(tri) {}
  844. virtual void apply(ScheduleDAGMI *DAG);
  845. protected:
  846. void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
  847. };
  848. } // anonymous
  849. bool LoadClusterMutation::LoadInfoLess(
  850. const LoadClusterMutation::LoadInfo &LHS,
  851. const LoadClusterMutation::LoadInfo &RHS) {
  852. if (LHS.BaseReg != RHS.BaseReg)
  853. return LHS.BaseReg < RHS.BaseReg;
  854. return LHS.Offset < RHS.Offset;
  855. }
  856. void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
  857. ScheduleDAGMI *DAG) {
  858. SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
  859. for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
  860. SUnit *SU = Loads[Idx];
  861. unsigned BaseReg;
  862. unsigned Offset;
  863. if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
  864. LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
  865. }
  866. if (LoadRecords.size() < 2)
  867. return;
  868. std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
  869. unsigned ClusterLength = 1;
  870. for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
  871. if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
  872. ClusterLength = 1;
  873. continue;
  874. }
  875. SUnit *SUa = LoadRecords[Idx].SU;
  876. SUnit *SUb = LoadRecords[Idx+1].SU;
  877. if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
  878. && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
  879. DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
  880. << SUb->NodeNum << ")\n");
  881. // Copy successor edges from SUa to SUb. Interleaving computation
  882. // dependent on SUa can prevent load combining due to register reuse.
  883. // Predecessor edges do not need to be copied from SUb to SUa since nearby
  884. // loads should have effectively the same inputs.
  885. for (SUnit::const_succ_iterator
  886. SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
  887. if (SI->getSUnit() == SUb)
  888. continue;
  889. DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
  890. DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
  891. }
  892. ++ClusterLength;
  893. }
  894. else
  895. ClusterLength = 1;
  896. }
  897. }
  898. /// \brief Callback from DAG postProcessing to create cluster edges for loads.
  899. void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
  900. // Map DAG NodeNum to store chain ID.
  901. DenseMap<unsigned, unsigned> StoreChainIDs;
  902. // Map each store chain to a set of dependent loads.
  903. SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
  904. for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
  905. SUnit *SU = &DAG->SUnits[Idx];
  906. if (!SU->getInstr()->mayLoad())
  907. continue;
  908. unsigned ChainPredID = DAG->SUnits.size();
  909. for (SUnit::const_pred_iterator
  910. PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
  911. if (PI->isCtrl()) {
  912. ChainPredID = PI->getSUnit()->NodeNum;
  913. break;
  914. }
  915. }
  916. // Check if this chain-like pred has been seen
  917. // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
  918. unsigned NumChains = StoreChainDependents.size();
  919. std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
  920. StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
  921. if (Result.second)
  922. StoreChainDependents.resize(NumChains + 1);
  923. StoreChainDependents[Result.first->second].push_back(SU);
  924. }
  925. // Iterate over the store chains.
  926. for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
  927. clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
  928. }
  929. //===----------------------------------------------------------------------===//
  930. // MacroFusion - DAG post-processing to encourage fusion of macro ops.
  931. //===----------------------------------------------------------------------===//
  932. namespace {
  933. /// \brief Post-process the DAG to create cluster edges between instructions
  934. /// that may be fused by the processor into a single operation.
  935. class MacroFusion : public ScheduleDAGMutation {
  936. const TargetInstrInfo *TII;
  937. public:
  938. MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
  939. virtual void apply(ScheduleDAGMI *DAG);
  940. };
  941. } // anonymous
  942. /// \brief Callback from DAG postProcessing to create cluster edges to encourage
  943. /// fused operations.
  944. void MacroFusion::apply(ScheduleDAGMI *DAG) {
  945. // For now, assume targets can only fuse with the branch.
  946. MachineInstr *Branch = DAG->ExitSU.getInstr();
  947. if (!Branch)
  948. return;
  949. for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
  950. SUnit *SU = &DAG->SUnits[--Idx];
  951. if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
  952. continue;
  953. // Create a single weak edge from SU to ExitSU. The only effect is to cause
  954. // bottom-up scheduling to heavily prioritize the clustered SU. There is no
  955. // need to copy predecessor edges from ExitSU to SU, since top-down
  956. // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
  957. // of SU, we could create an artificial edge from the deepest root, but it
  958. // hasn't been needed yet.
  959. bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
  960. (void)Success;
  961. assert(Success && "No DAG nodes should be reachable from ExitSU");
  962. DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
  963. break;
  964. }
  965. }
  966. //===----------------------------------------------------------------------===//
  967. // CopyConstrain - DAG post-processing to encourage copy elimination.
  968. //===----------------------------------------------------------------------===//
  969. namespace {
  970. /// \brief Post-process the DAG to create weak edges from all uses of a copy to
  971. /// the one use that defines the copy's source vreg, most likely an induction
  972. /// variable increment.
  973. class CopyConstrain : public ScheduleDAGMutation {
  974. // Transient state.
  975. SlotIndex RegionBeginIdx;
  976. // RegionEndIdx is the slot index of the last non-debug instruction in the
  977. // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
  978. SlotIndex RegionEndIdx;
  979. public:
  980. CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
  981. virtual void apply(ScheduleDAGMI *DAG);
  982. protected:
  983. void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG);
  984. };
  985. } // anonymous
  986. /// constrainLocalCopy handles two possibilities:
  987. /// 1) Local src:
  988. /// I0: = dst
  989. /// I1: src = ...
  990. /// I2: = dst
  991. /// I3: dst = src (copy)
  992. /// (create pred->succ edges I0->I1, I2->I1)
  993. ///
  994. /// 2) Local copy:
  995. /// I0: dst = src (copy)
  996. /// I1: = dst
  997. /// I2: src = ...
  998. /// I3: = dst
  999. /// (create pred->succ edges I1->I2, I3->I2)
  1000. ///
  1001. /// Although the MachineScheduler is currently constrained to single blocks,
  1002. /// this algorithm should handle extended blocks. An EBB is a set of
  1003. /// contiguously numbered blocks such that the previous block in the EBB is
  1004. /// always the single predecessor.
  1005. void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG) {
  1006. LiveIntervals *LIS = DAG->getLIS();
  1007. MachineInstr *Copy = CopySU->getInstr();
  1008. // Check for pure vreg copies.
  1009. unsigned SrcReg = Copy->getOperand(1).getReg();
  1010. if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
  1011. return;
  1012. unsigned DstReg = Copy->getOperand(0).getReg();
  1013. if (!TargetRegisterInfo::isVirtualRegister(DstReg))
  1014. return;
  1015. // Check if either the dest or source is local. If it's live across a back
  1016. // edge, it's not local. Note that if both vregs are live across the back
  1017. // edge, we cannot successfully contrain the copy without cyclic scheduling.
  1018. unsigned LocalReg = DstReg;
  1019. unsigned GlobalReg = SrcReg;
  1020. LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
  1021. if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
  1022. LocalReg = SrcReg;
  1023. GlobalReg = DstReg;
  1024. LocalLI = &LIS->getInterval(LocalReg);
  1025. if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
  1026. return;
  1027. }
  1028. LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
  1029. // Find the global segment after the start of the local LI.
  1030. LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
  1031. // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
  1032. // local live range. We could create edges from other global uses to the local
  1033. // start, but the coalescer should have already eliminated these cases, so
  1034. // don't bother dealing with it.
  1035. if (GlobalSegment == GlobalLI->end())
  1036. return;
  1037. // If GlobalSegment is killed at the LocalLI->start, the call to find()
  1038. // returned the next global segment. But if GlobalSegment overlaps with
  1039. // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
  1040. // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
  1041. if (GlobalSegment->contains(LocalLI->beginIndex()))
  1042. ++GlobalSegment;
  1043. if (GlobalSegment == GlobalLI->end())
  1044. return;
  1045. // Check if GlobalLI contains a hole in the vicinity of LocalLI.
  1046. if (GlobalSegment != GlobalLI->begin()) {
  1047. // Two address defs have no hole.
  1048. if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
  1049. GlobalSegment->start)) {
  1050. return;
  1051. }
  1052. // If the prior global segment may be defined by the same two-address
  1053. // instruction that also defines LocalLI, then can't make a hole here.
  1054. if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
  1055. LocalLI->beginIndex())) {
  1056. return;
  1057. }
  1058. // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
  1059. // it would be a disconnected component in the live range.
  1060. assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
  1061. "Disconnected LRG within the scheduling region.");
  1062. }
  1063. MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
  1064. if (!GlobalDef)
  1065. return;
  1066. SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
  1067. if (!GlobalSU)
  1068. return;
  1069. // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
  1070. // constraining the uses of the last local def to precede GlobalDef.
  1071. SmallVector<SUnit*,8> LocalUses;
  1072. const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
  1073. MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
  1074. SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
  1075. for (SUnit::const_succ_iterator
  1076. I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
  1077. I != E; ++I) {
  1078. if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
  1079. continue;
  1080. if (I->getSUnit() == GlobalSU)
  1081. continue;
  1082. if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
  1083. return;
  1084. LocalUses.push_back(I->getSUnit());
  1085. }
  1086. // Open the top of the GlobalLI hole by constraining any earlier global uses
  1087. // to precede the start of LocalLI.
  1088. SmallVector<SUnit*,8> GlobalUses;
  1089. MachineInstr *FirstLocalDef =
  1090. LIS->getInstructionFromIndex(LocalLI->beginIndex());
  1091. SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
  1092. for (SUnit::const_pred_iterator
  1093. I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
  1094. if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
  1095. continue;
  1096. if (I->getSUnit() == FirstLocalSU)
  1097. continue;
  1098. if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
  1099. return;
  1100. GlobalUses.push_back(I->getSUnit());
  1101. }
  1102. DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
  1103. // Add the weak edges.
  1104. for (SmallVectorImpl<SUnit*>::const_iterator
  1105. I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
  1106. DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
  1107. << GlobalSU->NodeNum << ")\n");
  1108. DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
  1109. }
  1110. for (SmallVectorImpl<SUnit*>::const_iterator
  1111. I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
  1112. DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
  1113. << FirstLocalSU->NodeNum << ")\n");
  1114. DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
  1115. }
  1116. }
  1117. /// \brief Callback from DAG postProcessing to create weak edges to encourage
  1118. /// copy elimination.
  1119. void CopyConstrain::apply(ScheduleDAGMI *DAG) {
  1120. MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
  1121. if (FirstPos == DAG->end())
  1122. return;
  1123. RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
  1124. RegionEndIdx = DAG->getLIS()->getInstructionIndex(
  1125. &*priorNonDebug(DAG->end(), DAG->begin()));
  1126. for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
  1127. SUnit *SU = &DAG->SUnits[Idx];
  1128. if (!SU->getInstr()->isCopy())
  1129. continue;
  1130. constrainLocalCopy(SU, DAG);
  1131. }
  1132. }
  1133. //===----------------------------------------------------------------------===//
  1134. // ConvergingScheduler - Implementation of the generic MachineSchedStrategy.
  1135. //===----------------------------------------------------------------------===//
  1136. namespace {
  1137. /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
  1138. /// the schedule.
  1139. class ConvergingScheduler : public MachineSchedStrategy {
  1140. public:
  1141. /// Represent the type of SchedCandidate found within a single queue.
  1142. /// pickNodeBidirectional depends on these listed by decreasing priority.
  1143. enum CandReason {
  1144. NoCand, PhysRegCopy, RegExcess, RegCritical, Cluster, Weak, RegMax,
  1145. ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
  1146. TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
  1147. #ifndef NDEBUG
  1148. static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
  1149. #endif
  1150. /// Policy for scheduling the next instruction in the candidate's zone.
  1151. struct CandPolicy {
  1152. bool ReduceLatency;
  1153. unsigned ReduceResIdx;
  1154. unsigned DemandResIdx;
  1155. CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
  1156. };
  1157. /// Status of an instruction's critical resource consumption.
  1158. struct SchedResourceDelta {
  1159. // Count critical resources in the scheduled region required by SU.
  1160. unsigned CritResources;
  1161. // Count critical resources from another region consumed by SU.
  1162. unsigned DemandedResources;
  1163. SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
  1164. bool operator==(const SchedResourceDelta &RHS) const {
  1165. return CritResources == RHS.CritResources
  1166. && DemandedResources == RHS.DemandedResources;
  1167. }
  1168. bool operator!=(const SchedResourceDelta &RHS) const {
  1169. return !operator==(RHS);
  1170. }
  1171. };
  1172. /// Store the state used by ConvergingScheduler heuristics, required for the
  1173. /// lifetime of one invocation of pickNode().
  1174. struct SchedCandidate {
  1175. CandPolicy Policy;
  1176. // The best SUnit candidate.
  1177. SUnit *SU;
  1178. // The reason for this candidate.
  1179. CandReason Reason;
  1180. // Set of reasons that apply to multiple candidates.
  1181. uint32_t RepeatReasonSet;
  1182. // Register pressure values for the best candidate.
  1183. RegPressureDelta RPDelta;
  1184. // Critical resource consumption of the best candidate.
  1185. SchedResourceDelta ResDelta;
  1186. SchedCandidate(const CandPolicy &policy)
  1187. : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
  1188. bool isValid() const { return SU; }
  1189. // Copy the status of another candidate without changing policy.
  1190. void setBest(SchedCandidate &Best) {
  1191. assert(Best.Reason != NoCand && "uninitialized Sched candidate");
  1192. SU = Best.SU;
  1193. Reason = Best.Reason;
  1194. RPDelta = Best.RPDelta;
  1195. ResDelta = Best.ResDelta;
  1196. }
  1197. bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
  1198. void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
  1199. void initResourceDelta(const ScheduleDAGMI *DAG,
  1200. const TargetSchedModel *SchedModel);
  1201. };
  1202. /// Summarize the unscheduled region.
  1203. struct SchedRemainder {
  1204. // Critical path through the DAG in expected latency.
  1205. unsigned CriticalPath;
  1206. unsigned CyclicCritPath;
  1207. // Scaled count of micro-ops left to schedule.
  1208. unsigned RemIssueCount;
  1209. bool IsAcyclicLatencyLimited;
  1210. // Unscheduled resources
  1211. SmallVector<unsigned, 16> RemainingCounts;
  1212. void reset() {
  1213. CriticalPath = 0;
  1214. CyclicCritPath = 0;
  1215. RemIssueCount = 0;
  1216. IsAcyclicLatencyLimited = false;
  1217. RemainingCounts.clear();
  1218. }
  1219. SchedRemainder() { reset(); }
  1220. void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
  1221. };
  1222. /// Each Scheduling boundary is associated with ready queues. It tracks the
  1223. /// current cycle in the direction of movement, and maintains the state
  1224. /// of "hazards" and other interlocks at the current cycle.
  1225. struct SchedBoundary {
  1226. ScheduleDAGMI *DAG;
  1227. const TargetSchedModel *SchedModel;
  1228. SchedRemainder *Rem;
  1229. ReadyQueue Available;
  1230. ReadyQueue Pending;
  1231. bool CheckPending;
  1232. // For heuristics, keep a list of the nodes that immediately depend on the
  1233. // most recently scheduled node.
  1234. SmallPtrSet<const SUnit*, 8> NextSUs;
  1235. ScheduleHazardRecognizer *HazardRec;
  1236. /// Number of cycles it takes to issue the instructions scheduled in this
  1237. /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
  1238. /// See getStalls().
  1239. unsigned CurrCycle;
  1240. /// Micro-ops issued in the current cycle
  1241. unsigned CurrMOps;
  1242. /// MinReadyCycle - Cycle of the soonest available instruction.
  1243. unsigned MinReadyCycle;
  1244. // The expected latency of the critical path in this scheduled zone.
  1245. unsigned ExpectedLatency;
  1246. // The latency of dependence chains leading into this zone.
  1247. // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
  1248. // For each cycle scheduled: DLat -= 1.
  1249. unsigned DependentLatency;
  1250. /// Count the scheduled (issued) micro-ops that can be retired by
  1251. /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
  1252. unsigned RetiredMOps;
  1253. // Count scheduled resources that have been executed. Resources are
  1254. // considered executed if they become ready in the time that it takes to
  1255. // saturate any resource including the one in question. Counts are scaled
  1256. // for direct comparison with other resources. Counts can be compared with
  1257. // MOps * getMicroOpFactor and Latency * getLatencyFactor.
  1258. SmallVector<unsigned, 16> ExecutedResCounts;
  1259. /// Cache the max count for a single resource.
  1260. unsigned MaxExecutedResCount;
  1261. // Cache the critical resources ID in this scheduled zone.
  1262. unsigned ZoneCritResIdx;
  1263. // Is the scheduled region resource limited vs. latency limited.
  1264. bool IsResourceLimited;
  1265. #ifndef NDEBUG
  1266. // Remember the greatest operand latency as an upper bound on the number of
  1267. // times we should retry the pending queue because of a hazard.
  1268. unsigned MaxObservedLatency;
  1269. #endif
  1270. void reset() {
  1271. // A new HazardRec is created for each DAG and owned by SchedBoundary.
  1272. // Destroying and reconstructing it is very expensive though. So keep
  1273. // invalid, placeholder HazardRecs.
  1274. if (HazardRec && HazardRec->isEnabled()) {
  1275. delete HazardRec;
  1276. HazardRec = 0;
  1277. }
  1278. Available.clear();
  1279. Pending.clear();
  1280. CheckPending = false;
  1281. NextSUs.clear();
  1282. CurrCycle = 0;
  1283. CurrMOps = 0;
  1284. MinReadyCycle = UINT_MAX;
  1285. ExpectedLatency = 0;
  1286. DependentLatency = 0;
  1287. RetiredMOps = 0;
  1288. MaxExecutedResCount = 0;
  1289. ZoneCritResIdx = 0;
  1290. IsResourceLimited = false;
  1291. #ifndef NDEBUG
  1292. MaxObservedLatency = 0;
  1293. #endif
  1294. // Reserve a zero-count for invalid CritResIdx.
  1295. ExecutedResCounts.resize(1);
  1296. assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
  1297. }
  1298. /// Pending queues extend the ready queues with the same ID and the
  1299. /// PendingFlag set.
  1300. SchedBoundary(unsigned ID, const Twine &Name):
  1301. DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
  1302. Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
  1303. HazardRec(0) {
  1304. reset();
  1305. }
  1306. ~SchedBoundary() { delete HazardRec; }
  1307. void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
  1308. SchedRemainder *rem);
  1309. bool isTop() const {
  1310. return Available.getID() == ConvergingScheduler::TopQID;
  1311. }
  1312. #ifndef NDEBUG
  1313. const char *getResourceName(unsigned PIdx) {
  1314. if (!PIdx)
  1315. return "MOps";
  1316. return SchedModel->getProcResource(PIdx)->Name;
  1317. }
  1318. #endif
  1319. /// Get the number of latency cycles "covered" by the scheduled
  1320. /// instructions. This is the larger of the critical path within the zone
  1321. /// and the number of cycles required to issue the instructions.
  1322. unsigned getScheduledLatency() const {
  1323. return std::max(ExpectedLatency, CurrCycle);
  1324. }
  1325. unsigned getUnscheduledLatency(SUnit *SU) const {
  1326. return isTop() ? SU->getHeight() : SU->getDepth();
  1327. }
  1328. unsigned getResourceCount(unsigned ResIdx) const {
  1329. return ExecutedResCounts[ResIdx];
  1330. }
  1331. /// Get the scaled count of scheduled micro-ops and resources, including
  1332. /// executed resources.
  1333. unsigned getCriticalCount() const {
  1334. if (!ZoneCritResIdx)
  1335. return RetiredMOps * SchedModel->getMicroOpFactor();
  1336. return getResourceCount(ZoneCritResIdx);
  1337. }
  1338. /// Get a scaled count for the minimum execution time of the scheduled
  1339. /// micro-ops that are ready to execute by getExecutedCount. Notice the
  1340. /// feedback loop.
  1341. unsigned getExecutedCount() const {
  1342. return std::max(CurrCycle * SchedModel->getLatencyFactor(),
  1343. MaxExecutedResCount);
  1344. }
  1345. bool checkHazard(SUnit *SU);
  1346. unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
  1347. unsigned getOtherResourceCount(unsigned &OtherCritIdx);
  1348. void setPolicy(CandPolicy &Policy, SchedBoundary &OtherZone);
  1349. void releaseNode(SUnit *SU, unsigned ReadyCycle);
  1350. void bumpCycle(unsigned NextCycle);
  1351. void incExecutedResources(unsigned PIdx, unsigned Count);
  1352. unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
  1353. void bumpNode(SUnit *SU);
  1354. void releasePending();
  1355. void removeReady(SUnit *SU);
  1356. SUnit *pickOnlyChoice();
  1357. #ifndef NDEBUG
  1358. void dumpScheduledState();
  1359. #endif
  1360. };
  1361. private:
  1362. const MachineSchedContext *Context;
  1363. ScheduleDAGMI *DAG;
  1364. const TargetSchedModel *SchedModel;
  1365. const TargetRegisterInfo *TRI;
  1366. // State of the top and bottom scheduled instruction boundaries.
  1367. SchedRemainder Rem;
  1368. SchedBoundary Top;
  1369. SchedBoundary Bot;
  1370. MachineSchedPolicy RegionPolicy;
  1371. public:
  1372. /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
  1373. enum {
  1374. TopQID = 1,
  1375. BotQID = 2,
  1376. LogMaxQID = 2
  1377. };
  1378. ConvergingScheduler(const MachineSchedContext *C):
  1379. Context(C), DAG(0), SchedModel(0), TRI(0),
  1380. Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
  1381. virtual void initPolicy(MachineBasicBlock::iterator Begin,
  1382. MachineBasicBlock::iterator End,
  1383. unsigned NumRegionInstrs);
  1384. bool shouldTrackPressure() const { return RegionPolicy.ShouldTrackPressure; }
  1385. virtual void initialize(ScheduleDAGMI *dag);
  1386. virtual SUnit *pickNode(bool &IsTopNode);
  1387. virtual void schedNode(SUnit *SU, bool IsTopNode);
  1388. virtual void releaseTopNode(SUnit *SU);
  1389. virtual void releaseBottomNode(SUnit *SU);
  1390. virtual void registerRoots();
  1391. protected:
  1392. void checkAcyclicLatency();
  1393. void tryCandidate(SchedCandidate &Cand,
  1394. SchedCandidate &TryCand,
  1395. SchedBoundary &Zone,
  1396. const RegPressureTracker &RPTracker,
  1397. RegPressureTracker &TempTracker);
  1398. SUnit *pickNodeBidirectional(bool &IsTopNode);
  1399. void pickNodeFromQueue(SchedBoundary &Zone,
  1400. const RegPressureTracker &RPTracker,
  1401. SchedCandidate &Candidate);
  1402. void reschedulePhysRegCopies(SUnit *SU, bool isTop);
  1403. #ifndef NDEBUG
  1404. void traceCandidate(const SchedCandidate &Cand);
  1405. #endif
  1406. };
  1407. } // namespace
  1408. void ConvergingScheduler::SchedRemainder::
  1409. init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
  1410. reset();
  1411. if (!SchedModel->hasInstrSchedModel())
  1412. return;
  1413. RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
  1414. for (std::vector<SUnit>::iterator
  1415. I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
  1416. const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
  1417. RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
  1418. * SchedModel->getMicroOpFactor();
  1419. for (TargetSchedModel::ProcResIter
  1420. PI = SchedModel->getWriteProcResBegin(SC),
  1421. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1422. unsigned PIdx = PI->ProcResourceIdx;
  1423. unsigned Factor = SchedModel->getResourceFactor(PIdx);
  1424. RemainingCounts[PIdx] += (Factor * PI->Cycles);
  1425. }
  1426. }
  1427. }
  1428. void ConvergingScheduler::SchedBoundary::
  1429. init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
  1430. reset();
  1431. DAG = dag;
  1432. SchedModel = smodel;
  1433. Rem = rem;
  1434. if (SchedModel->hasInstrSchedModel())
  1435. ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
  1436. }
  1437. /// Initialize the per-region scheduling policy.
  1438. void ConvergingScheduler::initPolicy(MachineBasicBlock::iterator Begin,
  1439. MachineBasicBlock::iterator End,
  1440. unsigned NumRegionInstrs) {
  1441. const TargetMachine &TM = Context->MF->getTarget();
  1442. // Avoid setting up the register pressure tracker for small regions to save
  1443. // compile time. As a rough heuristic, only track pressure when the number of
  1444. // schedulable instructions exceeds half the integer register file.
  1445. unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
  1446. TM.getTargetLowering()->getRegClassFor(MVT::i32));
  1447. RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
  1448. // For generic targets, we default to bottom-up, because it's simpler and more
  1449. // compile-time optimizations have been implemented in that direction.
  1450. RegionPolicy.OnlyBottomUp = true;
  1451. // Allow the subtarget to override default policy.
  1452. const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
  1453. ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
  1454. // After subtarget overrides, apply command line options.
  1455. if (!EnableRegPressure)
  1456. RegionPolicy.ShouldTrackPressure = false;
  1457. // Check -misched-topdown/bottomup can force or unforce scheduling direction.
  1458. // e.g. -misched-bottomup=false allows scheduling in both directions.
  1459. assert((!ForceTopDown || !ForceBottomUp) &&
  1460. "-misched-topdown incompatible with -misched-bottomup");
  1461. if (ForceBottomUp.getNumOccurrences() > 0) {
  1462. RegionPolicy.OnlyBottomUp = ForceBottomUp;
  1463. if (RegionPolicy.OnlyBottomUp)
  1464. RegionPolicy.OnlyTopDown = false;
  1465. }
  1466. if (ForceTopDown.getNumOccurrences() > 0) {
  1467. RegionPolicy.OnlyTopDown = ForceTopDown;
  1468. if (RegionPolicy.OnlyTopDown)
  1469. RegionPolicy.OnlyBottomUp = false;
  1470. }
  1471. }
  1472. void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
  1473. DAG = dag;
  1474. SchedModel = DAG->getSchedModel();
  1475. TRI = DAG->TRI;
  1476. Rem.init(DAG, SchedModel);
  1477. Top.init(DAG, SchedModel, &Rem);
  1478. Bot.init(DAG, SchedModel, &Rem);
  1479. // Initialize resource counts.
  1480. // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
  1481. // are disabled, then these HazardRecs will be disabled.
  1482. const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
  1483. const TargetMachine &TM = DAG->MF.getTarget();
  1484. if (!Top.HazardRec) {
  1485. Top.HazardRec =
  1486. TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
  1487. }
  1488. if (!Bot.HazardRec) {
  1489. Bot.HazardRec =
  1490. TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
  1491. }
  1492. }
  1493. void ConvergingScheduler::releaseTopNode(SUnit *SU) {
  1494. if (SU->isScheduled)
  1495. return;
  1496. for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
  1497. I != E; ++I) {
  1498. if (I->isWeak())
  1499. continue;
  1500. unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
  1501. unsigned Latency = I->getLatency();
  1502. #ifndef NDEBUG
  1503. Top.MaxObservedLatency = std::max(Latency, Top.MaxObservedLatency);
  1504. #endif
  1505. if (SU->TopReadyCycle < PredReadyCycle + Latency)
  1506. SU->TopReadyCycle = PredReadyCycle + Latency;
  1507. }
  1508. Top.releaseNode(SU, SU->TopReadyCycle);
  1509. }
  1510. void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
  1511. if (SU->isScheduled)
  1512. return;
  1513. assert(SU->getInstr() && "Scheduled SUnit must have instr");
  1514. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  1515. I != E; ++I) {
  1516. if (I->isWeak())
  1517. continue;
  1518. unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
  1519. unsigned Latency = I->getLatency();
  1520. #ifndef NDEBUG
  1521. Bot.MaxObservedLatency = std::max(Latency, Bot.MaxObservedLatency);
  1522. #endif
  1523. if (SU->BotReadyCycle < SuccReadyCycle + Latency)
  1524. SU->BotReadyCycle = SuccReadyCycle + Latency;
  1525. }
  1526. Bot.releaseNode(SU, SU->BotReadyCycle);
  1527. }
  1528. /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
  1529. /// critical path by more cycles than it takes to drain the instruction buffer.
  1530. /// We estimate an upper bounds on in-flight instructions as:
  1531. ///
  1532. /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
  1533. /// InFlightIterations = AcyclicPath / CyclesPerIteration
  1534. /// InFlightResources = InFlightIterations * LoopResources
  1535. ///
  1536. /// TODO: Check execution resources in addition to IssueCount.
  1537. void ConvergingScheduler::checkAcyclicLatency() {
  1538. if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
  1539. return;
  1540. // Scaled number of cycles per loop iteration.
  1541. unsigned IterCount =
  1542. std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
  1543. Rem.RemIssueCount);
  1544. // Scaled acyclic critical path.
  1545. unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
  1546. // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
  1547. unsigned InFlightCount =
  1548. (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
  1549. unsigned BufferLimit =
  1550. SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
  1551. Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
  1552. DEBUG(dbgs() << "IssueCycles="
  1553. << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
  1554. << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
  1555. << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
  1556. << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
  1557. << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
  1558. if (Rem.IsAcyclicLatencyLimited)
  1559. dbgs() << " ACYCLIC LATENCY LIMIT\n");
  1560. }
  1561. void ConvergingScheduler::registerRoots() {
  1562. Rem.CriticalPath = DAG->ExitSU.getDepth();
  1563. // Some roots may not feed into ExitSU. Check all of them in case.
  1564. for (std::vector<SUnit*>::const_iterator
  1565. I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
  1566. if ((*I)->getDepth() > Rem.CriticalPath)
  1567. Rem.CriticalPath = (*I)->getDepth();
  1568. }
  1569. DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
  1570. if (EnableCyclicPath) {
  1571. Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
  1572. checkAcyclicLatency();
  1573. }
  1574. }
  1575. /// Does this SU have a hazard within the current instruction group.
  1576. ///
  1577. /// The scheduler supports two modes of hazard recognition. The first is the
  1578. /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
  1579. /// supports highly complicated in-order reservation tables
  1580. /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
  1581. ///
  1582. /// The second is a streamlined mechanism that checks for hazards based on
  1583. /// simple counters that the scheduler itself maintains. It explicitly checks
  1584. /// for instruction dispatch limitations, including the number of micro-ops that
  1585. /// can dispatch per cycle.
  1586. ///
  1587. /// TODO: Also check whether the SU must start a new group.
  1588. bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
  1589. if (HazardRec->isEnabled())
  1590. return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
  1591. unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
  1592. if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
  1593. DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
  1594. << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
  1595. return true;
  1596. }
  1597. return false;
  1598. }
  1599. // Find the unscheduled node in ReadySUs with the highest latency.
  1600. unsigned ConvergingScheduler::SchedBoundary::
  1601. findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
  1602. SUnit *LateSU = 0;
  1603. unsigned RemLatency = 0;
  1604. for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
  1605. I != E; ++I) {
  1606. unsigned L = getUnscheduledLatency(*I);
  1607. if (L > RemLatency) {
  1608. RemLatency = L;
  1609. LateSU = *I;
  1610. }
  1611. }
  1612. if (LateSU) {
  1613. DEBUG(dbgs() << Available.getName() << " RemLatency SU("
  1614. << LateSU->NodeNum << ") " << RemLatency << "c\n");
  1615. }
  1616. return RemLatency;
  1617. }
  1618. // Count resources in this zone and the remaining unscheduled
  1619. // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
  1620. // resource index, or zero if the zone is issue limited.
  1621. unsigned ConvergingScheduler::SchedBoundary::
  1622. getOtherResourceCount(unsigned &OtherCritIdx) {
  1623. OtherCritIdx = 0;
  1624. if (!SchedModel->hasInstrSchedModel())
  1625. return 0;
  1626. unsigned OtherCritCount = Rem->RemIssueCount
  1627. + (RetiredMOps * SchedModel->getMicroOpFactor());
  1628. DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
  1629. << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
  1630. for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
  1631. PIdx != PEnd; ++PIdx) {
  1632. unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
  1633. if (OtherCount > OtherCritCount) {
  1634. OtherCritCount = OtherCount;
  1635. OtherCritIdx = PIdx;
  1636. }
  1637. }
  1638. if (OtherCritIdx) {
  1639. DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
  1640. << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
  1641. << " " << getResourceName(OtherCritIdx) << "\n");
  1642. }
  1643. return OtherCritCount;
  1644. }
  1645. /// Set the CandPolicy for this zone given the current resources and latencies
  1646. /// inside and outside the zone.
  1647. void ConvergingScheduler::SchedBoundary::setPolicy(CandPolicy &Policy,
  1648. SchedBoundary &OtherZone) {
  1649. // Now that potential stalls have been considered, apply preemptive heuristics
  1650. // based on the the total latency and resources inside and outside this
  1651. // zone.
  1652. // Compute remaining latency. We need this both to determine whether the
  1653. // overall schedule has become latency-limited and whether the instructions
  1654. // outside this zone are resource or latency limited.
  1655. //
  1656. // The "dependent" latency is updated incrementally during scheduling as the
  1657. // max height/depth of scheduled nodes minus the cycles since it was
  1658. // scheduled:
  1659. // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
  1660. //
  1661. // The "independent" latency is the max ready queue depth:
  1662. // ILat = max N.depth for N in Available|Pending
  1663. //
  1664. // RemainingLatency is the greater of independent and dependent latency.
  1665. unsigned RemLatency = DependentLatency;
  1666. RemLatency = std::max(RemLatency, findMaxLatency(Available.elements()));
  1667. RemLatency = std::max(RemLatency, findMaxLatency(Pending.elements()));
  1668. // Compute the critical resource outside the zone.
  1669. unsigned OtherCritIdx;
  1670. unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
  1671. bool OtherResLimited = false;
  1672. if (SchedModel->hasInstrSchedModel()) {
  1673. unsigned LFactor = SchedModel->getLatencyFactor();
  1674. OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
  1675. }
  1676. if (!OtherResLimited && (RemLatency + CurrCycle > Rem->CriticalPath)) {
  1677. Policy.ReduceLatency |= true;
  1678. DEBUG(dbgs() << " " << Available.getName() << " RemainingLatency "
  1679. << RemLatency << " + " << CurrCycle << "c > CritPath "
  1680. << Rem->CriticalPath << "\n");
  1681. }
  1682. // If the same resource is limiting inside and outside the zone, do nothing.
  1683. if (ZoneCritResIdx == OtherCritIdx)
  1684. return;
  1685. DEBUG(
  1686. if (IsResourceLimited) {
  1687. dbgs() << " " << Available.getName() << " ResourceLimited: "
  1688. << getResourceName(ZoneCritResIdx) << "\n";
  1689. }
  1690. if (OtherResLimited)
  1691. dbgs() << " RemainingLimit: " << getResourceName(OtherCritIdx) << "\n";
  1692. if (!IsResourceLimited && !OtherResLimited)
  1693. dbgs() << " Latency limited both directions.\n");
  1694. if (IsResourceLimited && !Policy.ReduceResIdx)
  1695. Policy.ReduceResIdx = ZoneCritResIdx;
  1696. if (OtherResLimited)
  1697. Policy.DemandResIdx = OtherCritIdx;
  1698. }
  1699. void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
  1700. unsigned ReadyCycle) {
  1701. if (ReadyCycle < MinReadyCycle)
  1702. MinReadyCycle = ReadyCycle;
  1703. // Check for interlocks first. For the purpose of other heuristics, an
  1704. // instruction that cannot issue appears as if it's not in the ReadyQueue.
  1705. bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
  1706. if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
  1707. Pending.push(SU);
  1708. else
  1709. Available.push(SU);
  1710. // Record this node as an immediate dependent of the scheduled node.
  1711. NextSUs.insert(SU);
  1712. }
  1713. /// Move the boundary of scheduled code by one cycle.
  1714. void ConvergingScheduler::SchedBoundary::bumpCycle(unsigned NextCycle) {
  1715. if (SchedModel->getMicroOpBufferSize() == 0) {
  1716. assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
  1717. if (MinReadyCycle > NextCycle)
  1718. NextCycle = MinReadyCycle;
  1719. }
  1720. // Update the current micro-ops, which will issue in the next cycle.
  1721. unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
  1722. CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
  1723. // Decrement DependentLatency based on the next cycle.
  1724. if ((NextCycle - CurrCycle) > DependentLatency)
  1725. DependentLatency = 0;
  1726. else
  1727. DependentLatency -= (NextCycle - CurrCycle);
  1728. if (!HazardRec->isEnabled()) {
  1729. // Bypass HazardRec virtual calls.
  1730. CurrCycle = NextCycle;
  1731. }
  1732. else {
  1733. // Bypass getHazardType calls in case of long latency.
  1734. for (; CurrCycle != NextCycle; ++CurrCycle) {
  1735. if (isTop())
  1736. HazardRec->AdvanceCycle();
  1737. else
  1738. HazardRec->RecedeCycle();
  1739. }
  1740. }
  1741. CheckPending = true;
  1742. unsigned LFactor = SchedModel->getLatencyFactor();
  1743. IsResourceLimited =
  1744. (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
  1745. > (int)LFactor;
  1746. DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
  1747. }
  1748. void ConvergingScheduler::SchedBoundary::incExecutedResources(unsigned PIdx,
  1749. unsigned Count) {
  1750. ExecutedResCounts[PIdx] += Count;
  1751. if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
  1752. MaxExecutedResCount = ExecutedResCounts[PIdx];
  1753. }
  1754. /// Add the given processor resource to this scheduled zone.
  1755. ///
  1756. /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
  1757. /// during which this resource is consumed.
  1758. ///
  1759. /// \return the next cycle at which the instruction may execute without
  1760. /// oversubscribing resources.
  1761. unsigned ConvergingScheduler::SchedBoundary::
  1762. countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle) {
  1763. unsigned Factor = SchedModel->getResourceFactor(PIdx);
  1764. unsigned Count = Factor * Cycles;
  1765. DEBUG(dbgs() << " " << getResourceName(PIdx)
  1766. << " +" << Cycles << "x" << Factor << "u\n");
  1767. // Update Executed resources counts.
  1768. incExecutedResources(PIdx, Count);
  1769. assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
  1770. Rem->RemainingCounts[PIdx] -= Count;
  1771. // Check if this resource exceeds the current critical resource. If so, it
  1772. // becomes the critical resource.
  1773. if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
  1774. ZoneCritResIdx = PIdx;
  1775. DEBUG(dbgs() << " *** Critical resource "
  1776. << getResourceName(PIdx) << ": "
  1777. << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
  1778. }
  1779. // TODO: We don't yet model reserved resources. It's not hard though.
  1780. return CurrCycle;
  1781. }
  1782. /// Move the boundary of scheduled code by one SUnit.
  1783. void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
  1784. // Update the reservation table.
  1785. if (HazardRec->isEnabled()) {
  1786. if (!isTop() && SU->isCall) {
  1787. // Calls are scheduled with their preceding instructions. For bottom-up
  1788. // scheduling, clear the pipeline state before emitting.
  1789. HazardRec->Reset();
  1790. }
  1791. HazardRec->EmitInstruction(SU);
  1792. }
  1793. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  1794. unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
  1795. CurrMOps += IncMOps;
  1796. // checkHazard prevents scheduling multiple instructions per cycle that exceed
  1797. // issue width. However, we commonly reach the maximum. In this case
  1798. // opportunistically bump the cycle to avoid uselessly checking everything in
  1799. // the readyQ. Furthermore, a single instruction may produce more than one
  1800. // cycle's worth of micro-ops.
  1801. //
  1802. // TODO: Also check if this SU must end a dispatch group.
  1803. unsigned NextCycle = CurrCycle;
  1804. if (CurrMOps >= SchedModel->getIssueWidth()) {
  1805. ++NextCycle;
  1806. DEBUG(dbgs() << " *** Max MOps " << CurrMOps
  1807. << " at cycle " << CurrCycle << '\n');
  1808. }
  1809. unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
  1810. DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
  1811. switch (SchedModel->getMicroOpBufferSize()) {
  1812. case 0:
  1813. assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
  1814. break;
  1815. case 1:
  1816. if (ReadyCycle > NextCycle) {
  1817. NextCycle = ReadyCycle;
  1818. DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
  1819. }
  1820. break;
  1821. default:
  1822. // We don't currently model the OOO reorder buffer, so consider all
  1823. // scheduled MOps to be "retired".
  1824. break;
  1825. }
  1826. RetiredMOps += IncMOps;
  1827. // Update resource counts and critical resource.
  1828. if (SchedModel->hasInstrSchedModel()) {
  1829. unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
  1830. assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
  1831. Rem->RemIssueCount -= DecRemIssue;
  1832. if (ZoneCritResIdx) {
  1833. // Scale scheduled micro-ops for comparing with the critical resource.
  1834. unsigned ScaledMOps =
  1835. RetiredMOps * SchedModel->getMicroOpFactor();
  1836. // If scaled micro-ops are now more than the previous critical resource by
  1837. // a full cycle, then micro-ops issue becomes critical.
  1838. if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
  1839. >= (int)SchedModel->getLatencyFactor()) {
  1840. ZoneCritResIdx = 0;
  1841. DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
  1842. << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
  1843. }
  1844. }
  1845. for (TargetSchedModel::ProcResIter
  1846. PI = SchedModel->getWriteProcResBegin(SC),
  1847. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1848. unsigned RCycle =
  1849. countResource(PI->ProcResourceIdx, PI->Cycles, ReadyCycle);
  1850. if (RCycle > NextCycle)
  1851. NextCycle = RCycle;
  1852. }
  1853. }
  1854. // Update ExpectedLatency and DependentLatency.
  1855. unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
  1856. unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
  1857. if (SU->getDepth() > TopLatency) {
  1858. TopLatency = SU->getDepth();
  1859. DEBUG(dbgs() << " " << Available.getName()
  1860. << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
  1861. }
  1862. if (SU->getHeight() > BotLatency) {
  1863. BotLatency = SU->getHeight();
  1864. DEBUG(dbgs() << " " << Available.getName()
  1865. << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
  1866. }
  1867. // If we stall for any reason, bump the cycle.
  1868. if (NextCycle > CurrCycle) {
  1869. bumpCycle(NextCycle);
  1870. }
  1871. else {
  1872. // After updating ZoneCritResIdx and ExpectedLatency, check if we're
  1873. // resource limited. If a stall occured, bumpCycle does this.
  1874. unsigned LFactor = SchedModel->getLatencyFactor();
  1875. IsResourceLimited =
  1876. (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
  1877. > (int)LFactor;
  1878. }
  1879. DEBUG(dumpScheduledState());
  1880. }
  1881. /// Release pending ready nodes in to the available queue. This makes them
  1882. /// visible to heuristics.
  1883. void ConvergingScheduler::SchedBoundary::releasePending() {
  1884. // If the available queue is empty, it is safe to reset MinReadyCycle.
  1885. if (Available.empty())
  1886. MinReadyCycle = UINT_MAX;
  1887. // Check to see if any of the pending instructions are ready to issue. If
  1888. // so, add them to the available queue.
  1889. bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
  1890. for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
  1891. SUnit *SU = *(Pending.begin()+i);
  1892. unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
  1893. if (ReadyCycle < MinReadyCycle)
  1894. MinReadyCycle = ReadyCycle;
  1895. if (!IsBuffered && ReadyCycle > CurrCycle)
  1896. continue;
  1897. if (checkHazard(SU))
  1898. continue;
  1899. Available.push(SU);
  1900. Pending.remove(Pending.begin()+i);
  1901. --i; --e;
  1902. }
  1903. DEBUG(if (!Pending.empty()) Pending.dump());
  1904. CheckPending = false;
  1905. }
  1906. /// Remove SU from the ready set for this boundary.
  1907. void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
  1908. if (Available.isInQueue(SU))
  1909. Available.remove(Available.find(SU));
  1910. else {
  1911. assert(Pending.isInQueue(SU) && "bad ready count");
  1912. Pending.remove(Pending.find(SU));
  1913. }
  1914. }
  1915. /// If this queue only has one ready candidate, return it. As a side effect,
  1916. /// defer any nodes that now hit a hazard, and advance the cycle until at least
  1917. /// one node is ready. If multiple instructions are ready, return NULL.
  1918. SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
  1919. if (CheckPending)
  1920. releasePending();
  1921. if (CurrMOps > 0) {
  1922. // Defer any ready instrs that now have a hazard.
  1923. for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
  1924. if (checkHazard(*I)) {
  1925. Pending.push(*I);
  1926. I = Available.remove(I);
  1927. continue;
  1928. }
  1929. ++I;
  1930. }
  1931. }
  1932. for (unsigned i = 0; Available.empty(); ++i) {
  1933. assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
  1934. "permanent hazard"); (void)i;
  1935. bumpCycle(CurrCycle + 1);
  1936. releasePending();
  1937. }
  1938. if (Available.size() == 1)
  1939. return *Available.begin();
  1940. return NULL;
  1941. }
  1942. #ifndef NDEBUG
  1943. // This is useful information to dump after bumpNode.
  1944. // Note that the Queue contents are more useful before pickNodeFromQueue.
  1945. void ConvergingScheduler::SchedBoundary::dumpScheduledState() {
  1946. unsigned ResFactor;
  1947. unsigned ResCount;
  1948. if (ZoneCritResIdx) {
  1949. ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
  1950. ResCount = getResourceCount(ZoneCritResIdx);
  1951. }
  1952. else {
  1953. ResFactor = SchedModel->getMicroOpFactor();
  1954. ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
  1955. }
  1956. unsigned LFactor = SchedModel->getLatencyFactor();
  1957. dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
  1958. << " Retired: " << RetiredMOps;
  1959. dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
  1960. dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
  1961. << ResCount / ResFactor << " " << getResourceName(ZoneCritResIdx)
  1962. << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
  1963. << (IsResourceLimited ? " - Resource" : " - Latency")
  1964. << " limited.\n";
  1965. }
  1966. #endif
  1967. void ConvergingScheduler::SchedCandidate::
  1968. initResourceDelta(const ScheduleDAGMI *DAG,
  1969. const TargetSchedModel *SchedModel) {
  1970. if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
  1971. return;
  1972. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  1973. for (TargetSchedModel::ProcResIter
  1974. PI = SchedModel->getWriteProcResBegin(SC),
  1975. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1976. if (PI->ProcResourceIdx == Policy.ReduceResIdx)
  1977. ResDelta.CritResources += PI->Cycles;
  1978. if (PI->ProcResourceIdx == Policy.DemandResIdx)
  1979. ResDelta.DemandedResources += PI->Cycles;
  1980. }
  1981. }
  1982. /// Return true if this heuristic determines order.
  1983. static bool tryLess(int TryVal, int CandVal,
  1984. ConvergingScheduler::SchedCandidate &TryCand,
  1985. ConvergingScheduler::SchedCandidate &Cand,
  1986. ConvergingScheduler::CandReason Reason) {
  1987. if (TryVal < CandVal) {
  1988. TryCand.Reason = Reason;
  1989. return true;
  1990. }
  1991. if (TryVal > CandVal) {
  1992. if (Cand.Reason > Reason)
  1993. Cand.Reason = Reason;
  1994. return true;
  1995. }
  1996. Cand.setRepeat(Reason);
  1997. return false;
  1998. }
  1999. static bool tryGreater(int TryVal, int CandVal,
  2000. ConvergingScheduler::SchedCandidate &TryCand,
  2001. ConvergingScheduler::SchedCandidate &Cand,
  2002. ConvergingScheduler::CandReason Reason) {
  2003. if (TryVal > CandVal) {
  2004. TryCand.Reason = Reason;
  2005. return true;
  2006. }
  2007. if (TryVal < CandVal) {
  2008. if (Cand.Reason > Reason)
  2009. Cand.Reason = Reason;
  2010. return true;
  2011. }
  2012. Cand.setRepeat(Reason);
  2013. return false;
  2014. }
  2015. static bool tryPressure(const PressureChange &TryP,
  2016. const PressureChange &CandP,
  2017. ConvergingScheduler::SchedCandidate &TryCand,
  2018. ConvergingScheduler::SchedCandidate &Cand,
  2019. ConvergingScheduler::CandReason Reason) {
  2020. int TryRank = TryP.getPSetOrMax();
  2021. int CandRank = CandP.getPSetOrMax();
  2022. // If both candidates affect the same set, go with the smallest increase.
  2023. if (TryRank == CandRank) {
  2024. return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
  2025. Reason);
  2026. }
  2027. // If one candidate decreases and the other increases, go with it.
  2028. // Invalid candidates have UnitInc==0.
  2029. if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
  2030. Reason)) {
  2031. return true;
  2032. }
  2033. // If the candidates are decreasing pressure, reverse priority.
  2034. if (TryP.getUnitInc() < 0)
  2035. std::swap(TryRank, CandRank);
  2036. return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
  2037. }
  2038. static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
  2039. return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
  2040. }
  2041. /// Minimize physical register live ranges. Regalloc wants them adjacent to
  2042. /// their physreg def/use.
  2043. ///
  2044. /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
  2045. /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
  2046. /// with the operation that produces or consumes the physreg. We'll do this when
  2047. /// regalloc has support for parallel copies.
  2048. static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
  2049. const MachineInstr *MI = SU->getInstr();
  2050. if (!MI->isCopy())
  2051. return 0;
  2052. unsigned ScheduledOper = isTop ? 1 : 0;
  2053. unsigned UnscheduledOper = isTop ? 0 : 1;
  2054. // If we have already scheduled the physreg produce/consumer, immediately
  2055. // schedule the copy.
  2056. if (TargetRegisterInfo::isPhysicalRegister(
  2057. MI->getOperand(ScheduledOper).getReg()))
  2058. return 1;
  2059. // If the physreg is at the boundary, defer it. Otherwise schedule it
  2060. // immediately to free the dependent. We can hoist the copy later.
  2061. bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
  2062. if (TargetRegisterInfo::isPhysicalRegister(
  2063. MI->getOperand(UnscheduledOper).getReg()))
  2064. return AtBoundary ? -1 : 1;
  2065. return 0;
  2066. }
  2067. static bool tryLatency(ConvergingScheduler::SchedCandidate &TryCand,
  2068. ConvergingScheduler::SchedCandidate &Cand,
  2069. ConvergingScheduler::SchedBoundary &Zone) {
  2070. if (Zone.isTop()) {
  2071. if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
  2072. if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
  2073. TryCand, Cand, ConvergingScheduler::TopDepthReduce))
  2074. return true;
  2075. }
  2076. if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
  2077. TryCand, Cand, ConvergingScheduler::TopPathReduce))
  2078. return true;
  2079. }
  2080. else {
  2081. if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
  2082. if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
  2083. TryCand, Cand, ConvergingScheduler::BotHeightReduce))
  2084. return true;
  2085. }
  2086. if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
  2087. TryCand, Cand, ConvergingScheduler::BotPathReduce))
  2088. return true;
  2089. }
  2090. return false;
  2091. }
  2092. /// Apply a set of heursitics to a new candidate. Heuristics are currently
  2093. /// hierarchical. This may be more efficient than a graduated cost model because
  2094. /// we don't need to evaluate all aspects of the model for each node in the
  2095. /// queue. But it's really done to make the heuristics easier to debug and
  2096. /// statistically analyze.
  2097. ///
  2098. /// \param Cand provides the policy and current best candidate.
  2099. /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
  2100. /// \param Zone describes the scheduled zone that we are extending.
  2101. /// \param RPTracker describes reg pressure within the scheduled zone.
  2102. /// \param TempTracker is a scratch pressure tracker to reuse in queries.
  2103. void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
  2104. SchedCandidate &TryCand,
  2105. SchedBoundary &Zone,
  2106. const RegPressureTracker &RPTracker,
  2107. RegPressureTracker &TempTracker) {
  2108. if (DAG->isTrackingPressure()) {
  2109. // Always initialize TryCand's RPDelta.
  2110. if (Zone.isTop()) {
  2111. TempTracker.getMaxDownwardPressureDelta(
  2112. TryCand.SU->getInstr(),
  2113. TryCand.RPDelta,
  2114. DAG->getRegionCriticalPSets(),
  2115. DAG->getRegPressure().MaxSetPressure);
  2116. }
  2117. else {
  2118. if (VerifyScheduling) {
  2119. TempTracker.getMaxUpwardPressureDelta(
  2120. TryCand.SU->getInstr(),
  2121. &DAG->getPressureDiff(TryCand.SU),
  2122. TryCand.RPDelta,
  2123. DAG->getRegionCriticalPSets(),
  2124. DAG->getRegPressure().MaxSetPressure);
  2125. }
  2126. else {
  2127. RPTracker.getUpwardPressureDelta(
  2128. TryCand.SU->getInstr(),
  2129. DAG->getPressureDiff(TryCand.SU),
  2130. TryCand.RPDelta,
  2131. DAG->getRegionCriticalPSets(),
  2132. DAG->getRegPressure().MaxSetPressure);
  2133. }
  2134. }
  2135. }
  2136. // Initialize the candidate if needed.
  2137. if (!Cand.isValid()) {
  2138. TryCand.Reason = NodeOrder;
  2139. return;
  2140. }
  2141. if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
  2142. biasPhysRegCopy(Cand.SU, Zone.isTop()),
  2143. TryCand, Cand, PhysRegCopy))
  2144. return;
  2145. // Avoid exceeding the target's limit. If signed PSetID is negative, it is
  2146. // invalid; convert it to INT_MAX to give it lowest priority.
  2147. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
  2148. Cand.RPDelta.Excess,
  2149. TryCand, Cand, RegExcess))
  2150. return;
  2151. // Avoid increasing the max critical pressure in the scheduled region.
  2152. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
  2153. Cand.RPDelta.CriticalMax,
  2154. TryCand, Cand, RegCritical))
  2155. return;
  2156. // For loops that are acyclic path limited, aggressively schedule for latency.
  2157. if (Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, Zone))
  2158. return;
  2159. // Keep clustered nodes together to encourage downstream peephole
  2160. // optimizations which may reduce resource requirements.
  2161. //
  2162. // This is a best effort to set things up for a post-RA pass. Optimizations
  2163. // like generating loads of multiple registers should ideally be done within
  2164. // the scheduler pass by combining the loads during DAG postprocessing.
  2165. const SUnit *NextClusterSU =
  2166. Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
  2167. if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
  2168. TryCand, Cand, Cluster))
  2169. return;
  2170. // Weak edges are for clustering and other constraints.
  2171. if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
  2172. getWeakLeft(Cand.SU, Zone.isTop()),
  2173. TryCand, Cand, Weak)) {
  2174. return;
  2175. }
  2176. // Avoid increasing the max pressure of the entire region.
  2177. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
  2178. Cand.RPDelta.CurrentMax,
  2179. TryCand, Cand, RegMax))
  2180. return;
  2181. // Avoid critical resource consumption and balance the schedule.
  2182. TryCand.initResourceDelta(DAG, SchedModel);
  2183. if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
  2184. TryCand, Cand, ResourceReduce))
  2185. return;
  2186. if (tryGreater(TryCand.ResDelta.DemandedResources,
  2187. Cand.ResDelta.DemandedResources,
  2188. TryCand, Cand, ResourceDemand))
  2189. return;
  2190. // Avoid serializing long latency dependence chains.
  2191. // For acyclic path limited loops, latency was already checked above.
  2192. if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
  2193. && tryLatency(TryCand, Cand, Zone)) {
  2194. return;
  2195. }
  2196. // Prefer immediate defs/users of the last scheduled instruction. This is a
  2197. // local pressure avoidance strategy that also makes the machine code
  2198. // readable.
  2199. if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
  2200. TryCand, Cand, NextDefUse))
  2201. return;
  2202. // Fall through to original instruction order.
  2203. if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
  2204. || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
  2205. TryCand.Reason = NodeOrder;
  2206. }
  2207. }
  2208. #ifndef NDEBUG
  2209. const char *ConvergingScheduler::getReasonStr(
  2210. ConvergingScheduler::CandReason Reason) {
  2211. switch (Reason) {
  2212. case NoCand: return "NOCAND ";
  2213. case PhysRegCopy: return "PREG-COPY";
  2214. case RegExcess: return "REG-EXCESS";
  2215. case RegCritical: return "REG-CRIT ";
  2216. case Cluster: return "CLUSTER ";
  2217. case Weak: return "WEAK ";
  2218. case RegMax: return "REG-MAX ";
  2219. case ResourceReduce: return "RES-REDUCE";
  2220. case ResourceDemand: return "RES-DEMAND";
  2221. case TopDepthReduce: return "TOP-DEPTH ";
  2222. case TopPathReduce: return "TOP-PATH ";
  2223. case BotHeightReduce:return "BOT-HEIGHT";
  2224. case BotPathReduce: return "BOT-PATH ";
  2225. case NextDefUse: return "DEF-USE ";
  2226. case NodeOrder: return "ORDER ";
  2227. };
  2228. llvm_unreachable("Unknown reason!");
  2229. }
  2230. void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
  2231. PressureChange P;
  2232. unsigned ResIdx = 0;
  2233. unsigned Latency = 0;
  2234. switch (Cand.Reason) {
  2235. default:
  2236. break;
  2237. case RegExcess:
  2238. P = Cand.RPDelta.Excess;
  2239. break;
  2240. case RegCritical:
  2241. P = Cand.RPDelta.CriticalMax;
  2242. break;
  2243. case RegMax:
  2244. P = Cand.RPDelta.CurrentMax;
  2245. break;
  2246. case ResourceReduce:
  2247. ResIdx = Cand.Policy.ReduceResIdx;
  2248. break;
  2249. case ResourceDemand:
  2250. ResIdx = Cand.Policy.DemandResIdx;
  2251. break;
  2252. case TopDepthReduce:
  2253. Latency = Cand.SU->getDepth();
  2254. break;
  2255. case TopPathReduce:
  2256. Latency = Cand.SU->getHeight();
  2257. break;
  2258. case BotHeightReduce:
  2259. Latency = Cand.SU->getHeight();
  2260. break;
  2261. case BotPathReduce:
  2262. Latency = Cand.SU->getDepth();
  2263. break;
  2264. }
  2265. dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
  2266. if (P.isValid())
  2267. dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
  2268. << ":" << P.getUnitInc() << " ";
  2269. else
  2270. dbgs() << " ";
  2271. if (ResIdx)
  2272. dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
  2273. else
  2274. dbgs() << " ";
  2275. if (Latency)
  2276. dbgs() << " " << Latency << " cycles ";
  2277. else
  2278. dbgs() << " ";
  2279. dbgs() << '\n';
  2280. }
  2281. #endif
  2282. /// Pick the best candidate from the top queue.
  2283. ///
  2284. /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
  2285. /// DAG building. To adjust for the current scheduling location we need to
  2286. /// maintain the number of vreg uses remaining to be top-scheduled.
  2287. void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
  2288. const RegPressureTracker &RPTracker,
  2289. SchedCandidate &Cand) {
  2290. ReadyQueue &Q = Zone.Available;
  2291. DEBUG(Q.dump());
  2292. // getMaxPressureDelta temporarily modifies the tracker.
  2293. RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
  2294. for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
  2295. SchedCandidate TryCand(Cand.Policy);
  2296. TryCand.SU = *I;
  2297. tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
  2298. if (TryCand.Reason != NoCand) {
  2299. // Initialize resource delta if needed in case future heuristics query it.
  2300. if (TryCand.ResDelta == SchedResourceDelta())
  2301. TryCand.initResourceDelta(DAG, SchedModel);
  2302. Cand.setBest(TryCand);
  2303. DEBUG(traceCandidate(Cand));
  2304. }
  2305. }
  2306. }
  2307. static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
  2308. bool IsTop) {
  2309. DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
  2310. << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
  2311. }
  2312. /// Pick the best candidate node from either the top or bottom queue.
  2313. SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
  2314. // Schedule as far as possible in the direction of no choice. This is most
  2315. // efficient, but also provides the best heuristics for CriticalPSets.
  2316. if (SUnit *SU = Bot.pickOnlyChoice()) {
  2317. IsTopNode = false;
  2318. DEBUG(dbgs() << "Pick Bot NOCAND\n");
  2319. return SU;
  2320. }
  2321. if (SUnit *SU = Top.pickOnlyChoice()) {
  2322. IsTopNode = true;
  2323. DEBUG(dbgs() << "Pick Top NOCAND\n");
  2324. return SU;
  2325. }
  2326. CandPolicy NoPolicy;
  2327. SchedCandidate BotCand(NoPolicy);
  2328. SchedCandidate TopCand(NoPolicy);
  2329. Bot.setPolicy(BotCand.Policy, Top);
  2330. Top.setPolicy(TopCand.Policy, Bot);
  2331. // Prefer bottom scheduling when heuristics are silent.
  2332. pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
  2333. assert(BotCand.Reason != NoCand && "failed to find the first candidate");
  2334. // If either Q has a single candidate that provides the least increase in
  2335. // Excess pressure, we can immediately schedule from that Q.
  2336. //
  2337. // RegionCriticalPSets summarizes the pressure within the scheduled region and
  2338. // affects picking from either Q. If scheduling in one direction must
  2339. // increase pressure for one of the excess PSets, then schedule in that
  2340. // direction first to provide more freedom in the other direction.
  2341. if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
  2342. || (BotCand.Reason == RegCritical
  2343. && !BotCand.isRepeat(RegCritical)))
  2344. {
  2345. IsTopNode = false;
  2346. tracePick(BotCand, IsTopNode);
  2347. return BotCand.SU;
  2348. }
  2349. // Check if the top Q has a better candidate.
  2350. pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
  2351. assert(TopCand.Reason != NoCand && "failed to find the first candidate");
  2352. // Choose the queue with the most important (lowest enum) reason.
  2353. if (TopCand.Reason < BotCand.Reason) {
  2354. IsTopNode = true;
  2355. tracePick(TopCand, IsTopNode);
  2356. return TopCand.SU;
  2357. }
  2358. // Otherwise prefer the bottom candidate, in node order if all else failed.
  2359. IsTopNode = false;
  2360. tracePick(BotCand, IsTopNode);
  2361. return BotCand.SU;
  2362. }
  2363. /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
  2364. SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
  2365. if (DAG->top() == DAG->bottom()) {
  2366. assert(Top.Available.empty() && Top.Pending.empty() &&
  2367. Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
  2368. return NULL;
  2369. }
  2370. SUnit *SU;
  2371. do {
  2372. if (RegionPolicy.OnlyTopDown) {
  2373. SU = Top.pickOnlyChoice();
  2374. if (!SU) {
  2375. CandPolicy NoPolicy;
  2376. SchedCandidate TopCand(NoPolicy);
  2377. pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
  2378. assert(TopCand.Reason != NoCand && "failed to find a candidate");
  2379. tracePick(TopCand, true);
  2380. SU = TopCand.SU;
  2381. }
  2382. IsTopNode = true;
  2383. }
  2384. else if (RegionPolicy.OnlyBottomUp) {
  2385. SU = Bot.pickOnlyChoice();
  2386. if (!SU) {
  2387. CandPolicy NoPolicy;
  2388. SchedCandidate BotCand(NoPolicy);
  2389. pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
  2390. assert(BotCand.Reason != NoCand && "failed to find a candidate");
  2391. tracePick(BotCand, false);
  2392. SU = BotCand.SU;
  2393. }
  2394. IsTopNode = false;
  2395. }
  2396. else {
  2397. SU = pickNodeBidirectional(IsTopNode);
  2398. }
  2399. } while (SU->isScheduled);
  2400. if (SU->isTopReady())
  2401. Top.removeReady(SU);
  2402. if (SU->isBottomReady())
  2403. Bot.removeReady(SU);
  2404. DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
  2405. return SU;
  2406. }
  2407. void ConvergingScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
  2408. MachineBasicBlock::iterator InsertPos = SU->getInstr();
  2409. if (!isTop)
  2410. ++InsertPos;
  2411. SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
  2412. // Find already scheduled copies with a single physreg dependence and move
  2413. // them just above the scheduled instruction.
  2414. for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
  2415. I != E; ++I) {
  2416. if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
  2417. continue;
  2418. SUnit *DepSU = I->getSUnit();
  2419. if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
  2420. continue;
  2421. MachineInstr *Copy = DepSU->getInstr();
  2422. if (!Copy->isCopy())
  2423. continue;
  2424. DEBUG(dbgs() << " Rescheduling physreg copy ";
  2425. I->getSUnit()->dump(DAG));
  2426. DAG->moveInstruction(Copy, InsertPos);
  2427. }
  2428. }
  2429. /// Update the scheduler's state after scheduling a node. This is the same node
  2430. /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
  2431. /// it's state based on the current cycle before MachineSchedStrategy does.
  2432. ///
  2433. /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
  2434. /// them here. See comments in biasPhysRegCopy.
  2435. void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
  2436. if (IsTopNode) {
  2437. SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.CurrCycle);
  2438. Top.bumpNode(SU);
  2439. if (SU->hasPhysRegUses)
  2440. reschedulePhysRegCopies(SU, true);
  2441. }
  2442. else {
  2443. SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.CurrCycle);
  2444. Bot.bumpNode(SU);
  2445. if (SU->hasPhysRegDefs)
  2446. reschedulePhysRegCopies(SU, false);
  2447. }
  2448. }
  2449. /// Create the standard converging machine scheduler. This will be used as the
  2450. /// default scheduler if the target does not set a default.
  2451. static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
  2452. ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler(C));
  2453. // Register DAG post-processors.
  2454. //
  2455. // FIXME: extend the mutation API to allow earlier mutations to instantiate
  2456. // data and pass it to later mutations. Have a single mutation that gathers
  2457. // the interesting nodes in one pass.
  2458. DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
  2459. if (EnableLoadCluster && DAG->TII->enableClusterLoads())
  2460. DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
  2461. if (EnableMacroFusion)
  2462. DAG->addMutation(new MacroFusion(DAG->TII));
  2463. return DAG;
  2464. }
  2465. static MachineSchedRegistry
  2466. ConvergingSchedRegistry("converge", "Standard converging scheduler.",
  2467. createConvergingSched);
  2468. //===----------------------------------------------------------------------===//
  2469. // ILP Scheduler. Currently for experimental analysis of heuristics.
  2470. //===----------------------------------------------------------------------===//
  2471. namespace {
  2472. /// \brief Order nodes by the ILP metric.
  2473. struct ILPOrder {
  2474. const SchedDFSResult *DFSResult;
  2475. const BitVector *ScheduledTrees;
  2476. bool MaximizeILP;
  2477. ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
  2478. /// \brief Apply a less-than relation on node priority.
  2479. ///
  2480. /// (Return true if A comes after B in the Q.)
  2481. bool operator()(const SUnit *A, const SUnit *B) const {
  2482. unsigned SchedTreeA = DFSResult->getSubtreeID(A);
  2483. unsigned SchedTreeB = DFSResult->getSubtreeID(B);
  2484. if (SchedTreeA != SchedTreeB) {
  2485. // Unscheduled trees have lower priority.
  2486. if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
  2487. return ScheduledTrees->test(SchedTreeB);
  2488. // Trees with shallower connections have have lower priority.
  2489. if (DFSResult->getSubtreeLevel(SchedTreeA)
  2490. != DFSResult->getSubtreeLevel(SchedTreeB)) {
  2491. return DFSResult->getSubtreeLevel(SchedTreeA)
  2492. < DFSResult->getSubtreeLevel(SchedTreeB);
  2493. }
  2494. }
  2495. if (MaximizeILP)
  2496. return DFSResult->getILP(A) < DFSResult->getILP(B);
  2497. else
  2498. return DFSResult->getILP(A) > DFSResult->getILP(B);
  2499. }
  2500. };
  2501. /// \brief Schedule based on the ILP metric.
  2502. class ILPScheduler : public MachineSchedStrategy {
  2503. ScheduleDAGMI *DAG;
  2504. ILPOrder Cmp;
  2505. std::vector<SUnit*> ReadyQ;
  2506. public:
  2507. ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
  2508. virtual void initialize(ScheduleDAGMI *dag) {
  2509. DAG = dag;
  2510. DAG->computeDFSResult();
  2511. Cmp.DFSResult = DAG->getDFSResult();
  2512. Cmp.ScheduledTrees = &DAG->getScheduledTrees();
  2513. ReadyQ.clear();
  2514. }
  2515. virtual void registerRoots() {
  2516. // Restore the heap in ReadyQ with the updated DFS results.
  2517. std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  2518. }
  2519. /// Implement MachineSchedStrategy interface.
  2520. /// -----------------------------------------
  2521. /// Callback to select the highest priority node from the ready Q.
  2522. virtual SUnit *pickNode(bool &IsTopNode) {
  2523. if (ReadyQ.empty()) return NULL;
  2524. std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  2525. SUnit *SU = ReadyQ.back();
  2526. ReadyQ.pop_back();
  2527. IsTopNode = false;
  2528. DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
  2529. << " ILP: " << DAG->getDFSResult()->getILP(SU)
  2530. << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
  2531. << DAG->getDFSResult()->getSubtreeLevel(
  2532. DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
  2533. << "Scheduling " << *SU->getInstr());
  2534. return SU;
  2535. }
  2536. /// \brief Scheduler callback to notify that a new subtree is scheduled.
  2537. virtual void scheduleTree(unsigned SubtreeID) {
  2538. std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  2539. }
  2540. /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
  2541. /// DFSResults, and resort the priority Q.
  2542. virtual void schedNode(SUnit *SU, bool IsTopNode) {
  2543. assert(!IsTopNode && "SchedDFSResult needs bottom-up");
  2544. }
  2545. virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
  2546. virtual void releaseBottomNode(SUnit *SU) {
  2547. ReadyQ.push_back(SU);
  2548. std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  2549. }
  2550. };
  2551. } // namespace
  2552. static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
  2553. return new ScheduleDAGMI(C, new ILPScheduler(true));
  2554. }
  2555. static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
  2556. return new ScheduleDAGMI(C, new ILPScheduler(false));
  2557. }
  2558. static MachineSchedRegistry ILPMaxRegistry(
  2559. "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
  2560. static MachineSchedRegistry ILPMinRegistry(
  2561. "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
  2562. //===----------------------------------------------------------------------===//
  2563. // Machine Instruction Shuffler for Correctness Testing
  2564. //===----------------------------------------------------------------------===//
  2565. #ifndef NDEBUG
  2566. namespace {
  2567. /// Apply a less-than relation on the node order, which corresponds to the
  2568. /// instruction order prior to scheduling. IsReverse implements greater-than.
  2569. template<bool IsReverse>
  2570. struct SUnitOrder {
  2571. bool operator()(SUnit *A, SUnit *B) const {
  2572. if (IsReverse)
  2573. return A->NodeNum > B->NodeNum;
  2574. else
  2575. return A->NodeNum < B->NodeNum;
  2576. }
  2577. };
  2578. /// Reorder instructions as much as possible.
  2579. class InstructionShuffler : public MachineSchedStrategy {
  2580. bool IsAlternating;
  2581. bool IsTopDown;
  2582. // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
  2583. // gives nodes with a higher number higher priority causing the latest
  2584. // instructions to be scheduled first.
  2585. PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
  2586. TopQ;
  2587. // When scheduling bottom-up, use greater-than as the queue priority.
  2588. PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
  2589. BottomQ;
  2590. public:
  2591. InstructionShuffler(bool alternate, bool topdown)
  2592. : IsAlternating(alternate), IsTopDown(topdown) {}
  2593. virtual void initialize(ScheduleDAGMI *) {
  2594. TopQ.clear();
  2595. BottomQ.clear();
  2596. }
  2597. /// Implement MachineSchedStrategy interface.
  2598. /// -----------------------------------------
  2599. virtual SUnit *pickNode(bool &IsTopNode) {
  2600. SUnit *SU;
  2601. if (IsTopDown) {
  2602. do {
  2603. if (TopQ.empty()) return NULL;
  2604. SU = TopQ.top();
  2605. TopQ.pop();
  2606. } while (SU->isScheduled);
  2607. IsTopNode = true;
  2608. }
  2609. else {
  2610. do {
  2611. if (BottomQ.empty()) return NULL;
  2612. SU = BottomQ.top();
  2613. BottomQ.pop();
  2614. } while (SU->isScheduled);
  2615. IsTopNode = false;
  2616. }
  2617. if (IsAlternating)
  2618. IsTopDown = !IsTopDown;
  2619. return SU;
  2620. }
  2621. virtual void schedNode(SUnit *SU, bool IsTopNode) {}
  2622. virtual void releaseTopNode(SUnit *SU) {
  2623. TopQ.push(SU);
  2624. }
  2625. virtual void releaseBottomNode(SUnit *SU) {
  2626. BottomQ.push(SU);
  2627. }
  2628. };
  2629. } // namespace
  2630. static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
  2631. bool Alternate = !ForceTopDown && !ForceBottomUp;
  2632. bool TopDown = !ForceBottomUp;
  2633. assert((TopDown || !ForceTopDown) &&
  2634. "-misched-topdown incompatible with -misched-bottomup");
  2635. return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
  2636. }
  2637. static MachineSchedRegistry ShufflerRegistry(
  2638. "shuffle", "Shuffle machine instructions alternating directions",
  2639. createInstructionShuffler);
  2640. #endif // !NDEBUG
  2641. //===----------------------------------------------------------------------===//
  2642. // GraphWriter support for ScheduleDAGMI.
  2643. //===----------------------------------------------------------------------===//
  2644. #ifndef NDEBUG
  2645. namespace llvm {
  2646. template<> struct GraphTraits<
  2647. ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
  2648. template<>
  2649. struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
  2650. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  2651. static std::string getGraphName(const ScheduleDAG *G) {
  2652. return G->MF.getName();
  2653. }
  2654. static bool renderGraphFromBottomUp() {
  2655. return true;
  2656. }
  2657. static bool isNodeHidden(const SUnit *Node) {
  2658. return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
  2659. }
  2660. static bool hasNodeAddressLabel(const SUnit *Node,
  2661. const ScheduleDAG *Graph) {
  2662. return false;
  2663. }
  2664. /// If you want to override the dot attributes printed for a particular
  2665. /// edge, override this method.
  2666. static std::string getEdgeAttributes(const SUnit *Node,
  2667. SUnitIterator EI,
  2668. const ScheduleDAG *Graph) {
  2669. if (EI.isArtificialDep())
  2670. return "color=cyan,style=dashed";
  2671. if (EI.isCtrlDep())
  2672. return "color=blue,style=dashed";
  2673. return "";
  2674. }
  2675. static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
  2676. std::string Str;
  2677. raw_string_ostream SS(Str);
  2678. SS << "SU(" << SU->NodeNum << ')';
  2679. return SS.str();
  2680. }
  2681. static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
  2682. return G->getGraphNodeLabel(SU);
  2683. }
  2684. static std::string getNodeAttributes(const SUnit *N,
  2685. const ScheduleDAG *Graph) {
  2686. std::string Str("shape=Mrecord");
  2687. const SchedDFSResult *DFS =
  2688. static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
  2689. if (DFS) {
  2690. Str += ",style=filled,fillcolor=\"#";
  2691. Str += DOT::getColorString(DFS->getSubtreeID(N));
  2692. Str += '"';
  2693. }
  2694. return Str;
  2695. }
  2696. };
  2697. } // namespace llvm
  2698. #endif // NDEBUG
  2699. /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
  2700. /// rendered using 'dot'.
  2701. ///
  2702. void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
  2703. #ifndef NDEBUG
  2704. ViewGraph(this, Name, false, Title);
  2705. #else
  2706. errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
  2707. << "systems with Graphviz or gv!\n";
  2708. #endif // NDEBUG
  2709. }
  2710. /// Out-of-line implementation with no arguments is handy for gdb.
  2711. void ScheduleDAGMI::viewGraph() {
  2712. viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
  2713. }