MachineScheduler.cpp 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756
  1. //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // MachineScheduler schedules machine instructions after phi elimination. It
  10. // preserves LiveIntervals so it can be invoked before register allocation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MachineScheduler.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/PriorityQueue.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/iterator_range.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/CodeGen/LiveInterval.h"
  23. #include "llvm/CodeGen/LiveIntervals.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineDominators.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineLoopInfo.h"
  30. #include "llvm/CodeGen/MachineOperand.h"
  31. #include "llvm/CodeGen/MachinePassRegistry.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/Passes.h"
  34. #include "llvm/CodeGen/RegisterClassInfo.h"
  35. #include "llvm/CodeGen/RegisterPressure.h"
  36. #include "llvm/CodeGen/ScheduleDAG.h"
  37. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  38. #include "llvm/CodeGen/ScheduleDAGMutation.h"
  39. #include "llvm/CodeGen/ScheduleDFS.h"
  40. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  41. #include "llvm/CodeGen/SlotIndexes.h"
  42. #include "llvm/CodeGen/TargetFrameLowering.h"
  43. #include "llvm/CodeGen/TargetInstrInfo.h"
  44. #include "llvm/CodeGen/TargetLowering.h"
  45. #include "llvm/CodeGen/TargetPassConfig.h"
  46. #include "llvm/CodeGen/TargetRegisterInfo.h"
  47. #include "llvm/CodeGen/TargetSchedule.h"
  48. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  49. #include "llvm/Config/llvm-config.h"
  50. #include "llvm/MC/LaneBitmask.h"
  51. #include "llvm/Pass.h"
  52. #include "llvm/Support/CommandLine.h"
  53. #include "llvm/Support/Compiler.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/Support/ErrorHandling.h"
  56. #include "llvm/Support/GraphWriter.h"
  57. #include "llvm/Support/MachineValueType.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include <algorithm>
  60. #include <cassert>
  61. #include <cstdint>
  62. #include <iterator>
  63. #include <limits>
  64. #include <memory>
  65. #include <string>
  66. #include <tuple>
  67. #include <utility>
  68. #include <vector>
  69. using namespace llvm;
  70. #define DEBUG_TYPE "machine-scheduler"
  71. namespace llvm {
  72. cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
  73. cl::desc("Force top-down list scheduling"));
  74. cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
  75. cl::desc("Force bottom-up list scheduling"));
  76. cl::opt<bool>
  77. DumpCriticalPathLength("misched-dcpl", cl::Hidden,
  78. cl::desc("Print critical path length to stdout"));
  79. } // end namespace llvm
  80. #ifndef NDEBUG
  81. static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
  82. cl::desc("Pop up a window to show MISched dags after they are processed"));
  83. /// In some situations a few uninteresting nodes depend on nearly all other
  84. /// nodes in the graph, provide a cutoff to hide them.
  85. static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
  86. cl::desc("Hide nodes with more predecessor/successor than cutoff"));
  87. static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
  88. cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
  89. static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
  90. cl::desc("Only schedule this function"));
  91. static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
  92. cl::desc("Only schedule this MBB#"));
  93. static cl::opt<bool> PrintDAGs("misched-print-dags", cl::Hidden,
  94. cl::desc("Print schedule DAGs"));
  95. #else
  96. static const bool ViewMISchedDAGs = false;
  97. static const bool PrintDAGs = false;
  98. #endif // NDEBUG
  99. /// Avoid quadratic complexity in unusually large basic blocks by limiting the
  100. /// size of the ready lists.
  101. static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
  102. cl::desc("Limit ready list to N instructions"), cl::init(256));
  103. static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
  104. cl::desc("Enable register pressure scheduling."), cl::init(true));
  105. static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
  106. cl::desc("Enable cyclic critical path analysis."), cl::init(true));
  107. static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
  108. cl::desc("Enable memop clustering."),
  109. cl::init(true));
  110. static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
  111. cl::desc("Verify machine instrs before and after machine scheduling"));
  112. // DAG subtrees must have at least this many nodes.
  113. static const unsigned MinSubtreeSize = 8;
  114. // Pin the vtables to this file.
  115. void MachineSchedStrategy::anchor() {}
  116. void ScheduleDAGMutation::anchor() {}
  117. //===----------------------------------------------------------------------===//
  118. // Machine Instruction Scheduling Pass and Registry
  119. //===----------------------------------------------------------------------===//
  120. MachineSchedContext::MachineSchedContext() {
  121. RegClassInfo = new RegisterClassInfo();
  122. }
  123. MachineSchedContext::~MachineSchedContext() {
  124. delete RegClassInfo;
  125. }
  126. namespace {
  127. /// Base class for a machine scheduler class that can run at any point.
  128. class MachineSchedulerBase : public MachineSchedContext,
  129. public MachineFunctionPass {
  130. public:
  131. MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
  132. void print(raw_ostream &O, const Module* = nullptr) const override;
  133. protected:
  134. void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
  135. };
  136. /// MachineScheduler runs after coalescing and before register allocation.
  137. class MachineScheduler : public MachineSchedulerBase {
  138. public:
  139. MachineScheduler();
  140. void getAnalysisUsage(AnalysisUsage &AU) const override;
  141. bool runOnMachineFunction(MachineFunction&) override;
  142. static char ID; // Class identification, replacement for typeinfo
  143. protected:
  144. ScheduleDAGInstrs *createMachineScheduler();
  145. };
  146. /// PostMachineScheduler runs after shortly before code emission.
  147. class PostMachineScheduler : public MachineSchedulerBase {
  148. public:
  149. PostMachineScheduler();
  150. void getAnalysisUsage(AnalysisUsage &AU) const override;
  151. bool runOnMachineFunction(MachineFunction&) override;
  152. static char ID; // Class identification, replacement for typeinfo
  153. protected:
  154. ScheduleDAGInstrs *createPostMachineScheduler();
  155. };
  156. } // end anonymous namespace
  157. char MachineScheduler::ID = 0;
  158. char &llvm::MachineSchedulerID = MachineScheduler::ID;
  159. INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
  160. "Machine Instruction Scheduler", false, false)
  161. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  162. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  163. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  164. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  165. INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
  166. "Machine Instruction Scheduler", false, false)
  167. MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
  168. initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
  169. }
  170. void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
  171. AU.setPreservesCFG();
  172. AU.addRequiredID(MachineDominatorsID);
  173. AU.addRequired<MachineLoopInfo>();
  174. AU.addRequired<AAResultsWrapperPass>();
  175. AU.addRequired<TargetPassConfig>();
  176. AU.addRequired<SlotIndexes>();
  177. AU.addPreserved<SlotIndexes>();
  178. AU.addRequired<LiveIntervals>();
  179. AU.addPreserved<LiveIntervals>();
  180. MachineFunctionPass::getAnalysisUsage(AU);
  181. }
  182. char PostMachineScheduler::ID = 0;
  183. char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
  184. INITIALIZE_PASS(PostMachineScheduler, "postmisched",
  185. "PostRA Machine Instruction Scheduler", false, false)
  186. PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
  187. initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
  188. }
  189. void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
  190. AU.setPreservesCFG();
  191. AU.addRequiredID(MachineDominatorsID);
  192. AU.addRequired<MachineLoopInfo>();
  193. AU.addRequired<TargetPassConfig>();
  194. MachineFunctionPass::getAnalysisUsage(AU);
  195. }
  196. MachinePassRegistry<MachineSchedRegistry::ScheduleDAGCtor>
  197. MachineSchedRegistry::Registry;
  198. /// A dummy default scheduler factory indicates whether the scheduler
  199. /// is overridden on the command line.
  200. static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
  201. return nullptr;
  202. }
  203. /// MachineSchedOpt allows command line selection of the scheduler.
  204. static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
  205. RegisterPassParser<MachineSchedRegistry>>
  206. MachineSchedOpt("misched",
  207. cl::init(&useDefaultMachineSched), cl::Hidden,
  208. cl::desc("Machine instruction scheduler to use"));
  209. static MachineSchedRegistry
  210. DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
  211. useDefaultMachineSched);
  212. static cl::opt<bool> EnableMachineSched(
  213. "enable-misched",
  214. cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
  215. cl::Hidden);
  216. static cl::opt<bool> EnablePostRAMachineSched(
  217. "enable-post-misched",
  218. cl::desc("Enable the post-ra machine instruction scheduling pass."),
  219. cl::init(true), cl::Hidden);
  220. /// Decrement this iterator until reaching the top or a non-debug instr.
  221. static MachineBasicBlock::const_iterator
  222. priorNonDebug(MachineBasicBlock::const_iterator I,
  223. MachineBasicBlock::const_iterator Beg) {
  224. assert(I != Beg && "reached the top of the region, cannot decrement");
  225. while (--I != Beg) {
  226. if (!I->isDebugInstr())
  227. break;
  228. }
  229. return I;
  230. }
  231. /// Non-const version.
  232. static MachineBasicBlock::iterator
  233. priorNonDebug(MachineBasicBlock::iterator I,
  234. MachineBasicBlock::const_iterator Beg) {
  235. return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
  236. .getNonConstIterator();
  237. }
  238. /// If this iterator is a debug value, increment until reaching the End or a
  239. /// non-debug instruction.
  240. static MachineBasicBlock::const_iterator
  241. nextIfDebug(MachineBasicBlock::const_iterator I,
  242. MachineBasicBlock::const_iterator End) {
  243. for(; I != End; ++I) {
  244. if (!I->isDebugInstr())
  245. break;
  246. }
  247. return I;
  248. }
  249. /// Non-const version.
  250. static MachineBasicBlock::iterator
  251. nextIfDebug(MachineBasicBlock::iterator I,
  252. MachineBasicBlock::const_iterator End) {
  253. return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
  254. .getNonConstIterator();
  255. }
  256. /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
  257. ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
  258. // Select the scheduler, or set the default.
  259. MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
  260. if (Ctor != useDefaultMachineSched)
  261. return Ctor(this);
  262. // Get the default scheduler set by the target for this function.
  263. ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
  264. if (Scheduler)
  265. return Scheduler;
  266. // Default to GenericScheduler.
  267. return createGenericSchedLive(this);
  268. }
  269. /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
  270. /// the caller. We don't have a command line option to override the postRA
  271. /// scheduler. The Target must configure it.
  272. ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
  273. // Get the postRA scheduler set by the target for this function.
  274. ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
  275. if (Scheduler)
  276. return Scheduler;
  277. // Default to GenericScheduler.
  278. return createGenericSchedPostRA(this);
  279. }
  280. /// Top-level MachineScheduler pass driver.
  281. ///
  282. /// Visit blocks in function order. Divide each block into scheduling regions
  283. /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
  284. /// consistent with the DAG builder, which traverses the interior of the
  285. /// scheduling regions bottom-up.
  286. ///
  287. /// This design avoids exposing scheduling boundaries to the DAG builder,
  288. /// simplifying the DAG builder's support for "special" target instructions.
  289. /// At the same time the design allows target schedulers to operate across
  290. /// scheduling boundaries, for example to bundle the boundary instructions
  291. /// without reordering them. This creates complexity, because the target
  292. /// scheduler must update the RegionBegin and RegionEnd positions cached by
  293. /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
  294. /// design would be to split blocks at scheduling boundaries, but LLVM has a
  295. /// general bias against block splitting purely for implementation simplicity.
  296. bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
  297. if (skipFunction(mf.getFunction()))
  298. return false;
  299. if (EnableMachineSched.getNumOccurrences()) {
  300. if (!EnableMachineSched)
  301. return false;
  302. } else if (!mf.getSubtarget().enableMachineScheduler())
  303. return false;
  304. LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
  305. // Initialize the context of the pass.
  306. MF = &mf;
  307. MLI = &getAnalysis<MachineLoopInfo>();
  308. MDT = &getAnalysis<MachineDominatorTree>();
  309. PassConfig = &getAnalysis<TargetPassConfig>();
  310. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  311. LIS = &getAnalysis<LiveIntervals>();
  312. if (VerifyScheduling) {
  313. LLVM_DEBUG(LIS->dump());
  314. MF->verify(this, "Before machine scheduling.");
  315. }
  316. RegClassInfo->runOnMachineFunction(*MF);
  317. // Instantiate the selected scheduler for this target, function, and
  318. // optimization level.
  319. std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
  320. scheduleRegions(*Scheduler, false);
  321. LLVM_DEBUG(LIS->dump());
  322. if (VerifyScheduling)
  323. MF->verify(this, "After machine scheduling.");
  324. return true;
  325. }
  326. bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
  327. if (skipFunction(mf.getFunction()))
  328. return false;
  329. if (EnablePostRAMachineSched.getNumOccurrences()) {
  330. if (!EnablePostRAMachineSched)
  331. return false;
  332. } else if (!mf.getSubtarget().enablePostRAScheduler()) {
  333. LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
  334. return false;
  335. }
  336. LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
  337. // Initialize the context of the pass.
  338. MF = &mf;
  339. MLI = &getAnalysis<MachineLoopInfo>();
  340. PassConfig = &getAnalysis<TargetPassConfig>();
  341. if (VerifyScheduling)
  342. MF->verify(this, "Before post machine scheduling.");
  343. // Instantiate the selected scheduler for this target, function, and
  344. // optimization level.
  345. std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
  346. scheduleRegions(*Scheduler, true);
  347. if (VerifyScheduling)
  348. MF->verify(this, "After post machine scheduling.");
  349. return true;
  350. }
  351. /// Return true of the given instruction should not be included in a scheduling
  352. /// region.
  353. ///
  354. /// MachineScheduler does not currently support scheduling across calls. To
  355. /// handle calls, the DAG builder needs to be modified to create register
  356. /// anti/output dependencies on the registers clobbered by the call's regmask
  357. /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
  358. /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
  359. /// the boundary, but there would be no benefit to postRA scheduling across
  360. /// calls this late anyway.
  361. static bool isSchedBoundary(MachineBasicBlock::iterator MI,
  362. MachineBasicBlock *MBB,
  363. MachineFunction *MF,
  364. const TargetInstrInfo *TII) {
  365. return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
  366. }
  367. /// A region of an MBB for scheduling.
  368. namespace {
  369. struct SchedRegion {
  370. /// RegionBegin is the first instruction in the scheduling region, and
  371. /// RegionEnd is either MBB->end() or the scheduling boundary after the
  372. /// last instruction in the scheduling region. These iterators cannot refer
  373. /// to instructions outside of the identified scheduling region because
  374. /// those may be reordered before scheduling this region.
  375. MachineBasicBlock::iterator RegionBegin;
  376. MachineBasicBlock::iterator RegionEnd;
  377. unsigned NumRegionInstrs;
  378. SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
  379. unsigned N) :
  380. RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
  381. };
  382. } // end anonymous namespace
  383. using MBBRegionsVector = SmallVector<SchedRegion, 16>;
  384. static void
  385. getSchedRegions(MachineBasicBlock *MBB,
  386. MBBRegionsVector &Regions,
  387. bool RegionsTopDown) {
  388. MachineFunction *MF = MBB->getParent();
  389. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  390. MachineBasicBlock::iterator I = nullptr;
  391. for(MachineBasicBlock::iterator RegionEnd = MBB->end();
  392. RegionEnd != MBB->begin(); RegionEnd = I) {
  393. // Avoid decrementing RegionEnd for blocks with no terminator.
  394. if (RegionEnd != MBB->end() ||
  395. isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
  396. --RegionEnd;
  397. }
  398. // The next region starts above the previous region. Look backward in the
  399. // instruction stream until we find the nearest boundary.
  400. unsigned NumRegionInstrs = 0;
  401. I = RegionEnd;
  402. for (;I != MBB->begin(); --I) {
  403. MachineInstr &MI = *std::prev(I);
  404. if (isSchedBoundary(&MI, &*MBB, MF, TII))
  405. break;
  406. if (!MI.isDebugInstr()) {
  407. // MBB::size() uses instr_iterator to count. Here we need a bundle to
  408. // count as a single instruction.
  409. ++NumRegionInstrs;
  410. }
  411. }
  412. // It's possible we found a scheduling region that only has debug
  413. // instructions. Don't bother scheduling these.
  414. if (NumRegionInstrs != 0)
  415. Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
  416. }
  417. if (RegionsTopDown)
  418. std::reverse(Regions.begin(), Regions.end());
  419. }
  420. /// Main driver for both MachineScheduler and PostMachineScheduler.
  421. void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
  422. bool FixKillFlags) {
  423. // Visit all machine basic blocks.
  424. //
  425. // TODO: Visit blocks in global postorder or postorder within the bottom-up
  426. // loop tree. Then we can optionally compute global RegPressure.
  427. for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
  428. MBB != MBBEnd; ++MBB) {
  429. Scheduler.startBlock(&*MBB);
  430. #ifndef NDEBUG
  431. if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
  432. continue;
  433. if (SchedOnlyBlock.getNumOccurrences()
  434. && (int)SchedOnlyBlock != MBB->getNumber())
  435. continue;
  436. #endif
  437. // Break the block into scheduling regions [I, RegionEnd). RegionEnd
  438. // points to the scheduling boundary at the bottom of the region. The DAG
  439. // does not include RegionEnd, but the region does (i.e. the next
  440. // RegionEnd is above the previous RegionBegin). If the current block has
  441. // no terminator then RegionEnd == MBB->end() for the bottom region.
  442. //
  443. // All the regions of MBB are first found and stored in MBBRegions, which
  444. // will be processed (MBB) top-down if initialized with true.
  445. //
  446. // The Scheduler may insert instructions during either schedule() or
  447. // exitRegion(), even for empty regions. So the local iterators 'I' and
  448. // 'RegionEnd' are invalid across these calls. Instructions must not be
  449. // added to other regions than the current one without updating MBBRegions.
  450. MBBRegionsVector MBBRegions;
  451. getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
  452. for (MBBRegionsVector::iterator R = MBBRegions.begin();
  453. R != MBBRegions.end(); ++R) {
  454. MachineBasicBlock::iterator I = R->RegionBegin;
  455. MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
  456. unsigned NumRegionInstrs = R->NumRegionInstrs;
  457. // Notify the scheduler of the region, even if we may skip scheduling
  458. // it. Perhaps it still needs to be bundled.
  459. Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
  460. // Skip empty scheduling regions (0 or 1 schedulable instructions).
  461. if (I == RegionEnd || I == std::prev(RegionEnd)) {
  462. // Close the current region. Bundle the terminator if needed.
  463. // This invalidates 'RegionEnd' and 'I'.
  464. Scheduler.exitRegion();
  465. continue;
  466. }
  467. LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
  468. LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
  469. << " " << MBB->getName() << "\n From: " << *I
  470. << " To: ";
  471. if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
  472. else dbgs() << "End";
  473. dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
  474. if (DumpCriticalPathLength) {
  475. errs() << MF->getName();
  476. errs() << ":%bb. " << MBB->getNumber();
  477. errs() << " " << MBB->getName() << " \n";
  478. }
  479. // Schedule a region: possibly reorder instructions.
  480. // This invalidates the original region iterators.
  481. Scheduler.schedule();
  482. // Close the current region.
  483. Scheduler.exitRegion();
  484. }
  485. Scheduler.finishBlock();
  486. // FIXME: Ideally, no further passes should rely on kill flags. However,
  487. // thumb2 size reduction is currently an exception, so the PostMIScheduler
  488. // needs to do this.
  489. if (FixKillFlags)
  490. Scheduler.fixupKills(*MBB);
  491. }
  492. Scheduler.finalizeSchedule();
  493. }
  494. void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
  495. // unimplemented
  496. }
  497. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  498. LLVM_DUMP_METHOD void ReadyQueue::dump() const {
  499. dbgs() << "Queue " << Name << ": ";
  500. for (const SUnit *SU : Queue)
  501. dbgs() << SU->NodeNum << " ";
  502. dbgs() << "\n";
  503. }
  504. #endif
  505. //===----------------------------------------------------------------------===//
  506. // ScheduleDAGMI - Basic machine instruction scheduling. This is
  507. // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
  508. // virtual registers.
  509. // ===----------------------------------------------------------------------===/
  510. // Provide a vtable anchor.
  511. ScheduleDAGMI::~ScheduleDAGMI() = default;
  512. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
  513. /// NumPredsLeft reaches zero, release the successor node.
  514. ///
  515. /// FIXME: Adjust SuccSU height based on MinLatency.
  516. void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
  517. SUnit *SuccSU = SuccEdge->getSUnit();
  518. if (SuccEdge->isWeak()) {
  519. --SuccSU->WeakPredsLeft;
  520. if (SuccEdge->isCluster())
  521. NextClusterSucc = SuccSU;
  522. return;
  523. }
  524. #ifndef NDEBUG
  525. if (SuccSU->NumPredsLeft == 0) {
  526. dbgs() << "*** Scheduling failed! ***\n";
  527. dumpNode(*SuccSU);
  528. dbgs() << " has been released too many times!\n";
  529. llvm_unreachable(nullptr);
  530. }
  531. #endif
  532. // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
  533. // CurrCycle may have advanced since then.
  534. if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
  535. SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
  536. --SuccSU->NumPredsLeft;
  537. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  538. SchedImpl->releaseTopNode(SuccSU);
  539. }
  540. /// releaseSuccessors - Call releaseSucc on each of SU's successors.
  541. void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
  542. for (SDep &Succ : SU->Succs)
  543. releaseSucc(SU, &Succ);
  544. }
  545. /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
  546. /// NumSuccsLeft reaches zero, release the predecessor node.
  547. ///
  548. /// FIXME: Adjust PredSU height based on MinLatency.
  549. void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
  550. SUnit *PredSU = PredEdge->getSUnit();
  551. if (PredEdge->isWeak()) {
  552. --PredSU->WeakSuccsLeft;
  553. if (PredEdge->isCluster())
  554. NextClusterPred = PredSU;
  555. return;
  556. }
  557. #ifndef NDEBUG
  558. if (PredSU->NumSuccsLeft == 0) {
  559. dbgs() << "*** Scheduling failed! ***\n";
  560. dumpNode(*PredSU);
  561. dbgs() << " has been released too many times!\n";
  562. llvm_unreachable(nullptr);
  563. }
  564. #endif
  565. // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
  566. // CurrCycle may have advanced since then.
  567. if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
  568. PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
  569. --PredSU->NumSuccsLeft;
  570. if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
  571. SchedImpl->releaseBottomNode(PredSU);
  572. }
  573. /// releasePredecessors - Call releasePred on each of SU's predecessors.
  574. void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
  575. for (SDep &Pred : SU->Preds)
  576. releasePred(SU, &Pred);
  577. }
  578. void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
  579. ScheduleDAGInstrs::startBlock(bb);
  580. SchedImpl->enterMBB(bb);
  581. }
  582. void ScheduleDAGMI::finishBlock() {
  583. SchedImpl->leaveMBB();
  584. ScheduleDAGInstrs::finishBlock();
  585. }
  586. /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
  587. /// crossing a scheduling boundary. [begin, end) includes all instructions in
  588. /// the region, including the boundary itself and single-instruction regions
  589. /// that don't get scheduled.
  590. void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
  591. MachineBasicBlock::iterator begin,
  592. MachineBasicBlock::iterator end,
  593. unsigned regioninstrs)
  594. {
  595. ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
  596. SchedImpl->initPolicy(begin, end, regioninstrs);
  597. }
  598. /// This is normally called from the main scheduler loop but may also be invoked
  599. /// by the scheduling strategy to perform additional code motion.
  600. void ScheduleDAGMI::moveInstruction(
  601. MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
  602. // Advance RegionBegin if the first instruction moves down.
  603. if (&*RegionBegin == MI)
  604. ++RegionBegin;
  605. // Update the instruction stream.
  606. BB->splice(InsertPos, BB, MI);
  607. // Update LiveIntervals
  608. if (LIS)
  609. LIS->handleMove(*MI, /*UpdateFlags=*/true);
  610. // Recede RegionBegin if an instruction moves above the first.
  611. if (RegionBegin == InsertPos)
  612. RegionBegin = MI;
  613. }
  614. bool ScheduleDAGMI::checkSchedLimit() {
  615. #ifndef NDEBUG
  616. if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
  617. CurrentTop = CurrentBottom;
  618. return false;
  619. }
  620. ++NumInstrsScheduled;
  621. #endif
  622. return true;
  623. }
  624. /// Per-region scheduling driver, called back from
  625. /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
  626. /// does not consider liveness or register pressure. It is useful for PostRA
  627. /// scheduling and potentially other custom schedulers.
  628. void ScheduleDAGMI::schedule() {
  629. LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
  630. LLVM_DEBUG(SchedImpl->dumpPolicy());
  631. // Build the DAG.
  632. buildSchedGraph(AA);
  633. postprocessDAG();
  634. SmallVector<SUnit*, 8> TopRoots, BotRoots;
  635. findRootsAndBiasEdges(TopRoots, BotRoots);
  636. LLVM_DEBUG(dump());
  637. if (PrintDAGs) dump();
  638. if (ViewMISchedDAGs) viewGraph();
  639. // Initialize the strategy before modifying the DAG.
  640. // This may initialize a DFSResult to be used for queue priority.
  641. SchedImpl->initialize(this);
  642. // Initialize ready queues now that the DAG and priority data are finalized.
  643. initQueues(TopRoots, BotRoots);
  644. bool IsTopNode = false;
  645. while (true) {
  646. LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
  647. SUnit *SU = SchedImpl->pickNode(IsTopNode);
  648. if (!SU) break;
  649. assert(!SU->isScheduled && "Node already scheduled");
  650. if (!checkSchedLimit())
  651. break;
  652. MachineInstr *MI = SU->getInstr();
  653. if (IsTopNode) {
  654. assert(SU->isTopReady() && "node still has unscheduled dependencies");
  655. if (&*CurrentTop == MI)
  656. CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
  657. else
  658. moveInstruction(MI, CurrentTop);
  659. } else {
  660. assert(SU->isBottomReady() && "node still has unscheduled dependencies");
  661. MachineBasicBlock::iterator priorII =
  662. priorNonDebug(CurrentBottom, CurrentTop);
  663. if (&*priorII == MI)
  664. CurrentBottom = priorII;
  665. else {
  666. if (&*CurrentTop == MI)
  667. CurrentTop = nextIfDebug(++CurrentTop, priorII);
  668. moveInstruction(MI, CurrentBottom);
  669. CurrentBottom = MI;
  670. }
  671. }
  672. // Notify the scheduling strategy before updating the DAG.
  673. // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
  674. // runs, it can then use the accurate ReadyCycle time to determine whether
  675. // newly released nodes can move to the readyQ.
  676. SchedImpl->schedNode(SU, IsTopNode);
  677. updateQueues(SU, IsTopNode);
  678. }
  679. assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
  680. placeDebugValues();
  681. LLVM_DEBUG({
  682. dbgs() << "*** Final schedule for "
  683. << printMBBReference(*begin()->getParent()) << " ***\n";
  684. dumpSchedule();
  685. dbgs() << '\n';
  686. });
  687. }
  688. /// Apply each ScheduleDAGMutation step in order.
  689. void ScheduleDAGMI::postprocessDAG() {
  690. for (auto &m : Mutations)
  691. m->apply(this);
  692. }
  693. void ScheduleDAGMI::
  694. findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
  695. SmallVectorImpl<SUnit*> &BotRoots) {
  696. for (SUnit &SU : SUnits) {
  697. assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
  698. // Order predecessors so DFSResult follows the critical path.
  699. SU.biasCriticalPath();
  700. // A SUnit is ready to top schedule if it has no predecessors.
  701. if (!SU.NumPredsLeft)
  702. TopRoots.push_back(&SU);
  703. // A SUnit is ready to bottom schedule if it has no successors.
  704. if (!SU.NumSuccsLeft)
  705. BotRoots.push_back(&SU);
  706. }
  707. ExitSU.biasCriticalPath();
  708. }
  709. /// Identify DAG roots and setup scheduler queues.
  710. void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
  711. ArrayRef<SUnit*> BotRoots) {
  712. NextClusterSucc = nullptr;
  713. NextClusterPred = nullptr;
  714. // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
  715. //
  716. // Nodes with unreleased weak edges can still be roots.
  717. // Release top roots in forward order.
  718. for (SUnit *SU : TopRoots)
  719. SchedImpl->releaseTopNode(SU);
  720. // Release bottom roots in reverse order so the higher priority nodes appear
  721. // first. This is more natural and slightly more efficient.
  722. for (SmallVectorImpl<SUnit*>::const_reverse_iterator
  723. I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
  724. SchedImpl->releaseBottomNode(*I);
  725. }
  726. releaseSuccessors(&EntrySU);
  727. releasePredecessors(&ExitSU);
  728. SchedImpl->registerRoots();
  729. // Advance past initial DebugValues.
  730. CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
  731. CurrentBottom = RegionEnd;
  732. }
  733. /// Update scheduler queues after scheduling an instruction.
  734. void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
  735. // Release dependent instructions for scheduling.
  736. if (IsTopNode)
  737. releaseSuccessors(SU);
  738. else
  739. releasePredecessors(SU);
  740. SU->isScheduled = true;
  741. }
  742. /// Reinsert any remaining debug_values, just like the PostRA scheduler.
  743. void ScheduleDAGMI::placeDebugValues() {
  744. // If first instruction was a DBG_VALUE then put it back.
  745. if (FirstDbgValue) {
  746. BB->splice(RegionBegin, BB, FirstDbgValue);
  747. RegionBegin = FirstDbgValue;
  748. }
  749. for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
  750. DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
  751. std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
  752. MachineInstr *DbgValue = P.first;
  753. MachineBasicBlock::iterator OrigPrevMI = P.second;
  754. if (&*RegionBegin == DbgValue)
  755. ++RegionBegin;
  756. BB->splice(++OrigPrevMI, BB, DbgValue);
  757. if (OrigPrevMI == std::prev(RegionEnd))
  758. RegionEnd = DbgValue;
  759. }
  760. DbgValues.clear();
  761. FirstDbgValue = nullptr;
  762. }
  763. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  764. LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
  765. for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
  766. if (SUnit *SU = getSUnit(&(*MI)))
  767. dumpNode(*SU);
  768. else
  769. dbgs() << "Missing SUnit\n";
  770. }
  771. }
  772. #endif
  773. //===----------------------------------------------------------------------===//
  774. // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
  775. // preservation.
  776. //===----------------------------------------------------------------------===//
  777. ScheduleDAGMILive::~ScheduleDAGMILive() {
  778. delete DFSResult;
  779. }
  780. void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
  781. const MachineInstr &MI = *SU.getInstr();
  782. for (const MachineOperand &MO : MI.operands()) {
  783. if (!MO.isReg())
  784. continue;
  785. if (!MO.readsReg())
  786. continue;
  787. if (TrackLaneMasks && !MO.isUse())
  788. continue;
  789. Register Reg = MO.getReg();
  790. if (!Register::isVirtualRegister(Reg))
  791. continue;
  792. // Ignore re-defs.
  793. if (TrackLaneMasks) {
  794. bool FoundDef = false;
  795. for (const MachineOperand &MO2 : MI.operands()) {
  796. if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
  797. FoundDef = true;
  798. break;
  799. }
  800. }
  801. if (FoundDef)
  802. continue;
  803. }
  804. // Record this local VReg use.
  805. VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
  806. for (; UI != VRegUses.end(); ++UI) {
  807. if (UI->SU == &SU)
  808. break;
  809. }
  810. if (UI == VRegUses.end())
  811. VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
  812. }
  813. }
  814. /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
  815. /// crossing a scheduling boundary. [begin, end) includes all instructions in
  816. /// the region, including the boundary itself and single-instruction regions
  817. /// that don't get scheduled.
  818. void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
  819. MachineBasicBlock::iterator begin,
  820. MachineBasicBlock::iterator end,
  821. unsigned regioninstrs)
  822. {
  823. // ScheduleDAGMI initializes SchedImpl's per-region policy.
  824. ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
  825. // For convenience remember the end of the liveness region.
  826. LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
  827. SUPressureDiffs.clear();
  828. ShouldTrackPressure = SchedImpl->shouldTrackPressure();
  829. ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
  830. assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
  831. "ShouldTrackLaneMasks requires ShouldTrackPressure");
  832. }
  833. // Setup the register pressure trackers for the top scheduled and bottom
  834. // scheduled regions.
  835. void ScheduleDAGMILive::initRegPressure() {
  836. VRegUses.clear();
  837. VRegUses.setUniverse(MRI.getNumVirtRegs());
  838. for (SUnit &SU : SUnits)
  839. collectVRegUses(SU);
  840. TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
  841. ShouldTrackLaneMasks, false);
  842. BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
  843. ShouldTrackLaneMasks, false);
  844. // Close the RPTracker to finalize live ins.
  845. RPTracker.closeRegion();
  846. LLVM_DEBUG(RPTracker.dump());
  847. // Initialize the live ins and live outs.
  848. TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
  849. BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
  850. // Close one end of the tracker so we can call
  851. // getMaxUpward/DownwardPressureDelta before advancing across any
  852. // instructions. This converts currently live regs into live ins/outs.
  853. TopRPTracker.closeTop();
  854. BotRPTracker.closeBottom();
  855. BotRPTracker.initLiveThru(RPTracker);
  856. if (!BotRPTracker.getLiveThru().empty()) {
  857. TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
  858. LLVM_DEBUG(dbgs() << "Live Thru: ";
  859. dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
  860. };
  861. // For each live out vreg reduce the pressure change associated with other
  862. // uses of the same vreg below the live-out reaching def.
  863. updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
  864. // Account for liveness generated by the region boundary.
  865. if (LiveRegionEnd != RegionEnd) {
  866. SmallVector<RegisterMaskPair, 8> LiveUses;
  867. BotRPTracker.recede(&LiveUses);
  868. updatePressureDiffs(LiveUses);
  869. }
  870. LLVM_DEBUG(dbgs() << "Top Pressure:\n";
  871. dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
  872. dbgs() << "Bottom Pressure:\n";
  873. dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
  874. assert((BotRPTracker.getPos() == RegionEnd ||
  875. (RegionEnd->isDebugInstr() &&
  876. BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
  877. "Can't find the region bottom");
  878. // Cache the list of excess pressure sets in this region. This will also track
  879. // the max pressure in the scheduled code for these sets.
  880. RegionCriticalPSets.clear();
  881. const std::vector<unsigned> &RegionPressure =
  882. RPTracker.getPressure().MaxSetPressure;
  883. for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
  884. unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
  885. if (RegionPressure[i] > Limit) {
  886. LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
  887. << " Actual " << RegionPressure[i] << "\n");
  888. RegionCriticalPSets.push_back(PressureChange(i));
  889. }
  890. }
  891. LLVM_DEBUG(dbgs() << "Excess PSets: ";
  892. for (const PressureChange &RCPS
  893. : RegionCriticalPSets) dbgs()
  894. << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
  895. dbgs() << "\n");
  896. }
  897. void ScheduleDAGMILive::
  898. updateScheduledPressure(const SUnit *SU,
  899. const std::vector<unsigned> &NewMaxPressure) {
  900. const PressureDiff &PDiff = getPressureDiff(SU);
  901. unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
  902. for (const PressureChange &PC : PDiff) {
  903. if (!PC.isValid())
  904. break;
  905. unsigned ID = PC.getPSet();
  906. while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
  907. ++CritIdx;
  908. if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
  909. if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
  910. && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
  911. RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
  912. }
  913. unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
  914. if (NewMaxPressure[ID] >= Limit - 2) {
  915. LLVM_DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
  916. << NewMaxPressure[ID]
  917. << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
  918. << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
  919. << " livethru)\n");
  920. }
  921. }
  922. }
  923. /// Update the PressureDiff array for liveness after scheduling this
  924. /// instruction.
  925. void ScheduleDAGMILive::updatePressureDiffs(
  926. ArrayRef<RegisterMaskPair> LiveUses) {
  927. for (const RegisterMaskPair &P : LiveUses) {
  928. unsigned Reg = P.RegUnit;
  929. /// FIXME: Currently assuming single-use physregs.
  930. if (!Register::isVirtualRegister(Reg))
  931. continue;
  932. if (ShouldTrackLaneMasks) {
  933. // If the register has just become live then other uses won't change
  934. // this fact anymore => decrement pressure.
  935. // If the register has just become dead then other uses make it come
  936. // back to life => increment pressure.
  937. bool Decrement = P.LaneMask.any();
  938. for (const VReg2SUnit &V2SU
  939. : make_range(VRegUses.find(Reg), VRegUses.end())) {
  940. SUnit &SU = *V2SU.SU;
  941. if (SU.isScheduled || &SU == &ExitSU)
  942. continue;
  943. PressureDiff &PDiff = getPressureDiff(&SU);
  944. PDiff.addPressureChange(Reg, Decrement, &MRI);
  945. LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
  946. << printReg(Reg, TRI) << ':'
  947. << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
  948. dbgs() << " to "; PDiff.dump(*TRI););
  949. }
  950. } else {
  951. assert(P.LaneMask.any());
  952. LLVM_DEBUG(dbgs() << " LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
  953. // This may be called before CurrentBottom has been initialized. However,
  954. // BotRPTracker must have a valid position. We want the value live into the
  955. // instruction or live out of the block, so ask for the previous
  956. // instruction's live-out.
  957. const LiveInterval &LI = LIS->getInterval(Reg);
  958. VNInfo *VNI;
  959. MachineBasicBlock::const_iterator I =
  960. nextIfDebug(BotRPTracker.getPos(), BB->end());
  961. if (I == BB->end())
  962. VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
  963. else {
  964. LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
  965. VNI = LRQ.valueIn();
  966. }
  967. // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
  968. assert(VNI && "No live value at use.");
  969. for (const VReg2SUnit &V2SU
  970. : make_range(VRegUses.find(Reg), VRegUses.end())) {
  971. SUnit *SU = V2SU.SU;
  972. // If this use comes before the reaching def, it cannot be a last use,
  973. // so decrease its pressure change.
  974. if (!SU->isScheduled && SU != &ExitSU) {
  975. LiveQueryResult LRQ =
  976. LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
  977. if (LRQ.valueIn() == VNI) {
  978. PressureDiff &PDiff = getPressureDiff(SU);
  979. PDiff.addPressureChange(Reg, true, &MRI);
  980. LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
  981. << *SU->getInstr();
  982. dbgs() << " to "; PDiff.dump(*TRI););
  983. }
  984. }
  985. }
  986. }
  987. }
  988. }
  989. void ScheduleDAGMILive::dump() const {
  990. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  991. if (EntrySU.getInstr() != nullptr)
  992. dumpNodeAll(EntrySU);
  993. for (const SUnit &SU : SUnits) {
  994. dumpNodeAll(SU);
  995. if (ShouldTrackPressure) {
  996. dbgs() << " Pressure Diff : ";
  997. getPressureDiff(&SU).dump(*TRI);
  998. }
  999. dbgs() << " Single Issue : ";
  1000. if (SchedModel.mustBeginGroup(SU.getInstr()) &&
  1001. SchedModel.mustEndGroup(SU.getInstr()))
  1002. dbgs() << "true;";
  1003. else
  1004. dbgs() << "false;";
  1005. dbgs() << '\n';
  1006. }
  1007. if (ExitSU.getInstr() != nullptr)
  1008. dumpNodeAll(ExitSU);
  1009. #endif
  1010. }
  1011. /// schedule - Called back from MachineScheduler::runOnMachineFunction
  1012. /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
  1013. /// only includes instructions that have DAG nodes, not scheduling boundaries.
  1014. ///
  1015. /// This is a skeletal driver, with all the functionality pushed into helpers,
  1016. /// so that it can be easily extended by experimental schedulers. Generally,
  1017. /// implementing MachineSchedStrategy should be sufficient to implement a new
  1018. /// scheduling algorithm. However, if a scheduler further subclasses
  1019. /// ScheduleDAGMILive then it will want to override this virtual method in order
  1020. /// to update any specialized state.
  1021. void ScheduleDAGMILive::schedule() {
  1022. LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
  1023. LLVM_DEBUG(SchedImpl->dumpPolicy());
  1024. buildDAGWithRegPressure();
  1025. postprocessDAG();
  1026. SmallVector<SUnit*, 8> TopRoots, BotRoots;
  1027. findRootsAndBiasEdges(TopRoots, BotRoots);
  1028. // Initialize the strategy before modifying the DAG.
  1029. // This may initialize a DFSResult to be used for queue priority.
  1030. SchedImpl->initialize(this);
  1031. LLVM_DEBUG(dump());
  1032. if (PrintDAGs) dump();
  1033. if (ViewMISchedDAGs) viewGraph();
  1034. // Initialize ready queues now that the DAG and priority data are finalized.
  1035. initQueues(TopRoots, BotRoots);
  1036. bool IsTopNode = false;
  1037. while (true) {
  1038. LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
  1039. SUnit *SU = SchedImpl->pickNode(IsTopNode);
  1040. if (!SU) break;
  1041. assert(!SU->isScheduled && "Node already scheduled");
  1042. if (!checkSchedLimit())
  1043. break;
  1044. scheduleMI(SU, IsTopNode);
  1045. if (DFSResult) {
  1046. unsigned SubtreeID = DFSResult->getSubtreeID(SU);
  1047. if (!ScheduledTrees.test(SubtreeID)) {
  1048. ScheduledTrees.set(SubtreeID);
  1049. DFSResult->scheduleTree(SubtreeID);
  1050. SchedImpl->scheduleTree(SubtreeID);
  1051. }
  1052. }
  1053. // Notify the scheduling strategy after updating the DAG.
  1054. SchedImpl->schedNode(SU, IsTopNode);
  1055. updateQueues(SU, IsTopNode);
  1056. }
  1057. assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
  1058. placeDebugValues();
  1059. LLVM_DEBUG({
  1060. dbgs() << "*** Final schedule for "
  1061. << printMBBReference(*begin()->getParent()) << " ***\n";
  1062. dumpSchedule();
  1063. dbgs() << '\n';
  1064. });
  1065. }
  1066. /// Build the DAG and setup three register pressure trackers.
  1067. void ScheduleDAGMILive::buildDAGWithRegPressure() {
  1068. if (!ShouldTrackPressure) {
  1069. RPTracker.reset();
  1070. RegionCriticalPSets.clear();
  1071. buildSchedGraph(AA);
  1072. return;
  1073. }
  1074. // Initialize the register pressure tracker used by buildSchedGraph.
  1075. RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
  1076. ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
  1077. // Account for liveness generate by the region boundary.
  1078. if (LiveRegionEnd != RegionEnd)
  1079. RPTracker.recede();
  1080. // Build the DAG, and compute current register pressure.
  1081. buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
  1082. // Initialize top/bottom trackers after computing region pressure.
  1083. initRegPressure();
  1084. }
  1085. void ScheduleDAGMILive::computeDFSResult() {
  1086. if (!DFSResult)
  1087. DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
  1088. DFSResult->clear();
  1089. ScheduledTrees.clear();
  1090. DFSResult->resize(SUnits.size());
  1091. DFSResult->compute(SUnits);
  1092. ScheduledTrees.resize(DFSResult->getNumSubtrees());
  1093. }
  1094. /// Compute the max cyclic critical path through the DAG. The scheduling DAG
  1095. /// only provides the critical path for single block loops. To handle loops that
  1096. /// span blocks, we could use the vreg path latencies provided by
  1097. /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
  1098. /// available for use in the scheduler.
  1099. ///
  1100. /// The cyclic path estimation identifies a def-use pair that crosses the back
  1101. /// edge and considers the depth and height of the nodes. For example, consider
  1102. /// the following instruction sequence where each instruction has unit latency
  1103. /// and defines an epomymous virtual register:
  1104. ///
  1105. /// a->b(a,c)->c(b)->d(c)->exit
  1106. ///
  1107. /// The cyclic critical path is a two cycles: b->c->b
  1108. /// The acyclic critical path is four cycles: a->b->c->d->exit
  1109. /// LiveOutHeight = height(c) = len(c->d->exit) = 2
  1110. /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
  1111. /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
  1112. /// LiveInDepth = depth(b) = len(a->b) = 1
  1113. ///
  1114. /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
  1115. /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
  1116. /// CyclicCriticalPath = min(2, 2) = 2
  1117. ///
  1118. /// This could be relevant to PostRA scheduling, but is currently implemented
  1119. /// assuming LiveIntervals.
  1120. unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
  1121. // This only applies to single block loop.
  1122. if (!BB->isSuccessor(BB))
  1123. return 0;
  1124. unsigned MaxCyclicLatency = 0;
  1125. // Visit each live out vreg def to find def/use pairs that cross iterations.
  1126. for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
  1127. unsigned Reg = P.RegUnit;
  1128. if (!Register::isVirtualRegister(Reg))
  1129. continue;
  1130. const LiveInterval &LI = LIS->getInterval(Reg);
  1131. const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
  1132. if (!DefVNI)
  1133. continue;
  1134. MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
  1135. const SUnit *DefSU = getSUnit(DefMI);
  1136. if (!DefSU)
  1137. continue;
  1138. unsigned LiveOutHeight = DefSU->getHeight();
  1139. unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
  1140. // Visit all local users of the vreg def.
  1141. for (const VReg2SUnit &V2SU
  1142. : make_range(VRegUses.find(Reg), VRegUses.end())) {
  1143. SUnit *SU = V2SU.SU;
  1144. if (SU == &ExitSU)
  1145. continue;
  1146. // Only consider uses of the phi.
  1147. LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
  1148. if (!LRQ.valueIn()->isPHIDef())
  1149. continue;
  1150. // Assume that a path spanning two iterations is a cycle, which could
  1151. // overestimate in strange cases. This allows cyclic latency to be
  1152. // estimated as the minimum slack of the vreg's depth or height.
  1153. unsigned CyclicLatency = 0;
  1154. if (LiveOutDepth > SU->getDepth())
  1155. CyclicLatency = LiveOutDepth - SU->getDepth();
  1156. unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
  1157. if (LiveInHeight > LiveOutHeight) {
  1158. if (LiveInHeight - LiveOutHeight < CyclicLatency)
  1159. CyclicLatency = LiveInHeight - LiveOutHeight;
  1160. } else
  1161. CyclicLatency = 0;
  1162. LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
  1163. << SU->NodeNum << ") = " << CyclicLatency << "c\n");
  1164. if (CyclicLatency > MaxCyclicLatency)
  1165. MaxCyclicLatency = CyclicLatency;
  1166. }
  1167. }
  1168. LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
  1169. return MaxCyclicLatency;
  1170. }
  1171. /// Release ExitSU predecessors and setup scheduler queues. Re-position
  1172. /// the Top RP tracker in case the region beginning has changed.
  1173. void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
  1174. ArrayRef<SUnit*> BotRoots) {
  1175. ScheduleDAGMI::initQueues(TopRoots, BotRoots);
  1176. if (ShouldTrackPressure) {
  1177. assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
  1178. TopRPTracker.setPos(CurrentTop);
  1179. }
  1180. }
  1181. /// Move an instruction and update register pressure.
  1182. void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
  1183. // Move the instruction to its new location in the instruction stream.
  1184. MachineInstr *MI = SU->getInstr();
  1185. if (IsTopNode) {
  1186. assert(SU->isTopReady() && "node still has unscheduled dependencies");
  1187. if (&*CurrentTop == MI)
  1188. CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
  1189. else {
  1190. moveInstruction(MI, CurrentTop);
  1191. TopRPTracker.setPos(MI);
  1192. }
  1193. if (ShouldTrackPressure) {
  1194. // Update top scheduled pressure.
  1195. RegisterOperands RegOpers;
  1196. RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
  1197. if (ShouldTrackLaneMasks) {
  1198. // Adjust liveness and add missing dead+read-undef flags.
  1199. SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
  1200. RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
  1201. } else {
  1202. // Adjust for missing dead-def flags.
  1203. RegOpers.detectDeadDefs(*MI, *LIS);
  1204. }
  1205. TopRPTracker.advance(RegOpers);
  1206. assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
  1207. LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
  1208. TopRPTracker.getRegSetPressureAtPos(), TRI););
  1209. updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
  1210. }
  1211. } else {
  1212. assert(SU->isBottomReady() && "node still has unscheduled dependencies");
  1213. MachineBasicBlock::iterator priorII =
  1214. priorNonDebug(CurrentBottom, CurrentTop);
  1215. if (&*priorII == MI)
  1216. CurrentBottom = priorII;
  1217. else {
  1218. if (&*CurrentTop == MI) {
  1219. CurrentTop = nextIfDebug(++CurrentTop, priorII);
  1220. TopRPTracker.setPos(CurrentTop);
  1221. }
  1222. moveInstruction(MI, CurrentBottom);
  1223. CurrentBottom = MI;
  1224. BotRPTracker.setPos(CurrentBottom);
  1225. }
  1226. if (ShouldTrackPressure) {
  1227. RegisterOperands RegOpers;
  1228. RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
  1229. if (ShouldTrackLaneMasks) {
  1230. // Adjust liveness and add missing dead+read-undef flags.
  1231. SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
  1232. RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
  1233. } else {
  1234. // Adjust for missing dead-def flags.
  1235. RegOpers.detectDeadDefs(*MI, *LIS);
  1236. }
  1237. if (BotRPTracker.getPos() != CurrentBottom)
  1238. BotRPTracker.recedeSkipDebugValues();
  1239. SmallVector<RegisterMaskPair, 8> LiveUses;
  1240. BotRPTracker.recede(RegOpers, &LiveUses);
  1241. assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
  1242. LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
  1243. BotRPTracker.getRegSetPressureAtPos(), TRI););
  1244. updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
  1245. updatePressureDiffs(LiveUses);
  1246. }
  1247. }
  1248. }
  1249. //===----------------------------------------------------------------------===//
  1250. // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
  1251. //===----------------------------------------------------------------------===//
  1252. namespace {
  1253. /// Post-process the DAG to create cluster edges between neighboring
  1254. /// loads or between neighboring stores.
  1255. class BaseMemOpClusterMutation : public ScheduleDAGMutation {
  1256. struct MemOpInfo {
  1257. SUnit *SU;
  1258. const MachineOperand *BaseOp;
  1259. int64_t Offset;
  1260. MemOpInfo(SUnit *su, const MachineOperand *Op, int64_t ofs)
  1261. : SU(su), BaseOp(Op), Offset(ofs) {}
  1262. bool operator<(const MemOpInfo &RHS) const {
  1263. if (BaseOp->getType() != RHS.BaseOp->getType())
  1264. return BaseOp->getType() < RHS.BaseOp->getType();
  1265. if (BaseOp->isReg())
  1266. return std::make_tuple(BaseOp->getReg(), Offset, SU->NodeNum) <
  1267. std::make_tuple(RHS.BaseOp->getReg(), RHS.Offset,
  1268. RHS.SU->NodeNum);
  1269. if (BaseOp->isFI()) {
  1270. const MachineFunction &MF =
  1271. *BaseOp->getParent()->getParent()->getParent();
  1272. const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
  1273. bool StackGrowsDown = TFI.getStackGrowthDirection() ==
  1274. TargetFrameLowering::StackGrowsDown;
  1275. // Can't use tuple comparison here since we might need to use a
  1276. // different order when the stack grows down.
  1277. if (BaseOp->getIndex() != RHS.BaseOp->getIndex())
  1278. return StackGrowsDown ? BaseOp->getIndex() > RHS.BaseOp->getIndex()
  1279. : BaseOp->getIndex() < RHS.BaseOp->getIndex();
  1280. if (Offset != RHS.Offset)
  1281. return StackGrowsDown ? Offset > RHS.Offset : Offset < RHS.Offset;
  1282. return SU->NodeNum < RHS.SU->NodeNum;
  1283. }
  1284. llvm_unreachable("MemOpClusterMutation only supports register or frame "
  1285. "index bases.");
  1286. }
  1287. };
  1288. const TargetInstrInfo *TII;
  1289. const TargetRegisterInfo *TRI;
  1290. bool IsLoad;
  1291. public:
  1292. BaseMemOpClusterMutation(const TargetInstrInfo *tii,
  1293. const TargetRegisterInfo *tri, bool IsLoad)
  1294. : TII(tii), TRI(tri), IsLoad(IsLoad) {}
  1295. void apply(ScheduleDAGInstrs *DAGInstrs) override;
  1296. protected:
  1297. void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG);
  1298. };
  1299. class StoreClusterMutation : public BaseMemOpClusterMutation {
  1300. public:
  1301. StoreClusterMutation(const TargetInstrInfo *tii,
  1302. const TargetRegisterInfo *tri)
  1303. : BaseMemOpClusterMutation(tii, tri, false) {}
  1304. };
  1305. class LoadClusterMutation : public BaseMemOpClusterMutation {
  1306. public:
  1307. LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
  1308. : BaseMemOpClusterMutation(tii, tri, true) {}
  1309. };
  1310. } // end anonymous namespace
  1311. namespace llvm {
  1312. std::unique_ptr<ScheduleDAGMutation>
  1313. createLoadClusterDAGMutation(const TargetInstrInfo *TII,
  1314. const TargetRegisterInfo *TRI) {
  1315. return EnableMemOpCluster ? std::make_unique<LoadClusterMutation>(TII, TRI)
  1316. : nullptr;
  1317. }
  1318. std::unique_ptr<ScheduleDAGMutation>
  1319. createStoreClusterDAGMutation(const TargetInstrInfo *TII,
  1320. const TargetRegisterInfo *TRI) {
  1321. return EnableMemOpCluster ? std::make_unique<StoreClusterMutation>(TII, TRI)
  1322. : nullptr;
  1323. }
  1324. } // end namespace llvm
  1325. void BaseMemOpClusterMutation::clusterNeighboringMemOps(
  1326. ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG) {
  1327. SmallVector<MemOpInfo, 32> MemOpRecords;
  1328. for (SUnit *SU : MemOps) {
  1329. const MachineOperand *BaseOp;
  1330. int64_t Offset;
  1331. if (TII->getMemOperandWithOffset(*SU->getInstr(), BaseOp, Offset, TRI))
  1332. MemOpRecords.push_back(MemOpInfo(SU, BaseOp, Offset));
  1333. }
  1334. if (MemOpRecords.size() < 2)
  1335. return;
  1336. llvm::sort(MemOpRecords);
  1337. unsigned ClusterLength = 1;
  1338. for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
  1339. SUnit *SUa = MemOpRecords[Idx].SU;
  1340. SUnit *SUb = MemOpRecords[Idx+1].SU;
  1341. if (TII->shouldClusterMemOps(*MemOpRecords[Idx].BaseOp,
  1342. *MemOpRecords[Idx + 1].BaseOp,
  1343. ClusterLength) &&
  1344. DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
  1345. LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
  1346. << SUb->NodeNum << ")\n");
  1347. // Copy successor edges from SUa to SUb. Interleaving computation
  1348. // dependent on SUa can prevent load combining due to register reuse.
  1349. // Predecessor edges do not need to be copied from SUb to SUa since nearby
  1350. // loads should have effectively the same inputs.
  1351. for (const SDep &Succ : SUa->Succs) {
  1352. if (Succ.getSUnit() == SUb)
  1353. continue;
  1354. LLVM_DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum
  1355. << ")\n");
  1356. DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
  1357. }
  1358. ++ClusterLength;
  1359. } else
  1360. ClusterLength = 1;
  1361. }
  1362. }
  1363. /// Callback from DAG postProcessing to create cluster edges for loads.
  1364. void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) {
  1365. // Map DAG NodeNum to store chain ID.
  1366. DenseMap<unsigned, unsigned> StoreChainIDs;
  1367. // Map each store chain to a set of dependent MemOps.
  1368. SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
  1369. for (SUnit &SU : DAG->SUnits) {
  1370. if ((IsLoad && !SU.getInstr()->mayLoad()) ||
  1371. (!IsLoad && !SU.getInstr()->mayStore()))
  1372. continue;
  1373. unsigned ChainPredID = DAG->SUnits.size();
  1374. for (const SDep &Pred : SU.Preds) {
  1375. if (Pred.isCtrl()) {
  1376. ChainPredID = Pred.getSUnit()->NodeNum;
  1377. break;
  1378. }
  1379. }
  1380. // Check if this chain-like pred has been seen
  1381. // before. ChainPredID==MaxNodeID at the top of the schedule.
  1382. unsigned NumChains = StoreChainDependents.size();
  1383. std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
  1384. StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
  1385. if (Result.second)
  1386. StoreChainDependents.resize(NumChains + 1);
  1387. StoreChainDependents[Result.first->second].push_back(&SU);
  1388. }
  1389. // Iterate over the store chains.
  1390. for (auto &SCD : StoreChainDependents)
  1391. clusterNeighboringMemOps(SCD, DAG);
  1392. }
  1393. //===----------------------------------------------------------------------===//
  1394. // CopyConstrain - DAG post-processing to encourage copy elimination.
  1395. //===----------------------------------------------------------------------===//
  1396. namespace {
  1397. /// Post-process the DAG to create weak edges from all uses of a copy to
  1398. /// the one use that defines the copy's source vreg, most likely an induction
  1399. /// variable increment.
  1400. class CopyConstrain : public ScheduleDAGMutation {
  1401. // Transient state.
  1402. SlotIndex RegionBeginIdx;
  1403. // RegionEndIdx is the slot index of the last non-debug instruction in the
  1404. // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
  1405. SlotIndex RegionEndIdx;
  1406. public:
  1407. CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
  1408. void apply(ScheduleDAGInstrs *DAGInstrs) override;
  1409. protected:
  1410. void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
  1411. };
  1412. } // end anonymous namespace
  1413. namespace llvm {
  1414. std::unique_ptr<ScheduleDAGMutation>
  1415. createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
  1416. const TargetRegisterInfo *TRI) {
  1417. return std::make_unique<CopyConstrain>(TII, TRI);
  1418. }
  1419. } // end namespace llvm
  1420. /// constrainLocalCopy handles two possibilities:
  1421. /// 1) Local src:
  1422. /// I0: = dst
  1423. /// I1: src = ...
  1424. /// I2: = dst
  1425. /// I3: dst = src (copy)
  1426. /// (create pred->succ edges I0->I1, I2->I1)
  1427. ///
  1428. /// 2) Local copy:
  1429. /// I0: dst = src (copy)
  1430. /// I1: = dst
  1431. /// I2: src = ...
  1432. /// I3: = dst
  1433. /// (create pred->succ edges I1->I2, I3->I2)
  1434. ///
  1435. /// Although the MachineScheduler is currently constrained to single blocks,
  1436. /// this algorithm should handle extended blocks. An EBB is a set of
  1437. /// contiguously numbered blocks such that the previous block in the EBB is
  1438. /// always the single predecessor.
  1439. void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
  1440. LiveIntervals *LIS = DAG->getLIS();
  1441. MachineInstr *Copy = CopySU->getInstr();
  1442. // Check for pure vreg copies.
  1443. const MachineOperand &SrcOp = Copy->getOperand(1);
  1444. Register SrcReg = SrcOp.getReg();
  1445. if (!Register::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
  1446. return;
  1447. const MachineOperand &DstOp = Copy->getOperand(0);
  1448. Register DstReg = DstOp.getReg();
  1449. if (!Register::isVirtualRegister(DstReg) || DstOp.isDead())
  1450. return;
  1451. // Check if either the dest or source is local. If it's live across a back
  1452. // edge, it's not local. Note that if both vregs are live across the back
  1453. // edge, we cannot successfully contrain the copy without cyclic scheduling.
  1454. // If both the copy's source and dest are local live intervals, then we
  1455. // should treat the dest as the global for the purpose of adding
  1456. // constraints. This adds edges from source's other uses to the copy.
  1457. unsigned LocalReg = SrcReg;
  1458. unsigned GlobalReg = DstReg;
  1459. LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
  1460. if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
  1461. LocalReg = DstReg;
  1462. GlobalReg = SrcReg;
  1463. LocalLI = &LIS->getInterval(LocalReg);
  1464. if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
  1465. return;
  1466. }
  1467. LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
  1468. // Find the global segment after the start of the local LI.
  1469. LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
  1470. // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
  1471. // local live range. We could create edges from other global uses to the local
  1472. // start, but the coalescer should have already eliminated these cases, so
  1473. // don't bother dealing with it.
  1474. if (GlobalSegment == GlobalLI->end())
  1475. return;
  1476. // If GlobalSegment is killed at the LocalLI->start, the call to find()
  1477. // returned the next global segment. But if GlobalSegment overlaps with
  1478. // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
  1479. // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
  1480. if (GlobalSegment->contains(LocalLI->beginIndex()))
  1481. ++GlobalSegment;
  1482. if (GlobalSegment == GlobalLI->end())
  1483. return;
  1484. // Check if GlobalLI contains a hole in the vicinity of LocalLI.
  1485. if (GlobalSegment != GlobalLI->begin()) {
  1486. // Two address defs have no hole.
  1487. if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
  1488. GlobalSegment->start)) {
  1489. return;
  1490. }
  1491. // If the prior global segment may be defined by the same two-address
  1492. // instruction that also defines LocalLI, then can't make a hole here.
  1493. if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
  1494. LocalLI->beginIndex())) {
  1495. return;
  1496. }
  1497. // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
  1498. // it would be a disconnected component in the live range.
  1499. assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
  1500. "Disconnected LRG within the scheduling region.");
  1501. }
  1502. MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
  1503. if (!GlobalDef)
  1504. return;
  1505. SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
  1506. if (!GlobalSU)
  1507. return;
  1508. // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
  1509. // constraining the uses of the last local def to precede GlobalDef.
  1510. SmallVector<SUnit*,8> LocalUses;
  1511. const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
  1512. MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
  1513. SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
  1514. for (const SDep &Succ : LastLocalSU->Succs) {
  1515. if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
  1516. continue;
  1517. if (Succ.getSUnit() == GlobalSU)
  1518. continue;
  1519. if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
  1520. return;
  1521. LocalUses.push_back(Succ.getSUnit());
  1522. }
  1523. // Open the top of the GlobalLI hole by constraining any earlier global uses
  1524. // to precede the start of LocalLI.
  1525. SmallVector<SUnit*,8> GlobalUses;
  1526. MachineInstr *FirstLocalDef =
  1527. LIS->getInstructionFromIndex(LocalLI->beginIndex());
  1528. SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
  1529. for (const SDep &Pred : GlobalSU->Preds) {
  1530. if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
  1531. continue;
  1532. if (Pred.getSUnit() == FirstLocalSU)
  1533. continue;
  1534. if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
  1535. return;
  1536. GlobalUses.push_back(Pred.getSUnit());
  1537. }
  1538. LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
  1539. // Add the weak edges.
  1540. for (SmallVectorImpl<SUnit*>::const_iterator
  1541. I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
  1542. LLVM_DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
  1543. << GlobalSU->NodeNum << ")\n");
  1544. DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
  1545. }
  1546. for (SmallVectorImpl<SUnit*>::const_iterator
  1547. I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
  1548. LLVM_DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
  1549. << FirstLocalSU->NodeNum << ")\n");
  1550. DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
  1551. }
  1552. }
  1553. /// Callback from DAG postProcessing to create weak edges to encourage
  1554. /// copy elimination.
  1555. void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
  1556. ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
  1557. assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
  1558. MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
  1559. if (FirstPos == DAG->end())
  1560. return;
  1561. RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
  1562. RegionEndIdx = DAG->getLIS()->getInstructionIndex(
  1563. *priorNonDebug(DAG->end(), DAG->begin()));
  1564. for (SUnit &SU : DAG->SUnits) {
  1565. if (!SU.getInstr()->isCopy())
  1566. continue;
  1567. constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
  1568. }
  1569. }
  1570. //===----------------------------------------------------------------------===//
  1571. // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
  1572. // and possibly other custom schedulers.
  1573. //===----------------------------------------------------------------------===//
  1574. static const unsigned InvalidCycle = ~0U;
  1575. SchedBoundary::~SchedBoundary() { delete HazardRec; }
  1576. /// Given a Count of resource usage and a Latency value, return true if a
  1577. /// SchedBoundary becomes resource limited.
  1578. /// If we are checking after scheduling a node, we should return true when
  1579. /// we just reach the resource limit.
  1580. static bool checkResourceLimit(unsigned LFactor, unsigned Count,
  1581. unsigned Latency, bool AfterSchedNode) {
  1582. int ResCntFactor = (int)(Count - (Latency * LFactor));
  1583. if (AfterSchedNode)
  1584. return ResCntFactor >= (int)LFactor;
  1585. else
  1586. return ResCntFactor > (int)LFactor;
  1587. }
  1588. void SchedBoundary::reset() {
  1589. // A new HazardRec is created for each DAG and owned by SchedBoundary.
  1590. // Destroying and reconstructing it is very expensive though. So keep
  1591. // invalid, placeholder HazardRecs.
  1592. if (HazardRec && HazardRec->isEnabled()) {
  1593. delete HazardRec;
  1594. HazardRec = nullptr;
  1595. }
  1596. Available.clear();
  1597. Pending.clear();
  1598. CheckPending = false;
  1599. CurrCycle = 0;
  1600. CurrMOps = 0;
  1601. MinReadyCycle = std::numeric_limits<unsigned>::max();
  1602. ExpectedLatency = 0;
  1603. DependentLatency = 0;
  1604. RetiredMOps = 0;
  1605. MaxExecutedResCount = 0;
  1606. ZoneCritResIdx = 0;
  1607. IsResourceLimited = false;
  1608. ReservedCycles.clear();
  1609. ReservedCyclesIndex.clear();
  1610. #ifndef NDEBUG
  1611. // Track the maximum number of stall cycles that could arise either from the
  1612. // latency of a DAG edge or the number of cycles that a processor resource is
  1613. // reserved (SchedBoundary::ReservedCycles).
  1614. MaxObservedStall = 0;
  1615. #endif
  1616. // Reserve a zero-count for invalid CritResIdx.
  1617. ExecutedResCounts.resize(1);
  1618. assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
  1619. }
  1620. void SchedRemainder::
  1621. init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
  1622. reset();
  1623. if (!SchedModel->hasInstrSchedModel())
  1624. return;
  1625. RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
  1626. for (SUnit &SU : DAG->SUnits) {
  1627. const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
  1628. RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
  1629. * SchedModel->getMicroOpFactor();
  1630. for (TargetSchedModel::ProcResIter
  1631. PI = SchedModel->getWriteProcResBegin(SC),
  1632. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1633. unsigned PIdx = PI->ProcResourceIdx;
  1634. unsigned Factor = SchedModel->getResourceFactor(PIdx);
  1635. RemainingCounts[PIdx] += (Factor * PI->Cycles);
  1636. }
  1637. }
  1638. }
  1639. void SchedBoundary::
  1640. init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
  1641. reset();
  1642. DAG = dag;
  1643. SchedModel = smodel;
  1644. Rem = rem;
  1645. if (SchedModel->hasInstrSchedModel()) {
  1646. unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
  1647. ReservedCyclesIndex.resize(ResourceCount);
  1648. ExecutedResCounts.resize(ResourceCount);
  1649. unsigned NumUnits = 0;
  1650. for (unsigned i = 0; i < ResourceCount; ++i) {
  1651. ReservedCyclesIndex[i] = NumUnits;
  1652. NumUnits += SchedModel->getProcResource(i)->NumUnits;
  1653. }
  1654. ReservedCycles.resize(NumUnits, InvalidCycle);
  1655. }
  1656. }
  1657. /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
  1658. /// these "soft stalls" differently than the hard stall cycles based on CPU
  1659. /// resources and computed by checkHazard(). A fully in-order model
  1660. /// (MicroOpBufferSize==0) will not make use of this since instructions are not
  1661. /// available for scheduling until they are ready. However, a weaker in-order
  1662. /// model may use this for heuristics. For example, if a processor has in-order
  1663. /// behavior when reading certain resources, this may come into play.
  1664. unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
  1665. if (!SU->isUnbuffered)
  1666. return 0;
  1667. unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
  1668. if (ReadyCycle > CurrCycle)
  1669. return ReadyCycle - CurrCycle;
  1670. return 0;
  1671. }
  1672. /// Compute the next cycle at which the given processor resource unit
  1673. /// can be scheduled.
  1674. unsigned SchedBoundary::getNextResourceCycleByInstance(unsigned InstanceIdx,
  1675. unsigned Cycles) {
  1676. unsigned NextUnreserved = ReservedCycles[InstanceIdx];
  1677. // If this resource has never been used, always return cycle zero.
  1678. if (NextUnreserved == InvalidCycle)
  1679. return 0;
  1680. // For bottom-up scheduling add the cycles needed for the current operation.
  1681. if (!isTop())
  1682. NextUnreserved += Cycles;
  1683. return NextUnreserved;
  1684. }
  1685. /// Compute the next cycle at which the given processor resource can be
  1686. /// scheduled. Returns the next cycle and the index of the processor resource
  1687. /// instance in the reserved cycles vector.
  1688. std::pair<unsigned, unsigned>
  1689. SchedBoundary::getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
  1690. unsigned MinNextUnreserved = InvalidCycle;
  1691. unsigned InstanceIdx = 0;
  1692. unsigned StartIndex = ReservedCyclesIndex[PIdx];
  1693. unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits;
  1694. assert(NumberOfInstances > 0 &&
  1695. "Cannot have zero instances of a ProcResource");
  1696. for (unsigned I = StartIndex, End = StartIndex + NumberOfInstances; I < End;
  1697. ++I) {
  1698. unsigned NextUnreserved = getNextResourceCycleByInstance(I, Cycles);
  1699. if (MinNextUnreserved > NextUnreserved) {
  1700. InstanceIdx = I;
  1701. MinNextUnreserved = NextUnreserved;
  1702. }
  1703. }
  1704. return std::make_pair(MinNextUnreserved, InstanceIdx);
  1705. }
  1706. /// Does this SU have a hazard within the current instruction group.
  1707. ///
  1708. /// The scheduler supports two modes of hazard recognition. The first is the
  1709. /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
  1710. /// supports highly complicated in-order reservation tables
  1711. /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
  1712. ///
  1713. /// The second is a streamlined mechanism that checks for hazards based on
  1714. /// simple counters that the scheduler itself maintains. It explicitly checks
  1715. /// for instruction dispatch limitations, including the number of micro-ops that
  1716. /// can dispatch per cycle.
  1717. ///
  1718. /// TODO: Also check whether the SU must start a new group.
  1719. bool SchedBoundary::checkHazard(SUnit *SU) {
  1720. if (HazardRec->isEnabled()
  1721. && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
  1722. return true;
  1723. }
  1724. unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
  1725. if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
  1726. LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
  1727. << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
  1728. return true;
  1729. }
  1730. if (CurrMOps > 0 &&
  1731. ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
  1732. (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
  1733. LLVM_DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
  1734. << (isTop() ? "begin" : "end") << " group\n");
  1735. return true;
  1736. }
  1737. if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
  1738. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  1739. for (const MCWriteProcResEntry &PE :
  1740. make_range(SchedModel->getWriteProcResBegin(SC),
  1741. SchedModel->getWriteProcResEnd(SC))) {
  1742. unsigned ResIdx = PE.ProcResourceIdx;
  1743. unsigned Cycles = PE.Cycles;
  1744. unsigned NRCycle, InstanceIdx;
  1745. std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(ResIdx, Cycles);
  1746. if (NRCycle > CurrCycle) {
  1747. #ifndef NDEBUG
  1748. MaxObservedStall = std::max(Cycles, MaxObservedStall);
  1749. #endif
  1750. LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
  1751. << SchedModel->getResourceName(ResIdx)
  1752. << '[' << InstanceIdx - ReservedCyclesIndex[ResIdx] << ']'
  1753. << "=" << NRCycle << "c\n");
  1754. return true;
  1755. }
  1756. }
  1757. }
  1758. return false;
  1759. }
  1760. // Find the unscheduled node in ReadySUs with the highest latency.
  1761. unsigned SchedBoundary::
  1762. findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
  1763. SUnit *LateSU = nullptr;
  1764. unsigned RemLatency = 0;
  1765. for (SUnit *SU : ReadySUs) {
  1766. unsigned L = getUnscheduledLatency(SU);
  1767. if (L > RemLatency) {
  1768. RemLatency = L;
  1769. LateSU = SU;
  1770. }
  1771. }
  1772. if (LateSU) {
  1773. LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
  1774. << LateSU->NodeNum << ") " << RemLatency << "c\n");
  1775. }
  1776. return RemLatency;
  1777. }
  1778. // Count resources in this zone and the remaining unscheduled
  1779. // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
  1780. // resource index, or zero if the zone is issue limited.
  1781. unsigned SchedBoundary::
  1782. getOtherResourceCount(unsigned &OtherCritIdx) {
  1783. OtherCritIdx = 0;
  1784. if (!SchedModel->hasInstrSchedModel())
  1785. return 0;
  1786. unsigned OtherCritCount = Rem->RemIssueCount
  1787. + (RetiredMOps * SchedModel->getMicroOpFactor());
  1788. LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
  1789. << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
  1790. for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
  1791. PIdx != PEnd; ++PIdx) {
  1792. unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
  1793. if (OtherCount > OtherCritCount) {
  1794. OtherCritCount = OtherCount;
  1795. OtherCritIdx = PIdx;
  1796. }
  1797. }
  1798. if (OtherCritIdx) {
  1799. LLVM_DEBUG(
  1800. dbgs() << " " << Available.getName() << " + Remain CritRes: "
  1801. << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
  1802. << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
  1803. }
  1804. return OtherCritCount;
  1805. }
  1806. void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
  1807. assert(SU->getInstr() && "Scheduled SUnit must have instr");
  1808. #ifndef NDEBUG
  1809. // ReadyCycle was been bumped up to the CurrCycle when this node was
  1810. // scheduled, but CurrCycle may have been eagerly advanced immediately after
  1811. // scheduling, so may now be greater than ReadyCycle.
  1812. if (ReadyCycle > CurrCycle)
  1813. MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
  1814. #endif
  1815. if (ReadyCycle < MinReadyCycle)
  1816. MinReadyCycle = ReadyCycle;
  1817. // Check for interlocks first. For the purpose of other heuristics, an
  1818. // instruction that cannot issue appears as if it's not in the ReadyQueue.
  1819. bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
  1820. if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
  1821. Available.size() >= ReadyListLimit)
  1822. Pending.push(SU);
  1823. else
  1824. Available.push(SU);
  1825. }
  1826. /// Move the boundary of scheduled code by one cycle.
  1827. void SchedBoundary::bumpCycle(unsigned NextCycle) {
  1828. if (SchedModel->getMicroOpBufferSize() == 0) {
  1829. assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
  1830. "MinReadyCycle uninitialized");
  1831. if (MinReadyCycle > NextCycle)
  1832. NextCycle = MinReadyCycle;
  1833. }
  1834. // Update the current micro-ops, which will issue in the next cycle.
  1835. unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
  1836. CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
  1837. // Decrement DependentLatency based on the next cycle.
  1838. if ((NextCycle - CurrCycle) > DependentLatency)
  1839. DependentLatency = 0;
  1840. else
  1841. DependentLatency -= (NextCycle - CurrCycle);
  1842. if (!HazardRec->isEnabled()) {
  1843. // Bypass HazardRec virtual calls.
  1844. CurrCycle = NextCycle;
  1845. } else {
  1846. // Bypass getHazardType calls in case of long latency.
  1847. for (; CurrCycle != NextCycle; ++CurrCycle) {
  1848. if (isTop())
  1849. HazardRec->AdvanceCycle();
  1850. else
  1851. HazardRec->RecedeCycle();
  1852. }
  1853. }
  1854. CheckPending = true;
  1855. IsResourceLimited =
  1856. checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
  1857. getScheduledLatency(), true);
  1858. LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
  1859. << '\n');
  1860. }
  1861. void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
  1862. ExecutedResCounts[PIdx] += Count;
  1863. if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
  1864. MaxExecutedResCount = ExecutedResCounts[PIdx];
  1865. }
  1866. /// Add the given processor resource to this scheduled zone.
  1867. ///
  1868. /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
  1869. /// during which this resource is consumed.
  1870. ///
  1871. /// \return the next cycle at which the instruction may execute without
  1872. /// oversubscribing resources.
  1873. unsigned SchedBoundary::
  1874. countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
  1875. unsigned Factor = SchedModel->getResourceFactor(PIdx);
  1876. unsigned Count = Factor * Cycles;
  1877. LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +"
  1878. << Cycles << "x" << Factor << "u\n");
  1879. // Update Executed resources counts.
  1880. incExecutedResources(PIdx, Count);
  1881. assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
  1882. Rem->RemainingCounts[PIdx] -= Count;
  1883. // Check if this resource exceeds the current critical resource. If so, it
  1884. // becomes the critical resource.
  1885. if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
  1886. ZoneCritResIdx = PIdx;
  1887. LLVM_DEBUG(dbgs() << " *** Critical resource "
  1888. << SchedModel->getResourceName(PIdx) << ": "
  1889. << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
  1890. << "c\n");
  1891. }
  1892. // For reserved resources, record the highest cycle using the resource.
  1893. unsigned NextAvailable, InstanceIdx;
  1894. std::tie(NextAvailable, InstanceIdx) = getNextResourceCycle(PIdx, Cycles);
  1895. if (NextAvailable > CurrCycle) {
  1896. LLVM_DEBUG(dbgs() << " Resource conflict: "
  1897. << SchedModel->getResourceName(PIdx)
  1898. << '[' << InstanceIdx - ReservedCyclesIndex[PIdx] << ']'
  1899. << " reserved until @" << NextAvailable << "\n");
  1900. }
  1901. return NextAvailable;
  1902. }
  1903. /// Move the boundary of scheduled code by one SUnit.
  1904. void SchedBoundary::bumpNode(SUnit *SU) {
  1905. // Update the reservation table.
  1906. if (HazardRec->isEnabled()) {
  1907. if (!isTop() && SU->isCall) {
  1908. // Calls are scheduled with their preceding instructions. For bottom-up
  1909. // scheduling, clear the pipeline state before emitting.
  1910. HazardRec->Reset();
  1911. }
  1912. HazardRec->EmitInstruction(SU);
  1913. // Scheduling an instruction may have made pending instructions available.
  1914. CheckPending = true;
  1915. }
  1916. // checkHazard should prevent scheduling multiple instructions per cycle that
  1917. // exceed the issue width.
  1918. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  1919. unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
  1920. assert(
  1921. (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
  1922. "Cannot schedule this instruction's MicroOps in the current cycle.");
  1923. unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
  1924. LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
  1925. unsigned NextCycle = CurrCycle;
  1926. switch (SchedModel->getMicroOpBufferSize()) {
  1927. case 0:
  1928. assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
  1929. break;
  1930. case 1:
  1931. if (ReadyCycle > NextCycle) {
  1932. NextCycle = ReadyCycle;
  1933. LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
  1934. }
  1935. break;
  1936. default:
  1937. // We don't currently model the OOO reorder buffer, so consider all
  1938. // scheduled MOps to be "retired". We do loosely model in-order resource
  1939. // latency. If this instruction uses an in-order resource, account for any
  1940. // likely stall cycles.
  1941. if (SU->isUnbuffered && ReadyCycle > NextCycle)
  1942. NextCycle = ReadyCycle;
  1943. break;
  1944. }
  1945. RetiredMOps += IncMOps;
  1946. // Update resource counts and critical resource.
  1947. if (SchedModel->hasInstrSchedModel()) {
  1948. unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
  1949. assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
  1950. Rem->RemIssueCount -= DecRemIssue;
  1951. if (ZoneCritResIdx) {
  1952. // Scale scheduled micro-ops for comparing with the critical resource.
  1953. unsigned ScaledMOps =
  1954. RetiredMOps * SchedModel->getMicroOpFactor();
  1955. // If scaled micro-ops are now more than the previous critical resource by
  1956. // a full cycle, then micro-ops issue becomes critical.
  1957. if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
  1958. >= (int)SchedModel->getLatencyFactor()) {
  1959. ZoneCritResIdx = 0;
  1960. LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
  1961. << ScaledMOps / SchedModel->getLatencyFactor()
  1962. << "c\n");
  1963. }
  1964. }
  1965. for (TargetSchedModel::ProcResIter
  1966. PI = SchedModel->getWriteProcResBegin(SC),
  1967. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1968. unsigned RCycle =
  1969. countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
  1970. if (RCycle > NextCycle)
  1971. NextCycle = RCycle;
  1972. }
  1973. if (SU->hasReservedResource) {
  1974. // For reserved resources, record the highest cycle using the resource.
  1975. // For top-down scheduling, this is the cycle in which we schedule this
  1976. // instruction plus the number of cycles the operations reserves the
  1977. // resource. For bottom-up is it simply the instruction's cycle.
  1978. for (TargetSchedModel::ProcResIter
  1979. PI = SchedModel->getWriteProcResBegin(SC),
  1980. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1981. unsigned PIdx = PI->ProcResourceIdx;
  1982. if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
  1983. unsigned ReservedUntil, InstanceIdx;
  1984. std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(PIdx, 0);
  1985. if (isTop()) {
  1986. ReservedCycles[InstanceIdx] =
  1987. std::max(ReservedUntil, NextCycle + PI->Cycles);
  1988. } else
  1989. ReservedCycles[InstanceIdx] = NextCycle;
  1990. }
  1991. }
  1992. }
  1993. }
  1994. // Update ExpectedLatency and DependentLatency.
  1995. unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
  1996. unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
  1997. if (SU->getDepth() > TopLatency) {
  1998. TopLatency = SU->getDepth();
  1999. LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency SU("
  2000. << SU->NodeNum << ") " << TopLatency << "c\n");
  2001. }
  2002. if (SU->getHeight() > BotLatency) {
  2003. BotLatency = SU->getHeight();
  2004. LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency SU("
  2005. << SU->NodeNum << ") " << BotLatency << "c\n");
  2006. }
  2007. // If we stall for any reason, bump the cycle.
  2008. if (NextCycle > CurrCycle)
  2009. bumpCycle(NextCycle);
  2010. else
  2011. // After updating ZoneCritResIdx and ExpectedLatency, check if we're
  2012. // resource limited. If a stall occurred, bumpCycle does this.
  2013. IsResourceLimited =
  2014. checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
  2015. getScheduledLatency(), true);
  2016. // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
  2017. // resets CurrMOps. Loop to handle instructions with more MOps than issue in
  2018. // one cycle. Since we commonly reach the max MOps here, opportunistically
  2019. // bump the cycle to avoid uselessly checking everything in the readyQ.
  2020. CurrMOps += IncMOps;
  2021. // Bump the cycle count for issue group constraints.
  2022. // This must be done after NextCycle has been adjust for all other stalls.
  2023. // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
  2024. // currCycle to X.
  2025. if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
  2026. (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
  2027. LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin")
  2028. << " group\n");
  2029. bumpCycle(++NextCycle);
  2030. }
  2031. while (CurrMOps >= SchedModel->getIssueWidth()) {
  2032. LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle "
  2033. << CurrCycle << '\n');
  2034. bumpCycle(++NextCycle);
  2035. }
  2036. LLVM_DEBUG(dumpScheduledState());
  2037. }
  2038. /// Release pending ready nodes in to the available queue. This makes them
  2039. /// visible to heuristics.
  2040. void SchedBoundary::releasePending() {
  2041. // If the available queue is empty, it is safe to reset MinReadyCycle.
  2042. if (Available.empty())
  2043. MinReadyCycle = std::numeric_limits<unsigned>::max();
  2044. // Check to see if any of the pending instructions are ready to issue. If
  2045. // so, add them to the available queue.
  2046. bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
  2047. for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
  2048. SUnit *SU = *(Pending.begin()+i);
  2049. unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
  2050. if (ReadyCycle < MinReadyCycle)
  2051. MinReadyCycle = ReadyCycle;
  2052. if (!IsBuffered && ReadyCycle > CurrCycle)
  2053. continue;
  2054. if (checkHazard(SU))
  2055. continue;
  2056. if (Available.size() >= ReadyListLimit)
  2057. break;
  2058. Available.push(SU);
  2059. Pending.remove(Pending.begin()+i);
  2060. --i; --e;
  2061. }
  2062. CheckPending = false;
  2063. }
  2064. /// Remove SU from the ready set for this boundary.
  2065. void SchedBoundary::removeReady(SUnit *SU) {
  2066. if (Available.isInQueue(SU))
  2067. Available.remove(Available.find(SU));
  2068. else {
  2069. assert(Pending.isInQueue(SU) && "bad ready count");
  2070. Pending.remove(Pending.find(SU));
  2071. }
  2072. }
  2073. /// If this queue only has one ready candidate, return it. As a side effect,
  2074. /// defer any nodes that now hit a hazard, and advance the cycle until at least
  2075. /// one node is ready. If multiple instructions are ready, return NULL.
  2076. SUnit *SchedBoundary::pickOnlyChoice() {
  2077. if (CheckPending)
  2078. releasePending();
  2079. if (CurrMOps > 0) {
  2080. // Defer any ready instrs that now have a hazard.
  2081. for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
  2082. if (checkHazard(*I)) {
  2083. Pending.push(*I);
  2084. I = Available.remove(I);
  2085. continue;
  2086. }
  2087. ++I;
  2088. }
  2089. }
  2090. for (unsigned i = 0; Available.empty(); ++i) {
  2091. // FIXME: Re-enable assert once PR20057 is resolved.
  2092. // assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
  2093. // "permanent hazard");
  2094. (void)i;
  2095. bumpCycle(CurrCycle + 1);
  2096. releasePending();
  2097. }
  2098. LLVM_DEBUG(Pending.dump());
  2099. LLVM_DEBUG(Available.dump());
  2100. if (Available.size() == 1)
  2101. return *Available.begin();
  2102. return nullptr;
  2103. }
  2104. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2105. // This is useful information to dump after bumpNode.
  2106. // Note that the Queue contents are more useful before pickNodeFromQueue.
  2107. LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
  2108. unsigned ResFactor;
  2109. unsigned ResCount;
  2110. if (ZoneCritResIdx) {
  2111. ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
  2112. ResCount = getResourceCount(ZoneCritResIdx);
  2113. } else {
  2114. ResFactor = SchedModel->getMicroOpFactor();
  2115. ResCount = RetiredMOps * ResFactor;
  2116. }
  2117. unsigned LFactor = SchedModel->getLatencyFactor();
  2118. dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
  2119. << " Retired: " << RetiredMOps;
  2120. dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
  2121. dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
  2122. << ResCount / ResFactor << " "
  2123. << SchedModel->getResourceName(ZoneCritResIdx)
  2124. << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
  2125. << (IsResourceLimited ? " - Resource" : " - Latency")
  2126. << " limited.\n";
  2127. }
  2128. #endif
  2129. //===----------------------------------------------------------------------===//
  2130. // GenericScheduler - Generic implementation of MachineSchedStrategy.
  2131. //===----------------------------------------------------------------------===//
  2132. void GenericSchedulerBase::SchedCandidate::
  2133. initResourceDelta(const ScheduleDAGMI *DAG,
  2134. const TargetSchedModel *SchedModel) {
  2135. if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
  2136. return;
  2137. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  2138. for (TargetSchedModel::ProcResIter
  2139. PI = SchedModel->getWriteProcResBegin(SC),
  2140. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  2141. if (PI->ProcResourceIdx == Policy.ReduceResIdx)
  2142. ResDelta.CritResources += PI->Cycles;
  2143. if (PI->ProcResourceIdx == Policy.DemandResIdx)
  2144. ResDelta.DemandedResources += PI->Cycles;
  2145. }
  2146. }
  2147. /// Compute remaining latency. We need this both to determine whether the
  2148. /// overall schedule has become latency-limited and whether the instructions
  2149. /// outside this zone are resource or latency limited.
  2150. ///
  2151. /// The "dependent" latency is updated incrementally during scheduling as the
  2152. /// max height/depth of scheduled nodes minus the cycles since it was
  2153. /// scheduled:
  2154. /// DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
  2155. ///
  2156. /// The "independent" latency is the max ready queue depth:
  2157. /// ILat = max N.depth for N in Available|Pending
  2158. ///
  2159. /// RemainingLatency is the greater of independent and dependent latency.
  2160. ///
  2161. /// These computations are expensive, especially in DAGs with many edges, so
  2162. /// only do them if necessary.
  2163. static unsigned computeRemLatency(SchedBoundary &CurrZone) {
  2164. unsigned RemLatency = CurrZone.getDependentLatency();
  2165. RemLatency = std::max(RemLatency,
  2166. CurrZone.findMaxLatency(CurrZone.Available.elements()));
  2167. RemLatency = std::max(RemLatency,
  2168. CurrZone.findMaxLatency(CurrZone.Pending.elements()));
  2169. return RemLatency;
  2170. }
  2171. /// Returns true if the current cycle plus remaning latency is greater than
  2172. /// the critical path in the scheduling region.
  2173. bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
  2174. SchedBoundary &CurrZone,
  2175. bool ComputeRemLatency,
  2176. unsigned &RemLatency) const {
  2177. // The current cycle is already greater than the critical path, so we are
  2178. // already latency limited and don't need to compute the remaining latency.
  2179. if (CurrZone.getCurrCycle() > Rem.CriticalPath)
  2180. return true;
  2181. // If we haven't scheduled anything yet, then we aren't latency limited.
  2182. if (CurrZone.getCurrCycle() == 0)
  2183. return false;
  2184. if (ComputeRemLatency)
  2185. RemLatency = computeRemLatency(CurrZone);
  2186. return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
  2187. }
  2188. /// Set the CandPolicy given a scheduling zone given the current resources and
  2189. /// latencies inside and outside the zone.
  2190. void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
  2191. SchedBoundary &CurrZone,
  2192. SchedBoundary *OtherZone) {
  2193. // Apply preemptive heuristics based on the total latency and resources
  2194. // inside and outside this zone. Potential stalls should be considered before
  2195. // following this policy.
  2196. // Compute the critical resource outside the zone.
  2197. unsigned OtherCritIdx = 0;
  2198. unsigned OtherCount =
  2199. OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
  2200. bool OtherResLimited = false;
  2201. unsigned RemLatency = 0;
  2202. bool RemLatencyComputed = false;
  2203. if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
  2204. RemLatency = computeRemLatency(CurrZone);
  2205. RemLatencyComputed = true;
  2206. OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
  2207. OtherCount, RemLatency, false);
  2208. }
  2209. // Schedule aggressively for latency in PostRA mode. We don't check for
  2210. // acyclic latency during PostRA, and highly out-of-order processors will
  2211. // skip PostRA scheduling.
  2212. if (!OtherResLimited &&
  2213. (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
  2214. RemLatency))) {
  2215. Policy.ReduceLatency |= true;
  2216. LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName()
  2217. << " RemainingLatency " << RemLatency << " + "
  2218. << CurrZone.getCurrCycle() << "c > CritPath "
  2219. << Rem.CriticalPath << "\n");
  2220. }
  2221. // If the same resource is limiting inside and outside the zone, do nothing.
  2222. if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
  2223. return;
  2224. LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
  2225. dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
  2226. << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
  2227. } if (OtherResLimited) dbgs()
  2228. << " RemainingLimit: "
  2229. << SchedModel->getResourceName(OtherCritIdx) << "\n";
  2230. if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
  2231. << " Latency limited both directions.\n");
  2232. if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
  2233. Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
  2234. if (OtherResLimited)
  2235. Policy.DemandResIdx = OtherCritIdx;
  2236. }
  2237. #ifndef NDEBUG
  2238. const char *GenericSchedulerBase::getReasonStr(
  2239. GenericSchedulerBase::CandReason Reason) {
  2240. switch (Reason) {
  2241. case NoCand: return "NOCAND ";
  2242. case Only1: return "ONLY1 ";
  2243. case PhysReg: return "PHYS-REG ";
  2244. case RegExcess: return "REG-EXCESS";
  2245. case RegCritical: return "REG-CRIT ";
  2246. case Stall: return "STALL ";
  2247. case Cluster: return "CLUSTER ";
  2248. case Weak: return "WEAK ";
  2249. case RegMax: return "REG-MAX ";
  2250. case ResourceReduce: return "RES-REDUCE";
  2251. case ResourceDemand: return "RES-DEMAND";
  2252. case TopDepthReduce: return "TOP-DEPTH ";
  2253. case TopPathReduce: return "TOP-PATH ";
  2254. case BotHeightReduce:return "BOT-HEIGHT";
  2255. case BotPathReduce: return "BOT-PATH ";
  2256. case NextDefUse: return "DEF-USE ";
  2257. case NodeOrder: return "ORDER ";
  2258. };
  2259. llvm_unreachable("Unknown reason!");
  2260. }
  2261. void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
  2262. PressureChange P;
  2263. unsigned ResIdx = 0;
  2264. unsigned Latency = 0;
  2265. switch (Cand.Reason) {
  2266. default:
  2267. break;
  2268. case RegExcess:
  2269. P = Cand.RPDelta.Excess;
  2270. break;
  2271. case RegCritical:
  2272. P = Cand.RPDelta.CriticalMax;
  2273. break;
  2274. case RegMax:
  2275. P = Cand.RPDelta.CurrentMax;
  2276. break;
  2277. case ResourceReduce:
  2278. ResIdx = Cand.Policy.ReduceResIdx;
  2279. break;
  2280. case ResourceDemand:
  2281. ResIdx = Cand.Policy.DemandResIdx;
  2282. break;
  2283. case TopDepthReduce:
  2284. Latency = Cand.SU->getDepth();
  2285. break;
  2286. case TopPathReduce:
  2287. Latency = Cand.SU->getHeight();
  2288. break;
  2289. case BotHeightReduce:
  2290. Latency = Cand.SU->getHeight();
  2291. break;
  2292. case BotPathReduce:
  2293. Latency = Cand.SU->getDepth();
  2294. break;
  2295. }
  2296. dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
  2297. if (P.isValid())
  2298. dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
  2299. << ":" << P.getUnitInc() << " ";
  2300. else
  2301. dbgs() << " ";
  2302. if (ResIdx)
  2303. dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
  2304. else
  2305. dbgs() << " ";
  2306. if (Latency)
  2307. dbgs() << " " << Latency << " cycles ";
  2308. else
  2309. dbgs() << " ";
  2310. dbgs() << '\n';
  2311. }
  2312. #endif
  2313. namespace llvm {
  2314. /// Return true if this heuristic determines order.
  2315. bool tryLess(int TryVal, int CandVal,
  2316. GenericSchedulerBase::SchedCandidate &TryCand,
  2317. GenericSchedulerBase::SchedCandidate &Cand,
  2318. GenericSchedulerBase::CandReason Reason) {
  2319. if (TryVal < CandVal) {
  2320. TryCand.Reason = Reason;
  2321. return true;
  2322. }
  2323. if (TryVal > CandVal) {
  2324. if (Cand.Reason > Reason)
  2325. Cand.Reason = Reason;
  2326. return true;
  2327. }
  2328. return false;
  2329. }
  2330. bool tryGreater(int TryVal, int CandVal,
  2331. GenericSchedulerBase::SchedCandidate &TryCand,
  2332. GenericSchedulerBase::SchedCandidate &Cand,
  2333. GenericSchedulerBase::CandReason Reason) {
  2334. if (TryVal > CandVal) {
  2335. TryCand.Reason = Reason;
  2336. return true;
  2337. }
  2338. if (TryVal < CandVal) {
  2339. if (Cand.Reason > Reason)
  2340. Cand.Reason = Reason;
  2341. return true;
  2342. }
  2343. return false;
  2344. }
  2345. bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
  2346. GenericSchedulerBase::SchedCandidate &Cand,
  2347. SchedBoundary &Zone) {
  2348. if (Zone.isTop()) {
  2349. if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
  2350. if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
  2351. TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
  2352. return true;
  2353. }
  2354. if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
  2355. TryCand, Cand, GenericSchedulerBase::TopPathReduce))
  2356. return true;
  2357. } else {
  2358. if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
  2359. if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
  2360. TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
  2361. return true;
  2362. }
  2363. if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
  2364. TryCand, Cand, GenericSchedulerBase::BotPathReduce))
  2365. return true;
  2366. }
  2367. return false;
  2368. }
  2369. } // end namespace llvm
  2370. static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
  2371. LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
  2372. << GenericSchedulerBase::getReasonStr(Reason) << '\n');
  2373. }
  2374. static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
  2375. tracePick(Cand.Reason, Cand.AtTop);
  2376. }
  2377. void GenericScheduler::initialize(ScheduleDAGMI *dag) {
  2378. assert(dag->hasVRegLiveness() &&
  2379. "(PreRA)GenericScheduler needs vreg liveness");
  2380. DAG = static_cast<ScheduleDAGMILive*>(dag);
  2381. SchedModel = DAG->getSchedModel();
  2382. TRI = DAG->TRI;
  2383. Rem.init(DAG, SchedModel);
  2384. Top.init(DAG, SchedModel, &Rem);
  2385. Bot.init(DAG, SchedModel, &Rem);
  2386. // Initialize resource counts.
  2387. // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
  2388. // are disabled, then these HazardRecs will be disabled.
  2389. const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
  2390. if (!Top.HazardRec) {
  2391. Top.HazardRec =
  2392. DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
  2393. Itin, DAG);
  2394. }
  2395. if (!Bot.HazardRec) {
  2396. Bot.HazardRec =
  2397. DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
  2398. Itin, DAG);
  2399. }
  2400. TopCand.SU = nullptr;
  2401. BotCand.SU = nullptr;
  2402. }
  2403. /// Initialize the per-region scheduling policy.
  2404. void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
  2405. MachineBasicBlock::iterator End,
  2406. unsigned NumRegionInstrs) {
  2407. const MachineFunction &MF = *Begin->getMF();
  2408. const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
  2409. // Avoid setting up the register pressure tracker for small regions to save
  2410. // compile time. As a rough heuristic, only track pressure when the number of
  2411. // schedulable instructions exceeds half the integer register file.
  2412. RegionPolicy.ShouldTrackPressure = true;
  2413. for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
  2414. MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
  2415. if (TLI->isTypeLegal(LegalIntVT)) {
  2416. unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
  2417. TLI->getRegClassFor(LegalIntVT));
  2418. RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
  2419. }
  2420. }
  2421. // For generic targets, we default to bottom-up, because it's simpler and more
  2422. // compile-time optimizations have been implemented in that direction.
  2423. RegionPolicy.OnlyBottomUp = true;
  2424. // Allow the subtarget to override default policy.
  2425. MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
  2426. // After subtarget overrides, apply command line options.
  2427. if (!EnableRegPressure) {
  2428. RegionPolicy.ShouldTrackPressure = false;
  2429. RegionPolicy.ShouldTrackLaneMasks = false;
  2430. }
  2431. // Check -misched-topdown/bottomup can force or unforce scheduling direction.
  2432. // e.g. -misched-bottomup=false allows scheduling in both directions.
  2433. assert((!ForceTopDown || !ForceBottomUp) &&
  2434. "-misched-topdown incompatible with -misched-bottomup");
  2435. if (ForceBottomUp.getNumOccurrences() > 0) {
  2436. RegionPolicy.OnlyBottomUp = ForceBottomUp;
  2437. if (RegionPolicy.OnlyBottomUp)
  2438. RegionPolicy.OnlyTopDown = false;
  2439. }
  2440. if (ForceTopDown.getNumOccurrences() > 0) {
  2441. RegionPolicy.OnlyTopDown = ForceTopDown;
  2442. if (RegionPolicy.OnlyTopDown)
  2443. RegionPolicy.OnlyBottomUp = false;
  2444. }
  2445. }
  2446. void GenericScheduler::dumpPolicy() const {
  2447. // Cannot completely remove virtual function even in release mode.
  2448. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2449. dbgs() << "GenericScheduler RegionPolicy: "
  2450. << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
  2451. << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
  2452. << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
  2453. << "\n";
  2454. #endif
  2455. }
  2456. /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
  2457. /// critical path by more cycles than it takes to drain the instruction buffer.
  2458. /// We estimate an upper bounds on in-flight instructions as:
  2459. ///
  2460. /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
  2461. /// InFlightIterations = AcyclicPath / CyclesPerIteration
  2462. /// InFlightResources = InFlightIterations * LoopResources
  2463. ///
  2464. /// TODO: Check execution resources in addition to IssueCount.
  2465. void GenericScheduler::checkAcyclicLatency() {
  2466. if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
  2467. return;
  2468. // Scaled number of cycles per loop iteration.
  2469. unsigned IterCount =
  2470. std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
  2471. Rem.RemIssueCount);
  2472. // Scaled acyclic critical path.
  2473. unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
  2474. // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
  2475. unsigned InFlightCount =
  2476. (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
  2477. unsigned BufferLimit =
  2478. SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
  2479. Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
  2480. LLVM_DEBUG(
  2481. dbgs() << "IssueCycles="
  2482. << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
  2483. << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
  2484. << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
  2485. << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
  2486. << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
  2487. if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n");
  2488. }
  2489. void GenericScheduler::registerRoots() {
  2490. Rem.CriticalPath = DAG->ExitSU.getDepth();
  2491. // Some roots may not feed into ExitSU. Check all of them in case.
  2492. for (const SUnit *SU : Bot.Available) {
  2493. if (SU->getDepth() > Rem.CriticalPath)
  2494. Rem.CriticalPath = SU->getDepth();
  2495. }
  2496. LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
  2497. if (DumpCriticalPathLength) {
  2498. errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
  2499. }
  2500. if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
  2501. Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
  2502. checkAcyclicLatency();
  2503. }
  2504. }
  2505. namespace llvm {
  2506. bool tryPressure(const PressureChange &TryP,
  2507. const PressureChange &CandP,
  2508. GenericSchedulerBase::SchedCandidate &TryCand,
  2509. GenericSchedulerBase::SchedCandidate &Cand,
  2510. GenericSchedulerBase::CandReason Reason,
  2511. const TargetRegisterInfo *TRI,
  2512. const MachineFunction &MF) {
  2513. // If one candidate decreases and the other increases, go with it.
  2514. // Invalid candidates have UnitInc==0.
  2515. if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
  2516. Reason)) {
  2517. return true;
  2518. }
  2519. // Do not compare the magnitude of pressure changes between top and bottom
  2520. // boundary.
  2521. if (Cand.AtTop != TryCand.AtTop)
  2522. return false;
  2523. // If both candidates affect the same set in the same boundary, go with the
  2524. // smallest increase.
  2525. unsigned TryPSet = TryP.getPSetOrMax();
  2526. unsigned CandPSet = CandP.getPSetOrMax();
  2527. if (TryPSet == CandPSet) {
  2528. return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
  2529. Reason);
  2530. }
  2531. int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
  2532. std::numeric_limits<int>::max();
  2533. int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
  2534. std::numeric_limits<int>::max();
  2535. // If the candidates are decreasing pressure, reverse priority.
  2536. if (TryP.getUnitInc() < 0)
  2537. std::swap(TryRank, CandRank);
  2538. return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
  2539. }
  2540. unsigned getWeakLeft(const SUnit *SU, bool isTop) {
  2541. return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
  2542. }
  2543. /// Minimize physical register live ranges. Regalloc wants them adjacent to
  2544. /// their physreg def/use.
  2545. ///
  2546. /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
  2547. /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
  2548. /// with the operation that produces or consumes the physreg. We'll do this when
  2549. /// regalloc has support for parallel copies.
  2550. int biasPhysReg(const SUnit *SU, bool isTop) {
  2551. const MachineInstr *MI = SU->getInstr();
  2552. if (MI->isCopy()) {
  2553. unsigned ScheduledOper = isTop ? 1 : 0;
  2554. unsigned UnscheduledOper = isTop ? 0 : 1;
  2555. // If we have already scheduled the physreg produce/consumer, immediately
  2556. // schedule the copy.
  2557. if (Register::isPhysicalRegister(MI->getOperand(ScheduledOper).getReg()))
  2558. return 1;
  2559. // If the physreg is at the boundary, defer it. Otherwise schedule it
  2560. // immediately to free the dependent. We can hoist the copy later.
  2561. bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
  2562. if (Register::isPhysicalRegister(MI->getOperand(UnscheduledOper).getReg()))
  2563. return AtBoundary ? -1 : 1;
  2564. }
  2565. if (MI->isMoveImmediate()) {
  2566. // If we have a move immediate and all successors have been assigned, bias
  2567. // towards scheduling this later. Make sure all register defs are to
  2568. // physical registers.
  2569. bool DoBias = true;
  2570. for (const MachineOperand &Op : MI->defs()) {
  2571. if (Op.isReg() && !Register::isPhysicalRegister(Op.getReg())) {
  2572. DoBias = false;
  2573. break;
  2574. }
  2575. }
  2576. if (DoBias)
  2577. return isTop ? -1 : 1;
  2578. }
  2579. return 0;
  2580. }
  2581. } // end namespace llvm
  2582. void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
  2583. bool AtTop,
  2584. const RegPressureTracker &RPTracker,
  2585. RegPressureTracker &TempTracker) {
  2586. Cand.SU = SU;
  2587. Cand.AtTop = AtTop;
  2588. if (DAG->isTrackingPressure()) {
  2589. if (AtTop) {
  2590. TempTracker.getMaxDownwardPressureDelta(
  2591. Cand.SU->getInstr(),
  2592. Cand.RPDelta,
  2593. DAG->getRegionCriticalPSets(),
  2594. DAG->getRegPressure().MaxSetPressure);
  2595. } else {
  2596. if (VerifyScheduling) {
  2597. TempTracker.getMaxUpwardPressureDelta(
  2598. Cand.SU->getInstr(),
  2599. &DAG->getPressureDiff(Cand.SU),
  2600. Cand.RPDelta,
  2601. DAG->getRegionCriticalPSets(),
  2602. DAG->getRegPressure().MaxSetPressure);
  2603. } else {
  2604. RPTracker.getUpwardPressureDelta(
  2605. Cand.SU->getInstr(),
  2606. DAG->getPressureDiff(Cand.SU),
  2607. Cand.RPDelta,
  2608. DAG->getRegionCriticalPSets(),
  2609. DAG->getRegPressure().MaxSetPressure);
  2610. }
  2611. }
  2612. }
  2613. LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
  2614. << " Try SU(" << Cand.SU->NodeNum << ") "
  2615. << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
  2616. << Cand.RPDelta.Excess.getUnitInc() << "\n");
  2617. }
  2618. /// Apply a set of heuristics to a new candidate. Heuristics are currently
  2619. /// hierarchical. This may be more efficient than a graduated cost model because
  2620. /// we don't need to evaluate all aspects of the model for each node in the
  2621. /// queue. But it's really done to make the heuristics easier to debug and
  2622. /// statistically analyze.
  2623. ///
  2624. /// \param Cand provides the policy and current best candidate.
  2625. /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
  2626. /// \param Zone describes the scheduled zone that we are extending, or nullptr
  2627. // if Cand is from a different zone than TryCand.
  2628. void GenericScheduler::tryCandidate(SchedCandidate &Cand,
  2629. SchedCandidate &TryCand,
  2630. SchedBoundary *Zone) const {
  2631. // Initialize the candidate if needed.
  2632. if (!Cand.isValid()) {
  2633. TryCand.Reason = NodeOrder;
  2634. return;
  2635. }
  2636. // Bias PhysReg Defs and copies to their uses and defined respectively.
  2637. if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
  2638. biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
  2639. return;
  2640. // Avoid exceeding the target's limit.
  2641. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
  2642. Cand.RPDelta.Excess,
  2643. TryCand, Cand, RegExcess, TRI,
  2644. DAG->MF))
  2645. return;
  2646. // Avoid increasing the max critical pressure in the scheduled region.
  2647. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
  2648. Cand.RPDelta.CriticalMax,
  2649. TryCand, Cand, RegCritical, TRI,
  2650. DAG->MF))
  2651. return;
  2652. // We only compare a subset of features when comparing nodes between
  2653. // Top and Bottom boundary. Some properties are simply incomparable, in many
  2654. // other instances we should only override the other boundary if something
  2655. // is a clear good pick on one boundary. Skip heuristics that are more
  2656. // "tie-breaking" in nature.
  2657. bool SameBoundary = Zone != nullptr;
  2658. if (SameBoundary) {
  2659. // For loops that are acyclic path limited, aggressively schedule for
  2660. // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
  2661. // heuristics to take precedence.
  2662. if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
  2663. tryLatency(TryCand, Cand, *Zone))
  2664. return;
  2665. // Prioritize instructions that read unbuffered resources by stall cycles.
  2666. if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
  2667. Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
  2668. return;
  2669. }
  2670. // Keep clustered nodes together to encourage downstream peephole
  2671. // optimizations which may reduce resource requirements.
  2672. //
  2673. // This is a best effort to set things up for a post-RA pass. Optimizations
  2674. // like generating loads of multiple registers should ideally be done within
  2675. // the scheduler pass by combining the loads during DAG postprocessing.
  2676. const SUnit *CandNextClusterSU =
  2677. Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
  2678. const SUnit *TryCandNextClusterSU =
  2679. TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
  2680. if (tryGreater(TryCand.SU == TryCandNextClusterSU,
  2681. Cand.SU == CandNextClusterSU,
  2682. TryCand, Cand, Cluster))
  2683. return;
  2684. if (SameBoundary) {
  2685. // Weak edges are for clustering and other constraints.
  2686. if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
  2687. getWeakLeft(Cand.SU, Cand.AtTop),
  2688. TryCand, Cand, Weak))
  2689. return;
  2690. }
  2691. // Avoid increasing the max pressure of the entire region.
  2692. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
  2693. Cand.RPDelta.CurrentMax,
  2694. TryCand, Cand, RegMax, TRI,
  2695. DAG->MF))
  2696. return;
  2697. if (SameBoundary) {
  2698. // Avoid critical resource consumption and balance the schedule.
  2699. TryCand.initResourceDelta(DAG, SchedModel);
  2700. if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
  2701. TryCand, Cand, ResourceReduce))
  2702. return;
  2703. if (tryGreater(TryCand.ResDelta.DemandedResources,
  2704. Cand.ResDelta.DemandedResources,
  2705. TryCand, Cand, ResourceDemand))
  2706. return;
  2707. // Avoid serializing long latency dependence chains.
  2708. // For acyclic path limited loops, latency was already checked above.
  2709. if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
  2710. !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
  2711. return;
  2712. // Fall through to original instruction order.
  2713. if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
  2714. || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
  2715. TryCand.Reason = NodeOrder;
  2716. }
  2717. }
  2718. }
  2719. /// Pick the best candidate from the queue.
  2720. ///
  2721. /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
  2722. /// DAG building. To adjust for the current scheduling location we need to
  2723. /// maintain the number of vreg uses remaining to be top-scheduled.
  2724. void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
  2725. const CandPolicy &ZonePolicy,
  2726. const RegPressureTracker &RPTracker,
  2727. SchedCandidate &Cand) {
  2728. // getMaxPressureDelta temporarily modifies the tracker.
  2729. RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
  2730. ReadyQueue &Q = Zone.Available;
  2731. for (SUnit *SU : Q) {
  2732. SchedCandidate TryCand(ZonePolicy);
  2733. initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
  2734. // Pass SchedBoundary only when comparing nodes from the same boundary.
  2735. SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
  2736. tryCandidate(Cand, TryCand, ZoneArg);
  2737. if (TryCand.Reason != NoCand) {
  2738. // Initialize resource delta if needed in case future heuristics query it.
  2739. if (TryCand.ResDelta == SchedResourceDelta())
  2740. TryCand.initResourceDelta(DAG, SchedModel);
  2741. Cand.setBest(TryCand);
  2742. LLVM_DEBUG(traceCandidate(Cand));
  2743. }
  2744. }
  2745. }
  2746. /// Pick the best candidate node from either the top or bottom queue.
  2747. SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
  2748. // Schedule as far as possible in the direction of no choice. This is most
  2749. // efficient, but also provides the best heuristics for CriticalPSets.
  2750. if (SUnit *SU = Bot.pickOnlyChoice()) {
  2751. IsTopNode = false;
  2752. tracePick(Only1, false);
  2753. return SU;
  2754. }
  2755. if (SUnit *SU = Top.pickOnlyChoice()) {
  2756. IsTopNode = true;
  2757. tracePick(Only1, true);
  2758. return SU;
  2759. }
  2760. // Set the bottom-up policy based on the state of the current bottom zone and
  2761. // the instructions outside the zone, including the top zone.
  2762. CandPolicy BotPolicy;
  2763. setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
  2764. // Set the top-down policy based on the state of the current top zone and
  2765. // the instructions outside the zone, including the bottom zone.
  2766. CandPolicy TopPolicy;
  2767. setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
  2768. // See if BotCand is still valid (because we previously scheduled from Top).
  2769. LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
  2770. if (!BotCand.isValid() || BotCand.SU->isScheduled ||
  2771. BotCand.Policy != BotPolicy) {
  2772. BotCand.reset(CandPolicy());
  2773. pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
  2774. assert(BotCand.Reason != NoCand && "failed to find the first candidate");
  2775. } else {
  2776. LLVM_DEBUG(traceCandidate(BotCand));
  2777. #ifndef NDEBUG
  2778. if (VerifyScheduling) {
  2779. SchedCandidate TCand;
  2780. TCand.reset(CandPolicy());
  2781. pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
  2782. assert(TCand.SU == BotCand.SU &&
  2783. "Last pick result should correspond to re-picking right now");
  2784. }
  2785. #endif
  2786. }
  2787. // Check if the top Q has a better candidate.
  2788. LLVM_DEBUG(dbgs() << "Picking from Top:\n");
  2789. if (!TopCand.isValid() || TopCand.SU->isScheduled ||
  2790. TopCand.Policy != TopPolicy) {
  2791. TopCand.reset(CandPolicy());
  2792. pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
  2793. assert(TopCand.Reason != NoCand && "failed to find the first candidate");
  2794. } else {
  2795. LLVM_DEBUG(traceCandidate(TopCand));
  2796. #ifndef NDEBUG
  2797. if (VerifyScheduling) {
  2798. SchedCandidate TCand;
  2799. TCand.reset(CandPolicy());
  2800. pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
  2801. assert(TCand.SU == TopCand.SU &&
  2802. "Last pick result should correspond to re-picking right now");
  2803. }
  2804. #endif
  2805. }
  2806. // Pick best from BotCand and TopCand.
  2807. assert(BotCand.isValid());
  2808. assert(TopCand.isValid());
  2809. SchedCandidate Cand = BotCand;
  2810. TopCand.Reason = NoCand;
  2811. tryCandidate(Cand, TopCand, nullptr);
  2812. if (TopCand.Reason != NoCand) {
  2813. Cand.setBest(TopCand);
  2814. LLVM_DEBUG(traceCandidate(Cand));
  2815. }
  2816. IsTopNode = Cand.AtTop;
  2817. tracePick(Cand);
  2818. return Cand.SU;
  2819. }
  2820. /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
  2821. SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
  2822. if (DAG->top() == DAG->bottom()) {
  2823. assert(Top.Available.empty() && Top.Pending.empty() &&
  2824. Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
  2825. return nullptr;
  2826. }
  2827. SUnit *SU;
  2828. do {
  2829. if (RegionPolicy.OnlyTopDown) {
  2830. SU = Top.pickOnlyChoice();
  2831. if (!SU) {
  2832. CandPolicy NoPolicy;
  2833. TopCand.reset(NoPolicy);
  2834. pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
  2835. assert(TopCand.Reason != NoCand && "failed to find a candidate");
  2836. tracePick(TopCand);
  2837. SU = TopCand.SU;
  2838. }
  2839. IsTopNode = true;
  2840. } else if (RegionPolicy.OnlyBottomUp) {
  2841. SU = Bot.pickOnlyChoice();
  2842. if (!SU) {
  2843. CandPolicy NoPolicy;
  2844. BotCand.reset(NoPolicy);
  2845. pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
  2846. assert(BotCand.Reason != NoCand && "failed to find a candidate");
  2847. tracePick(BotCand);
  2848. SU = BotCand.SU;
  2849. }
  2850. IsTopNode = false;
  2851. } else {
  2852. SU = pickNodeBidirectional(IsTopNode);
  2853. }
  2854. } while (SU->isScheduled);
  2855. if (SU->isTopReady())
  2856. Top.removeReady(SU);
  2857. if (SU->isBottomReady())
  2858. Bot.removeReady(SU);
  2859. LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
  2860. << *SU->getInstr());
  2861. return SU;
  2862. }
  2863. void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) {
  2864. MachineBasicBlock::iterator InsertPos = SU->getInstr();
  2865. if (!isTop)
  2866. ++InsertPos;
  2867. SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
  2868. // Find already scheduled copies with a single physreg dependence and move
  2869. // them just above the scheduled instruction.
  2870. for (SDep &Dep : Deps) {
  2871. if (Dep.getKind() != SDep::Data ||
  2872. !Register::isPhysicalRegister(Dep.getReg()))
  2873. continue;
  2874. SUnit *DepSU = Dep.getSUnit();
  2875. if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
  2876. continue;
  2877. MachineInstr *Copy = DepSU->getInstr();
  2878. if (!Copy->isCopy() && !Copy->isMoveImmediate())
  2879. continue;
  2880. LLVM_DEBUG(dbgs() << " Rescheduling physreg copy ";
  2881. DAG->dumpNode(*Dep.getSUnit()));
  2882. DAG->moveInstruction(Copy, InsertPos);
  2883. }
  2884. }
  2885. /// Update the scheduler's state after scheduling a node. This is the same node
  2886. /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
  2887. /// update it's state based on the current cycle before MachineSchedStrategy
  2888. /// does.
  2889. ///
  2890. /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
  2891. /// them here. See comments in biasPhysReg.
  2892. void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
  2893. if (IsTopNode) {
  2894. SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
  2895. Top.bumpNode(SU);
  2896. if (SU->hasPhysRegUses)
  2897. reschedulePhysReg(SU, true);
  2898. } else {
  2899. SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
  2900. Bot.bumpNode(SU);
  2901. if (SU->hasPhysRegDefs)
  2902. reschedulePhysReg(SU, false);
  2903. }
  2904. }
  2905. /// Create the standard converging machine scheduler. This will be used as the
  2906. /// default scheduler if the target does not set a default.
  2907. ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
  2908. ScheduleDAGMILive *DAG =
  2909. new ScheduleDAGMILive(C, std::make_unique<GenericScheduler>(C));
  2910. // Register DAG post-processors.
  2911. //
  2912. // FIXME: extend the mutation API to allow earlier mutations to instantiate
  2913. // data and pass it to later mutations. Have a single mutation that gathers
  2914. // the interesting nodes in one pass.
  2915. DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
  2916. return DAG;
  2917. }
  2918. static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
  2919. return createGenericSchedLive(C);
  2920. }
  2921. static MachineSchedRegistry
  2922. GenericSchedRegistry("converge", "Standard converging scheduler.",
  2923. createConveringSched);
  2924. //===----------------------------------------------------------------------===//
  2925. // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
  2926. //===----------------------------------------------------------------------===//
  2927. void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
  2928. DAG = Dag;
  2929. SchedModel = DAG->getSchedModel();
  2930. TRI = DAG->TRI;
  2931. Rem.init(DAG, SchedModel);
  2932. Top.init(DAG, SchedModel, &Rem);
  2933. BotRoots.clear();
  2934. // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
  2935. // or are disabled, then these HazardRecs will be disabled.
  2936. const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
  2937. if (!Top.HazardRec) {
  2938. Top.HazardRec =
  2939. DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
  2940. Itin, DAG);
  2941. }
  2942. }
  2943. void PostGenericScheduler::registerRoots() {
  2944. Rem.CriticalPath = DAG->ExitSU.getDepth();
  2945. // Some roots may not feed into ExitSU. Check all of them in case.
  2946. for (const SUnit *SU : BotRoots) {
  2947. if (SU->getDepth() > Rem.CriticalPath)
  2948. Rem.CriticalPath = SU->getDepth();
  2949. }
  2950. LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
  2951. if (DumpCriticalPathLength) {
  2952. errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
  2953. }
  2954. }
  2955. /// Apply a set of heuristics to a new candidate for PostRA scheduling.
  2956. ///
  2957. /// \param Cand provides the policy and current best candidate.
  2958. /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
  2959. void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
  2960. SchedCandidate &TryCand) {
  2961. // Initialize the candidate if needed.
  2962. if (!Cand.isValid()) {
  2963. TryCand.Reason = NodeOrder;
  2964. return;
  2965. }
  2966. // Prioritize instructions that read unbuffered resources by stall cycles.
  2967. if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
  2968. Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
  2969. return;
  2970. // Keep clustered nodes together.
  2971. if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
  2972. Cand.SU == DAG->getNextClusterSucc(),
  2973. TryCand, Cand, Cluster))
  2974. return;
  2975. // Avoid critical resource consumption and balance the schedule.
  2976. if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
  2977. TryCand, Cand, ResourceReduce))
  2978. return;
  2979. if (tryGreater(TryCand.ResDelta.DemandedResources,
  2980. Cand.ResDelta.DemandedResources,
  2981. TryCand, Cand, ResourceDemand))
  2982. return;
  2983. // Avoid serializing long latency dependence chains.
  2984. if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
  2985. return;
  2986. }
  2987. // Fall through to original instruction order.
  2988. if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
  2989. TryCand.Reason = NodeOrder;
  2990. }
  2991. void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
  2992. ReadyQueue &Q = Top.Available;
  2993. for (SUnit *SU : Q) {
  2994. SchedCandidate TryCand(Cand.Policy);
  2995. TryCand.SU = SU;
  2996. TryCand.AtTop = true;
  2997. TryCand.initResourceDelta(DAG, SchedModel);
  2998. tryCandidate(Cand, TryCand);
  2999. if (TryCand.Reason != NoCand) {
  3000. Cand.setBest(TryCand);
  3001. LLVM_DEBUG(traceCandidate(Cand));
  3002. }
  3003. }
  3004. }
  3005. /// Pick the next node to schedule.
  3006. SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
  3007. if (DAG->top() == DAG->bottom()) {
  3008. assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
  3009. return nullptr;
  3010. }
  3011. SUnit *SU;
  3012. do {
  3013. SU = Top.pickOnlyChoice();
  3014. if (SU) {
  3015. tracePick(Only1, true);
  3016. } else {
  3017. CandPolicy NoPolicy;
  3018. SchedCandidate TopCand(NoPolicy);
  3019. // Set the top-down policy based on the state of the current top zone and
  3020. // the instructions outside the zone, including the bottom zone.
  3021. setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
  3022. pickNodeFromQueue(TopCand);
  3023. assert(TopCand.Reason != NoCand && "failed to find a candidate");
  3024. tracePick(TopCand);
  3025. SU = TopCand.SU;
  3026. }
  3027. } while (SU->isScheduled);
  3028. IsTopNode = true;
  3029. Top.removeReady(SU);
  3030. LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
  3031. << *SU->getInstr());
  3032. return SU;
  3033. }
  3034. /// Called after ScheduleDAGMI has scheduled an instruction and updated
  3035. /// scheduled/remaining flags in the DAG nodes.
  3036. void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
  3037. SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
  3038. Top.bumpNode(SU);
  3039. }
  3040. ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
  3041. return new ScheduleDAGMI(C, std::make_unique<PostGenericScheduler>(C),
  3042. /*RemoveKillFlags=*/true);
  3043. }
  3044. //===----------------------------------------------------------------------===//
  3045. // ILP Scheduler. Currently for experimental analysis of heuristics.
  3046. //===----------------------------------------------------------------------===//
  3047. namespace {
  3048. /// Order nodes by the ILP metric.
  3049. struct ILPOrder {
  3050. const SchedDFSResult *DFSResult = nullptr;
  3051. const BitVector *ScheduledTrees = nullptr;
  3052. bool MaximizeILP;
  3053. ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
  3054. /// Apply a less-than relation on node priority.
  3055. ///
  3056. /// (Return true if A comes after B in the Q.)
  3057. bool operator()(const SUnit *A, const SUnit *B) const {
  3058. unsigned SchedTreeA = DFSResult->getSubtreeID(A);
  3059. unsigned SchedTreeB = DFSResult->getSubtreeID(B);
  3060. if (SchedTreeA != SchedTreeB) {
  3061. // Unscheduled trees have lower priority.
  3062. if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
  3063. return ScheduledTrees->test(SchedTreeB);
  3064. // Trees with shallower connections have have lower priority.
  3065. if (DFSResult->getSubtreeLevel(SchedTreeA)
  3066. != DFSResult->getSubtreeLevel(SchedTreeB)) {
  3067. return DFSResult->getSubtreeLevel(SchedTreeA)
  3068. < DFSResult->getSubtreeLevel(SchedTreeB);
  3069. }
  3070. }
  3071. if (MaximizeILP)
  3072. return DFSResult->getILP(A) < DFSResult->getILP(B);
  3073. else
  3074. return DFSResult->getILP(A) > DFSResult->getILP(B);
  3075. }
  3076. };
  3077. /// Schedule based on the ILP metric.
  3078. class ILPScheduler : public MachineSchedStrategy {
  3079. ScheduleDAGMILive *DAG = nullptr;
  3080. ILPOrder Cmp;
  3081. std::vector<SUnit*> ReadyQ;
  3082. public:
  3083. ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
  3084. void initialize(ScheduleDAGMI *dag) override {
  3085. assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
  3086. DAG = static_cast<ScheduleDAGMILive*>(dag);
  3087. DAG->computeDFSResult();
  3088. Cmp.DFSResult = DAG->getDFSResult();
  3089. Cmp.ScheduledTrees = &DAG->getScheduledTrees();
  3090. ReadyQ.clear();
  3091. }
  3092. void registerRoots() override {
  3093. // Restore the heap in ReadyQ with the updated DFS results.
  3094. std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  3095. }
  3096. /// Implement MachineSchedStrategy interface.
  3097. /// -----------------------------------------
  3098. /// Callback to select the highest priority node from the ready Q.
  3099. SUnit *pickNode(bool &IsTopNode) override {
  3100. if (ReadyQ.empty()) return nullptr;
  3101. std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  3102. SUnit *SU = ReadyQ.back();
  3103. ReadyQ.pop_back();
  3104. IsTopNode = false;
  3105. LLVM_DEBUG(dbgs() << "Pick node "
  3106. << "SU(" << SU->NodeNum << ") "
  3107. << " ILP: " << DAG->getDFSResult()->getILP(SU)
  3108. << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
  3109. << " @"
  3110. << DAG->getDFSResult()->getSubtreeLevel(
  3111. DAG->getDFSResult()->getSubtreeID(SU))
  3112. << '\n'
  3113. << "Scheduling " << *SU->getInstr());
  3114. return SU;
  3115. }
  3116. /// Scheduler callback to notify that a new subtree is scheduled.
  3117. void scheduleTree(unsigned SubtreeID) override {
  3118. std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  3119. }
  3120. /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
  3121. /// DFSResults, and resort the priority Q.
  3122. void schedNode(SUnit *SU, bool IsTopNode) override {
  3123. assert(!IsTopNode && "SchedDFSResult needs bottom-up");
  3124. }
  3125. void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
  3126. void releaseBottomNode(SUnit *SU) override {
  3127. ReadyQ.push_back(SU);
  3128. std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  3129. }
  3130. };
  3131. } // end anonymous namespace
  3132. static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
  3133. return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(true));
  3134. }
  3135. static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
  3136. return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(false));
  3137. }
  3138. static MachineSchedRegistry ILPMaxRegistry(
  3139. "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
  3140. static MachineSchedRegistry ILPMinRegistry(
  3141. "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
  3142. //===----------------------------------------------------------------------===//
  3143. // Machine Instruction Shuffler for Correctness Testing
  3144. //===----------------------------------------------------------------------===//
  3145. #ifndef NDEBUG
  3146. namespace {
  3147. /// Apply a less-than relation on the node order, which corresponds to the
  3148. /// instruction order prior to scheduling. IsReverse implements greater-than.
  3149. template<bool IsReverse>
  3150. struct SUnitOrder {
  3151. bool operator()(SUnit *A, SUnit *B) const {
  3152. if (IsReverse)
  3153. return A->NodeNum > B->NodeNum;
  3154. else
  3155. return A->NodeNum < B->NodeNum;
  3156. }
  3157. };
  3158. /// Reorder instructions as much as possible.
  3159. class InstructionShuffler : public MachineSchedStrategy {
  3160. bool IsAlternating;
  3161. bool IsTopDown;
  3162. // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
  3163. // gives nodes with a higher number higher priority causing the latest
  3164. // instructions to be scheduled first.
  3165. PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
  3166. TopQ;
  3167. // When scheduling bottom-up, use greater-than as the queue priority.
  3168. PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
  3169. BottomQ;
  3170. public:
  3171. InstructionShuffler(bool alternate, bool topdown)
  3172. : IsAlternating(alternate), IsTopDown(topdown) {}
  3173. void initialize(ScheduleDAGMI*) override {
  3174. TopQ.clear();
  3175. BottomQ.clear();
  3176. }
  3177. /// Implement MachineSchedStrategy interface.
  3178. /// -----------------------------------------
  3179. SUnit *pickNode(bool &IsTopNode) override {
  3180. SUnit *SU;
  3181. if (IsTopDown) {
  3182. do {
  3183. if (TopQ.empty()) return nullptr;
  3184. SU = TopQ.top();
  3185. TopQ.pop();
  3186. } while (SU->isScheduled);
  3187. IsTopNode = true;
  3188. } else {
  3189. do {
  3190. if (BottomQ.empty()) return nullptr;
  3191. SU = BottomQ.top();
  3192. BottomQ.pop();
  3193. } while (SU->isScheduled);
  3194. IsTopNode = false;
  3195. }
  3196. if (IsAlternating)
  3197. IsTopDown = !IsTopDown;
  3198. return SU;
  3199. }
  3200. void schedNode(SUnit *SU, bool IsTopNode) override {}
  3201. void releaseTopNode(SUnit *SU) override {
  3202. TopQ.push(SU);
  3203. }
  3204. void releaseBottomNode(SUnit *SU) override {
  3205. BottomQ.push(SU);
  3206. }
  3207. };
  3208. } // end anonymous namespace
  3209. static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
  3210. bool Alternate = !ForceTopDown && !ForceBottomUp;
  3211. bool TopDown = !ForceBottomUp;
  3212. assert((TopDown || !ForceTopDown) &&
  3213. "-misched-topdown incompatible with -misched-bottomup");
  3214. return new ScheduleDAGMILive(
  3215. C, std::make_unique<InstructionShuffler>(Alternate, TopDown));
  3216. }
  3217. static MachineSchedRegistry ShufflerRegistry(
  3218. "shuffle", "Shuffle machine instructions alternating directions",
  3219. createInstructionShuffler);
  3220. #endif // !NDEBUG
  3221. //===----------------------------------------------------------------------===//
  3222. // GraphWriter support for ScheduleDAGMILive.
  3223. //===----------------------------------------------------------------------===//
  3224. #ifndef NDEBUG
  3225. namespace llvm {
  3226. template<> struct GraphTraits<
  3227. ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
  3228. template<>
  3229. struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
  3230. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  3231. static std::string getGraphName(const ScheduleDAG *G) {
  3232. return G->MF.getName();
  3233. }
  3234. static bool renderGraphFromBottomUp() {
  3235. return true;
  3236. }
  3237. static bool isNodeHidden(const SUnit *Node) {
  3238. if (ViewMISchedCutoff == 0)
  3239. return false;
  3240. return (Node->Preds.size() > ViewMISchedCutoff
  3241. || Node->Succs.size() > ViewMISchedCutoff);
  3242. }
  3243. /// If you want to override the dot attributes printed for a particular
  3244. /// edge, override this method.
  3245. static std::string getEdgeAttributes(const SUnit *Node,
  3246. SUnitIterator EI,
  3247. const ScheduleDAG *Graph) {
  3248. if (EI.isArtificialDep())
  3249. return "color=cyan,style=dashed";
  3250. if (EI.isCtrlDep())
  3251. return "color=blue,style=dashed";
  3252. return "";
  3253. }
  3254. static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
  3255. std::string Str;
  3256. raw_string_ostream SS(Str);
  3257. const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
  3258. const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
  3259. static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
  3260. SS << "SU:" << SU->NodeNum;
  3261. if (DFS)
  3262. SS << " I:" << DFS->getNumInstrs(SU);
  3263. return SS.str();
  3264. }
  3265. static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
  3266. return G->getGraphNodeLabel(SU);
  3267. }
  3268. static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
  3269. std::string Str("shape=Mrecord");
  3270. const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
  3271. const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
  3272. static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
  3273. if (DFS) {
  3274. Str += ",style=filled,fillcolor=\"#";
  3275. Str += DOT::getColorString(DFS->getSubtreeID(N));
  3276. Str += '"';
  3277. }
  3278. return Str;
  3279. }
  3280. };
  3281. } // end namespace llvm
  3282. #endif // NDEBUG
  3283. /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
  3284. /// rendered using 'dot'.
  3285. void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
  3286. #ifndef NDEBUG
  3287. ViewGraph(this, Name, false, Title);
  3288. #else
  3289. errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
  3290. << "systems with Graphviz or gv!\n";
  3291. #endif // NDEBUG
  3292. }
  3293. /// Out-of-line implementation with no arguments is handy for gdb.
  3294. void ScheduleDAGMI::viewGraph() {
  3295. viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
  3296. }