MachinePipeliner.cpp 142 KB

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