MachinePipeliner.cpp 148 KB

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