MachinePipeliner.cpp 151 KB

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