MachineScheduler.cpp 110 KB

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