MachineScheduler.cpp 128 KB

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