MachineScheduler.cpp 125 KB

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