MachinePipeliner.cpp 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200
  1. //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
  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. // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
  11. //
  12. // Software pipelining (SWP) is an instruction scheduling technique for loops
  13. // that overlap loop iterations and exploits ILP via a compiler transformation.
  14. //
  15. // Swing Modulo Scheduling is an implementation of software pipelining
  16. // that generates schedules that are near optimal in terms of initiation
  17. // interval, register requirements, and stage count. See the papers:
  18. //
  19. // "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa,
  20. // A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Processings of the 1996
  21. // Conference on Parallel Architectures and Compilation Techiniques.
  22. //
  23. // "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J.
  24. // Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE
  25. // Transactions on Computers, Vol. 50, No. 3, 2001.
  26. //
  27. // "An Implementation of Swing Modulo Scheduling With Extensions for
  28. // Superblocks", by T. Lattner, Master's Thesis, University of Illinois at
  29. // Urbana-Chambpain, 2005.
  30. //
  31. //
  32. // The SMS algorithm consists of three main steps after computing the minimal
  33. // initiation interval (MII).
  34. // 1) Analyze the dependence graph and compute information about each
  35. // instruction in the graph.
  36. // 2) Order the nodes (instructions) by priority based upon the heuristics
  37. // described in the algorithm.
  38. // 3) Attempt to schedule the nodes in the specified order using the MII.
  39. //
  40. // This SMS implementation is a target-independent back-end pass. When enabled,
  41. // the pass runs just prior to the register allocation pass, while the machine
  42. // IR is in SSA form. If software pipelining is successful, then the original
  43. // loop is replaced by the optimized loop. The optimized loop contains one or
  44. // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
  45. // the instructions cannot be scheduled in a given MII, we increase the MII by
  46. // one and try again.
  47. //
  48. // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
  49. // represent loop carried dependences in the DAG as order edges to the Phi
  50. // nodes. We also perform several passes over the DAG to eliminate unnecessary
  51. // edges that inhibit the ability to pipeline. The implementation uses the
  52. // DFAPacketizer class to compute the minimum initiation interval and the check
  53. // where an instruction may be inserted in the pipelined schedule.
  54. //
  55. // In order for the SMS pass to work, several target specific hooks need to be
  56. // implemented to get information about the loop structure and to rewrite
  57. // instructions.
  58. //
  59. //===----------------------------------------------------------------------===//
  60. #include "llvm/ADT/ArrayRef.h"
  61. #include "llvm/ADT/BitVector.h"
  62. #include "llvm/ADT/DenseMap.h"
  63. #include "llvm/ADT/MapVector.h"
  64. #include "llvm/ADT/PriorityQueue.h"
  65. #include "llvm/ADT/SetVector.h"
  66. #include "llvm/ADT/SmallPtrSet.h"
  67. #include "llvm/ADT/SmallSet.h"
  68. #include "llvm/ADT/SmallVector.h"
  69. #include "llvm/ADT/Statistic.h"
  70. #include "llvm/ADT/iterator_range.h"
  71. #include "llvm/Analysis/AliasAnalysis.h"
  72. #include "llvm/Analysis/MemoryLocation.h"
  73. #include "llvm/Analysis/ValueTracking.h"
  74. #include "llvm/CodeGen/DFAPacketizer.h"
  75. #include "llvm/CodeGen/LiveIntervals.h"
  76. #include "llvm/CodeGen/MachineBasicBlock.h"
  77. #include "llvm/CodeGen/MachineDominators.h"
  78. #include "llvm/CodeGen/MachineFunction.h"
  79. #include "llvm/CodeGen/MachineFunctionPass.h"
  80. #include "llvm/CodeGen/MachineInstr.h"
  81. #include "llvm/CodeGen/MachineInstrBuilder.h"
  82. #include "llvm/CodeGen/MachineLoopInfo.h"
  83. #include "llvm/CodeGen/MachineMemOperand.h"
  84. #include "llvm/CodeGen/MachineOperand.h"
  85. #include "llvm/CodeGen/MachineRegisterInfo.h"
  86. #include "llvm/CodeGen/RegisterClassInfo.h"
  87. #include "llvm/CodeGen/RegisterPressure.h"
  88. #include "llvm/CodeGen/ScheduleDAG.h"
  89. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  90. #include "llvm/CodeGen/ScheduleDAGMutation.h"
  91. #include "llvm/CodeGen/TargetInstrInfo.h"
  92. #include "llvm/CodeGen/TargetOpcodes.h"
  93. #include "llvm/CodeGen/TargetRegisterInfo.h"
  94. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  95. #include "llvm/IR/Attributes.h"
  96. #include "llvm/IR/DebugLoc.h"
  97. #include "llvm/IR/Function.h"
  98. #include "llvm/MC/LaneBitmask.h"
  99. #include "llvm/MC/MCInstrDesc.h"
  100. #include "llvm/MC/MCInstrItineraries.h"
  101. #include "llvm/MC/MCRegisterInfo.h"
  102. #include "llvm/Pass.h"
  103. #include "llvm/Support/CommandLine.h"
  104. #include "llvm/Support/Compiler.h"
  105. #include "llvm/Support/Debug.h"
  106. #include "llvm/Support/MathExtras.h"
  107. #include "llvm/Support/raw_ostream.h"
  108. #include <algorithm>
  109. #include <cassert>
  110. #include <climits>
  111. #include <cstdint>
  112. #include <deque>
  113. #include <functional>
  114. #include <iterator>
  115. #include <map>
  116. #include <memory>
  117. #include <tuple>
  118. #include <utility>
  119. #include <vector>
  120. using namespace llvm;
  121. #define DEBUG_TYPE "pipeliner"
  122. STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
  123. STATISTIC(NumPipelined, "Number of loops software pipelined");
  124. STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
  125. /// A command line option to turn software pipelining on or off.
  126. static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
  127. cl::ZeroOrMore,
  128. cl::desc("Enable Software Pipelining"));
  129. /// A command line option to enable SWP at -Os.
  130. static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
  131. cl::desc("Enable SWP at Os."), cl::Hidden,
  132. cl::init(false));
  133. /// A command line argument to limit minimum initial interval for pipelining.
  134. static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
  135. cl::desc("Size limit for the MII."),
  136. cl::Hidden, cl::init(27));
  137. /// A command line argument to limit the number of stages in the pipeline.
  138. static cl::opt<int>
  139. SwpMaxStages("pipeliner-max-stages",
  140. cl::desc("Maximum stages allowed in the generated scheduled."),
  141. cl::Hidden, cl::init(3));
  142. /// A command line option to disable the pruning of chain dependences due to
  143. /// an unrelated Phi.
  144. static cl::opt<bool>
  145. SwpPruneDeps("pipeliner-prune-deps",
  146. cl::desc("Prune dependences between unrelated Phi nodes."),
  147. cl::Hidden, cl::init(true));
  148. /// A command line option to disable the pruning of loop carried order
  149. /// dependences.
  150. static cl::opt<bool>
  151. SwpPruneLoopCarried("pipeliner-prune-loop-carried",
  152. cl::desc("Prune loop carried order dependences."),
  153. cl::Hidden, cl::init(true));
  154. #ifndef NDEBUG
  155. static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
  156. #endif
  157. static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
  158. cl::ReallyHidden, cl::init(false),
  159. cl::ZeroOrMore, cl::desc("Ignore RecMII"));
  160. namespace {
  161. class NodeSet;
  162. class SMSchedule;
  163. /// The main class in the implementation of the target independent
  164. /// software pipeliner pass.
  165. class MachinePipeliner : public MachineFunctionPass {
  166. public:
  167. MachineFunction *MF = nullptr;
  168. const MachineLoopInfo *MLI = nullptr;
  169. const MachineDominatorTree *MDT = nullptr;
  170. const InstrItineraryData *InstrItins;
  171. const TargetInstrInfo *TII = nullptr;
  172. RegisterClassInfo RegClassInfo;
  173. #ifndef NDEBUG
  174. static int NumTries;
  175. #endif
  176. /// Cache the target analysis information about the loop.
  177. struct LoopInfo {
  178. MachineBasicBlock *TBB = nullptr;
  179. MachineBasicBlock *FBB = nullptr;
  180. SmallVector<MachineOperand, 4> BrCond;
  181. MachineInstr *LoopInductionVar = nullptr;
  182. MachineInstr *LoopCompare = nullptr;
  183. };
  184. LoopInfo LI;
  185. static char ID;
  186. MachinePipeliner() : MachineFunctionPass(ID) {
  187. initializeMachinePipelinerPass(*PassRegistry::getPassRegistry());
  188. }
  189. bool runOnMachineFunction(MachineFunction &MF) override;
  190. void getAnalysisUsage(AnalysisUsage &AU) const override {
  191. AU.addRequired<AAResultsWrapperPass>();
  192. AU.addPreserved<AAResultsWrapperPass>();
  193. AU.addRequired<MachineLoopInfo>();
  194. AU.addRequired<MachineDominatorTree>();
  195. AU.addRequired<LiveIntervals>();
  196. MachineFunctionPass::getAnalysisUsage(AU);
  197. }
  198. private:
  199. void preprocessPhiNodes(MachineBasicBlock &B);
  200. bool canPipelineLoop(MachineLoop &L);
  201. bool scheduleLoop(MachineLoop &L);
  202. bool swingModuloScheduler(MachineLoop &L);
  203. };
  204. /// This class builds the dependence graph for the instructions in a loop,
  205. /// and attempts to schedule the instructions using the SMS algorithm.
  206. class SwingSchedulerDAG : public ScheduleDAGInstrs {
  207. MachinePipeliner &Pass;
  208. /// The minimum initiation interval between iterations for this schedule.
  209. unsigned MII = 0;
  210. /// Set to true if a valid pipelined schedule is found for the loop.
  211. bool Scheduled = false;
  212. MachineLoop &Loop;
  213. LiveIntervals &LIS;
  214. const RegisterClassInfo &RegClassInfo;
  215. /// A toplogical ordering of the SUnits, which is needed for changing
  216. /// dependences and iterating over the SUnits.
  217. ScheduleDAGTopologicalSort Topo;
  218. struct NodeInfo {
  219. int ASAP = 0;
  220. int ALAP = 0;
  221. int ZeroLatencyDepth = 0;
  222. int ZeroLatencyHeight = 0;
  223. NodeInfo() = default;
  224. };
  225. /// Computed properties for each node in the graph.
  226. std::vector<NodeInfo> ScheduleInfo;
  227. enum OrderKind { BottomUp = 0, TopDown = 1 };
  228. /// Computed node ordering for scheduling.
  229. SetVector<SUnit *> NodeOrder;
  230. using NodeSetType = SmallVector<NodeSet, 8>;
  231. using ValueMapTy = DenseMap<unsigned, unsigned>;
  232. using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
  233. using InstrMapTy = DenseMap<MachineInstr *, MachineInstr *>;
  234. /// Instructions to change when emitting the final schedule.
  235. DenseMap<SUnit *, std::pair<unsigned, int64_t>> InstrChanges;
  236. /// We may create a new instruction, so remember it because it
  237. /// must be deleted when the pass is finished.
  238. SmallPtrSet<MachineInstr *, 4> NewMIs;
  239. /// Ordered list of DAG postprocessing steps.
  240. std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
  241. /// Helper class to implement Johnson's circuit finding algorithm.
  242. class Circuits {
  243. std::vector<SUnit> &SUnits;
  244. SetVector<SUnit *> Stack;
  245. BitVector Blocked;
  246. SmallVector<SmallPtrSet<SUnit *, 4>, 10> B;
  247. SmallVector<SmallVector<int, 4>, 16> AdjK;
  248. unsigned NumPaths;
  249. static unsigned MaxPaths;
  250. public:
  251. Circuits(std::vector<SUnit> &SUs)
  252. : SUnits(SUs), Blocked(SUs.size()), B(SUs.size()), AdjK(SUs.size()) {}
  253. /// Reset the data structures used in the circuit algorithm.
  254. void reset() {
  255. Stack.clear();
  256. Blocked.reset();
  257. B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
  258. NumPaths = 0;
  259. }
  260. void createAdjacencyStructure(SwingSchedulerDAG *DAG);
  261. bool circuit(int V, int S, NodeSetType &NodeSets, bool HasBackedge = false);
  262. void unblock(int U);
  263. };
  264. public:
  265. SwingSchedulerDAG(MachinePipeliner &P, MachineLoop &L, LiveIntervals &lis,
  266. const RegisterClassInfo &rci)
  267. : ScheduleDAGInstrs(*P.MF, P.MLI, false), Pass(P), Loop(L), LIS(lis),
  268. RegClassInfo(rci), Topo(SUnits, &ExitSU) {
  269. P.MF->getSubtarget().getSMSMutations(Mutations);
  270. }
  271. void schedule() override;
  272. void finishBlock() override;
  273. /// Return true if the loop kernel has been scheduled.
  274. bool hasNewSchedule() { return Scheduled; }
  275. /// Return the earliest time an instruction may be scheduled.
  276. int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
  277. /// Return the latest time an instruction my be scheduled.
  278. int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
  279. /// The mobility function, which the number of slots in which
  280. /// an instruction may be scheduled.
  281. int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
  282. /// The depth, in the dependence graph, for a node.
  283. int getDepth(SUnit *Node) { return Node->getDepth(); }
  284. /// The maximum unweighted length of a path from an arbitrary node to the
  285. /// given node in which each edge has latency 0
  286. int getZeroLatencyDepth(SUnit *Node) {
  287. return ScheduleInfo[Node->NodeNum].ZeroLatencyDepth;
  288. }
  289. /// The height, in the dependence graph, for a node.
  290. int getHeight(SUnit *Node) { return Node->getHeight(); }
  291. /// The maximum unweighted length of a path from the given node to an
  292. /// arbitrary node in which each edge has latency 0
  293. int getZeroLatencyHeight(SUnit *Node) {
  294. return ScheduleInfo[Node->NodeNum].ZeroLatencyHeight;
  295. }
  296. /// Return true if the dependence is a back-edge in the data dependence graph.
  297. /// Since the DAG doesn't contain cycles, we represent a cycle in the graph
  298. /// using an anti dependence from a Phi to an instruction.
  299. bool isBackedge(SUnit *Source, const SDep &Dep) {
  300. if (Dep.getKind() != SDep::Anti)
  301. return false;
  302. return Source->getInstr()->isPHI() || Dep.getSUnit()->getInstr()->isPHI();
  303. }
  304. bool isLoopCarriedDep(SUnit *Source, const SDep &Dep, bool isSucc = true);
  305. /// The distance function, which indicates that operation V of iteration I
  306. /// depends on operations U of iteration I-distance.
  307. unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep) {
  308. // Instructions that feed a Phi have a distance of 1. Computing larger
  309. // values for arrays requires data dependence information.
  310. if (V->getInstr()->isPHI() && Dep.getKind() == SDep::Anti)
  311. return 1;
  312. return 0;
  313. }
  314. /// Set the Minimum Initiation Interval for this schedule attempt.
  315. void setMII(unsigned mii) { MII = mii; }
  316. void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule);
  317. void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs);
  318. /// Return the new base register that was stored away for the changed
  319. /// instruction.
  320. unsigned getInstrBaseReg(SUnit *SU) {
  321. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  322. InstrChanges.find(SU);
  323. if (It != InstrChanges.end())
  324. return It->second.first;
  325. return 0;
  326. }
  327. void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
  328. Mutations.push_back(std::move(Mutation));
  329. }
  330. private:
  331. void addLoopCarriedDependences(AliasAnalysis *AA);
  332. void updatePhiDependences();
  333. void changeDependences();
  334. unsigned calculateResMII();
  335. unsigned calculateRecMII(NodeSetType &RecNodeSets);
  336. void findCircuits(NodeSetType &NodeSets);
  337. void fuseRecs(NodeSetType &NodeSets);
  338. void removeDuplicateNodes(NodeSetType &NodeSets);
  339. void computeNodeFunctions(NodeSetType &NodeSets);
  340. void registerPressureFilter(NodeSetType &NodeSets);
  341. void colocateNodeSets(NodeSetType &NodeSets);
  342. void checkNodeSets(NodeSetType &NodeSets);
  343. void groupRemainingNodes(NodeSetType &NodeSets);
  344. void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
  345. SetVector<SUnit *> &NodesAdded);
  346. void computeNodeOrder(NodeSetType &NodeSets);
  347. void checkValidNodeOrder(const NodeSetType &Circuits) const;
  348. bool schedulePipeline(SMSchedule &Schedule);
  349. void generatePipelinedLoop(SMSchedule &Schedule);
  350. void generateProlog(SMSchedule &Schedule, unsigned LastStage,
  351. MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
  352. MBBVectorTy &PrologBBs);
  353. void generateEpilog(SMSchedule &Schedule, unsigned LastStage,
  354. MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
  355. MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs);
  356. void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
  357. MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
  358. SMSchedule &Schedule, ValueMapTy *VRMap,
  359. InstrMapTy &InstrMap, unsigned LastStageNum,
  360. unsigned CurStageNum, bool IsLast);
  361. void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
  362. MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
  363. SMSchedule &Schedule, ValueMapTy *VRMap,
  364. InstrMapTy &InstrMap, unsigned LastStageNum,
  365. unsigned CurStageNum, bool IsLast);
  366. void removeDeadInstructions(MachineBasicBlock *KernelBB,
  367. MBBVectorTy &EpilogBBs);
  368. void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs,
  369. SMSchedule &Schedule);
  370. void addBranches(MBBVectorTy &PrologBBs, MachineBasicBlock *KernelBB,
  371. MBBVectorTy &EpilogBBs, SMSchedule &Schedule,
  372. ValueMapTy *VRMap);
  373. bool computeDelta(MachineInstr &MI, unsigned &Delta);
  374. void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI,
  375. unsigned Num);
  376. MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum,
  377. unsigned InstStageNum);
  378. MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum,
  379. unsigned InstStageNum,
  380. SMSchedule &Schedule);
  381. void updateInstruction(MachineInstr *NewMI, bool LastDef,
  382. unsigned CurStageNum, unsigned InstStageNum,
  383. SMSchedule &Schedule, ValueMapTy *VRMap);
  384. MachineInstr *findDefInLoop(unsigned Reg);
  385. unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal,
  386. unsigned LoopStage, ValueMapTy *VRMap,
  387. MachineBasicBlock *BB);
  388. void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum,
  389. SMSchedule &Schedule, ValueMapTy *VRMap,
  390. InstrMapTy &InstrMap);
  391. void rewriteScheduledInstr(MachineBasicBlock *BB, SMSchedule &Schedule,
  392. InstrMapTy &InstrMap, unsigned CurStageNum,
  393. unsigned PhiNum, MachineInstr *Phi,
  394. unsigned OldReg, unsigned NewReg,
  395. unsigned PrevReg = 0);
  396. bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
  397. unsigned &OffsetPos, unsigned &NewBase,
  398. int64_t &NewOffset);
  399. void postprocessDAG();
  400. };
  401. /// A NodeSet contains a set of SUnit DAG nodes with additional information
  402. /// that assigns a priority to the set.
  403. class NodeSet {
  404. SetVector<SUnit *> Nodes;
  405. bool HasRecurrence = false;
  406. unsigned RecMII = 0;
  407. int MaxMOV = 0;
  408. int MaxDepth = 0;
  409. unsigned Colocate = 0;
  410. SUnit *ExceedPressure = nullptr;
  411. unsigned Latency = 0;
  412. public:
  413. using iterator = SetVector<SUnit *>::const_iterator;
  414. NodeSet() = default;
  415. NodeSet(iterator S, iterator E) : Nodes(S, E), HasRecurrence(true) {
  416. Latency = 0;
  417. for (unsigned i = 0, e = Nodes.size(); i < e; ++i)
  418. for (const SDep &Succ : Nodes[i]->Succs)
  419. if (Nodes.count(Succ.getSUnit()))
  420. Latency += Succ.getLatency();
  421. }
  422. bool insert(SUnit *SU) { return Nodes.insert(SU); }
  423. void insert(iterator S, iterator E) { Nodes.insert(S, E); }
  424. template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
  425. return Nodes.remove_if(P);
  426. }
  427. unsigned count(SUnit *SU) const { return Nodes.count(SU); }
  428. bool hasRecurrence() { return HasRecurrence; };
  429. unsigned size() const { return Nodes.size(); }
  430. bool empty() const { return Nodes.empty(); }
  431. SUnit *getNode(unsigned i) const { return Nodes[i]; };
  432. void setRecMII(unsigned mii) { RecMII = mii; };
  433. void setColocate(unsigned c) { Colocate = c; };
  434. void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
  435. bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
  436. int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
  437. int getRecMII() { return RecMII; }
  438. /// Summarize node functions for the entire node set.
  439. void computeNodeSetInfo(SwingSchedulerDAG *SSD) {
  440. for (SUnit *SU : *this) {
  441. MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
  442. MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
  443. }
  444. }
  445. unsigned getLatency() { return Latency; }
  446. void clear() {
  447. Nodes.clear();
  448. RecMII = 0;
  449. HasRecurrence = false;
  450. MaxMOV = 0;
  451. MaxDepth = 0;
  452. Colocate = 0;
  453. ExceedPressure = nullptr;
  454. }
  455. operator SetVector<SUnit *> &() { return Nodes; }
  456. /// Sort the node sets by importance. First, rank them by recurrence MII,
  457. /// then by mobility (least mobile done first), and finally by depth.
  458. /// Each node set may contain a colocate value which is used as the first
  459. /// tie breaker, if it's set.
  460. bool operator>(const NodeSet &RHS) const {
  461. if (RecMII == RHS.RecMII) {
  462. if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
  463. return Colocate < RHS.Colocate;
  464. if (MaxMOV == RHS.MaxMOV)
  465. return MaxDepth > RHS.MaxDepth;
  466. return MaxMOV < RHS.MaxMOV;
  467. }
  468. return RecMII > RHS.RecMII;
  469. }
  470. bool operator==(const NodeSet &RHS) const {
  471. return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
  472. MaxDepth == RHS.MaxDepth;
  473. }
  474. bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
  475. iterator begin() { return Nodes.begin(); }
  476. iterator end() { return Nodes.end(); }
  477. void print(raw_ostream &os) const {
  478. os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
  479. << " depth " << MaxDepth << " col " << Colocate << "\n";
  480. for (const auto &I : Nodes)
  481. os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
  482. os << "\n";
  483. }
  484. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  485. LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
  486. #endif
  487. };
  488. /// This class repesents the scheduled code. The main data structure is a
  489. /// map from scheduled cycle to instructions. During scheduling, the
  490. /// data structure explicitly represents all stages/iterations. When
  491. /// the algorithm finshes, the schedule is collapsed into a single stage,
  492. /// which represents instructions from different loop iterations.
  493. ///
  494. /// The SMS algorithm allows negative values for cycles, so the first cycle
  495. /// in the schedule is the smallest cycle value.
  496. class SMSchedule {
  497. private:
  498. /// Map from execution cycle to instructions.
  499. DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
  500. /// Map from instruction to execution cycle.
  501. std::map<SUnit *, int> InstrToCycle;
  502. /// Map for each register and the max difference between its uses and def.
  503. /// The first element in the pair is the max difference in stages. The
  504. /// second is true if the register defines a Phi value and loop value is
  505. /// scheduled before the Phi.
  506. std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
  507. /// Keep track of the first cycle value in the schedule. It starts
  508. /// as zero, but the algorithm allows negative values.
  509. int FirstCycle = 0;
  510. /// Keep track of the last cycle value in the schedule.
  511. int LastCycle = 0;
  512. /// The initiation interval (II) for the schedule.
  513. int InitiationInterval = 0;
  514. /// Target machine information.
  515. const TargetSubtargetInfo &ST;
  516. /// Virtual register information.
  517. MachineRegisterInfo &MRI;
  518. std::unique_ptr<DFAPacketizer> Resources;
  519. public:
  520. SMSchedule(MachineFunction *mf)
  521. : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
  522. Resources(ST.getInstrInfo()->CreateTargetScheduleState(ST)) {}
  523. void reset() {
  524. ScheduledInstrs.clear();
  525. InstrToCycle.clear();
  526. RegToStageDiff.clear();
  527. FirstCycle = 0;
  528. LastCycle = 0;
  529. InitiationInterval = 0;
  530. }
  531. /// Set the initiation interval for this schedule.
  532. void setInitiationInterval(int ii) { InitiationInterval = ii; }
  533. /// Return the first cycle in the completed schedule. This
  534. /// can be a negative value.
  535. int getFirstCycle() const { return FirstCycle; }
  536. /// Return the last cycle in the finalized schedule.
  537. int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
  538. /// Return the cycle of the earliest scheduled instruction in the dependence
  539. /// chain.
  540. int earliestCycleInChain(const SDep &Dep);
  541. /// Return the cycle of the latest scheduled instruction in the dependence
  542. /// chain.
  543. int latestCycleInChain(const SDep &Dep);
  544. void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  545. int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG);
  546. bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
  547. /// Iterators for the cycle to instruction map.
  548. using sched_iterator = DenseMap<int, std::deque<SUnit *>>::iterator;
  549. using const_sched_iterator =
  550. DenseMap<int, std::deque<SUnit *>>::const_iterator;
  551. /// Return true if the instruction is scheduled at the specified stage.
  552. bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
  553. return (stageScheduled(SU) == (int)StageNum);
  554. }
  555. /// Return the stage for a scheduled instruction. Return -1 if
  556. /// the instruction has not been scheduled.
  557. int stageScheduled(SUnit *SU) const {
  558. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
  559. if (it == InstrToCycle.end())
  560. return -1;
  561. return (it->second - FirstCycle) / InitiationInterval;
  562. }
  563. /// Return the cycle for a scheduled instruction. This function normalizes
  564. /// the first cycle to be 0.
  565. unsigned cycleScheduled(SUnit *SU) const {
  566. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
  567. assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
  568. return (it->second - FirstCycle) % InitiationInterval;
  569. }
  570. /// Return the maximum stage count needed for this schedule.
  571. unsigned getMaxStageCount() {
  572. return (LastCycle - FirstCycle) / InitiationInterval;
  573. }
  574. /// Return the max. number of stages/iterations that can occur between a
  575. /// register definition and its uses.
  576. unsigned getStagesForReg(int Reg, unsigned CurStage) {
  577. std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
  578. if (CurStage > getMaxStageCount() && Stages.first == 0 && Stages.second)
  579. return 1;
  580. return Stages.first;
  581. }
  582. /// The number of stages for a Phi is a little different than other
  583. /// instructions. The minimum value computed in RegToStageDiff is 1
  584. /// because we assume the Phi is needed for at least 1 iteration.
  585. /// This is not the case if the loop value is scheduled prior to the
  586. /// Phi in the same stage. This function returns the number of stages
  587. /// or iterations needed between the Phi definition and any uses.
  588. unsigned getStagesForPhi(int Reg) {
  589. std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
  590. if (Stages.second)
  591. return Stages.first;
  592. return Stages.first - 1;
  593. }
  594. /// Return the instructions that are scheduled at the specified cycle.
  595. std::deque<SUnit *> &getInstructions(int cycle) {
  596. return ScheduledInstrs[cycle];
  597. }
  598. bool isValidSchedule(SwingSchedulerDAG *SSD);
  599. void finalizeSchedule(SwingSchedulerDAG *SSD);
  600. void orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  601. std::deque<SUnit *> &Insts);
  602. bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi);
  603. bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Inst,
  604. MachineOperand &MO);
  605. void print(raw_ostream &os) const;
  606. void dump() const;
  607. };
  608. } // end anonymous namespace
  609. unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
  610. char MachinePipeliner::ID = 0;
  611. #ifndef NDEBUG
  612. int MachinePipeliner::NumTries = 0;
  613. #endif
  614. char &llvm::MachinePipelinerID = MachinePipeliner::ID;
  615. INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
  616. "Modulo Software Pipelining", false, false)
  617. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  618. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  619. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  620. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  621. INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
  622. "Modulo Software Pipelining", false, false)
  623. /// The "main" function for implementing Swing Modulo Scheduling.
  624. bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
  625. if (skipFunction(mf.getFunction()))
  626. return false;
  627. if (!EnableSWP)
  628. return false;
  629. if (mf.getFunction().getAttributes().hasAttribute(
  630. AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
  631. !EnableSWPOptSize.getPosition())
  632. return false;
  633. MF = &mf;
  634. MLI = &getAnalysis<MachineLoopInfo>();
  635. MDT = &getAnalysis<MachineDominatorTree>();
  636. TII = MF->getSubtarget().getInstrInfo();
  637. RegClassInfo.runOnMachineFunction(*MF);
  638. for (auto &L : *MLI)
  639. scheduleLoop(*L);
  640. return false;
  641. }
  642. /// Attempt to perform the SMS algorithm on the specified loop. This function is
  643. /// the main entry point for the algorithm. The function identifies candidate
  644. /// loops, calculates the minimum initiation interval, and attempts to schedule
  645. /// the loop.
  646. bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
  647. bool Changed = false;
  648. for (auto &InnerLoop : L)
  649. Changed |= scheduleLoop(*InnerLoop);
  650. #ifndef NDEBUG
  651. // Stop trying after reaching the limit (if any).
  652. int Limit = SwpLoopLimit;
  653. if (Limit >= 0) {
  654. if (NumTries >= SwpLoopLimit)
  655. return Changed;
  656. NumTries++;
  657. }
  658. #endif
  659. if (!canPipelineLoop(L))
  660. return Changed;
  661. ++NumTrytoPipeline;
  662. Changed = swingModuloScheduler(L);
  663. return Changed;
  664. }
  665. /// Return true if the loop can be software pipelined. The algorithm is
  666. /// restricted to loops with a single basic block. Make sure that the
  667. /// branch in the loop can be analyzed.
  668. bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
  669. if (L.getNumBlocks() != 1)
  670. return false;
  671. // Check if the branch can't be understood because we can't do pipelining
  672. // if that's the case.
  673. LI.TBB = nullptr;
  674. LI.FBB = nullptr;
  675. LI.BrCond.clear();
  676. if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond))
  677. return false;
  678. LI.LoopInductionVar = nullptr;
  679. LI.LoopCompare = nullptr;
  680. if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare))
  681. return false;
  682. if (!L.getLoopPreheader())
  683. return false;
  684. // Remove any subregisters from inputs to phi nodes.
  685. preprocessPhiNodes(*L.getHeader());
  686. return true;
  687. }
  688. void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
  689. MachineRegisterInfo &MRI = MF->getRegInfo();
  690. SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
  691. for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
  692. MachineOperand &DefOp = PI.getOperand(0);
  693. assert(DefOp.getSubReg() == 0);
  694. auto *RC = MRI.getRegClass(DefOp.getReg());
  695. for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
  696. MachineOperand &RegOp = PI.getOperand(i);
  697. if (RegOp.getSubReg() == 0)
  698. continue;
  699. // If the operand uses a subregister, replace it with a new register
  700. // without subregisters, and generate a copy to the new register.
  701. unsigned NewReg = MRI.createVirtualRegister(RC);
  702. MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
  703. MachineBasicBlock::iterator At = PredB.getFirstTerminator();
  704. const DebugLoc &DL = PredB.findDebugLoc(At);
  705. auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
  706. .addReg(RegOp.getReg(), getRegState(RegOp),
  707. RegOp.getSubReg());
  708. Slots.insertMachineInstrInMaps(*Copy);
  709. RegOp.setReg(NewReg);
  710. RegOp.setSubReg(0);
  711. }
  712. }
  713. }
  714. /// The SMS algorithm consists of the following main steps:
  715. /// 1. Computation and analysis of the dependence graph.
  716. /// 2. Ordering of the nodes (instructions).
  717. /// 3. Attempt to Schedule the loop.
  718. bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
  719. assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
  720. SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo);
  721. MachineBasicBlock *MBB = L.getHeader();
  722. // The kernel should not include any terminator instructions. These
  723. // will be added back later.
  724. SMS.startBlock(MBB);
  725. // Compute the number of 'real' instructions in the basic block by
  726. // ignoring terminators.
  727. unsigned size = MBB->size();
  728. for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
  729. E = MBB->instr_end();
  730. I != E; ++I, --size)
  731. ;
  732. SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
  733. SMS.schedule();
  734. SMS.exitRegion();
  735. SMS.finishBlock();
  736. return SMS.hasNewSchedule();
  737. }
  738. /// We override the schedule function in ScheduleDAGInstrs to implement the
  739. /// scheduling part of the Swing Modulo Scheduling algorithm.
  740. void SwingSchedulerDAG::schedule() {
  741. AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
  742. buildSchedGraph(AA);
  743. addLoopCarriedDependences(AA);
  744. updatePhiDependences();
  745. Topo.InitDAGTopologicalSorting();
  746. postprocessDAG();
  747. changeDependences();
  748. DEBUG({
  749. for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  750. SUnits[su].dumpAll(this);
  751. });
  752. NodeSetType NodeSets;
  753. findCircuits(NodeSets);
  754. NodeSetType Circuits = NodeSets;
  755. // Calculate the MII.
  756. unsigned ResMII = calculateResMII();
  757. unsigned RecMII = calculateRecMII(NodeSets);
  758. fuseRecs(NodeSets);
  759. // This flag is used for testing and can cause correctness problems.
  760. if (SwpIgnoreRecMII)
  761. RecMII = 0;
  762. MII = std::max(ResMII, RecMII);
  763. DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII << ", res=" << ResMII
  764. << ")\n");
  765. // Can't schedule a loop without a valid MII.
  766. if (MII == 0)
  767. return;
  768. // Don't pipeline large loops.
  769. if (SwpMaxMii != -1 && (int)MII > SwpMaxMii)
  770. return;
  771. computeNodeFunctions(NodeSets);
  772. registerPressureFilter(NodeSets);
  773. colocateNodeSets(NodeSets);
  774. checkNodeSets(NodeSets);
  775. DEBUG({
  776. for (auto &I : NodeSets) {
  777. dbgs() << " Rec NodeSet ";
  778. I.dump();
  779. }
  780. });
  781. std::sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>());
  782. groupRemainingNodes(NodeSets);
  783. removeDuplicateNodes(NodeSets);
  784. DEBUG({
  785. for (auto &I : NodeSets) {
  786. dbgs() << " NodeSet ";
  787. I.dump();
  788. }
  789. });
  790. computeNodeOrder(NodeSets);
  791. // check for node order issues
  792. checkValidNodeOrder(Circuits);
  793. SMSchedule Schedule(Pass.MF);
  794. Scheduled = schedulePipeline(Schedule);
  795. if (!Scheduled)
  796. return;
  797. unsigned numStages = Schedule.getMaxStageCount();
  798. // No need to generate pipeline if there are no overlapped iterations.
  799. if (numStages == 0)
  800. return;
  801. // Check that the maximum stage count is less than user-defined limit.
  802. if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages)
  803. return;
  804. generatePipelinedLoop(Schedule);
  805. ++NumPipelined;
  806. }
  807. /// Clean up after the software pipeliner runs.
  808. void SwingSchedulerDAG::finishBlock() {
  809. for (MachineInstr *I : NewMIs)
  810. MF.DeleteMachineInstr(I);
  811. NewMIs.clear();
  812. // Call the superclass.
  813. ScheduleDAGInstrs::finishBlock();
  814. }
  815. /// Return the register values for the operands of a Phi instruction.
  816. /// This function assume the instruction is a Phi.
  817. static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
  818. unsigned &InitVal, unsigned &LoopVal) {
  819. assert(Phi.isPHI() && "Expecting a Phi.");
  820. InitVal = 0;
  821. LoopVal = 0;
  822. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  823. if (Phi.getOperand(i + 1).getMBB() != Loop)
  824. InitVal = Phi.getOperand(i).getReg();
  825. else
  826. LoopVal = Phi.getOperand(i).getReg();
  827. assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
  828. }
  829. /// Return the Phi register value that comes from the incoming block.
  830. static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  831. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  832. if (Phi.getOperand(i + 1).getMBB() != LoopBB)
  833. return Phi.getOperand(i).getReg();
  834. return 0;
  835. }
  836. /// Return the Phi register value that comes the loop block.
  837. static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  838. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  839. if (Phi.getOperand(i + 1).getMBB() == LoopBB)
  840. return Phi.getOperand(i).getReg();
  841. return 0;
  842. }
  843. /// Return true if SUb can be reached from SUa following the chain edges.
  844. static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
  845. SmallPtrSet<SUnit *, 8> Visited;
  846. SmallVector<SUnit *, 8> Worklist;
  847. Worklist.push_back(SUa);
  848. while (!Worklist.empty()) {
  849. const SUnit *SU = Worklist.pop_back_val();
  850. for (auto &SI : SU->Succs) {
  851. SUnit *SuccSU = SI.getSUnit();
  852. if (SI.getKind() == SDep::Order) {
  853. if (Visited.count(SuccSU))
  854. continue;
  855. if (SuccSU == SUb)
  856. return true;
  857. Worklist.push_back(SuccSU);
  858. Visited.insert(SuccSU);
  859. }
  860. }
  861. }
  862. return false;
  863. }
  864. /// Return true if the instruction causes a chain between memory
  865. /// references before and after it.
  866. static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
  867. return MI.isCall() || MI.hasUnmodeledSideEffects() ||
  868. (MI.hasOrderedMemoryRef() &&
  869. (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
  870. }
  871. /// Return the underlying objects for the memory references of an instruction.
  872. /// This function calls the code in ValueTracking, but first checks that the
  873. /// instruction has a memory operand.
  874. static void getUnderlyingObjects(MachineInstr *MI,
  875. SmallVectorImpl<Value *> &Objs,
  876. const DataLayout &DL) {
  877. if (!MI->hasOneMemOperand())
  878. return;
  879. MachineMemOperand *MM = *MI->memoperands_begin();
  880. if (!MM->getValue())
  881. return;
  882. GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL);
  883. for (Value *V : Objs) {
  884. if (!isIdentifiedObject(V)) {
  885. Objs.clear();
  886. return;
  887. }
  888. Objs.push_back(V);
  889. }
  890. }
  891. /// Add a chain edge between a load and store if the store can be an
  892. /// alias of the load on a subsequent iteration, i.e., a loop carried
  893. /// dependence. This code is very similar to the code in ScheduleDAGInstrs
  894. /// but that code doesn't create loop carried dependences.
  895. void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
  896. MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads;
  897. Value *UnknownValue =
  898. UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
  899. for (auto &SU : SUnits) {
  900. MachineInstr &MI = *SU.getInstr();
  901. if (isDependenceBarrier(MI, AA))
  902. PendingLoads.clear();
  903. else if (MI.mayLoad()) {
  904. SmallVector<Value *, 4> Objs;
  905. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  906. if (Objs.empty())
  907. Objs.push_back(UnknownValue);
  908. for (auto V : Objs) {
  909. SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
  910. SUs.push_back(&SU);
  911. }
  912. } else if (MI.mayStore()) {
  913. SmallVector<Value *, 4> Objs;
  914. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  915. if (Objs.empty())
  916. Objs.push_back(UnknownValue);
  917. for (auto V : Objs) {
  918. MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I =
  919. PendingLoads.find(V);
  920. if (I == PendingLoads.end())
  921. continue;
  922. for (auto Load : I->second) {
  923. if (isSuccOrder(Load, &SU))
  924. continue;
  925. MachineInstr &LdMI = *Load->getInstr();
  926. // First, perform the cheaper check that compares the base register.
  927. // If they are the same and the load offset is less than the store
  928. // offset, then mark the dependence as loop carried potentially.
  929. unsigned BaseReg1, BaseReg2;
  930. int64_t Offset1, Offset2;
  931. if (TII->getMemOpBaseRegImmOfs(LdMI, BaseReg1, Offset1, TRI) &&
  932. TII->getMemOpBaseRegImmOfs(MI, BaseReg2, Offset2, TRI)) {
  933. if (BaseReg1 == BaseReg2 && (int)Offset1 < (int)Offset2) {
  934. assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
  935. "What happened to the chain edge?");
  936. SDep Dep(Load, SDep::Barrier);
  937. Dep.setLatency(1);
  938. SU.addPred(Dep);
  939. continue;
  940. }
  941. }
  942. // Second, the more expensive check that uses alias analysis on the
  943. // base registers. If they alias, and the load offset is less than
  944. // the store offset, the mark the dependence as loop carried.
  945. if (!AA) {
  946. SDep Dep(Load, SDep::Barrier);
  947. Dep.setLatency(1);
  948. SU.addPred(Dep);
  949. continue;
  950. }
  951. MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
  952. MachineMemOperand *MMO2 = *MI.memoperands_begin();
  953. if (!MMO1->getValue() || !MMO2->getValue()) {
  954. SDep Dep(Load, SDep::Barrier);
  955. Dep.setLatency(1);
  956. SU.addPred(Dep);
  957. continue;
  958. }
  959. if (MMO1->getValue() == MMO2->getValue() &&
  960. MMO1->getOffset() <= MMO2->getOffset()) {
  961. SDep Dep(Load, SDep::Barrier);
  962. Dep.setLatency(1);
  963. SU.addPred(Dep);
  964. continue;
  965. }
  966. AliasResult AAResult = AA->alias(
  967. MemoryLocation(MMO1->getValue(), MemoryLocation::UnknownSize,
  968. MMO1->getAAInfo()),
  969. MemoryLocation(MMO2->getValue(), MemoryLocation::UnknownSize,
  970. MMO2->getAAInfo()));
  971. if (AAResult != NoAlias) {
  972. SDep Dep(Load, SDep::Barrier);
  973. Dep.setLatency(1);
  974. SU.addPred(Dep);
  975. }
  976. }
  977. }
  978. }
  979. }
  980. }
  981. /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
  982. /// processes dependences for PHIs. This function adds true dependences
  983. /// from a PHI to a use, and a loop carried dependence from the use to the
  984. /// PHI. The loop carried dependence is represented as an anti dependence
  985. /// edge. This function also removes chain dependences between unrelated
  986. /// PHIs.
  987. void SwingSchedulerDAG::updatePhiDependences() {
  988. SmallVector<SDep, 4> RemoveDeps;
  989. const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
  990. // Iterate over each DAG node.
  991. for (SUnit &I : SUnits) {
  992. RemoveDeps.clear();
  993. // Set to true if the instruction has an operand defined by a Phi.
  994. unsigned HasPhiUse = 0;
  995. unsigned HasPhiDef = 0;
  996. MachineInstr *MI = I.getInstr();
  997. // Iterate over each operand, and we process the definitions.
  998. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  999. MOE = MI->operands_end();
  1000. MOI != MOE; ++MOI) {
  1001. if (!MOI->isReg())
  1002. continue;
  1003. unsigned Reg = MOI->getReg();
  1004. if (MOI->isDef()) {
  1005. // If the register is used by a Phi, then create an anti dependence.
  1006. for (MachineRegisterInfo::use_instr_iterator
  1007. UI = MRI.use_instr_begin(Reg),
  1008. UE = MRI.use_instr_end();
  1009. UI != UE; ++UI) {
  1010. MachineInstr *UseMI = &*UI;
  1011. SUnit *SU = getSUnit(UseMI);
  1012. if (SU != nullptr && UseMI->isPHI()) {
  1013. if (!MI->isPHI()) {
  1014. SDep Dep(SU, SDep::Anti, Reg);
  1015. Dep.setLatency(1);
  1016. I.addPred(Dep);
  1017. } else {
  1018. HasPhiDef = Reg;
  1019. // Add a chain edge to a dependent Phi that isn't an existing
  1020. // predecessor.
  1021. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  1022. I.addPred(SDep(SU, SDep::Barrier));
  1023. }
  1024. }
  1025. }
  1026. } else if (MOI->isUse()) {
  1027. // If the register is defined by a Phi, then create a true dependence.
  1028. MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
  1029. if (DefMI == nullptr)
  1030. continue;
  1031. SUnit *SU = getSUnit(DefMI);
  1032. if (SU != nullptr && DefMI->isPHI()) {
  1033. if (!MI->isPHI()) {
  1034. SDep Dep(SU, SDep::Data, Reg);
  1035. Dep.setLatency(0);
  1036. ST.adjustSchedDependency(SU, &I, Dep);
  1037. I.addPred(Dep);
  1038. } else {
  1039. HasPhiUse = Reg;
  1040. // Add a chain edge to a dependent Phi that isn't an existing
  1041. // predecessor.
  1042. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  1043. I.addPred(SDep(SU, SDep::Barrier));
  1044. }
  1045. }
  1046. }
  1047. }
  1048. // Remove order dependences from an unrelated Phi.
  1049. if (!SwpPruneDeps)
  1050. continue;
  1051. for (auto &PI : I.Preds) {
  1052. MachineInstr *PMI = PI.getSUnit()->getInstr();
  1053. if (PMI->isPHI() && PI.getKind() == SDep::Order) {
  1054. if (I.getInstr()->isPHI()) {
  1055. if (PMI->getOperand(0).getReg() == HasPhiUse)
  1056. continue;
  1057. if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
  1058. continue;
  1059. }
  1060. RemoveDeps.push_back(PI);
  1061. }
  1062. }
  1063. for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
  1064. I.removePred(RemoveDeps[i]);
  1065. }
  1066. }
  1067. /// Iterate over each DAG node and see if we can change any dependences
  1068. /// in order to reduce the recurrence MII.
  1069. void SwingSchedulerDAG::changeDependences() {
  1070. // See if an instruction can use a value from the previous iteration.
  1071. // If so, we update the base and offset of the instruction and change
  1072. // the dependences.
  1073. for (SUnit &I : SUnits) {
  1074. unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
  1075. int64_t NewOffset = 0;
  1076. if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
  1077. NewOffset))
  1078. continue;
  1079. // Get the MI and SUnit for the instruction that defines the original base.
  1080. unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
  1081. MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
  1082. if (!DefMI)
  1083. continue;
  1084. SUnit *DefSU = getSUnit(DefMI);
  1085. if (!DefSU)
  1086. continue;
  1087. // Get the MI and SUnit for the instruction that defins the new base.
  1088. MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
  1089. if (!LastMI)
  1090. continue;
  1091. SUnit *LastSU = getSUnit(LastMI);
  1092. if (!LastSU)
  1093. continue;
  1094. if (Topo.IsReachable(&I, LastSU))
  1095. continue;
  1096. // Remove the dependence. The value now depends on a prior iteration.
  1097. SmallVector<SDep, 4> Deps;
  1098. for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
  1099. ++P)
  1100. if (P->getSUnit() == DefSU)
  1101. Deps.push_back(*P);
  1102. for (int i = 0, e = Deps.size(); i != e; i++) {
  1103. Topo.RemovePred(&I, Deps[i].getSUnit());
  1104. I.removePred(Deps[i]);
  1105. }
  1106. // Remove the chain dependence between the instructions.
  1107. Deps.clear();
  1108. for (auto &P : LastSU->Preds)
  1109. if (P.getSUnit() == &I && P.getKind() == SDep::Order)
  1110. Deps.push_back(P);
  1111. for (int i = 0, e = Deps.size(); i != e; i++) {
  1112. Topo.RemovePred(LastSU, Deps[i].getSUnit());
  1113. LastSU->removePred(Deps[i]);
  1114. }
  1115. // Add a dependence between the new instruction and the instruction
  1116. // that defines the new base.
  1117. SDep Dep(&I, SDep::Anti, NewBase);
  1118. LastSU->addPred(Dep);
  1119. // Remember the base and offset information so that we can update the
  1120. // instruction during code generation.
  1121. InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
  1122. }
  1123. }
  1124. namespace {
  1125. // FuncUnitSorter - Comparison operator used to sort instructions by
  1126. // the number of functional unit choices.
  1127. struct FuncUnitSorter {
  1128. const InstrItineraryData *InstrItins;
  1129. DenseMap<unsigned, unsigned> Resources;
  1130. FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {}
  1131. // Compute the number of functional unit alternatives needed
  1132. // at each stage, and take the minimum value. We prioritize the
  1133. // instructions by the least number of choices first.
  1134. unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
  1135. unsigned schedClass = Inst->getDesc().getSchedClass();
  1136. unsigned min = UINT_MAX;
  1137. for (const InstrStage *IS = InstrItins->beginStage(schedClass),
  1138. *IE = InstrItins->endStage(schedClass);
  1139. IS != IE; ++IS) {
  1140. unsigned funcUnits = IS->getUnits();
  1141. unsigned numAlternatives = countPopulation(funcUnits);
  1142. if (numAlternatives < min) {
  1143. min = numAlternatives;
  1144. F = funcUnits;
  1145. }
  1146. }
  1147. return min;
  1148. }
  1149. // Compute the critical resources needed by the instruction. This
  1150. // function records the functional units needed by instructions that
  1151. // must use only one functional unit. We use this as a tie breaker
  1152. // for computing the resource MII. The instrutions that require
  1153. // the same, highly used, functional unit have high priority.
  1154. void calcCriticalResources(MachineInstr &MI) {
  1155. unsigned SchedClass = MI.getDesc().getSchedClass();
  1156. for (const InstrStage *IS = InstrItins->beginStage(SchedClass),
  1157. *IE = InstrItins->endStage(SchedClass);
  1158. IS != IE; ++IS) {
  1159. unsigned FuncUnits = IS->getUnits();
  1160. if (countPopulation(FuncUnits) == 1)
  1161. Resources[FuncUnits]++;
  1162. }
  1163. }
  1164. /// Return true if IS1 has less priority than IS2.
  1165. bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
  1166. unsigned F1 = 0, F2 = 0;
  1167. unsigned MFUs1 = minFuncUnits(IS1, F1);
  1168. unsigned MFUs2 = minFuncUnits(IS2, F2);
  1169. if (MFUs1 == 1 && MFUs2 == 1)
  1170. return Resources.lookup(F1) < Resources.lookup(F2);
  1171. return MFUs1 > MFUs2;
  1172. }
  1173. };
  1174. } // end anonymous namespace
  1175. /// Calculate the resource constrained minimum initiation interval for the
  1176. /// specified loop. We use the DFA to model the resources needed for
  1177. /// each instruction, and we ignore dependences. A different DFA is created
  1178. /// for each cycle that is required. When adding a new instruction, we attempt
  1179. /// to add it to each existing DFA, until a legal space is found. If the
  1180. /// instruction cannot be reserved in an existing DFA, we create a new one.
  1181. unsigned SwingSchedulerDAG::calculateResMII() {
  1182. SmallVector<DFAPacketizer *, 8> Resources;
  1183. MachineBasicBlock *MBB = Loop.getHeader();
  1184. Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget()));
  1185. // Sort the instructions by the number of available choices for scheduling,
  1186. // least to most. Use the number of critical resources as the tie breaker.
  1187. FuncUnitSorter FUS =
  1188. FuncUnitSorter(MF.getSubtarget().getInstrItineraryData());
  1189. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  1190. E = MBB->getFirstTerminator();
  1191. I != E; ++I)
  1192. FUS.calcCriticalResources(*I);
  1193. PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
  1194. FuncUnitOrder(FUS);
  1195. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  1196. E = MBB->getFirstTerminator();
  1197. I != E; ++I)
  1198. FuncUnitOrder.push(&*I);
  1199. while (!FuncUnitOrder.empty()) {
  1200. MachineInstr *MI = FuncUnitOrder.top();
  1201. FuncUnitOrder.pop();
  1202. if (TII->isZeroCost(MI->getOpcode()))
  1203. continue;
  1204. // Attempt to reserve the instruction in an existing DFA. At least one
  1205. // DFA is needed for each cycle.
  1206. unsigned NumCycles = getSUnit(MI)->Latency;
  1207. unsigned ReservedCycles = 0;
  1208. SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin();
  1209. SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end();
  1210. for (unsigned C = 0; C < NumCycles; ++C)
  1211. while (RI != RE) {
  1212. if ((*RI++)->canReserveResources(*MI)) {
  1213. ++ReservedCycles;
  1214. break;
  1215. }
  1216. }
  1217. // Start reserving resources using existing DFAs.
  1218. for (unsigned C = 0; C < ReservedCycles; ++C) {
  1219. --RI;
  1220. (*RI)->reserveResources(*MI);
  1221. }
  1222. // Add new DFAs, if needed, to reserve resources.
  1223. for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
  1224. DFAPacketizer *NewResource =
  1225. TII->CreateTargetScheduleState(MF.getSubtarget());
  1226. assert(NewResource->canReserveResources(*MI) && "Reserve error.");
  1227. NewResource->reserveResources(*MI);
  1228. Resources.push_back(NewResource);
  1229. }
  1230. }
  1231. int Resmii = Resources.size();
  1232. // Delete the memory for each of the DFAs that were created earlier.
  1233. for (DFAPacketizer *RI : Resources) {
  1234. DFAPacketizer *D = RI;
  1235. delete D;
  1236. }
  1237. Resources.clear();
  1238. return Resmii;
  1239. }
  1240. /// Calculate the recurrence-constrainted minimum initiation interval.
  1241. /// Iterate over each circuit. Compute the delay(c) and distance(c)
  1242. /// for each circuit. The II needs to satisfy the inequality
  1243. /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
  1244. /// II that satistifies the inequality, and the RecMII is the maximum
  1245. /// of those values.
  1246. unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
  1247. unsigned RecMII = 0;
  1248. for (NodeSet &Nodes : NodeSets) {
  1249. if (Nodes.empty())
  1250. continue;
  1251. unsigned Delay = Nodes.getLatency();
  1252. unsigned Distance = 1;
  1253. // ii = ceil(delay / distance)
  1254. unsigned CurMII = (Delay + Distance - 1) / Distance;
  1255. Nodes.setRecMII(CurMII);
  1256. if (CurMII > RecMII)
  1257. RecMII = CurMII;
  1258. }
  1259. return RecMII;
  1260. }
  1261. /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  1262. /// but we do this to find the circuits, and then change them back.
  1263. static void swapAntiDependences(std::vector<SUnit> &SUnits) {
  1264. SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
  1265. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  1266. SUnit *SU = &SUnits[i];
  1267. for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
  1268. IP != EP; ++IP) {
  1269. if (IP->getKind() != SDep::Anti)
  1270. continue;
  1271. DepsAdded.push_back(std::make_pair(SU, *IP));
  1272. }
  1273. }
  1274. for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
  1275. E = DepsAdded.end();
  1276. I != E; ++I) {
  1277. // Remove this anti dependency and add one in the reverse direction.
  1278. SUnit *SU = I->first;
  1279. SDep &D = I->second;
  1280. SUnit *TargetSU = D.getSUnit();
  1281. unsigned Reg = D.getReg();
  1282. unsigned Lat = D.getLatency();
  1283. SU->removePred(D);
  1284. SDep Dep(SU, SDep::Anti, Reg);
  1285. Dep.setLatency(Lat);
  1286. TargetSU->addPred(Dep);
  1287. }
  1288. }
  1289. /// Create the adjacency structure of the nodes in the graph.
  1290. void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
  1291. SwingSchedulerDAG *DAG) {
  1292. BitVector Added(SUnits.size());
  1293. DenseMap<int, int> OutputDeps;
  1294. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  1295. Added.reset();
  1296. // Add any successor to the adjacency matrix and exclude duplicates.
  1297. for (auto &SI : SUnits[i].Succs) {
  1298. // Only create a back-edge on the first and last nodes of a dependence
  1299. // chain. This records any chains and adds them later.
  1300. if (SI.getKind() == SDep::Output) {
  1301. int N = SI.getSUnit()->NodeNum;
  1302. int BackEdge = i;
  1303. auto Dep = OutputDeps.find(BackEdge);
  1304. if (Dep != OutputDeps.end()) {
  1305. BackEdge = Dep->second;
  1306. OutputDeps.erase(Dep);
  1307. }
  1308. OutputDeps[N] = BackEdge;
  1309. }
  1310. // Do not process a boundary node and a back-edge is processed only
  1311. // if it goes to a Phi.
  1312. if (SI.getSUnit()->isBoundaryNode() ||
  1313. (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
  1314. continue;
  1315. int N = SI.getSUnit()->NodeNum;
  1316. if (!Added.test(N)) {
  1317. AdjK[i].push_back(N);
  1318. Added.set(N);
  1319. }
  1320. }
  1321. // A chain edge between a store and a load is treated as a back-edge in the
  1322. // adjacency matrix.
  1323. for (auto &PI : SUnits[i].Preds) {
  1324. if (!SUnits[i].getInstr()->mayStore() ||
  1325. !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
  1326. continue;
  1327. if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
  1328. int N = PI.getSUnit()->NodeNum;
  1329. if (!Added.test(N)) {
  1330. AdjK[i].push_back(N);
  1331. Added.set(N);
  1332. }
  1333. }
  1334. }
  1335. }
  1336. // Add back-eges in the adjacency matrix for the output dependences.
  1337. for (auto &OD : OutputDeps)
  1338. if (!Added.test(OD.second)) {
  1339. AdjK[OD.first].push_back(OD.second);
  1340. Added.set(OD.second);
  1341. }
  1342. }
  1343. /// Identify an elementary circuit in the dependence graph starting at the
  1344. /// specified node.
  1345. bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
  1346. bool HasBackedge) {
  1347. SUnit *SV = &SUnits[V];
  1348. bool F = false;
  1349. Stack.insert(SV);
  1350. Blocked.set(V);
  1351. for (auto W : AdjK[V]) {
  1352. if (NumPaths > MaxPaths)
  1353. break;
  1354. if (W < S)
  1355. continue;
  1356. if (W == S) {
  1357. if (!HasBackedge)
  1358. NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
  1359. F = true;
  1360. ++NumPaths;
  1361. break;
  1362. } else if (!Blocked.test(W)) {
  1363. if (circuit(W, S, NodeSets, W < V ? true : HasBackedge))
  1364. F = true;
  1365. }
  1366. }
  1367. if (F)
  1368. unblock(V);
  1369. else {
  1370. for (auto W : AdjK[V]) {
  1371. if (W < S)
  1372. continue;
  1373. if (B[W].count(SV) == 0)
  1374. B[W].insert(SV);
  1375. }
  1376. }
  1377. Stack.pop_back();
  1378. return F;
  1379. }
  1380. /// Unblock a node in the circuit finding algorithm.
  1381. void SwingSchedulerDAG::Circuits::unblock(int U) {
  1382. Blocked.reset(U);
  1383. SmallPtrSet<SUnit *, 4> &BU = B[U];
  1384. while (!BU.empty()) {
  1385. SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
  1386. assert(SI != BU.end() && "Invalid B set.");
  1387. SUnit *W = *SI;
  1388. BU.erase(W);
  1389. if (Blocked.test(W->NodeNum))
  1390. unblock(W->NodeNum);
  1391. }
  1392. }
  1393. /// Identify all the elementary circuits in the dependence graph using
  1394. /// Johnson's circuit algorithm.
  1395. void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
  1396. // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  1397. // but we do this to find the circuits, and then change them back.
  1398. swapAntiDependences(SUnits);
  1399. Circuits Cir(SUnits);
  1400. // Create the adjacency structure.
  1401. Cir.createAdjacencyStructure(this);
  1402. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  1403. Cir.reset();
  1404. Cir.circuit(i, i, NodeSets);
  1405. }
  1406. // Change the dependences back so that we've created a DAG again.
  1407. swapAntiDependences(SUnits);
  1408. }
  1409. /// Return true for DAG nodes that we ignore when computing the cost functions.
  1410. /// We ignore the back-edge recurrence in order to avoid unbounded recurison
  1411. /// in the calculation of the ASAP, ALAP, etc functions.
  1412. static bool ignoreDependence(const SDep &D, bool isPred) {
  1413. if (D.isArtificial())
  1414. return true;
  1415. return D.getKind() == SDep::Anti && isPred;
  1416. }
  1417. /// Compute several functions need to order the nodes for scheduling.
  1418. /// ASAP - Earliest time to schedule a node.
  1419. /// ALAP - Latest time to schedule a node.
  1420. /// MOV - Mobility function, difference between ALAP and ASAP.
  1421. /// D - Depth of each node.
  1422. /// H - Height of each node.
  1423. void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
  1424. ScheduleInfo.resize(SUnits.size());
  1425. DEBUG({
  1426. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1427. E = Topo.end();
  1428. I != E; ++I) {
  1429. SUnit *SU = &SUnits[*I];
  1430. SU->dump(this);
  1431. }
  1432. });
  1433. int maxASAP = 0;
  1434. // Compute ASAP and ZeroLatencyDepth.
  1435. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1436. E = Topo.end();
  1437. I != E; ++I) {
  1438. int asap = 0;
  1439. int zeroLatencyDepth = 0;
  1440. SUnit *SU = &SUnits[*I];
  1441. for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
  1442. EP = SU->Preds.end();
  1443. IP != EP; ++IP) {
  1444. SUnit *pred = IP->getSUnit();
  1445. if (IP->getLatency() == 0)
  1446. zeroLatencyDepth =
  1447. std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
  1448. if (ignoreDependence(*IP, true))
  1449. continue;
  1450. asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
  1451. getDistance(pred, SU, *IP) * MII));
  1452. }
  1453. maxASAP = std::max(maxASAP, asap);
  1454. ScheduleInfo[*I].ASAP = asap;
  1455. ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
  1456. }
  1457. // Compute ALAP, ZeroLatencyHeight, and MOV.
  1458. for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
  1459. E = Topo.rend();
  1460. I != E; ++I) {
  1461. int alap = maxASAP;
  1462. int zeroLatencyHeight = 0;
  1463. SUnit *SU = &SUnits[*I];
  1464. for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
  1465. ES = SU->Succs.end();
  1466. IS != ES; ++IS) {
  1467. SUnit *succ = IS->getSUnit();
  1468. if (IS->getLatency() == 0)
  1469. zeroLatencyHeight =
  1470. std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
  1471. if (ignoreDependence(*IS, true))
  1472. continue;
  1473. alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
  1474. getDistance(SU, succ, *IS) * MII));
  1475. }
  1476. ScheduleInfo[*I].ALAP = alap;
  1477. ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
  1478. }
  1479. // After computing the node functions, compute the summary for each node set.
  1480. for (NodeSet &I : NodeSets)
  1481. I.computeNodeSetInfo(this);
  1482. DEBUG({
  1483. for (unsigned i = 0; i < SUnits.size(); i++) {
  1484. dbgs() << "\tNode " << i << ":\n";
  1485. dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
  1486. dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
  1487. dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
  1488. dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
  1489. dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
  1490. dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
  1491. dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
  1492. }
  1493. });
  1494. }
  1495. /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
  1496. /// as the predecessors of the elements of NodeOrder that are not also in
  1497. /// NodeOrder.
  1498. static bool pred_L(SetVector<SUnit *> &NodeOrder,
  1499. SmallSetVector<SUnit *, 8> &Preds,
  1500. const NodeSet *S = nullptr) {
  1501. Preds.clear();
  1502. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1503. I != E; ++I) {
  1504. for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
  1505. PI != PE; ++PI) {
  1506. if (S && S->count(PI->getSUnit()) == 0)
  1507. continue;
  1508. if (ignoreDependence(*PI, true))
  1509. continue;
  1510. if (NodeOrder.count(PI->getSUnit()) == 0)
  1511. Preds.insert(PI->getSUnit());
  1512. }
  1513. // Back-edges are predecessors with an anti-dependence.
  1514. for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
  1515. ES = (*I)->Succs.end();
  1516. IS != ES; ++IS) {
  1517. if (IS->getKind() != SDep::Anti)
  1518. continue;
  1519. if (S && S->count(IS->getSUnit()) == 0)
  1520. continue;
  1521. if (NodeOrder.count(IS->getSUnit()) == 0)
  1522. Preds.insert(IS->getSUnit());
  1523. }
  1524. }
  1525. return !Preds.empty();
  1526. }
  1527. /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
  1528. /// as the successors of the elements of NodeOrder that are not also in
  1529. /// NodeOrder.
  1530. static bool succ_L(SetVector<SUnit *> &NodeOrder,
  1531. SmallSetVector<SUnit *, 8> &Succs,
  1532. const NodeSet *S = nullptr) {
  1533. Succs.clear();
  1534. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1535. I != E; ++I) {
  1536. for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
  1537. SI != SE; ++SI) {
  1538. if (S && S->count(SI->getSUnit()) == 0)
  1539. continue;
  1540. if (ignoreDependence(*SI, false))
  1541. continue;
  1542. if (NodeOrder.count(SI->getSUnit()) == 0)
  1543. Succs.insert(SI->getSUnit());
  1544. }
  1545. for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
  1546. PE = (*I)->Preds.end();
  1547. PI != PE; ++PI) {
  1548. if (PI->getKind() != SDep::Anti)
  1549. continue;
  1550. if (S && S->count(PI->getSUnit()) == 0)
  1551. continue;
  1552. if (NodeOrder.count(PI->getSUnit()) == 0)
  1553. Succs.insert(PI->getSUnit());
  1554. }
  1555. }
  1556. return !Succs.empty();
  1557. }
  1558. /// Return true if there is a path from the specified node to any of the nodes
  1559. /// in DestNodes. Keep track and return the nodes in any path.
  1560. static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
  1561. SetVector<SUnit *> &DestNodes,
  1562. SetVector<SUnit *> &Exclude,
  1563. SmallPtrSet<SUnit *, 8> &Visited) {
  1564. if (Cur->isBoundaryNode())
  1565. return false;
  1566. if (Exclude.count(Cur) != 0)
  1567. return false;
  1568. if (DestNodes.count(Cur) != 0)
  1569. return true;
  1570. if (!Visited.insert(Cur).second)
  1571. return Path.count(Cur) != 0;
  1572. bool FoundPath = false;
  1573. for (auto &SI : Cur->Succs)
  1574. FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1575. for (auto &PI : Cur->Preds)
  1576. if (PI.getKind() == SDep::Anti)
  1577. FoundPath |=
  1578. computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1579. if (FoundPath)
  1580. Path.insert(Cur);
  1581. return FoundPath;
  1582. }
  1583. /// Return true if Set1 is a subset of Set2.
  1584. template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
  1585. for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
  1586. if (Set2.count(*I) == 0)
  1587. return false;
  1588. return true;
  1589. }
  1590. /// Compute the live-out registers for the instructions in a node-set.
  1591. /// The live-out registers are those that are defined in the node-set,
  1592. /// but not used. Except for use operands of Phis.
  1593. static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
  1594. NodeSet &NS) {
  1595. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1596. MachineRegisterInfo &MRI = MF.getRegInfo();
  1597. SmallVector<RegisterMaskPair, 8> LiveOutRegs;
  1598. SmallSet<unsigned, 4> Uses;
  1599. for (SUnit *SU : NS) {
  1600. const MachineInstr *MI = SU->getInstr();
  1601. if (MI->isPHI())
  1602. continue;
  1603. for (const MachineOperand &MO : MI->operands())
  1604. if (MO.isReg() && MO.isUse()) {
  1605. unsigned Reg = MO.getReg();
  1606. if (TargetRegisterInfo::isVirtualRegister(Reg))
  1607. Uses.insert(Reg);
  1608. else if (MRI.isAllocatable(Reg))
  1609. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1610. Uses.insert(*Units);
  1611. }
  1612. }
  1613. for (SUnit *SU : NS)
  1614. for (const MachineOperand &MO : SU->getInstr()->operands())
  1615. if (MO.isReg() && MO.isDef() && !MO.isDead()) {
  1616. unsigned Reg = MO.getReg();
  1617. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  1618. if (!Uses.count(Reg))
  1619. LiveOutRegs.push_back(RegisterMaskPair(Reg,
  1620. LaneBitmask::getNone()));
  1621. } else if (MRI.isAllocatable(Reg)) {
  1622. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1623. if (!Uses.count(*Units))
  1624. LiveOutRegs.push_back(RegisterMaskPair(*Units,
  1625. LaneBitmask::getNone()));
  1626. }
  1627. }
  1628. RPTracker.addLiveRegs(LiveOutRegs);
  1629. }
  1630. /// A heuristic to filter nodes in recurrent node-sets if the register
  1631. /// pressure of a set is too high.
  1632. void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
  1633. for (auto &NS : NodeSets) {
  1634. // Skip small node-sets since they won't cause register pressure problems.
  1635. if (NS.size() <= 2)
  1636. continue;
  1637. IntervalPressure RecRegPressure;
  1638. RegPressureTracker RecRPTracker(RecRegPressure);
  1639. RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
  1640. computeLiveOuts(MF, RecRPTracker, NS);
  1641. RecRPTracker.closeBottom();
  1642. std::vector<SUnit *> SUnits(NS.begin(), NS.end());
  1643. std::sort(SUnits.begin(), SUnits.end(), [](const SUnit *A, const SUnit *B) {
  1644. return A->NodeNum > B->NodeNum;
  1645. });
  1646. for (auto &SU : SUnits) {
  1647. // Since we're computing the register pressure for a subset of the
  1648. // instructions in a block, we need to set the tracker for each
  1649. // instruction in the node-set. The tracker is set to the instruction
  1650. // just after the one we're interested in.
  1651. MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
  1652. RecRPTracker.setPos(std::next(CurInstI));
  1653. RegPressureDelta RPDelta;
  1654. ArrayRef<PressureChange> CriticalPSets;
  1655. RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
  1656. CriticalPSets,
  1657. RecRegPressure.MaxSetPressure);
  1658. if (RPDelta.Excess.isValid()) {
  1659. DEBUG(dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
  1660. << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
  1661. << ":" << RPDelta.Excess.getUnitInc());
  1662. NS.setExceedPressure(SU);
  1663. break;
  1664. }
  1665. RecRPTracker.recede();
  1666. }
  1667. }
  1668. }
  1669. /// A heuristic to colocate node sets that have the same set of
  1670. /// successors.
  1671. void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
  1672. unsigned Colocate = 0;
  1673. for (int i = 0, e = NodeSets.size(); i < e; ++i) {
  1674. NodeSet &N1 = NodeSets[i];
  1675. SmallSetVector<SUnit *, 8> S1;
  1676. if (N1.empty() || !succ_L(N1, S1))
  1677. continue;
  1678. for (int j = i + 1; j < e; ++j) {
  1679. NodeSet &N2 = NodeSets[j];
  1680. if (N1.compareRecMII(N2) != 0)
  1681. continue;
  1682. SmallSetVector<SUnit *, 8> S2;
  1683. if (N2.empty() || !succ_L(N2, S2))
  1684. continue;
  1685. if (isSubset(S1, S2) && S1.size() == S2.size()) {
  1686. N1.setColocate(++Colocate);
  1687. N2.setColocate(Colocate);
  1688. break;
  1689. }
  1690. }
  1691. }
  1692. }
  1693. /// Check if the existing node-sets are profitable. If not, then ignore the
  1694. /// recurrent node-sets, and attempt to schedule all nodes together. This is
  1695. /// a heuristic. If the MII is large and there is a non-recurrent node with
  1696. /// a large depth compared to the MII, then it's best to try and schedule
  1697. /// all instruction together instead of starting with the recurrent node-sets.
  1698. void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
  1699. // Look for loops with a large MII.
  1700. if (MII <= 20)
  1701. return;
  1702. // Check if the node-set contains only a simple add recurrence.
  1703. for (auto &NS : NodeSets)
  1704. if (NS.size() > 2)
  1705. return;
  1706. // If the depth of any instruction is significantly larger than the MII, then
  1707. // ignore the recurrent node-sets and treat all instructions equally.
  1708. for (auto &SU : SUnits)
  1709. if (SU.getDepth() > MII * 1.5) {
  1710. NodeSets.clear();
  1711. DEBUG(dbgs() << "Clear recurrence node-sets\n");
  1712. return;
  1713. }
  1714. }
  1715. /// Add the nodes that do not belong to a recurrence set into groups
  1716. /// based upon connected componenets.
  1717. void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
  1718. SetVector<SUnit *> NodesAdded;
  1719. SmallPtrSet<SUnit *, 8> Visited;
  1720. // Add the nodes that are on a path between the previous node sets and
  1721. // the current node set.
  1722. for (NodeSet &I : NodeSets) {
  1723. SmallSetVector<SUnit *, 8> N;
  1724. // Add the nodes from the current node set to the previous node set.
  1725. if (succ_L(I, N)) {
  1726. SetVector<SUnit *> Path;
  1727. for (SUnit *NI : N) {
  1728. Visited.clear();
  1729. computePath(NI, Path, NodesAdded, I, Visited);
  1730. }
  1731. if (!Path.empty())
  1732. I.insert(Path.begin(), Path.end());
  1733. }
  1734. // Add the nodes from the previous node set to the current node set.
  1735. N.clear();
  1736. if (succ_L(NodesAdded, N)) {
  1737. SetVector<SUnit *> Path;
  1738. for (SUnit *NI : N) {
  1739. Visited.clear();
  1740. computePath(NI, Path, I, NodesAdded, Visited);
  1741. }
  1742. if (!Path.empty())
  1743. I.insert(Path.begin(), Path.end());
  1744. }
  1745. NodesAdded.insert(I.begin(), I.end());
  1746. }
  1747. // Create a new node set with the connected nodes of any successor of a node
  1748. // in a recurrent set.
  1749. NodeSet NewSet;
  1750. SmallSetVector<SUnit *, 8> N;
  1751. if (succ_L(NodesAdded, N))
  1752. for (SUnit *I : N)
  1753. addConnectedNodes(I, NewSet, NodesAdded);
  1754. if (!NewSet.empty())
  1755. NodeSets.push_back(NewSet);
  1756. // Create a new node set with the connected nodes of any predecessor of a node
  1757. // in a recurrent set.
  1758. NewSet.clear();
  1759. if (pred_L(NodesAdded, N))
  1760. for (SUnit *I : N)
  1761. addConnectedNodes(I, NewSet, NodesAdded);
  1762. if (!NewSet.empty())
  1763. NodeSets.push_back(NewSet);
  1764. // Create new nodes sets with the connected nodes any any remaining node that
  1765. // has no predecessor.
  1766. for (unsigned i = 0; i < SUnits.size(); ++i) {
  1767. SUnit *SU = &SUnits[i];
  1768. if (NodesAdded.count(SU) == 0) {
  1769. NewSet.clear();
  1770. addConnectedNodes(SU, NewSet, NodesAdded);
  1771. if (!NewSet.empty())
  1772. NodeSets.push_back(NewSet);
  1773. }
  1774. }
  1775. }
  1776. /// Add the node to the set, and add all is its connected nodes to the set.
  1777. void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
  1778. SetVector<SUnit *> &NodesAdded) {
  1779. NewSet.insert(SU);
  1780. NodesAdded.insert(SU);
  1781. for (auto &SI : SU->Succs) {
  1782. SUnit *Successor = SI.getSUnit();
  1783. if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
  1784. addConnectedNodes(Successor, NewSet, NodesAdded);
  1785. }
  1786. for (auto &PI : SU->Preds) {
  1787. SUnit *Predecessor = PI.getSUnit();
  1788. if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
  1789. addConnectedNodes(Predecessor, NewSet, NodesAdded);
  1790. }
  1791. }
  1792. /// Return true if Set1 contains elements in Set2. The elements in common
  1793. /// are returned in a different container.
  1794. static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
  1795. SmallSetVector<SUnit *, 8> &Result) {
  1796. Result.clear();
  1797. for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
  1798. SUnit *SU = Set1[i];
  1799. if (Set2.count(SU) != 0)
  1800. Result.insert(SU);
  1801. }
  1802. return !Result.empty();
  1803. }
  1804. /// Merge the recurrence node sets that have the same initial node.
  1805. void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
  1806. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1807. ++I) {
  1808. NodeSet &NI = *I;
  1809. for (NodeSetType::iterator J = I + 1; J != E;) {
  1810. NodeSet &NJ = *J;
  1811. if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
  1812. if (NJ.compareRecMII(NI) > 0)
  1813. NI.setRecMII(NJ.getRecMII());
  1814. for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
  1815. ++NII)
  1816. I->insert(*NII);
  1817. NodeSets.erase(J);
  1818. E = NodeSets.end();
  1819. } else {
  1820. ++J;
  1821. }
  1822. }
  1823. }
  1824. }
  1825. /// Remove nodes that have been scheduled in previous NodeSets.
  1826. void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
  1827. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1828. ++I)
  1829. for (NodeSetType::iterator J = I + 1; J != E;) {
  1830. J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
  1831. if (J->empty()) {
  1832. NodeSets.erase(J);
  1833. E = NodeSets.end();
  1834. } else {
  1835. ++J;
  1836. }
  1837. }
  1838. }
  1839. /// Compute an ordered list of the dependence graph nodes, which
  1840. /// indicates the order that the nodes will be scheduled. This is a
  1841. /// two-level algorithm. First, a partial order is created, which
  1842. /// consists of a list of sets ordered from highest to lowest priority.
  1843. void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
  1844. SmallSetVector<SUnit *, 8> R;
  1845. NodeOrder.clear();
  1846. for (auto &Nodes : NodeSets) {
  1847. DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
  1848. OrderKind Order;
  1849. SmallSetVector<SUnit *, 8> N;
  1850. if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1851. R.insert(N.begin(), N.end());
  1852. Order = BottomUp;
  1853. DEBUG(dbgs() << " Bottom up (preds) ");
  1854. } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1855. R.insert(N.begin(), N.end());
  1856. Order = TopDown;
  1857. DEBUG(dbgs() << " Top down (succs) ");
  1858. } else if (isIntersect(N, Nodes, R)) {
  1859. // If some of the successors are in the existing node-set, then use the
  1860. // top-down ordering.
  1861. Order = TopDown;
  1862. DEBUG(dbgs() << " Top down (intersect) ");
  1863. } else if (NodeSets.size() == 1) {
  1864. for (auto &N : Nodes)
  1865. if (N->Succs.size() == 0)
  1866. R.insert(N);
  1867. Order = BottomUp;
  1868. DEBUG(dbgs() << " Bottom up (all) ");
  1869. } else {
  1870. // Find the node with the highest ASAP.
  1871. SUnit *maxASAP = nullptr;
  1872. for (SUnit *SU : Nodes) {
  1873. if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
  1874. (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
  1875. maxASAP = SU;
  1876. }
  1877. R.insert(maxASAP);
  1878. Order = BottomUp;
  1879. DEBUG(dbgs() << " Bottom up (default) ");
  1880. }
  1881. while (!R.empty()) {
  1882. if (Order == TopDown) {
  1883. // Choose the node with the maximum height. If more than one, choose
  1884. // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
  1885. // choose the node with the lowest MOV.
  1886. while (!R.empty()) {
  1887. SUnit *maxHeight = nullptr;
  1888. for (SUnit *I : R) {
  1889. if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
  1890. maxHeight = I;
  1891. else if (getHeight(I) == getHeight(maxHeight) &&
  1892. getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
  1893. maxHeight = I;
  1894. else if (getHeight(I) == getHeight(maxHeight) &&
  1895. getZeroLatencyHeight(I) ==
  1896. getZeroLatencyHeight(maxHeight) &&
  1897. getMOV(I) < getMOV(maxHeight))
  1898. maxHeight = I;
  1899. }
  1900. NodeOrder.insert(maxHeight);
  1901. DEBUG(dbgs() << maxHeight->NodeNum << " ");
  1902. R.remove(maxHeight);
  1903. for (const auto &I : maxHeight->Succs) {
  1904. if (Nodes.count(I.getSUnit()) == 0)
  1905. continue;
  1906. if (NodeOrder.count(I.getSUnit()) != 0)
  1907. continue;
  1908. if (ignoreDependence(I, false))
  1909. continue;
  1910. R.insert(I.getSUnit());
  1911. }
  1912. // Back-edges are predecessors with an anti-dependence.
  1913. for (const auto &I : maxHeight->Preds) {
  1914. if (I.getKind() != SDep::Anti)
  1915. continue;
  1916. if (Nodes.count(I.getSUnit()) == 0)
  1917. continue;
  1918. if (NodeOrder.count(I.getSUnit()) != 0)
  1919. continue;
  1920. R.insert(I.getSUnit());
  1921. }
  1922. }
  1923. Order = BottomUp;
  1924. DEBUG(dbgs() << "\n Switching order to bottom up ");
  1925. SmallSetVector<SUnit *, 8> N;
  1926. if (pred_L(NodeOrder, N, &Nodes))
  1927. R.insert(N.begin(), N.end());
  1928. } else {
  1929. // Choose the node with the maximum depth. If more than one, choose
  1930. // the node with the maximum ZeroLatencyDepth. If still more than one,
  1931. // choose the node with the lowest MOV.
  1932. while (!R.empty()) {
  1933. SUnit *maxDepth = nullptr;
  1934. for (SUnit *I : R) {
  1935. if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
  1936. maxDepth = I;
  1937. else if (getDepth(I) == getDepth(maxDepth) &&
  1938. getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
  1939. maxDepth = I;
  1940. else if (getDepth(I) == getDepth(maxDepth) &&
  1941. getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
  1942. getMOV(I) < getMOV(maxDepth))
  1943. maxDepth = I;
  1944. }
  1945. NodeOrder.insert(maxDepth);
  1946. DEBUG(dbgs() << maxDepth->NodeNum << " ");
  1947. R.remove(maxDepth);
  1948. if (Nodes.isExceedSU(maxDepth)) {
  1949. Order = TopDown;
  1950. R.clear();
  1951. R.insert(Nodes.getNode(0));
  1952. break;
  1953. }
  1954. for (const auto &I : maxDepth->Preds) {
  1955. if (Nodes.count(I.getSUnit()) == 0)
  1956. continue;
  1957. if (NodeOrder.count(I.getSUnit()) != 0)
  1958. continue;
  1959. if (I.getKind() == SDep::Anti)
  1960. continue;
  1961. R.insert(I.getSUnit());
  1962. }
  1963. // Back-edges are predecessors with an anti-dependence.
  1964. for (const auto &I : maxDepth->Succs) {
  1965. if (I.getKind() != SDep::Anti)
  1966. continue;
  1967. if (Nodes.count(I.getSUnit()) == 0)
  1968. continue;
  1969. if (NodeOrder.count(I.getSUnit()) != 0)
  1970. continue;
  1971. R.insert(I.getSUnit());
  1972. }
  1973. }
  1974. Order = TopDown;
  1975. DEBUG(dbgs() << "\n Switching order to top down ");
  1976. SmallSetVector<SUnit *, 8> N;
  1977. if (succ_L(NodeOrder, N, &Nodes))
  1978. R.insert(N.begin(), N.end());
  1979. }
  1980. }
  1981. DEBUG(dbgs() << "\nDone with Nodeset\n");
  1982. }
  1983. DEBUG({
  1984. dbgs() << "Node order: ";
  1985. for (SUnit *I : NodeOrder)
  1986. dbgs() << " " << I->NodeNum << " ";
  1987. dbgs() << "\n";
  1988. });
  1989. }
  1990. /// Process the nodes in the computed order and create the pipelined schedule
  1991. /// of the instructions, if possible. Return true if a schedule is found.
  1992. bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
  1993. if (NodeOrder.empty())
  1994. return false;
  1995. bool scheduleFound = false;
  1996. // Keep increasing II until a valid schedule is found.
  1997. for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) {
  1998. Schedule.reset();
  1999. Schedule.setInitiationInterval(II);
  2000. DEBUG(dbgs() << "Try to schedule with " << II << "\n");
  2001. SetVector<SUnit *>::iterator NI = NodeOrder.begin();
  2002. SetVector<SUnit *>::iterator NE = NodeOrder.end();
  2003. do {
  2004. SUnit *SU = *NI;
  2005. // Compute the schedule time for the instruction, which is based
  2006. // upon the scheduled time for any predecessors/successors.
  2007. int EarlyStart = INT_MIN;
  2008. int LateStart = INT_MAX;
  2009. // These values are set when the size of the schedule window is limited
  2010. // due to chain dependences.
  2011. int SchedEnd = INT_MAX;
  2012. int SchedStart = INT_MIN;
  2013. Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
  2014. II, this);
  2015. DEBUG({
  2016. dbgs() << "Inst (" << SU->NodeNum << ") ";
  2017. SU->getInstr()->dump();
  2018. dbgs() << "\n";
  2019. });
  2020. DEBUG({
  2021. dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart
  2022. << " me: " << SchedEnd << " ms: " << SchedStart << "\n";
  2023. });
  2024. if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
  2025. SchedStart > LateStart)
  2026. scheduleFound = false;
  2027. else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
  2028. SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
  2029. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  2030. } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
  2031. SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
  2032. scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
  2033. } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
  2034. SchedEnd =
  2035. std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
  2036. // When scheduling a Phi it is better to start at the late cycle and go
  2037. // backwards. The default order may insert the Phi too far away from
  2038. // its first dependence.
  2039. if (SU->getInstr()->isPHI())
  2040. scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
  2041. else
  2042. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  2043. } else {
  2044. int FirstCycle = Schedule.getFirstCycle();
  2045. scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
  2046. FirstCycle + getASAP(SU) + II - 1, II);
  2047. }
  2048. // Even if we find a schedule, make sure the schedule doesn't exceed the
  2049. // allowable number of stages. We keep trying if this happens.
  2050. if (scheduleFound)
  2051. if (SwpMaxStages > -1 &&
  2052. Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
  2053. scheduleFound = false;
  2054. DEBUG({
  2055. if (!scheduleFound)
  2056. dbgs() << "\tCan't schedule\n";
  2057. });
  2058. } while (++NI != NE && scheduleFound);
  2059. // If a schedule is found, check if it is a valid schedule too.
  2060. if (scheduleFound)
  2061. scheduleFound = Schedule.isValidSchedule(this);
  2062. }
  2063. DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n");
  2064. if (scheduleFound)
  2065. Schedule.finalizeSchedule(this);
  2066. else
  2067. Schedule.reset();
  2068. return scheduleFound && Schedule.getMaxStageCount() > 0;
  2069. }
  2070. /// Given a schedule for the loop, generate a new version of the loop,
  2071. /// and replace the old version. This function generates a prolog
  2072. /// that contains the initial iterations in the pipeline, and kernel
  2073. /// loop, and the epilogue that contains the code for the final
  2074. /// iterations.
  2075. void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
  2076. // Create a new basic block for the kernel and add it to the CFG.
  2077. MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  2078. unsigned MaxStageCount = Schedule.getMaxStageCount();
  2079. // Remember the registers that are used in different stages. The index is
  2080. // the iteration, or stage, that the instruction is scheduled in. This is
  2081. // a map between register names in the orignal block and the names created
  2082. // in each stage of the pipelined loop.
  2083. ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
  2084. InstrMapTy InstrMap;
  2085. SmallVector<MachineBasicBlock *, 4> PrologBBs;
  2086. // Generate the prolog instructions that set up the pipeline.
  2087. generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
  2088. MF.insert(BB->getIterator(), KernelBB);
  2089. // Rearrange the instructions to generate the new, pipelined loop,
  2090. // and update register names as needed.
  2091. for (int Cycle = Schedule.getFirstCycle(),
  2092. LastCycle = Schedule.getFinalCycle();
  2093. Cycle <= LastCycle; ++Cycle) {
  2094. std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
  2095. // This inner loop schedules each instruction in the cycle.
  2096. for (SUnit *CI : CycleInstrs) {
  2097. if (CI->getInstr()->isPHI())
  2098. continue;
  2099. unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
  2100. MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
  2101. updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
  2102. KernelBB->push_back(NewMI);
  2103. InstrMap[NewMI] = CI->getInstr();
  2104. }
  2105. }
  2106. // Copy any terminator instructions to the new kernel, and update
  2107. // names as needed.
  2108. for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
  2109. E = BB->instr_end();
  2110. I != E; ++I) {
  2111. MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
  2112. updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
  2113. KernelBB->push_back(NewMI);
  2114. InstrMap[NewMI] = &*I;
  2115. }
  2116. KernelBB->transferSuccessors(BB);
  2117. KernelBB->replaceSuccessor(BB, KernelBB);
  2118. generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
  2119. VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
  2120. generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
  2121. InstrMap, MaxStageCount, MaxStageCount, false);
  2122. DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
  2123. SmallVector<MachineBasicBlock *, 4> EpilogBBs;
  2124. // Generate the epilog instructions to complete the pipeline.
  2125. generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
  2126. PrologBBs);
  2127. // We need this step because the register allocation doesn't handle some
  2128. // situations well, so we insert copies to help out.
  2129. splitLifetimes(KernelBB, EpilogBBs, Schedule);
  2130. // Remove dead instructions due to loop induction variables.
  2131. removeDeadInstructions(KernelBB, EpilogBBs);
  2132. // Add branches between prolog and epilog blocks.
  2133. addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
  2134. // Remove the original loop since it's no longer referenced.
  2135. for (auto &I : *BB)
  2136. LIS.RemoveMachineInstrFromMaps(I);
  2137. BB->clear();
  2138. BB->eraseFromParent();
  2139. delete[] VRMap;
  2140. }
  2141. /// Generate the pipeline prolog code.
  2142. void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
  2143. MachineBasicBlock *KernelBB,
  2144. ValueMapTy *VRMap,
  2145. MBBVectorTy &PrologBBs) {
  2146. MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
  2147. assert(PreheaderBB != nullptr &&
  2148. "Need to add code to handle loops w/o preheader");
  2149. MachineBasicBlock *PredBB = PreheaderBB;
  2150. InstrMapTy InstrMap;
  2151. // Generate a basic block for each stage, not including the last stage,
  2152. // which will be generated in the kernel. Each basic block may contain
  2153. // instructions from multiple stages/iterations.
  2154. for (unsigned i = 0; i < LastStage; ++i) {
  2155. // Create and insert the prolog basic block prior to the original loop
  2156. // basic block. The original loop is removed later.
  2157. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  2158. PrologBBs.push_back(NewBB);
  2159. MF.insert(BB->getIterator(), NewBB);
  2160. NewBB->transferSuccessors(PredBB);
  2161. PredBB->addSuccessor(NewBB);
  2162. PredBB = NewBB;
  2163. // Generate instructions for each appropriate stage. Process instructions
  2164. // in original program order.
  2165. for (int StageNum = i; StageNum >= 0; --StageNum) {
  2166. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  2167. BBE = BB->getFirstTerminator();
  2168. BBI != BBE; ++BBI) {
  2169. if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
  2170. if (BBI->isPHI())
  2171. continue;
  2172. MachineInstr *NewMI =
  2173. cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
  2174. updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
  2175. VRMap);
  2176. NewBB->push_back(NewMI);
  2177. InstrMap[NewMI] = &*BBI;
  2178. }
  2179. }
  2180. }
  2181. rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
  2182. DEBUG({
  2183. dbgs() << "prolog:\n";
  2184. NewBB->dump();
  2185. });
  2186. }
  2187. PredBB->replaceSuccessor(BB, KernelBB);
  2188. // Check if we need to remove the branch from the preheader to the original
  2189. // loop, and replace it with a branch to the new loop.
  2190. unsigned numBranches = TII->removeBranch(*PreheaderBB);
  2191. if (numBranches) {
  2192. SmallVector<MachineOperand, 0> Cond;
  2193. TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
  2194. }
  2195. }
  2196. /// Generate the pipeline epilog code. The epilog code finishes the iterations
  2197. /// that were started in either the prolog or the kernel. We create a basic
  2198. /// block for each stage that needs to complete.
  2199. void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
  2200. MachineBasicBlock *KernelBB,
  2201. ValueMapTy *VRMap,
  2202. MBBVectorTy &EpilogBBs,
  2203. MBBVectorTy &PrologBBs) {
  2204. // We need to change the branch from the kernel to the first epilog block, so
  2205. // this call to analyze branch uses the kernel rather than the original BB.
  2206. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  2207. SmallVector<MachineOperand, 4> Cond;
  2208. bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
  2209. assert(!checkBranch && "generateEpilog must be able to analyze the branch");
  2210. if (checkBranch)
  2211. return;
  2212. MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
  2213. if (*LoopExitI == KernelBB)
  2214. ++LoopExitI;
  2215. assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
  2216. MachineBasicBlock *LoopExitBB = *LoopExitI;
  2217. MachineBasicBlock *PredBB = KernelBB;
  2218. MachineBasicBlock *EpilogStart = LoopExitBB;
  2219. InstrMapTy InstrMap;
  2220. // Generate a basic block for each stage, not including the last stage,
  2221. // which was generated for the kernel. Each basic block may contain
  2222. // instructions from multiple stages/iterations.
  2223. int EpilogStage = LastStage + 1;
  2224. for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
  2225. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
  2226. EpilogBBs.push_back(NewBB);
  2227. MF.insert(BB->getIterator(), NewBB);
  2228. PredBB->replaceSuccessor(LoopExitBB, NewBB);
  2229. NewBB->addSuccessor(LoopExitBB);
  2230. if (EpilogStart == LoopExitBB)
  2231. EpilogStart = NewBB;
  2232. // Add instructions to the epilog depending on the current block.
  2233. // Process instructions in original program order.
  2234. for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
  2235. for (auto &BBI : *BB) {
  2236. if (BBI.isPHI())
  2237. continue;
  2238. MachineInstr *In = &BBI;
  2239. if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
  2240. // Instructions with memoperands in the epilog are updated with
  2241. // conservative values.
  2242. MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
  2243. updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
  2244. NewBB->push_back(NewMI);
  2245. InstrMap[NewMI] = In;
  2246. }
  2247. }
  2248. }
  2249. generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
  2250. VRMap, InstrMap, LastStage, EpilogStage, i == 1);
  2251. generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
  2252. InstrMap, LastStage, EpilogStage, i == 1);
  2253. PredBB = NewBB;
  2254. DEBUG({
  2255. dbgs() << "epilog:\n";
  2256. NewBB->dump();
  2257. });
  2258. }
  2259. // Fix any Phi nodes in the loop exit block.
  2260. for (MachineInstr &MI : *LoopExitBB) {
  2261. if (!MI.isPHI())
  2262. break;
  2263. for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
  2264. MachineOperand &MO = MI.getOperand(i);
  2265. if (MO.getMBB() == BB)
  2266. MO.setMBB(PredBB);
  2267. }
  2268. }
  2269. // Create a branch to the new epilog from the kernel.
  2270. // Remove the original branch and add a new branch to the epilog.
  2271. TII->removeBranch(*KernelBB);
  2272. TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
  2273. // Add a branch to the loop exit.
  2274. if (EpilogBBs.size() > 0) {
  2275. MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
  2276. SmallVector<MachineOperand, 4> Cond1;
  2277. TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
  2278. }
  2279. }
  2280. /// Replace all uses of FromReg that appear outside the specified
  2281. /// basic block with ToReg.
  2282. static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
  2283. MachineBasicBlock *MBB,
  2284. MachineRegisterInfo &MRI,
  2285. LiveIntervals &LIS) {
  2286. for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
  2287. E = MRI.use_end();
  2288. I != E;) {
  2289. MachineOperand &O = *I;
  2290. ++I;
  2291. if (O.getParent()->getParent() != MBB)
  2292. O.setReg(ToReg);
  2293. }
  2294. if (!LIS.hasInterval(ToReg))
  2295. LIS.createEmptyInterval(ToReg);
  2296. }
  2297. /// Return true if the register has a use that occurs outside the
  2298. /// specified loop.
  2299. static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
  2300. MachineRegisterInfo &MRI) {
  2301. for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
  2302. E = MRI.use_end();
  2303. I != E; ++I)
  2304. if (I->getParent()->getParent() != BB)
  2305. return true;
  2306. return false;
  2307. }
  2308. /// Generate Phis for the specific block in the generated pipelined code.
  2309. /// This function looks at the Phis from the original code to guide the
  2310. /// creation of new Phis.
  2311. void SwingSchedulerDAG::generateExistingPhis(
  2312. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  2313. MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
  2314. InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
  2315. bool IsLast) {
  2316. // Compute the stage number for the initial value of the Phi, which
  2317. // comes from the prolog. The prolog to use depends on to which kernel/
  2318. // epilog that we're adding the Phi.
  2319. unsigned PrologStage = 0;
  2320. unsigned PrevStage = 0;
  2321. bool InKernel = (LastStageNum == CurStageNum);
  2322. if (InKernel) {
  2323. PrologStage = LastStageNum - 1;
  2324. PrevStage = CurStageNum;
  2325. } else {
  2326. PrologStage = LastStageNum - (CurStageNum - LastStageNum);
  2327. PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
  2328. }
  2329. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  2330. BBE = BB->getFirstNonPHI();
  2331. BBI != BBE; ++BBI) {
  2332. unsigned Def = BBI->getOperand(0).getReg();
  2333. unsigned InitVal = 0;
  2334. unsigned LoopVal = 0;
  2335. getPhiRegs(*BBI, BB, InitVal, LoopVal);
  2336. unsigned PhiOp1 = 0;
  2337. // The Phi value from the loop body typically is defined in the loop, but
  2338. // not always. So, we need to check if the value is defined in the loop.
  2339. unsigned PhiOp2 = LoopVal;
  2340. if (VRMap[LastStageNum].count(LoopVal))
  2341. PhiOp2 = VRMap[LastStageNum][LoopVal];
  2342. int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
  2343. int LoopValStage =
  2344. Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
  2345. unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
  2346. if (NumStages == 0) {
  2347. // We don't need to generate a Phi anymore, but we need to rename any uses
  2348. // of the Phi value.
  2349. unsigned NewReg = VRMap[PrevStage][LoopVal];
  2350. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
  2351. Def, InitVal, NewReg);
  2352. if (VRMap[CurStageNum].count(LoopVal))
  2353. VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
  2354. }
  2355. // Adjust the number of Phis needed depending on the number of prologs left,
  2356. // and the distance from where the Phi is first scheduled. The number of
  2357. // Phis cannot exceed the number of prolog stages. Each stage can
  2358. // potentially define two values.
  2359. unsigned MaxPhis = PrologStage + 2;
  2360. if (!InKernel && (int)PrologStage <= LoopValStage)
  2361. MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
  2362. unsigned NumPhis = std::min(NumStages, MaxPhis);
  2363. unsigned NewReg = 0;
  2364. unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
  2365. // In the epilog, we may need to look back one stage to get the correct
  2366. // Phi name because the epilog and prolog blocks execute the same stage.
  2367. // The correct name is from the previous block only when the Phi has
  2368. // been completely scheduled prior to the epilog, and Phi value is not
  2369. // needed in multiple stages.
  2370. int StageDiff = 0;
  2371. if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
  2372. NumPhis == 1)
  2373. StageDiff = 1;
  2374. // Adjust the computations below when the phi and the loop definition
  2375. // are scheduled in different stages.
  2376. if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
  2377. StageDiff = StageScheduled - LoopValStage;
  2378. for (unsigned np = 0; np < NumPhis; ++np) {
  2379. // If the Phi hasn't been scheduled, then use the initial Phi operand
  2380. // value. Otherwise, use the scheduled version of the instruction. This
  2381. // is a little complicated when a Phi references another Phi.
  2382. if (np > PrologStage || StageScheduled >= (int)LastStageNum)
  2383. PhiOp1 = InitVal;
  2384. // Check if the Phi has already been scheduled in a prolog stage.
  2385. else if (PrologStage >= AccessStage + StageDiff + np &&
  2386. VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
  2387. PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
  2388. // Check if the Phi has already been scheduled, but the loop intruction
  2389. // is either another Phi, or doesn't occur in the loop.
  2390. else if (PrologStage >= AccessStage + StageDiff + np) {
  2391. // If the Phi references another Phi, we need to examine the other
  2392. // Phi to get the correct value.
  2393. PhiOp1 = LoopVal;
  2394. MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
  2395. int Indirects = 1;
  2396. while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
  2397. int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
  2398. if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
  2399. PhiOp1 = getInitPhiReg(*InstOp1, BB);
  2400. else
  2401. PhiOp1 = getLoopPhiReg(*InstOp1, BB);
  2402. InstOp1 = MRI.getVRegDef(PhiOp1);
  2403. int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
  2404. int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
  2405. if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
  2406. VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
  2407. PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
  2408. break;
  2409. }
  2410. ++Indirects;
  2411. }
  2412. } else
  2413. PhiOp1 = InitVal;
  2414. // If this references a generated Phi in the kernel, get the Phi operand
  2415. // from the incoming block.
  2416. if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
  2417. if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
  2418. PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
  2419. MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
  2420. bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
  2421. // In the epilog, a map lookup is needed to get the value from the kernel,
  2422. // or previous epilog block. How is does this depends on if the
  2423. // instruction is scheduled in the previous block.
  2424. if (!InKernel) {
  2425. int StageDiffAdj = 0;
  2426. if (LoopValStage != -1 && StageScheduled > LoopValStage)
  2427. StageDiffAdj = StageScheduled - LoopValStage;
  2428. // Use the loop value defined in the kernel, unless the kernel
  2429. // contains the last definition of the Phi.
  2430. if (np == 0 && PrevStage == LastStageNum &&
  2431. (StageScheduled != 0 || LoopValStage != 0) &&
  2432. VRMap[PrevStage - StageDiffAdj].count(LoopVal))
  2433. PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
  2434. // Use the value defined by the Phi. We add one because we switch
  2435. // from looking at the loop value to the Phi definition.
  2436. else if (np > 0 && PrevStage == LastStageNum &&
  2437. VRMap[PrevStage - np + 1].count(Def))
  2438. PhiOp2 = VRMap[PrevStage - np + 1][Def];
  2439. // Use the loop value defined in the kernel.
  2440. else if ((unsigned)LoopValStage + StageDiffAdj > PrologStage + 1 &&
  2441. VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
  2442. PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
  2443. // Use the value defined by the Phi, unless we're generating the first
  2444. // epilog and the Phi refers to a Phi in a different stage.
  2445. else if (VRMap[PrevStage - np].count(Def) &&
  2446. (!LoopDefIsPhi || PrevStage != LastStageNum))
  2447. PhiOp2 = VRMap[PrevStage - np][Def];
  2448. }
  2449. // Check if we can reuse an existing Phi. This occurs when a Phi
  2450. // references another Phi, and the other Phi is scheduled in an
  2451. // earlier stage. We can try to reuse an existing Phi up until the last
  2452. // stage of the current Phi.
  2453. if (LoopDefIsPhi && (int)(PrologStage - np) >= StageScheduled) {
  2454. int LVNumStages = Schedule.getStagesForPhi(LoopVal);
  2455. int StageDiff = (StageScheduled - LoopValStage);
  2456. LVNumStages -= StageDiff;
  2457. // Make sure the loop value Phi has been processed already.
  2458. if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
  2459. NewReg = PhiOp2;
  2460. unsigned ReuseStage = CurStageNum;
  2461. if (Schedule.isLoopCarried(this, *PhiInst))
  2462. ReuseStage -= LVNumStages;
  2463. // Check if the Phi to reuse has been generated yet. If not, then
  2464. // there is nothing to reuse.
  2465. if (VRMap[ReuseStage - np].count(LoopVal)) {
  2466. NewReg = VRMap[ReuseStage - np][LoopVal];
  2467. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2468. &*BBI, Def, NewReg);
  2469. // Update the map with the new Phi name.
  2470. VRMap[CurStageNum - np][Def] = NewReg;
  2471. PhiOp2 = NewReg;
  2472. if (VRMap[LastStageNum - np - 1].count(LoopVal))
  2473. PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
  2474. if (IsLast && np == NumPhis - 1)
  2475. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2476. continue;
  2477. }
  2478. } else if (InKernel && StageDiff > 0 &&
  2479. VRMap[CurStageNum - StageDiff - np].count(LoopVal))
  2480. PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
  2481. }
  2482. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  2483. NewReg = MRI.createVirtualRegister(RC);
  2484. MachineInstrBuilder NewPhi =
  2485. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  2486. TII->get(TargetOpcode::PHI), NewReg);
  2487. NewPhi.addReg(PhiOp1).addMBB(BB1);
  2488. NewPhi.addReg(PhiOp2).addMBB(BB2);
  2489. if (np == 0)
  2490. InstrMap[NewPhi] = &*BBI;
  2491. // We define the Phis after creating the new pipelined code, so
  2492. // we need to rename the Phi values in scheduled instructions.
  2493. unsigned PrevReg = 0;
  2494. if (InKernel && VRMap[PrevStage - np].count(LoopVal))
  2495. PrevReg = VRMap[PrevStage - np][LoopVal];
  2496. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
  2497. Def, NewReg, PrevReg);
  2498. // If the Phi has been scheduled, use the new name for rewriting.
  2499. if (VRMap[CurStageNum - np].count(Def)) {
  2500. unsigned R = VRMap[CurStageNum - np][Def];
  2501. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
  2502. R, NewReg);
  2503. }
  2504. // Check if we need to rename any uses that occurs after the loop. The
  2505. // register to replace depends on whether the Phi is scheduled in the
  2506. // epilog.
  2507. if (IsLast && np == NumPhis - 1)
  2508. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2509. // In the kernel, a dependent Phi uses the value from this Phi.
  2510. if (InKernel)
  2511. PhiOp2 = NewReg;
  2512. // Update the map with the new Phi name.
  2513. VRMap[CurStageNum - np][Def] = NewReg;
  2514. }
  2515. while (NumPhis++ < NumStages) {
  2516. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
  2517. &*BBI, Def, NewReg, 0);
  2518. }
  2519. // Check if we need to rename a Phi that has been eliminated due to
  2520. // scheduling.
  2521. if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
  2522. replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
  2523. }
  2524. }
  2525. /// Generate Phis for the specified block in the generated pipelined code.
  2526. /// These are new Phis needed because the definition is scheduled after the
  2527. /// use in the pipelened sequence.
  2528. void SwingSchedulerDAG::generatePhis(
  2529. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  2530. MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
  2531. InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
  2532. bool IsLast) {
  2533. // Compute the stage number that contains the initial Phi value, and
  2534. // the Phi from the previous stage.
  2535. unsigned PrologStage = 0;
  2536. unsigned PrevStage = 0;
  2537. unsigned StageDiff = CurStageNum - LastStageNum;
  2538. bool InKernel = (StageDiff == 0);
  2539. if (InKernel) {
  2540. PrologStage = LastStageNum - 1;
  2541. PrevStage = CurStageNum;
  2542. } else {
  2543. PrologStage = LastStageNum - StageDiff;
  2544. PrevStage = LastStageNum + StageDiff - 1;
  2545. }
  2546. for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
  2547. BBE = BB->instr_end();
  2548. BBI != BBE; ++BBI) {
  2549. for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
  2550. MachineOperand &MO = BBI->getOperand(i);
  2551. if (!MO.isReg() || !MO.isDef() ||
  2552. !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2553. continue;
  2554. int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
  2555. assert(StageScheduled != -1 && "Expecting scheduled instruction.");
  2556. unsigned Def = MO.getReg();
  2557. unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
  2558. // An instruction scheduled in stage 0 and is used after the loop
  2559. // requires a phi in the epilog for the last definition from either
  2560. // the kernel or prolog.
  2561. if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
  2562. hasUseAfterLoop(Def, BB, MRI))
  2563. NumPhis = 1;
  2564. if (!InKernel && (unsigned)StageScheduled > PrologStage)
  2565. continue;
  2566. unsigned PhiOp2 = VRMap[PrevStage][Def];
  2567. if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
  2568. if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
  2569. PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
  2570. // The number of Phis can't exceed the number of prolog stages. The
  2571. // prolog stage number is zero based.
  2572. if (NumPhis > PrologStage + 1 - StageScheduled)
  2573. NumPhis = PrologStage + 1 - StageScheduled;
  2574. for (unsigned np = 0; np < NumPhis; ++np) {
  2575. unsigned PhiOp1 = VRMap[PrologStage][Def];
  2576. if (np <= PrologStage)
  2577. PhiOp1 = VRMap[PrologStage - np][Def];
  2578. if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
  2579. if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
  2580. PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
  2581. if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
  2582. PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
  2583. }
  2584. if (!InKernel)
  2585. PhiOp2 = VRMap[PrevStage - np][Def];
  2586. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  2587. unsigned NewReg = MRI.createVirtualRegister(RC);
  2588. MachineInstrBuilder NewPhi =
  2589. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  2590. TII->get(TargetOpcode::PHI), NewReg);
  2591. NewPhi.addReg(PhiOp1).addMBB(BB1);
  2592. NewPhi.addReg(PhiOp2).addMBB(BB2);
  2593. if (np == 0)
  2594. InstrMap[NewPhi] = &*BBI;
  2595. // Rewrite uses and update the map. The actions depend upon whether
  2596. // we generating code for the kernel or epilog blocks.
  2597. if (InKernel) {
  2598. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2599. &*BBI, PhiOp1, NewReg);
  2600. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2601. &*BBI, PhiOp2, NewReg);
  2602. PhiOp2 = NewReg;
  2603. VRMap[PrevStage - np - 1][Def] = NewReg;
  2604. } else {
  2605. VRMap[CurStageNum - np][Def] = NewReg;
  2606. if (np == NumPhis - 1)
  2607. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2608. &*BBI, Def, NewReg);
  2609. }
  2610. if (IsLast && np == NumPhis - 1)
  2611. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2612. }
  2613. }
  2614. }
  2615. }
  2616. /// Remove instructions that generate values with no uses.
  2617. /// Typically, these are induction variable operations that generate values
  2618. /// used in the loop itself. A dead instruction has a definition with
  2619. /// no uses, or uses that occur in the original loop only.
  2620. void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
  2621. MBBVectorTy &EpilogBBs) {
  2622. // For each epilog block, check that the value defined by each instruction
  2623. // is used. If not, delete it.
  2624. for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
  2625. MBE = EpilogBBs.rend();
  2626. MBB != MBE; ++MBB)
  2627. for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
  2628. ME = (*MBB)->instr_rend();
  2629. MI != ME;) {
  2630. // From DeadMachineInstructionElem. Don't delete inline assembly.
  2631. if (MI->isInlineAsm()) {
  2632. ++MI;
  2633. continue;
  2634. }
  2635. bool SawStore = false;
  2636. // Check if it's safe to remove the instruction due to side effects.
  2637. // We can, and want to, remove Phis here.
  2638. if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
  2639. ++MI;
  2640. continue;
  2641. }
  2642. bool used = true;
  2643. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  2644. MOE = MI->operands_end();
  2645. MOI != MOE; ++MOI) {
  2646. if (!MOI->isReg() || !MOI->isDef())
  2647. continue;
  2648. unsigned reg = MOI->getReg();
  2649. // Assume physical registers are used, unless they are marked dead.
  2650. if (TargetRegisterInfo::isPhysicalRegister(reg)) {
  2651. used = !MOI->isDead();
  2652. if (used)
  2653. break;
  2654. continue;
  2655. }
  2656. unsigned realUses = 0;
  2657. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
  2658. EI = MRI.use_end();
  2659. UI != EI; ++UI) {
  2660. // Check if there are any uses that occur only in the original
  2661. // loop. If so, that's not a real use.
  2662. if (UI->getParent()->getParent() != BB) {
  2663. realUses++;
  2664. used = true;
  2665. break;
  2666. }
  2667. }
  2668. if (realUses > 0)
  2669. break;
  2670. used = false;
  2671. }
  2672. if (!used) {
  2673. LIS.RemoveMachineInstrFromMaps(*MI);
  2674. MI++->eraseFromParent();
  2675. continue;
  2676. }
  2677. ++MI;
  2678. }
  2679. // In the kernel block, check if we can remove a Phi that generates a value
  2680. // used in an instruction removed in the epilog block.
  2681. for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
  2682. BBE = KernelBB->getFirstNonPHI();
  2683. BBI != BBE;) {
  2684. MachineInstr *MI = &*BBI;
  2685. ++BBI;
  2686. unsigned reg = MI->getOperand(0).getReg();
  2687. if (MRI.use_begin(reg) == MRI.use_end()) {
  2688. LIS.RemoveMachineInstrFromMaps(*MI);
  2689. MI->eraseFromParent();
  2690. }
  2691. }
  2692. }
  2693. /// For loop carried definitions, we split the lifetime of a virtual register
  2694. /// that has uses past the definition in the next iteration. A copy with a new
  2695. /// virtual register is inserted before the definition, which helps with
  2696. /// generating a better register assignment.
  2697. ///
  2698. /// v1 = phi(a, v2) v1 = phi(a, v2)
  2699. /// v2 = phi(b, v3) v2 = phi(b, v3)
  2700. /// v3 = .. v4 = copy v1
  2701. /// .. = V1 v3 = ..
  2702. /// .. = v4
  2703. void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
  2704. MBBVectorTy &EpilogBBs,
  2705. SMSchedule &Schedule) {
  2706. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2707. for (auto &PHI : KernelBB->phis()) {
  2708. unsigned Def = PHI.getOperand(0).getReg();
  2709. // Check for any Phi definition that used as an operand of another Phi
  2710. // in the same block.
  2711. for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
  2712. E = MRI.use_instr_end();
  2713. I != E; ++I) {
  2714. if (I->isPHI() && I->getParent() == KernelBB) {
  2715. // Get the loop carried definition.
  2716. unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
  2717. if (!LCDef)
  2718. continue;
  2719. MachineInstr *MI = MRI.getVRegDef(LCDef);
  2720. if (!MI || MI->getParent() != KernelBB || MI->isPHI())
  2721. continue;
  2722. // Search through the rest of the block looking for uses of the Phi
  2723. // definition. If one occurs, then split the lifetime.
  2724. unsigned SplitReg = 0;
  2725. for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
  2726. KernelBB->instr_end()))
  2727. if (BBJ.readsRegister(Def)) {
  2728. // We split the lifetime when we find the first use.
  2729. if (SplitReg == 0) {
  2730. SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
  2731. BuildMI(*KernelBB, MI, MI->getDebugLoc(),
  2732. TII->get(TargetOpcode::COPY), SplitReg)
  2733. .addReg(Def);
  2734. }
  2735. BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
  2736. }
  2737. if (!SplitReg)
  2738. continue;
  2739. // Search through each of the epilog blocks for any uses to be renamed.
  2740. for (auto &Epilog : EpilogBBs)
  2741. for (auto &I : *Epilog)
  2742. if (I.readsRegister(Def))
  2743. I.substituteRegister(Def, SplitReg, 0, *TRI);
  2744. break;
  2745. }
  2746. }
  2747. }
  2748. }
  2749. /// Remove the incoming block from the Phis in a basic block.
  2750. static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
  2751. for (MachineInstr &MI : *BB) {
  2752. if (!MI.isPHI())
  2753. break;
  2754. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
  2755. if (MI.getOperand(i + 1).getMBB() == Incoming) {
  2756. MI.RemoveOperand(i + 1);
  2757. MI.RemoveOperand(i);
  2758. break;
  2759. }
  2760. }
  2761. }
  2762. /// Create branches from each prolog basic block to the appropriate epilog
  2763. /// block. These edges are needed if the loop ends before reaching the
  2764. /// kernel.
  2765. void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
  2766. MachineBasicBlock *KernelBB,
  2767. MBBVectorTy &EpilogBBs,
  2768. SMSchedule &Schedule, ValueMapTy *VRMap) {
  2769. assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
  2770. MachineInstr *IndVar = Pass.LI.LoopInductionVar;
  2771. MachineInstr *Cmp = Pass.LI.LoopCompare;
  2772. MachineBasicBlock *LastPro = KernelBB;
  2773. MachineBasicBlock *LastEpi = KernelBB;
  2774. // Start from the blocks connected to the kernel and work "out"
  2775. // to the first prolog and the last epilog blocks.
  2776. SmallVector<MachineInstr *, 4> PrevInsts;
  2777. unsigned MaxIter = PrologBBs.size() - 1;
  2778. unsigned LC = UINT_MAX;
  2779. unsigned LCMin = UINT_MAX;
  2780. for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
  2781. // Add branches to the prolog that go to the corresponding
  2782. // epilog, and the fall-thru prolog/kernel block.
  2783. MachineBasicBlock *Prolog = PrologBBs[j];
  2784. MachineBasicBlock *Epilog = EpilogBBs[i];
  2785. // We've executed one iteration, so decrement the loop count and check for
  2786. // the loop end.
  2787. SmallVector<MachineOperand, 4> Cond;
  2788. // Check if the LOOP0 has already been removed. If so, then there is no need
  2789. // to reduce the trip count.
  2790. if (LC != 0)
  2791. LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j,
  2792. MaxIter);
  2793. // Record the value of the first trip count, which is used to determine if
  2794. // branches and blocks can be removed for constant trip counts.
  2795. if (LCMin == UINT_MAX)
  2796. LCMin = LC;
  2797. unsigned numAdded = 0;
  2798. if (TargetRegisterInfo::isVirtualRegister(LC)) {
  2799. Prolog->addSuccessor(Epilog);
  2800. numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
  2801. } else if (j >= LCMin) {
  2802. Prolog->addSuccessor(Epilog);
  2803. Prolog->removeSuccessor(LastPro);
  2804. LastEpi->removeSuccessor(Epilog);
  2805. numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
  2806. removePhis(Epilog, LastEpi);
  2807. // Remove the blocks that are no longer referenced.
  2808. if (LastPro != LastEpi) {
  2809. LastEpi->clear();
  2810. LastEpi->eraseFromParent();
  2811. }
  2812. LastPro->clear();
  2813. LastPro->eraseFromParent();
  2814. } else {
  2815. numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
  2816. removePhis(Epilog, Prolog);
  2817. }
  2818. LastPro = Prolog;
  2819. LastEpi = Epilog;
  2820. for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
  2821. E = Prolog->instr_rend();
  2822. I != E && numAdded > 0; ++I, --numAdded)
  2823. updateInstruction(&*I, false, j, 0, Schedule, VRMap);
  2824. }
  2825. }
  2826. /// Return true if we can compute the amount the instruction changes
  2827. /// during each iteration. Set Delta to the amount of the change.
  2828. bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
  2829. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2830. unsigned BaseReg;
  2831. int64_t Offset;
  2832. if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
  2833. return false;
  2834. MachineRegisterInfo &MRI = MF.getRegInfo();
  2835. // Check if there is a Phi. If so, get the definition in the loop.
  2836. MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
  2837. if (BaseDef && BaseDef->isPHI()) {
  2838. BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
  2839. BaseDef = MRI.getVRegDef(BaseReg);
  2840. }
  2841. if (!BaseDef)
  2842. return false;
  2843. int D = 0;
  2844. if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
  2845. return false;
  2846. Delta = D;
  2847. return true;
  2848. }
  2849. /// Update the memory operand with a new offset when the pipeliner
  2850. /// generates a new copy of the instruction that refers to a
  2851. /// different memory location.
  2852. void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
  2853. MachineInstr &OldMI, unsigned Num) {
  2854. if (Num == 0)
  2855. return;
  2856. // If the instruction has memory operands, then adjust the offset
  2857. // when the instruction appears in different stages.
  2858. unsigned NumRefs = NewMI.memoperands_end() - NewMI.memoperands_begin();
  2859. if (NumRefs == 0)
  2860. return;
  2861. MachineInstr::mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NumRefs);
  2862. unsigned Refs = 0;
  2863. for (MachineMemOperand *MMO : NewMI.memoperands()) {
  2864. if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) ||
  2865. (!MMO->getValue())) {
  2866. NewMemRefs[Refs++] = MMO;
  2867. continue;
  2868. }
  2869. unsigned Delta;
  2870. if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
  2871. int64_t AdjOffset = Delta * Num;
  2872. NewMemRefs[Refs++] =
  2873. MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize());
  2874. } else {
  2875. NewMI.dropMemRefs();
  2876. return;
  2877. }
  2878. }
  2879. NewMI.setMemRefs(NewMemRefs, NewMemRefs + NumRefs);
  2880. }
  2881. /// Clone the instruction for the new pipelined loop and update the
  2882. /// memory operands, if needed.
  2883. MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
  2884. unsigned CurStageNum,
  2885. unsigned InstStageNum) {
  2886. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2887. // Check for tied operands in inline asm instructions. This should be handled
  2888. // elsewhere, but I'm not sure of the best solution.
  2889. if (OldMI->isInlineAsm())
  2890. for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
  2891. const auto &MO = OldMI->getOperand(i);
  2892. if (MO.isReg() && MO.isUse())
  2893. break;
  2894. unsigned UseIdx;
  2895. if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
  2896. NewMI->tieOperands(i, UseIdx);
  2897. }
  2898. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2899. return NewMI;
  2900. }
  2901. /// Clone the instruction for the new pipelined loop. If needed, this
  2902. /// function updates the instruction using the values saved in the
  2903. /// InstrChanges structure.
  2904. MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
  2905. unsigned CurStageNum,
  2906. unsigned InstStageNum,
  2907. SMSchedule &Schedule) {
  2908. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2909. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  2910. InstrChanges.find(getSUnit(OldMI));
  2911. if (It != InstrChanges.end()) {
  2912. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  2913. unsigned BasePos, OffsetPos;
  2914. if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
  2915. return nullptr;
  2916. int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
  2917. MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
  2918. if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
  2919. NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
  2920. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  2921. }
  2922. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2923. return NewMI;
  2924. }
  2925. /// Update the machine instruction with new virtual registers. This
  2926. /// function may change the defintions and/or uses.
  2927. void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
  2928. unsigned CurStageNum,
  2929. unsigned InstrStageNum,
  2930. SMSchedule &Schedule,
  2931. ValueMapTy *VRMap) {
  2932. for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
  2933. MachineOperand &MO = NewMI->getOperand(i);
  2934. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2935. continue;
  2936. unsigned reg = MO.getReg();
  2937. if (MO.isDef()) {
  2938. // Create a new virtual register for the definition.
  2939. const TargetRegisterClass *RC = MRI.getRegClass(reg);
  2940. unsigned NewReg = MRI.createVirtualRegister(RC);
  2941. MO.setReg(NewReg);
  2942. VRMap[CurStageNum][reg] = NewReg;
  2943. if (LastDef)
  2944. replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
  2945. } else if (MO.isUse()) {
  2946. MachineInstr *Def = MRI.getVRegDef(reg);
  2947. // Compute the stage that contains the last definition for instruction.
  2948. int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
  2949. unsigned StageNum = CurStageNum;
  2950. if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
  2951. // Compute the difference in stages between the defintion and the use.
  2952. unsigned StageDiff = (InstrStageNum - DefStageNum);
  2953. // Make an adjustment to get the last definition.
  2954. StageNum -= StageDiff;
  2955. }
  2956. if (VRMap[StageNum].count(reg))
  2957. MO.setReg(VRMap[StageNum][reg]);
  2958. }
  2959. }
  2960. }
  2961. /// Return the instruction in the loop that defines the register.
  2962. /// If the definition is a Phi, then follow the Phi operand to
  2963. /// the instruction in the loop.
  2964. MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
  2965. SmallPtrSet<MachineInstr *, 8> Visited;
  2966. MachineInstr *Def = MRI.getVRegDef(Reg);
  2967. while (Def->isPHI()) {
  2968. if (!Visited.insert(Def).second)
  2969. break;
  2970. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
  2971. if (Def->getOperand(i + 1).getMBB() == BB) {
  2972. Def = MRI.getVRegDef(Def->getOperand(i).getReg());
  2973. break;
  2974. }
  2975. }
  2976. return Def;
  2977. }
  2978. /// Return the new name for the value from the previous stage.
  2979. unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
  2980. unsigned LoopVal, unsigned LoopStage,
  2981. ValueMapTy *VRMap,
  2982. MachineBasicBlock *BB) {
  2983. unsigned PrevVal = 0;
  2984. if (StageNum > PhiStage) {
  2985. MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
  2986. if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
  2987. // The name is defined in the previous stage.
  2988. PrevVal = VRMap[StageNum - 1][LoopVal];
  2989. else if (VRMap[StageNum].count(LoopVal))
  2990. // The previous name is defined in the current stage when the instruction
  2991. // order is swapped.
  2992. PrevVal = VRMap[StageNum][LoopVal];
  2993. else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
  2994. // The loop value hasn't yet been scheduled.
  2995. PrevVal = LoopVal;
  2996. else if (StageNum == PhiStage + 1)
  2997. // The loop value is another phi, which has not been scheduled.
  2998. PrevVal = getInitPhiReg(*LoopInst, BB);
  2999. else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
  3000. // The loop value is another phi, which has been scheduled.
  3001. PrevVal =
  3002. getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
  3003. LoopStage, VRMap, BB);
  3004. }
  3005. return PrevVal;
  3006. }
  3007. /// Rewrite the Phi values in the specified block to use the mappings
  3008. /// from the initial operand. Once the Phi is scheduled, we switch
  3009. /// to using the loop value instead of the Phi value, so those names
  3010. /// do not need to be rewritten.
  3011. void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
  3012. unsigned StageNum,
  3013. SMSchedule &Schedule,
  3014. ValueMapTy *VRMap,
  3015. InstrMapTy &InstrMap) {
  3016. for (auto &PHI : BB->phis()) {
  3017. unsigned InitVal = 0;
  3018. unsigned LoopVal = 0;
  3019. getPhiRegs(PHI, BB, InitVal, LoopVal);
  3020. unsigned PhiDef = PHI.getOperand(0).getReg();
  3021. unsigned PhiStage =
  3022. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
  3023. unsigned LoopStage =
  3024. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
  3025. unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
  3026. if (NumPhis > StageNum)
  3027. NumPhis = StageNum;
  3028. for (unsigned np = 0; np <= NumPhis; ++np) {
  3029. unsigned NewVal =
  3030. getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
  3031. if (!NewVal)
  3032. NewVal = InitVal;
  3033. rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
  3034. PhiDef, NewVal);
  3035. }
  3036. }
  3037. }
  3038. /// Rewrite a previously scheduled instruction to use the register value
  3039. /// from the new instruction. Make sure the instruction occurs in the
  3040. /// basic block, and we don't change the uses in the new instruction.
  3041. void SwingSchedulerDAG::rewriteScheduledInstr(
  3042. MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
  3043. unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
  3044. unsigned NewReg, unsigned PrevReg) {
  3045. bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
  3046. int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
  3047. // Rewrite uses that have been scheduled already to use the new
  3048. // Phi register.
  3049. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
  3050. EI = MRI.use_end();
  3051. UI != EI;) {
  3052. MachineOperand &UseOp = *UI;
  3053. MachineInstr *UseMI = UseOp.getParent();
  3054. ++UI;
  3055. if (UseMI->getParent() != BB)
  3056. continue;
  3057. if (UseMI->isPHI()) {
  3058. if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
  3059. continue;
  3060. if (getLoopPhiReg(*UseMI, BB) != OldReg)
  3061. continue;
  3062. }
  3063. InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
  3064. assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
  3065. SUnit *OrigMISU = getSUnit(OrigInstr->second);
  3066. int StageSched = Schedule.stageScheduled(OrigMISU);
  3067. int CycleSched = Schedule.cycleScheduled(OrigMISU);
  3068. unsigned ReplaceReg = 0;
  3069. // This is the stage for the scheduled instruction.
  3070. if (StagePhi == StageSched && Phi->isPHI()) {
  3071. int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
  3072. if (PrevReg && InProlog)
  3073. ReplaceReg = PrevReg;
  3074. else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
  3075. (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
  3076. ReplaceReg = PrevReg;
  3077. else
  3078. ReplaceReg = NewReg;
  3079. }
  3080. // The scheduled instruction occurs before the scheduled Phi, and the
  3081. // Phi is not loop carried.
  3082. if (!InProlog && StagePhi + 1 == StageSched &&
  3083. !Schedule.isLoopCarried(this, *Phi))
  3084. ReplaceReg = NewReg;
  3085. if (StagePhi > StageSched && Phi->isPHI())
  3086. ReplaceReg = NewReg;
  3087. if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
  3088. ReplaceReg = NewReg;
  3089. if (ReplaceReg) {
  3090. MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
  3091. UseOp.setReg(ReplaceReg);
  3092. }
  3093. }
  3094. }
  3095. /// Check if we can change the instruction to use an offset value from the
  3096. /// previous iteration. If so, return true and set the base and offset values
  3097. /// so that we can rewrite the load, if necessary.
  3098. /// v1 = Phi(v0, v3)
  3099. /// v2 = load v1, 0
  3100. /// v3 = post_store v1, 4, x
  3101. /// This function enables the load to be rewritten as v2 = load v3, 4.
  3102. bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
  3103. unsigned &BasePos,
  3104. unsigned &OffsetPos,
  3105. unsigned &NewBase,
  3106. int64_t &Offset) {
  3107. // Get the load instruction.
  3108. if (TII->isPostIncrement(*MI))
  3109. return false;
  3110. unsigned BasePosLd, OffsetPosLd;
  3111. if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
  3112. return false;
  3113. unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
  3114. // Look for the Phi instruction.
  3115. MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
  3116. MachineInstr *Phi = MRI.getVRegDef(BaseReg);
  3117. if (!Phi || !Phi->isPHI())
  3118. return false;
  3119. // Get the register defined in the loop block.
  3120. unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
  3121. if (!PrevReg)
  3122. return false;
  3123. // Check for the post-increment load/store instruction.
  3124. MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
  3125. if (!PrevDef || PrevDef == MI)
  3126. return false;
  3127. if (!TII->isPostIncrement(*PrevDef))
  3128. return false;
  3129. unsigned BasePos1 = 0, OffsetPos1 = 0;
  3130. if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
  3131. return false;
  3132. // Make sure that the instructions do not access the same memory location in
  3133. // the next iteration.
  3134. int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
  3135. int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
  3136. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3137. NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
  3138. bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
  3139. MF.DeleteMachineInstr(NewMI);
  3140. if (!Disjoint)
  3141. return false;
  3142. // Set the return value once we determine that we return true.
  3143. BasePos = BasePosLd;
  3144. OffsetPos = OffsetPosLd;
  3145. NewBase = PrevReg;
  3146. Offset = StoreOffset;
  3147. return true;
  3148. }
  3149. /// Apply changes to the instruction if needed. The changes are need
  3150. /// to improve the scheduling and depend up on the final schedule.
  3151. void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
  3152. SMSchedule &Schedule) {
  3153. SUnit *SU = getSUnit(MI);
  3154. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  3155. InstrChanges.find(SU);
  3156. if (It != InstrChanges.end()) {
  3157. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  3158. unsigned BasePos, OffsetPos;
  3159. if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  3160. return;
  3161. unsigned BaseReg = MI->getOperand(BasePos).getReg();
  3162. MachineInstr *LoopDef = findDefInLoop(BaseReg);
  3163. int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
  3164. int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
  3165. int BaseStageNum = Schedule.stageScheduled(SU);
  3166. int BaseCycleNum = Schedule.cycleScheduled(SU);
  3167. if (BaseStageNum < DefStageNum) {
  3168. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3169. int OffsetDiff = DefStageNum - BaseStageNum;
  3170. if (DefCycleNum < BaseCycleNum) {
  3171. NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
  3172. if (OffsetDiff > 0)
  3173. --OffsetDiff;
  3174. }
  3175. int64_t NewOffset =
  3176. MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
  3177. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  3178. SU->setInstr(NewMI);
  3179. MISUnitMap[NewMI] = SU;
  3180. NewMIs.insert(NewMI);
  3181. }
  3182. }
  3183. }
  3184. /// Return true for an order or output dependence that is loop carried
  3185. /// potentially. A dependence is loop carried if the destination defines a valu
  3186. /// that may be used or defined by the source in a subsequent iteration.
  3187. bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
  3188. bool isSucc) {
  3189. if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
  3190. Dep.isArtificial())
  3191. return false;
  3192. if (!SwpPruneLoopCarried)
  3193. return true;
  3194. if (Dep.getKind() == SDep::Output)
  3195. return true;
  3196. MachineInstr *SI = Source->getInstr();
  3197. MachineInstr *DI = Dep.getSUnit()->getInstr();
  3198. if (!isSucc)
  3199. std::swap(SI, DI);
  3200. assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
  3201. // Assume ordered loads and stores may have a loop carried dependence.
  3202. if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
  3203. SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
  3204. return true;
  3205. // Only chain dependences between a load and store can be loop carried.
  3206. if (!DI->mayStore() || !SI->mayLoad())
  3207. return false;
  3208. unsigned DeltaS, DeltaD;
  3209. if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
  3210. return true;
  3211. unsigned BaseRegS, BaseRegD;
  3212. int64_t OffsetS, OffsetD;
  3213. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  3214. if (!TII->getMemOpBaseRegImmOfs(*SI, BaseRegS, OffsetS, TRI) ||
  3215. !TII->getMemOpBaseRegImmOfs(*DI, BaseRegD, OffsetD, TRI))
  3216. return true;
  3217. if (BaseRegS != BaseRegD)
  3218. return true;
  3219. uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
  3220. uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
  3221. // This is the main test, which checks the offset values and the loop
  3222. // increment value to determine if the accesses may be loop carried.
  3223. if (OffsetS >= OffsetD)
  3224. return OffsetS + AccessSizeS > DeltaS;
  3225. else
  3226. return OffsetD + AccessSizeD > DeltaD;
  3227. return true;
  3228. }
  3229. void SwingSchedulerDAG::postprocessDAG() {
  3230. for (auto &M : Mutations)
  3231. M->apply(this);
  3232. }
  3233. /// Try to schedule the node at the specified StartCycle and continue
  3234. /// until the node is schedule or the EndCycle is reached. This function
  3235. /// returns true if the node is scheduled. This routine may search either
  3236. /// forward or backward for a place to insert the instruction based upon
  3237. /// the relative values of StartCycle and EndCycle.
  3238. bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
  3239. bool forward = true;
  3240. if (StartCycle > EndCycle)
  3241. forward = false;
  3242. // The terminating condition depends on the direction.
  3243. int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
  3244. for (int curCycle = StartCycle; curCycle != termCycle;
  3245. forward ? ++curCycle : --curCycle) {
  3246. // Add the already scheduled instructions at the specified cycle to the DFA.
  3247. Resources->clearResources();
  3248. for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
  3249. checkCycle <= LastCycle; checkCycle += II) {
  3250. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
  3251. for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
  3252. E = cycleInstrs.end();
  3253. I != E; ++I) {
  3254. if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
  3255. continue;
  3256. assert(Resources->canReserveResources(*(*I)->getInstr()) &&
  3257. "These instructions have already been scheduled.");
  3258. Resources->reserveResources(*(*I)->getInstr());
  3259. }
  3260. }
  3261. if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
  3262. Resources->canReserveResources(*SU->getInstr())) {
  3263. DEBUG({
  3264. dbgs() << "\tinsert at cycle " << curCycle << " ";
  3265. SU->getInstr()->dump();
  3266. });
  3267. ScheduledInstrs[curCycle].push_back(SU);
  3268. InstrToCycle.insert(std::make_pair(SU, curCycle));
  3269. if (curCycle > LastCycle)
  3270. LastCycle = curCycle;
  3271. if (curCycle < FirstCycle)
  3272. FirstCycle = curCycle;
  3273. return true;
  3274. }
  3275. DEBUG({
  3276. dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
  3277. SU->getInstr()->dump();
  3278. });
  3279. }
  3280. return false;
  3281. }
  3282. // Return the cycle of the earliest scheduled instruction in the chain.
  3283. int SMSchedule::earliestCycleInChain(const SDep &Dep) {
  3284. SmallPtrSet<SUnit *, 8> Visited;
  3285. SmallVector<SDep, 8> Worklist;
  3286. Worklist.push_back(Dep);
  3287. int EarlyCycle = INT_MAX;
  3288. while (!Worklist.empty()) {
  3289. const SDep &Cur = Worklist.pop_back_val();
  3290. SUnit *PrevSU = Cur.getSUnit();
  3291. if (Visited.count(PrevSU))
  3292. continue;
  3293. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
  3294. if (it == InstrToCycle.end())
  3295. continue;
  3296. EarlyCycle = std::min(EarlyCycle, it->second);
  3297. for (const auto &PI : PrevSU->Preds)
  3298. if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  3299. Worklist.push_back(PI);
  3300. Visited.insert(PrevSU);
  3301. }
  3302. return EarlyCycle;
  3303. }
  3304. // Return the cycle of the latest scheduled instruction in the chain.
  3305. int SMSchedule::latestCycleInChain(const SDep &Dep) {
  3306. SmallPtrSet<SUnit *, 8> Visited;
  3307. SmallVector<SDep, 8> Worklist;
  3308. Worklist.push_back(Dep);
  3309. int LateCycle = INT_MIN;
  3310. while (!Worklist.empty()) {
  3311. const SDep &Cur = Worklist.pop_back_val();
  3312. SUnit *SuccSU = Cur.getSUnit();
  3313. if (Visited.count(SuccSU))
  3314. continue;
  3315. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
  3316. if (it == InstrToCycle.end())
  3317. continue;
  3318. LateCycle = std::max(LateCycle, it->second);
  3319. for (const auto &SI : SuccSU->Succs)
  3320. if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  3321. Worklist.push_back(SI);
  3322. Visited.insert(SuccSU);
  3323. }
  3324. return LateCycle;
  3325. }
  3326. /// If an instruction has a use that spans multiple iterations, then
  3327. /// return true. These instructions are characterized by having a back-ege
  3328. /// to a Phi, which contains a reference to another Phi.
  3329. static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
  3330. for (auto &P : SU->Preds)
  3331. if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
  3332. for (auto &S : P.getSUnit()->Succs)
  3333. if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
  3334. return P.getSUnit();
  3335. return nullptr;
  3336. }
  3337. /// Compute the scheduling start slot for the instruction. The start slot
  3338. /// depends on any predecessor or successor nodes scheduled already.
  3339. void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  3340. int *MinEnd, int *MaxStart, int II,
  3341. SwingSchedulerDAG *DAG) {
  3342. // Iterate over each instruction that has been scheduled already. The start
  3343. // slot computuation depends on whether the previously scheduled instruction
  3344. // is a predecessor or successor of the specified instruction.
  3345. for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
  3346. // Iterate over each instruction in the current cycle.
  3347. for (SUnit *I : getInstructions(cycle)) {
  3348. // Because we're processing a DAG for the dependences, we recognize
  3349. // the back-edge in recurrences by anti dependences.
  3350. for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
  3351. const SDep &Dep = SU->Preds[i];
  3352. if (Dep.getSUnit() == I) {
  3353. if (!DAG->isBackedge(SU, Dep)) {
  3354. int EarlyStart = cycle + Dep.getLatency() -
  3355. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3356. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3357. if (DAG->isLoopCarriedDep(SU, Dep, false)) {
  3358. int End = earliestCycleInChain(Dep) + (II - 1);
  3359. *MinEnd = std::min(*MinEnd, End);
  3360. }
  3361. } else {
  3362. int LateStart = cycle - Dep.getLatency() +
  3363. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3364. *MinLateStart = std::min(*MinLateStart, LateStart);
  3365. }
  3366. }
  3367. // For instruction that requires multiple iterations, make sure that
  3368. // the dependent instruction is not scheduled past the definition.
  3369. SUnit *BE = multipleIterations(I, DAG);
  3370. if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
  3371. !SU->isPred(I))
  3372. *MinLateStart = std::min(*MinLateStart, cycle);
  3373. }
  3374. for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
  3375. if (SU->Succs[i].getSUnit() == I) {
  3376. const SDep &Dep = SU->Succs[i];
  3377. if (!DAG->isBackedge(SU, Dep)) {
  3378. int LateStart = cycle - Dep.getLatency() +
  3379. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3380. *MinLateStart = std::min(*MinLateStart, LateStart);
  3381. if (DAG->isLoopCarriedDep(SU, Dep)) {
  3382. int Start = latestCycleInChain(Dep) + 1 - II;
  3383. *MaxStart = std::max(*MaxStart, Start);
  3384. }
  3385. } else {
  3386. int EarlyStart = cycle + Dep.getLatency() -
  3387. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3388. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3389. }
  3390. }
  3391. }
  3392. }
  3393. }
  3394. }
  3395. /// Order the instructions within a cycle so that the definitions occur
  3396. /// before the uses. Returns true if the instruction is added to the start
  3397. /// of the list, or false if added to the end.
  3398. void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  3399. std::deque<SUnit *> &Insts) {
  3400. MachineInstr *MI = SU->getInstr();
  3401. bool OrderBeforeUse = false;
  3402. bool OrderAfterDef = false;
  3403. bool OrderBeforeDef = false;
  3404. unsigned MoveDef = 0;
  3405. unsigned MoveUse = 0;
  3406. int StageInst1 = stageScheduled(SU);
  3407. unsigned Pos = 0;
  3408. for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
  3409. ++I, ++Pos) {
  3410. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3411. MachineOperand &MO = MI->getOperand(i);
  3412. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  3413. continue;
  3414. unsigned Reg = MO.getReg();
  3415. unsigned BasePos, OffsetPos;
  3416. if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  3417. if (MI->getOperand(BasePos).getReg() == Reg)
  3418. if (unsigned NewReg = SSD->getInstrBaseReg(SU))
  3419. Reg = NewReg;
  3420. bool Reads, Writes;
  3421. std::tie(Reads, Writes) =
  3422. (*I)->getInstr()->readsWritesVirtualRegister(Reg);
  3423. if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
  3424. OrderBeforeUse = true;
  3425. if (MoveUse == 0)
  3426. MoveUse = Pos;
  3427. } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
  3428. // Add the instruction after the scheduled instruction.
  3429. OrderAfterDef = true;
  3430. MoveDef = Pos;
  3431. } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
  3432. if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
  3433. OrderBeforeUse = true;
  3434. if (MoveUse == 0)
  3435. MoveUse = Pos;
  3436. } else {
  3437. OrderAfterDef = true;
  3438. MoveDef = Pos;
  3439. }
  3440. } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
  3441. OrderBeforeUse = true;
  3442. if (MoveUse == 0)
  3443. MoveUse = Pos;
  3444. if (MoveUse != 0) {
  3445. OrderAfterDef = true;
  3446. MoveDef = Pos - 1;
  3447. }
  3448. } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
  3449. // Add the instruction before the scheduled instruction.
  3450. OrderBeforeUse = true;
  3451. if (MoveUse == 0)
  3452. MoveUse = Pos;
  3453. } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
  3454. isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
  3455. if (MoveUse == 0) {
  3456. OrderBeforeDef = true;
  3457. MoveUse = Pos;
  3458. }
  3459. }
  3460. }
  3461. // Check for order dependences between instructions. Make sure the source
  3462. // is ordered before the destination.
  3463. for (auto &S : SU->Succs) {
  3464. if (S.getSUnit() != *I)
  3465. continue;
  3466. if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3467. OrderBeforeUse = true;
  3468. if (Pos < MoveUse)
  3469. MoveUse = Pos;
  3470. }
  3471. }
  3472. for (auto &P : SU->Preds) {
  3473. if (P.getSUnit() != *I)
  3474. continue;
  3475. if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3476. OrderAfterDef = true;
  3477. MoveDef = Pos;
  3478. }
  3479. }
  3480. }
  3481. // A circular dependence.
  3482. if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
  3483. OrderBeforeUse = false;
  3484. // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
  3485. // to a loop-carried dependence.
  3486. if (OrderBeforeDef)
  3487. OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
  3488. // The uncommon case when the instruction order needs to be updated because
  3489. // there is both a use and def.
  3490. if (OrderBeforeUse && OrderAfterDef) {
  3491. SUnit *UseSU = Insts.at(MoveUse);
  3492. SUnit *DefSU = Insts.at(MoveDef);
  3493. if (MoveUse > MoveDef) {
  3494. Insts.erase(Insts.begin() + MoveUse);
  3495. Insts.erase(Insts.begin() + MoveDef);
  3496. } else {
  3497. Insts.erase(Insts.begin() + MoveDef);
  3498. Insts.erase(Insts.begin() + MoveUse);
  3499. }
  3500. orderDependence(SSD, UseSU, Insts);
  3501. orderDependence(SSD, SU, Insts);
  3502. orderDependence(SSD, DefSU, Insts);
  3503. return;
  3504. }
  3505. // Put the new instruction first if there is a use in the list. Otherwise,
  3506. // put it at the end of the list.
  3507. if (OrderBeforeUse)
  3508. Insts.push_front(SU);
  3509. else
  3510. Insts.push_back(SU);
  3511. }
  3512. /// Return true if the scheduled Phi has a loop carried operand.
  3513. bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
  3514. if (!Phi.isPHI())
  3515. return false;
  3516. assert(Phi.isPHI() && "Expecing a Phi.");
  3517. SUnit *DefSU = SSD->getSUnit(&Phi);
  3518. unsigned DefCycle = cycleScheduled(DefSU);
  3519. int DefStage = stageScheduled(DefSU);
  3520. unsigned InitVal = 0;
  3521. unsigned LoopVal = 0;
  3522. getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
  3523. SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
  3524. if (!UseSU)
  3525. return true;
  3526. if (UseSU->getInstr()->isPHI())
  3527. return true;
  3528. unsigned LoopCycle = cycleScheduled(UseSU);
  3529. int LoopStage = stageScheduled(UseSU);
  3530. return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
  3531. }
  3532. /// Return true if the instruction is a definition that is loop carried
  3533. /// and defines the use on the next iteration.
  3534. /// v1 = phi(v2, v3)
  3535. /// (Def) v3 = op v1
  3536. /// (MO) = v1
  3537. /// If MO appears before Def, then then v1 and v3 may get assigned to the same
  3538. /// register.
  3539. bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
  3540. MachineInstr *Def, MachineOperand &MO) {
  3541. if (!MO.isReg())
  3542. return false;
  3543. if (Def->isPHI())
  3544. return false;
  3545. MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
  3546. if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
  3547. return false;
  3548. if (!isLoopCarried(SSD, *Phi))
  3549. return false;
  3550. unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
  3551. for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
  3552. MachineOperand &DMO = Def->getOperand(i);
  3553. if (!DMO.isReg() || !DMO.isDef())
  3554. continue;
  3555. if (DMO.getReg() == LoopReg)
  3556. return true;
  3557. }
  3558. return false;
  3559. }
  3560. // Check if the generated schedule is valid. This function checks if
  3561. // an instruction that uses a physical register is scheduled in a
  3562. // different stage than the definition. The pipeliner does not handle
  3563. // physical register values that may cross a basic block boundary.
  3564. bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
  3565. for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
  3566. SUnit &SU = SSD->SUnits[i];
  3567. if (!SU.hasPhysRegDefs)
  3568. continue;
  3569. int StageDef = stageScheduled(&SU);
  3570. assert(StageDef != -1 && "Instruction should have been scheduled.");
  3571. for (auto &SI : SU.Succs)
  3572. if (SI.isAssignedRegDep())
  3573. if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
  3574. if (stageScheduled(SI.getSUnit()) != StageDef)
  3575. return false;
  3576. }
  3577. return true;
  3578. }
  3579. /// A property of the node order in swing-modulo-scheduling is
  3580. /// that for nodes outside circuits the following holds:
  3581. /// none of them is scheduled after both a successor and a
  3582. /// predecessor.
  3583. /// The method below checks whether the property is met.
  3584. /// If not, debug information is printed and statistics information updated.
  3585. /// Note that we do not use an assert statement.
  3586. /// The reason is that although an invalid node oder may prevent
  3587. /// the pipeliner from finding a pipelined schedule for arbitrary II,
  3588. /// it does not lead to the generation of incorrect code.
  3589. void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
  3590. // a sorted vector that maps each SUnit to its index in the NodeOrder
  3591. typedef std::pair<SUnit *, unsigned> UnitIndex;
  3592. std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
  3593. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
  3594. Indices.push_back(std::make_pair(NodeOrder[i], i));
  3595. auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
  3596. return std::get<0>(i1) < std::get<0>(i2);
  3597. };
  3598. // sort, so that we can perform a binary search
  3599. std::sort(Indices.begin(), Indices.end(), CompareKey);
  3600. bool Valid = true;
  3601. (void)Valid;
  3602. // for each SUnit in the NodeOrder, check whether
  3603. // it appears after both a successor and a predecessor
  3604. // of the SUnit. If this is the case, and the SUnit
  3605. // is not part of circuit, then the NodeOrder is not
  3606. // valid.
  3607. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
  3608. SUnit *SU = NodeOrder[i];
  3609. unsigned Index = i;
  3610. bool PredBefore = false;
  3611. bool SuccBefore = false;
  3612. SUnit *Succ;
  3613. SUnit *Pred;
  3614. (void)Succ;
  3615. (void)Pred;
  3616. for (SDep &PredEdge : SU->Preds) {
  3617. SUnit *PredSU = PredEdge.getSUnit();
  3618. unsigned PredIndex =
  3619. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3620. std::make_pair(PredSU, 0), CompareKey));
  3621. if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
  3622. PredBefore = true;
  3623. Pred = PredSU;
  3624. break;
  3625. }
  3626. }
  3627. for (SDep &SuccEdge : SU->Succs) {
  3628. SUnit *SuccSU = SuccEdge.getSUnit();
  3629. unsigned SuccIndex =
  3630. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3631. std::make_pair(SuccSU, 0), CompareKey));
  3632. if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
  3633. SuccBefore = true;
  3634. Succ = SuccSU;
  3635. break;
  3636. }
  3637. }
  3638. if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
  3639. // instructions in circuits are allowed to be scheduled
  3640. // after both a successor and predecessor.
  3641. bool InCircuit = std::any_of(
  3642. Circuits.begin(), Circuits.end(),
  3643. [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
  3644. if (InCircuit)
  3645. DEBUG(dbgs() << "In a circuit, predecessor ";);
  3646. else {
  3647. Valid = false;
  3648. NumNodeOrderIssues++;
  3649. DEBUG(dbgs() << "Predecessor ";);
  3650. }
  3651. DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
  3652. << " are scheduled before node " << SU->NodeNum << "\n";);
  3653. }
  3654. }
  3655. DEBUG({
  3656. if (!Valid)
  3657. dbgs() << "Invalid node order found!\n";
  3658. });
  3659. }
  3660. /// Attempt to fix the degenerate cases when the instruction serialization
  3661. /// causes the register lifetimes to overlap. For example,
  3662. /// p' = store_pi(p, b)
  3663. /// = load p, offset
  3664. /// In this case p and p' overlap, which means that two registers are needed.
  3665. /// Instead, this function changes the load to use p' and updates the offset.
  3666. void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
  3667. unsigned OverlapReg = 0;
  3668. unsigned NewBaseReg = 0;
  3669. for (SUnit *SU : Instrs) {
  3670. MachineInstr *MI = SU->getInstr();
  3671. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3672. const MachineOperand &MO = MI->getOperand(i);
  3673. // Look for an instruction that uses p. The instruction occurs in the
  3674. // same cycle but occurs later in the serialized order.
  3675. if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
  3676. // Check that the instruction appears in the InstrChanges structure,
  3677. // which contains instructions that can have the offset updated.
  3678. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  3679. InstrChanges.find(SU);
  3680. if (It != InstrChanges.end()) {
  3681. unsigned BasePos, OffsetPos;
  3682. // Update the base register and adjust the offset.
  3683. if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
  3684. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3685. NewMI->getOperand(BasePos).setReg(NewBaseReg);
  3686. int64_t NewOffset =
  3687. MI->getOperand(OffsetPos).getImm() - It->second.second;
  3688. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  3689. SU->setInstr(NewMI);
  3690. MISUnitMap[NewMI] = SU;
  3691. NewMIs.insert(NewMI);
  3692. }
  3693. }
  3694. OverlapReg = 0;
  3695. NewBaseReg = 0;
  3696. break;
  3697. }
  3698. // Look for an instruction of the form p' = op(p), which uses and defines
  3699. // two virtual registers that get allocated to the same physical register.
  3700. unsigned TiedUseIdx = 0;
  3701. if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
  3702. // OverlapReg is p in the example above.
  3703. OverlapReg = MI->getOperand(TiedUseIdx).getReg();
  3704. // NewBaseReg is p' in the example above.
  3705. NewBaseReg = MI->getOperand(i).getReg();
  3706. break;
  3707. }
  3708. }
  3709. }
  3710. }
  3711. /// After the schedule has been formed, call this function to combine
  3712. /// the instructions from the different stages/cycles. That is, this
  3713. /// function creates a schedule that represents a single iteration.
  3714. void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
  3715. // Move all instructions to the first stage from later stages.
  3716. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3717. for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
  3718. ++stage) {
  3719. std::deque<SUnit *> &cycleInstrs =
  3720. ScheduledInstrs[cycle + (stage * InitiationInterval)];
  3721. for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
  3722. E = cycleInstrs.rend();
  3723. I != E; ++I)
  3724. ScheduledInstrs[cycle].push_front(*I);
  3725. }
  3726. }
  3727. // Iterate over the definitions in each instruction, and compute the
  3728. // stage difference for each use. Keep the maximum value.
  3729. for (auto &I : InstrToCycle) {
  3730. int DefStage = stageScheduled(I.first);
  3731. MachineInstr *MI = I.first->getInstr();
  3732. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3733. MachineOperand &Op = MI->getOperand(i);
  3734. if (!Op.isReg() || !Op.isDef())
  3735. continue;
  3736. unsigned Reg = Op.getReg();
  3737. unsigned MaxDiff = 0;
  3738. bool PhiIsSwapped = false;
  3739. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
  3740. EI = MRI.use_end();
  3741. UI != EI; ++UI) {
  3742. MachineOperand &UseOp = *UI;
  3743. MachineInstr *UseMI = UseOp.getParent();
  3744. SUnit *SUnitUse = SSD->getSUnit(UseMI);
  3745. int UseStage = stageScheduled(SUnitUse);
  3746. unsigned Diff = 0;
  3747. if (UseStage != -1 && UseStage >= DefStage)
  3748. Diff = UseStage - DefStage;
  3749. if (MI->isPHI()) {
  3750. if (isLoopCarried(SSD, *MI))
  3751. ++Diff;
  3752. else
  3753. PhiIsSwapped = true;
  3754. }
  3755. MaxDiff = std::max(Diff, MaxDiff);
  3756. }
  3757. RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
  3758. }
  3759. }
  3760. // Erase all the elements in the later stages. Only one iteration should
  3761. // remain in the scheduled list, and it contains all the instructions.
  3762. for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
  3763. ScheduledInstrs.erase(cycle);
  3764. // Change the registers in instruction as specified in the InstrChanges
  3765. // map. We need to use the new registers to create the correct order.
  3766. for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
  3767. SUnit *SU = &SSD->SUnits[i];
  3768. SSD->applyInstrChange(SU->getInstr(), *this);
  3769. }
  3770. // Reorder the instructions in each cycle to fix and improve the
  3771. // generated code.
  3772. for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
  3773. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
  3774. std::deque<SUnit *> newOrderPhi;
  3775. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3776. SUnit *SU = cycleInstrs[i];
  3777. if (SU->getInstr()->isPHI())
  3778. newOrderPhi.push_back(SU);
  3779. }
  3780. std::deque<SUnit *> newOrderI;
  3781. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3782. SUnit *SU = cycleInstrs[i];
  3783. if (!SU->getInstr()->isPHI())
  3784. orderDependence(SSD, SU, newOrderI);
  3785. }
  3786. // Replace the old order with the new order.
  3787. cycleInstrs.swap(newOrderPhi);
  3788. cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
  3789. SSD->fixupRegisterOverlaps(cycleInstrs);
  3790. }
  3791. DEBUG(dump(););
  3792. }
  3793. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3794. /// Print the schedule information to the given output.
  3795. void SMSchedule::print(raw_ostream &os) const {
  3796. // Iterate over each cycle.
  3797. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3798. // Iterate over each instruction in the cycle.
  3799. const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
  3800. for (SUnit *CI : cycleInstrs->second) {
  3801. os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
  3802. os << "(" << CI->NodeNum << ") ";
  3803. CI->getInstr()->print(os);
  3804. os << "\n";
  3805. }
  3806. }
  3807. }
  3808. /// Utility function used for debugging to print the schedule.
  3809. LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
  3810. #endif