MachineScheduler.cpp 119 KB

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