MachinePipeliner.cpp 157 KB

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