MachinePipeliner.cpp 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814
  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. // TODO: Figure out whether isAtomic is really necessary (see D57601).
  2515. if (MMO->isVolatile() || MMO->isAtomic() ||
  2516. (MMO->isInvariant() && MMO->isDereferenceable()) ||
  2517. (!MMO->getValue())) {
  2518. NewMMOs.push_back(MMO);
  2519. continue;
  2520. }
  2521. unsigned Delta;
  2522. if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
  2523. int64_t AdjOffset = Delta * Num;
  2524. NewMMOs.push_back(
  2525. MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
  2526. } else {
  2527. NewMMOs.push_back(
  2528. MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
  2529. }
  2530. }
  2531. NewMI.setMemRefs(MF, NewMMOs);
  2532. }
  2533. /// Clone the instruction for the new pipelined loop and update the
  2534. /// memory operands, if needed.
  2535. MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
  2536. unsigned CurStageNum,
  2537. unsigned InstStageNum) {
  2538. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2539. // Check for tied operands in inline asm instructions. This should be handled
  2540. // elsewhere, but I'm not sure of the best solution.
  2541. if (OldMI->isInlineAsm())
  2542. for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
  2543. const auto &MO = OldMI->getOperand(i);
  2544. if (MO.isReg() && MO.isUse())
  2545. break;
  2546. unsigned UseIdx;
  2547. if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
  2548. NewMI->tieOperands(i, UseIdx);
  2549. }
  2550. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2551. return NewMI;
  2552. }
  2553. /// Clone the instruction for the new pipelined loop. If needed, this
  2554. /// function updates the instruction using the values saved in the
  2555. /// InstrChanges structure.
  2556. MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
  2557. unsigned CurStageNum,
  2558. unsigned InstStageNum,
  2559. SMSchedule &Schedule) {
  2560. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2561. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  2562. InstrChanges.find(getSUnit(OldMI));
  2563. if (It != InstrChanges.end()) {
  2564. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  2565. unsigned BasePos, OffsetPos;
  2566. if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
  2567. return nullptr;
  2568. int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
  2569. MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
  2570. if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
  2571. NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
  2572. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  2573. }
  2574. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2575. return NewMI;
  2576. }
  2577. /// Update the machine instruction with new virtual registers. This
  2578. /// function may change the defintions and/or uses.
  2579. void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
  2580. unsigned CurStageNum,
  2581. unsigned InstrStageNum,
  2582. SMSchedule &Schedule,
  2583. ValueMapTy *VRMap) {
  2584. for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
  2585. MachineOperand &MO = NewMI->getOperand(i);
  2586. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2587. continue;
  2588. unsigned reg = MO.getReg();
  2589. if (MO.isDef()) {
  2590. // Create a new virtual register for the definition.
  2591. const TargetRegisterClass *RC = MRI.getRegClass(reg);
  2592. unsigned NewReg = MRI.createVirtualRegister(RC);
  2593. MO.setReg(NewReg);
  2594. VRMap[CurStageNum][reg] = NewReg;
  2595. if (LastDef)
  2596. replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
  2597. } else if (MO.isUse()) {
  2598. MachineInstr *Def = MRI.getVRegDef(reg);
  2599. // Compute the stage that contains the last definition for instruction.
  2600. int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
  2601. unsigned StageNum = CurStageNum;
  2602. if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
  2603. // Compute the difference in stages between the defintion and the use.
  2604. unsigned StageDiff = (InstrStageNum - DefStageNum);
  2605. // Make an adjustment to get the last definition.
  2606. StageNum -= StageDiff;
  2607. }
  2608. if (VRMap[StageNum].count(reg))
  2609. MO.setReg(VRMap[StageNum][reg]);
  2610. }
  2611. }
  2612. }
  2613. /// Return the instruction in the loop that defines the register.
  2614. /// If the definition is a Phi, then follow the Phi operand to
  2615. /// the instruction in the loop.
  2616. MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
  2617. SmallPtrSet<MachineInstr *, 8> Visited;
  2618. MachineInstr *Def = MRI.getVRegDef(Reg);
  2619. while (Def->isPHI()) {
  2620. if (!Visited.insert(Def).second)
  2621. break;
  2622. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
  2623. if (Def->getOperand(i + 1).getMBB() == BB) {
  2624. Def = MRI.getVRegDef(Def->getOperand(i).getReg());
  2625. break;
  2626. }
  2627. }
  2628. return Def;
  2629. }
  2630. /// Return the new name for the value from the previous stage.
  2631. unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
  2632. unsigned LoopVal, unsigned LoopStage,
  2633. ValueMapTy *VRMap,
  2634. MachineBasicBlock *BB) {
  2635. unsigned PrevVal = 0;
  2636. if (StageNum > PhiStage) {
  2637. MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
  2638. if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
  2639. // The name is defined in the previous stage.
  2640. PrevVal = VRMap[StageNum - 1][LoopVal];
  2641. else if (VRMap[StageNum].count(LoopVal))
  2642. // The previous name is defined in the current stage when the instruction
  2643. // order is swapped.
  2644. PrevVal = VRMap[StageNum][LoopVal];
  2645. else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
  2646. // The loop value hasn't yet been scheduled.
  2647. PrevVal = LoopVal;
  2648. else if (StageNum == PhiStage + 1)
  2649. // The loop value is another phi, which has not been scheduled.
  2650. PrevVal = getInitPhiReg(*LoopInst, BB);
  2651. else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
  2652. // The loop value is another phi, which has been scheduled.
  2653. PrevVal =
  2654. getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
  2655. LoopStage, VRMap, BB);
  2656. }
  2657. return PrevVal;
  2658. }
  2659. /// Rewrite the Phi values in the specified block to use the mappings
  2660. /// from the initial operand. Once the Phi is scheduled, we switch
  2661. /// to using the loop value instead of the Phi value, so those names
  2662. /// do not need to be rewritten.
  2663. void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
  2664. unsigned StageNum,
  2665. SMSchedule &Schedule,
  2666. ValueMapTy *VRMap,
  2667. InstrMapTy &InstrMap) {
  2668. for (auto &PHI : BB->phis()) {
  2669. unsigned InitVal = 0;
  2670. unsigned LoopVal = 0;
  2671. getPhiRegs(PHI, BB, InitVal, LoopVal);
  2672. unsigned PhiDef = PHI.getOperand(0).getReg();
  2673. unsigned PhiStage =
  2674. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
  2675. unsigned LoopStage =
  2676. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
  2677. unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
  2678. if (NumPhis > StageNum)
  2679. NumPhis = StageNum;
  2680. for (unsigned np = 0; np <= NumPhis; ++np) {
  2681. unsigned NewVal =
  2682. getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
  2683. if (!NewVal)
  2684. NewVal = InitVal;
  2685. rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
  2686. PhiDef, NewVal);
  2687. }
  2688. }
  2689. }
  2690. /// Rewrite a previously scheduled instruction to use the register value
  2691. /// from the new instruction. Make sure the instruction occurs in the
  2692. /// basic block, and we don't change the uses in the new instruction.
  2693. void SwingSchedulerDAG::rewriteScheduledInstr(
  2694. MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
  2695. unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
  2696. unsigned NewReg, unsigned PrevReg) {
  2697. bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
  2698. int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
  2699. // Rewrite uses that have been scheduled already to use the new
  2700. // Phi register.
  2701. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
  2702. EI = MRI.use_end();
  2703. UI != EI;) {
  2704. MachineOperand &UseOp = *UI;
  2705. MachineInstr *UseMI = UseOp.getParent();
  2706. ++UI;
  2707. if (UseMI->getParent() != BB)
  2708. continue;
  2709. if (UseMI->isPHI()) {
  2710. if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
  2711. continue;
  2712. if (getLoopPhiReg(*UseMI, BB) != OldReg)
  2713. continue;
  2714. }
  2715. InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
  2716. assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
  2717. SUnit *OrigMISU = getSUnit(OrigInstr->second);
  2718. int StageSched = Schedule.stageScheduled(OrigMISU);
  2719. int CycleSched = Schedule.cycleScheduled(OrigMISU);
  2720. unsigned ReplaceReg = 0;
  2721. // This is the stage for the scheduled instruction.
  2722. if (StagePhi == StageSched && Phi->isPHI()) {
  2723. int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
  2724. if (PrevReg && InProlog)
  2725. ReplaceReg = PrevReg;
  2726. else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
  2727. (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
  2728. ReplaceReg = PrevReg;
  2729. else
  2730. ReplaceReg = NewReg;
  2731. }
  2732. // The scheduled instruction occurs before the scheduled Phi, and the
  2733. // Phi is not loop carried.
  2734. if (!InProlog && StagePhi + 1 == StageSched &&
  2735. !Schedule.isLoopCarried(this, *Phi))
  2736. ReplaceReg = NewReg;
  2737. if (StagePhi > StageSched && Phi->isPHI())
  2738. ReplaceReg = NewReg;
  2739. if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
  2740. ReplaceReg = NewReg;
  2741. if (ReplaceReg) {
  2742. MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
  2743. UseOp.setReg(ReplaceReg);
  2744. }
  2745. }
  2746. }
  2747. /// Check if we can change the instruction to use an offset value from the
  2748. /// previous iteration. If so, return true and set the base and offset values
  2749. /// so that we can rewrite the load, if necessary.
  2750. /// v1 = Phi(v0, v3)
  2751. /// v2 = load v1, 0
  2752. /// v3 = post_store v1, 4, x
  2753. /// This function enables the load to be rewritten as v2 = load v3, 4.
  2754. bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
  2755. unsigned &BasePos,
  2756. unsigned &OffsetPos,
  2757. unsigned &NewBase,
  2758. int64_t &Offset) {
  2759. // Get the load instruction.
  2760. if (TII->isPostIncrement(*MI))
  2761. return false;
  2762. unsigned BasePosLd, OffsetPosLd;
  2763. if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
  2764. return false;
  2765. unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
  2766. // Look for the Phi instruction.
  2767. MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
  2768. MachineInstr *Phi = MRI.getVRegDef(BaseReg);
  2769. if (!Phi || !Phi->isPHI())
  2770. return false;
  2771. // Get the register defined in the loop block.
  2772. unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
  2773. if (!PrevReg)
  2774. return false;
  2775. // Check for the post-increment load/store instruction.
  2776. MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
  2777. if (!PrevDef || PrevDef == MI)
  2778. return false;
  2779. if (!TII->isPostIncrement(*PrevDef))
  2780. return false;
  2781. unsigned BasePos1 = 0, OffsetPos1 = 0;
  2782. if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
  2783. return false;
  2784. // Make sure that the instructions do not access the same memory location in
  2785. // the next iteration.
  2786. int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
  2787. int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
  2788. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  2789. NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
  2790. bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
  2791. MF.DeleteMachineInstr(NewMI);
  2792. if (!Disjoint)
  2793. return false;
  2794. // Set the return value once we determine that we return true.
  2795. BasePos = BasePosLd;
  2796. OffsetPos = OffsetPosLd;
  2797. NewBase = PrevReg;
  2798. Offset = StoreOffset;
  2799. return true;
  2800. }
  2801. /// Apply changes to the instruction if needed. The changes are need
  2802. /// to improve the scheduling and depend up on the final schedule.
  2803. void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
  2804. SMSchedule &Schedule) {
  2805. SUnit *SU = getSUnit(MI);
  2806. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  2807. InstrChanges.find(SU);
  2808. if (It != InstrChanges.end()) {
  2809. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  2810. unsigned BasePos, OffsetPos;
  2811. if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  2812. return;
  2813. unsigned BaseReg = MI->getOperand(BasePos).getReg();
  2814. MachineInstr *LoopDef = findDefInLoop(BaseReg);
  2815. int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
  2816. int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
  2817. int BaseStageNum = Schedule.stageScheduled(SU);
  2818. int BaseCycleNum = Schedule.cycleScheduled(SU);
  2819. if (BaseStageNum < DefStageNum) {
  2820. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  2821. int OffsetDiff = DefStageNum - BaseStageNum;
  2822. if (DefCycleNum < BaseCycleNum) {
  2823. NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
  2824. if (OffsetDiff > 0)
  2825. --OffsetDiff;
  2826. }
  2827. int64_t NewOffset =
  2828. MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
  2829. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  2830. SU->setInstr(NewMI);
  2831. MISUnitMap[NewMI] = SU;
  2832. NewMIs.insert(NewMI);
  2833. }
  2834. }
  2835. }
  2836. /// Return true for an order or output dependence that is loop carried
  2837. /// potentially. A dependence is loop carried if the destination defines a valu
  2838. /// that may be used or defined by the source in a subsequent iteration.
  2839. bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
  2840. bool isSucc) {
  2841. if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
  2842. Dep.isArtificial())
  2843. return false;
  2844. if (!SwpPruneLoopCarried)
  2845. return true;
  2846. if (Dep.getKind() == SDep::Output)
  2847. return true;
  2848. MachineInstr *SI = Source->getInstr();
  2849. MachineInstr *DI = Dep.getSUnit()->getInstr();
  2850. if (!isSucc)
  2851. std::swap(SI, DI);
  2852. assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
  2853. // Assume ordered loads and stores may have a loop carried dependence.
  2854. if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
  2855. SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
  2856. return true;
  2857. // Only chain dependences between a load and store can be loop carried.
  2858. if (!DI->mayStore() || !SI->mayLoad())
  2859. return false;
  2860. unsigned DeltaS, DeltaD;
  2861. if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
  2862. return true;
  2863. MachineOperand *BaseOpS, *BaseOpD;
  2864. int64_t OffsetS, OffsetD;
  2865. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2866. if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
  2867. !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
  2868. return true;
  2869. if (!BaseOpS->isIdenticalTo(*BaseOpD))
  2870. return true;
  2871. // Check that the base register is incremented by a constant value for each
  2872. // iteration.
  2873. MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
  2874. if (!Def || !Def->isPHI())
  2875. return true;
  2876. unsigned InitVal = 0;
  2877. unsigned LoopVal = 0;
  2878. getPhiRegs(*Def, BB, InitVal, LoopVal);
  2879. MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
  2880. int D = 0;
  2881. if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
  2882. return true;
  2883. uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
  2884. uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
  2885. // This is the main test, which checks the offset values and the loop
  2886. // increment value to determine if the accesses may be loop carried.
  2887. if (OffsetS >= OffsetD)
  2888. return OffsetS + AccessSizeS > DeltaS;
  2889. else
  2890. return OffsetD + AccessSizeD > DeltaD;
  2891. return true;
  2892. }
  2893. void SwingSchedulerDAG::postprocessDAG() {
  2894. for (auto &M : Mutations)
  2895. M->apply(this);
  2896. }
  2897. /// Try to schedule the node at the specified StartCycle and continue
  2898. /// until the node is schedule or the EndCycle is reached. This function
  2899. /// returns true if the node is scheduled. This routine may search either
  2900. /// forward or backward for a place to insert the instruction based upon
  2901. /// the relative values of StartCycle and EndCycle.
  2902. bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
  2903. bool forward = true;
  2904. if (StartCycle > EndCycle)
  2905. forward = false;
  2906. // The terminating condition depends on the direction.
  2907. int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
  2908. for (int curCycle = StartCycle; curCycle != termCycle;
  2909. forward ? ++curCycle : --curCycle) {
  2910. // Add the already scheduled instructions at the specified cycle to the DFA.
  2911. Resources->clearResources();
  2912. for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
  2913. checkCycle <= LastCycle; checkCycle += II) {
  2914. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
  2915. for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
  2916. E = cycleInstrs.end();
  2917. I != E; ++I) {
  2918. if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
  2919. continue;
  2920. assert(Resources->canReserveResources(*(*I)->getInstr()) &&
  2921. "These instructions have already been scheduled.");
  2922. Resources->reserveResources(*(*I)->getInstr());
  2923. }
  2924. }
  2925. if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
  2926. Resources->canReserveResources(*SU->getInstr())) {
  2927. LLVM_DEBUG({
  2928. dbgs() << "\tinsert at cycle " << curCycle << " ";
  2929. SU->getInstr()->dump();
  2930. });
  2931. ScheduledInstrs[curCycle].push_back(SU);
  2932. InstrToCycle.insert(std::make_pair(SU, curCycle));
  2933. if (curCycle > LastCycle)
  2934. LastCycle = curCycle;
  2935. if (curCycle < FirstCycle)
  2936. FirstCycle = curCycle;
  2937. return true;
  2938. }
  2939. LLVM_DEBUG({
  2940. dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
  2941. SU->getInstr()->dump();
  2942. });
  2943. }
  2944. return false;
  2945. }
  2946. // Return the cycle of the earliest scheduled instruction in the chain.
  2947. int SMSchedule::earliestCycleInChain(const SDep &Dep) {
  2948. SmallPtrSet<SUnit *, 8> Visited;
  2949. SmallVector<SDep, 8> Worklist;
  2950. Worklist.push_back(Dep);
  2951. int EarlyCycle = INT_MAX;
  2952. while (!Worklist.empty()) {
  2953. const SDep &Cur = Worklist.pop_back_val();
  2954. SUnit *PrevSU = Cur.getSUnit();
  2955. if (Visited.count(PrevSU))
  2956. continue;
  2957. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
  2958. if (it == InstrToCycle.end())
  2959. continue;
  2960. EarlyCycle = std::min(EarlyCycle, it->second);
  2961. for (const auto &PI : PrevSU->Preds)
  2962. if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  2963. Worklist.push_back(PI);
  2964. Visited.insert(PrevSU);
  2965. }
  2966. return EarlyCycle;
  2967. }
  2968. // Return the cycle of the latest scheduled instruction in the chain.
  2969. int SMSchedule::latestCycleInChain(const SDep &Dep) {
  2970. SmallPtrSet<SUnit *, 8> Visited;
  2971. SmallVector<SDep, 8> Worklist;
  2972. Worklist.push_back(Dep);
  2973. int LateCycle = INT_MIN;
  2974. while (!Worklist.empty()) {
  2975. const SDep &Cur = Worklist.pop_back_val();
  2976. SUnit *SuccSU = Cur.getSUnit();
  2977. if (Visited.count(SuccSU))
  2978. continue;
  2979. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
  2980. if (it == InstrToCycle.end())
  2981. continue;
  2982. LateCycle = std::max(LateCycle, it->second);
  2983. for (const auto &SI : SuccSU->Succs)
  2984. if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  2985. Worklist.push_back(SI);
  2986. Visited.insert(SuccSU);
  2987. }
  2988. return LateCycle;
  2989. }
  2990. /// If an instruction has a use that spans multiple iterations, then
  2991. /// return true. These instructions are characterized by having a back-ege
  2992. /// to a Phi, which contains a reference to another Phi.
  2993. static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
  2994. for (auto &P : SU->Preds)
  2995. if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
  2996. for (auto &S : P.getSUnit()->Succs)
  2997. if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
  2998. return P.getSUnit();
  2999. return nullptr;
  3000. }
  3001. /// Compute the scheduling start slot for the instruction. The start slot
  3002. /// depends on any predecessor or successor nodes scheduled already.
  3003. void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  3004. int *MinEnd, int *MaxStart, int II,
  3005. SwingSchedulerDAG *DAG) {
  3006. // Iterate over each instruction that has been scheduled already. The start
  3007. // slot computation depends on whether the previously scheduled instruction
  3008. // is a predecessor or successor of the specified instruction.
  3009. for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
  3010. // Iterate over each instruction in the current cycle.
  3011. for (SUnit *I : getInstructions(cycle)) {
  3012. // Because we're processing a DAG for the dependences, we recognize
  3013. // the back-edge in recurrences by anti dependences.
  3014. for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
  3015. const SDep &Dep = SU->Preds[i];
  3016. if (Dep.getSUnit() == I) {
  3017. if (!DAG->isBackedge(SU, Dep)) {
  3018. int EarlyStart = cycle + Dep.getLatency() -
  3019. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3020. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3021. if (DAG->isLoopCarriedDep(SU, Dep, false)) {
  3022. int End = earliestCycleInChain(Dep) + (II - 1);
  3023. *MinEnd = std::min(*MinEnd, End);
  3024. }
  3025. } else {
  3026. int LateStart = cycle - Dep.getLatency() +
  3027. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3028. *MinLateStart = std::min(*MinLateStart, LateStart);
  3029. }
  3030. }
  3031. // For instruction that requires multiple iterations, make sure that
  3032. // the dependent instruction is not scheduled past the definition.
  3033. SUnit *BE = multipleIterations(I, DAG);
  3034. if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
  3035. !SU->isPred(I))
  3036. *MinLateStart = std::min(*MinLateStart, cycle);
  3037. }
  3038. for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
  3039. if (SU->Succs[i].getSUnit() == I) {
  3040. const SDep &Dep = SU->Succs[i];
  3041. if (!DAG->isBackedge(SU, Dep)) {
  3042. int LateStart = cycle - Dep.getLatency() +
  3043. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3044. *MinLateStart = std::min(*MinLateStart, LateStart);
  3045. if (DAG->isLoopCarriedDep(SU, Dep)) {
  3046. int Start = latestCycleInChain(Dep) + 1 - II;
  3047. *MaxStart = std::max(*MaxStart, Start);
  3048. }
  3049. } else {
  3050. int EarlyStart = cycle + Dep.getLatency() -
  3051. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3052. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3053. }
  3054. }
  3055. }
  3056. }
  3057. }
  3058. }
  3059. /// Order the instructions within a cycle so that the definitions occur
  3060. /// before the uses. Returns true if the instruction is added to the start
  3061. /// of the list, or false if added to the end.
  3062. void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  3063. std::deque<SUnit *> &Insts) {
  3064. MachineInstr *MI = SU->getInstr();
  3065. bool OrderBeforeUse = false;
  3066. bool OrderAfterDef = false;
  3067. bool OrderBeforeDef = false;
  3068. unsigned MoveDef = 0;
  3069. unsigned MoveUse = 0;
  3070. int StageInst1 = stageScheduled(SU);
  3071. unsigned Pos = 0;
  3072. for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
  3073. ++I, ++Pos) {
  3074. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3075. MachineOperand &MO = MI->getOperand(i);
  3076. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  3077. continue;
  3078. unsigned Reg = MO.getReg();
  3079. unsigned BasePos, OffsetPos;
  3080. if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  3081. if (MI->getOperand(BasePos).getReg() == Reg)
  3082. if (unsigned NewReg = SSD->getInstrBaseReg(SU))
  3083. Reg = NewReg;
  3084. bool Reads, Writes;
  3085. std::tie(Reads, Writes) =
  3086. (*I)->getInstr()->readsWritesVirtualRegister(Reg);
  3087. if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
  3088. OrderBeforeUse = true;
  3089. if (MoveUse == 0)
  3090. MoveUse = Pos;
  3091. } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
  3092. // Add the instruction after the scheduled instruction.
  3093. OrderAfterDef = true;
  3094. MoveDef = Pos;
  3095. } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
  3096. if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
  3097. OrderBeforeUse = true;
  3098. if (MoveUse == 0)
  3099. MoveUse = Pos;
  3100. } else {
  3101. OrderAfterDef = true;
  3102. MoveDef = Pos;
  3103. }
  3104. } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
  3105. OrderBeforeUse = true;
  3106. if (MoveUse == 0)
  3107. MoveUse = Pos;
  3108. if (MoveUse != 0) {
  3109. OrderAfterDef = true;
  3110. MoveDef = Pos - 1;
  3111. }
  3112. } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
  3113. // Add the instruction before the scheduled instruction.
  3114. OrderBeforeUse = true;
  3115. if (MoveUse == 0)
  3116. MoveUse = Pos;
  3117. } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
  3118. isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
  3119. if (MoveUse == 0) {
  3120. OrderBeforeDef = true;
  3121. MoveUse = Pos;
  3122. }
  3123. }
  3124. }
  3125. // Check for order dependences between instructions. Make sure the source
  3126. // is ordered before the destination.
  3127. for (auto &S : SU->Succs) {
  3128. if (S.getSUnit() != *I)
  3129. continue;
  3130. if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3131. OrderBeforeUse = true;
  3132. if (Pos < MoveUse)
  3133. MoveUse = Pos;
  3134. }
  3135. }
  3136. for (auto &P : SU->Preds) {
  3137. if (P.getSUnit() != *I)
  3138. continue;
  3139. if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3140. OrderAfterDef = true;
  3141. MoveDef = Pos;
  3142. }
  3143. }
  3144. }
  3145. // A circular dependence.
  3146. if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
  3147. OrderBeforeUse = false;
  3148. // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
  3149. // to a loop-carried dependence.
  3150. if (OrderBeforeDef)
  3151. OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
  3152. // The uncommon case when the instruction order needs to be updated because
  3153. // there is both a use and def.
  3154. if (OrderBeforeUse && OrderAfterDef) {
  3155. SUnit *UseSU = Insts.at(MoveUse);
  3156. SUnit *DefSU = Insts.at(MoveDef);
  3157. if (MoveUse > MoveDef) {
  3158. Insts.erase(Insts.begin() + MoveUse);
  3159. Insts.erase(Insts.begin() + MoveDef);
  3160. } else {
  3161. Insts.erase(Insts.begin() + MoveDef);
  3162. Insts.erase(Insts.begin() + MoveUse);
  3163. }
  3164. orderDependence(SSD, UseSU, Insts);
  3165. orderDependence(SSD, SU, Insts);
  3166. orderDependence(SSD, DefSU, Insts);
  3167. return;
  3168. }
  3169. // Put the new instruction first if there is a use in the list. Otherwise,
  3170. // put it at the end of the list.
  3171. if (OrderBeforeUse)
  3172. Insts.push_front(SU);
  3173. else
  3174. Insts.push_back(SU);
  3175. }
  3176. /// Return true if the scheduled Phi has a loop carried operand.
  3177. bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
  3178. if (!Phi.isPHI())
  3179. return false;
  3180. assert(Phi.isPHI() && "Expecting a Phi.");
  3181. SUnit *DefSU = SSD->getSUnit(&Phi);
  3182. unsigned DefCycle = cycleScheduled(DefSU);
  3183. int DefStage = stageScheduled(DefSU);
  3184. unsigned InitVal = 0;
  3185. unsigned LoopVal = 0;
  3186. getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
  3187. SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
  3188. if (!UseSU)
  3189. return true;
  3190. if (UseSU->getInstr()->isPHI())
  3191. return true;
  3192. unsigned LoopCycle = cycleScheduled(UseSU);
  3193. int LoopStage = stageScheduled(UseSU);
  3194. return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
  3195. }
  3196. /// Return true if the instruction is a definition that is loop carried
  3197. /// and defines the use on the next iteration.
  3198. /// v1 = phi(v2, v3)
  3199. /// (Def) v3 = op v1
  3200. /// (MO) = v1
  3201. /// If MO appears before Def, then then v1 and v3 may get assigned to the same
  3202. /// register.
  3203. bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
  3204. MachineInstr *Def, MachineOperand &MO) {
  3205. if (!MO.isReg())
  3206. return false;
  3207. if (Def->isPHI())
  3208. return false;
  3209. MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
  3210. if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
  3211. return false;
  3212. if (!isLoopCarried(SSD, *Phi))
  3213. return false;
  3214. unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
  3215. for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
  3216. MachineOperand &DMO = Def->getOperand(i);
  3217. if (!DMO.isReg() || !DMO.isDef())
  3218. continue;
  3219. if (DMO.getReg() == LoopReg)
  3220. return true;
  3221. }
  3222. return false;
  3223. }
  3224. // Check if the generated schedule is valid. This function checks if
  3225. // an instruction that uses a physical register is scheduled in a
  3226. // different stage than the definition. The pipeliner does not handle
  3227. // physical register values that may cross a basic block boundary.
  3228. bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
  3229. for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
  3230. SUnit &SU = SSD->SUnits[i];
  3231. if (!SU.hasPhysRegDefs)
  3232. continue;
  3233. int StageDef = stageScheduled(&SU);
  3234. assert(StageDef != -1 && "Instruction should have been scheduled.");
  3235. for (auto &SI : SU.Succs)
  3236. if (SI.isAssignedRegDep())
  3237. if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
  3238. if (stageScheduled(SI.getSUnit()) != StageDef)
  3239. return false;
  3240. }
  3241. return true;
  3242. }
  3243. /// A property of the node order in swing-modulo-scheduling is
  3244. /// that for nodes outside circuits the following holds:
  3245. /// none of them is scheduled after both a successor and a
  3246. /// predecessor.
  3247. /// The method below checks whether the property is met.
  3248. /// If not, debug information is printed and statistics information updated.
  3249. /// Note that we do not use an assert statement.
  3250. /// The reason is that although an invalid node oder may prevent
  3251. /// the pipeliner from finding a pipelined schedule for arbitrary II,
  3252. /// it does not lead to the generation of incorrect code.
  3253. void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
  3254. // a sorted vector that maps each SUnit to its index in the NodeOrder
  3255. typedef std::pair<SUnit *, unsigned> UnitIndex;
  3256. std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
  3257. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
  3258. Indices.push_back(std::make_pair(NodeOrder[i], i));
  3259. auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
  3260. return std::get<0>(i1) < std::get<0>(i2);
  3261. };
  3262. // sort, so that we can perform a binary search
  3263. llvm::sort(Indices, CompareKey);
  3264. bool Valid = true;
  3265. (void)Valid;
  3266. // for each SUnit in the NodeOrder, check whether
  3267. // it appears after both a successor and a predecessor
  3268. // of the SUnit. If this is the case, and the SUnit
  3269. // is not part of circuit, then the NodeOrder is not
  3270. // valid.
  3271. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
  3272. SUnit *SU = NodeOrder[i];
  3273. unsigned Index = i;
  3274. bool PredBefore = false;
  3275. bool SuccBefore = false;
  3276. SUnit *Succ;
  3277. SUnit *Pred;
  3278. (void)Succ;
  3279. (void)Pred;
  3280. for (SDep &PredEdge : SU->Preds) {
  3281. SUnit *PredSU = PredEdge.getSUnit();
  3282. unsigned PredIndex =
  3283. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3284. std::make_pair(PredSU, 0), CompareKey));
  3285. if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
  3286. PredBefore = true;
  3287. Pred = PredSU;
  3288. break;
  3289. }
  3290. }
  3291. for (SDep &SuccEdge : SU->Succs) {
  3292. SUnit *SuccSU = SuccEdge.getSUnit();
  3293. unsigned SuccIndex =
  3294. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3295. std::make_pair(SuccSU, 0), CompareKey));
  3296. if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
  3297. SuccBefore = true;
  3298. Succ = SuccSU;
  3299. break;
  3300. }
  3301. }
  3302. if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
  3303. // instructions in circuits are allowed to be scheduled
  3304. // after both a successor and predecessor.
  3305. bool InCircuit = std::any_of(
  3306. Circuits.begin(), Circuits.end(),
  3307. [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
  3308. if (InCircuit)
  3309. LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
  3310. else {
  3311. Valid = false;
  3312. NumNodeOrderIssues++;
  3313. LLVM_DEBUG(dbgs() << "Predecessor ";);
  3314. }
  3315. LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
  3316. << " are scheduled before node " << SU->NodeNum
  3317. << "\n";);
  3318. }
  3319. }
  3320. LLVM_DEBUG({
  3321. if (!Valid)
  3322. dbgs() << "Invalid node order found!\n";
  3323. });
  3324. }
  3325. /// Attempt to fix the degenerate cases when the instruction serialization
  3326. /// causes the register lifetimes to overlap. For example,
  3327. /// p' = store_pi(p, b)
  3328. /// = load p, offset
  3329. /// In this case p and p' overlap, which means that two registers are needed.
  3330. /// Instead, this function changes the load to use p' and updates the offset.
  3331. void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
  3332. unsigned OverlapReg = 0;
  3333. unsigned NewBaseReg = 0;
  3334. for (SUnit *SU : Instrs) {
  3335. MachineInstr *MI = SU->getInstr();
  3336. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3337. const MachineOperand &MO = MI->getOperand(i);
  3338. // Look for an instruction that uses p. The instruction occurs in the
  3339. // same cycle but occurs later in the serialized order.
  3340. if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
  3341. // Check that the instruction appears in the InstrChanges structure,
  3342. // which contains instructions that can have the offset updated.
  3343. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  3344. InstrChanges.find(SU);
  3345. if (It != InstrChanges.end()) {
  3346. unsigned BasePos, OffsetPos;
  3347. // Update the base register and adjust the offset.
  3348. if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
  3349. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3350. NewMI->getOperand(BasePos).setReg(NewBaseReg);
  3351. int64_t NewOffset =
  3352. MI->getOperand(OffsetPos).getImm() - It->second.second;
  3353. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  3354. SU->setInstr(NewMI);
  3355. MISUnitMap[NewMI] = SU;
  3356. NewMIs.insert(NewMI);
  3357. }
  3358. }
  3359. OverlapReg = 0;
  3360. NewBaseReg = 0;
  3361. break;
  3362. }
  3363. // Look for an instruction of the form p' = op(p), which uses and defines
  3364. // two virtual registers that get allocated to the same physical register.
  3365. unsigned TiedUseIdx = 0;
  3366. if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
  3367. // OverlapReg is p in the example above.
  3368. OverlapReg = MI->getOperand(TiedUseIdx).getReg();
  3369. // NewBaseReg is p' in the example above.
  3370. NewBaseReg = MI->getOperand(i).getReg();
  3371. break;
  3372. }
  3373. }
  3374. }
  3375. }
  3376. /// After the schedule has been formed, call this function to combine
  3377. /// the instructions from the different stages/cycles. That is, this
  3378. /// function creates a schedule that represents a single iteration.
  3379. void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
  3380. // Move all instructions to the first stage from later stages.
  3381. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3382. for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
  3383. ++stage) {
  3384. std::deque<SUnit *> &cycleInstrs =
  3385. ScheduledInstrs[cycle + (stage * InitiationInterval)];
  3386. for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
  3387. E = cycleInstrs.rend();
  3388. I != E; ++I)
  3389. ScheduledInstrs[cycle].push_front(*I);
  3390. }
  3391. }
  3392. // Iterate over the definitions in each instruction, and compute the
  3393. // stage difference for each use. Keep the maximum value.
  3394. for (auto &I : InstrToCycle) {
  3395. int DefStage = stageScheduled(I.first);
  3396. MachineInstr *MI = I.first->getInstr();
  3397. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3398. MachineOperand &Op = MI->getOperand(i);
  3399. if (!Op.isReg() || !Op.isDef())
  3400. continue;
  3401. unsigned Reg = Op.getReg();
  3402. unsigned MaxDiff = 0;
  3403. bool PhiIsSwapped = false;
  3404. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
  3405. EI = MRI.use_end();
  3406. UI != EI; ++UI) {
  3407. MachineOperand &UseOp = *UI;
  3408. MachineInstr *UseMI = UseOp.getParent();
  3409. SUnit *SUnitUse = SSD->getSUnit(UseMI);
  3410. int UseStage = stageScheduled(SUnitUse);
  3411. unsigned Diff = 0;
  3412. if (UseStage != -1 && UseStage >= DefStage)
  3413. Diff = UseStage - DefStage;
  3414. if (MI->isPHI()) {
  3415. if (isLoopCarried(SSD, *MI))
  3416. ++Diff;
  3417. else
  3418. PhiIsSwapped = true;
  3419. }
  3420. MaxDiff = std::max(Diff, MaxDiff);
  3421. }
  3422. RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
  3423. }
  3424. }
  3425. // Erase all the elements in the later stages. Only one iteration should
  3426. // remain in the scheduled list, and it contains all the instructions.
  3427. for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
  3428. ScheduledInstrs.erase(cycle);
  3429. // Change the registers in instruction as specified in the InstrChanges
  3430. // map. We need to use the new registers to create the correct order.
  3431. for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
  3432. SUnit *SU = &SSD->SUnits[i];
  3433. SSD->applyInstrChange(SU->getInstr(), *this);
  3434. }
  3435. // Reorder the instructions in each cycle to fix and improve the
  3436. // generated code.
  3437. for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
  3438. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
  3439. std::deque<SUnit *> newOrderPhi;
  3440. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3441. SUnit *SU = cycleInstrs[i];
  3442. if (SU->getInstr()->isPHI())
  3443. newOrderPhi.push_back(SU);
  3444. }
  3445. std::deque<SUnit *> newOrderI;
  3446. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3447. SUnit *SU = cycleInstrs[i];
  3448. if (!SU->getInstr()->isPHI())
  3449. orderDependence(SSD, SU, newOrderI);
  3450. }
  3451. // Replace the old order with the new order.
  3452. cycleInstrs.swap(newOrderPhi);
  3453. cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
  3454. SSD->fixupRegisterOverlaps(cycleInstrs);
  3455. }
  3456. LLVM_DEBUG(dump(););
  3457. }
  3458. void NodeSet::print(raw_ostream &os) const {
  3459. os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
  3460. << " depth " << MaxDepth << " col " << Colocate << "\n";
  3461. for (const auto &I : Nodes)
  3462. os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
  3463. os << "\n";
  3464. }
  3465. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3466. /// Print the schedule information to the given output.
  3467. void SMSchedule::print(raw_ostream &os) const {
  3468. // Iterate over each cycle.
  3469. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3470. // Iterate over each instruction in the cycle.
  3471. const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
  3472. for (SUnit *CI : cycleInstrs->second) {
  3473. os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
  3474. os << "(" << CI->NodeNum << ") ";
  3475. CI->getInstr()->print(os);
  3476. os << "\n";
  3477. }
  3478. }
  3479. }
  3480. /// Utility function used for debugging to print the schedule.
  3481. LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
  3482. LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
  3483. #endif