MachinePipeliner.cpp 157 KB

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