MachineScheduler.cpp 130 KB

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