ScheduleDAGRRList.cpp 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184
  1. //===- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler ------===//
  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. // This implements bottom-up and top-down register pressure reduction list
  10. // schedulers, using standard algorithms. The basic approach uses a priority
  11. // queue of available nodes to schedule. One at a time, nodes are taken from
  12. // the priority queue (thus in priority order), checked for legality to
  13. // schedule, and emitted if legal.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "ScheduleDAGSDNodes.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/CodeGen/ISDOpcodes.h"
  24. #include "llvm/CodeGen/MachineFunction.h"
  25. #include "llvm/CodeGen/MachineOperand.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/CodeGen/ScheduleDAG.h"
  28. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  29. #include "llvm/CodeGen/SchedulerRegistry.h"
  30. #include "llvm/CodeGen/SelectionDAGISel.h"
  31. #include "llvm/CodeGen/SelectionDAGNodes.h"
  32. #include "llvm/CodeGen/TargetInstrInfo.h"
  33. #include "llvm/CodeGen/TargetLowering.h"
  34. #include "llvm/CodeGen/TargetOpcodes.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/Config/llvm-config.h"
  38. #include "llvm/IR/InlineAsm.h"
  39. #include "llvm/MC/MCInstrDesc.h"
  40. #include "llvm/MC/MCRegisterInfo.h"
  41. #include "llvm/Support/Casting.h"
  42. #include "llvm/Support/CodeGen.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Compiler.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Support/MachineValueType.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include <algorithm>
  50. #include <cassert>
  51. #include <cstdint>
  52. #include <cstdlib>
  53. #include <iterator>
  54. #include <limits>
  55. #include <memory>
  56. #include <utility>
  57. #include <vector>
  58. using namespace llvm;
  59. #define DEBUG_TYPE "pre-RA-sched"
  60. STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
  61. STATISTIC(NumUnfolds, "Number of nodes unfolded");
  62. STATISTIC(NumDups, "Number of duplicated nodes");
  63. STATISTIC(NumPRCopies, "Number of physical register copies");
  64. static RegisterScheduler
  65. burrListDAGScheduler("list-burr",
  66. "Bottom-up register reduction list scheduling",
  67. createBURRListDAGScheduler);
  68. static RegisterScheduler
  69. sourceListDAGScheduler("source",
  70. "Similar to list-burr but schedules in source "
  71. "order when possible",
  72. createSourceListDAGScheduler);
  73. static RegisterScheduler
  74. hybridListDAGScheduler("list-hybrid",
  75. "Bottom-up register pressure aware list scheduling "
  76. "which tries to balance latency and register pressure",
  77. createHybridListDAGScheduler);
  78. static RegisterScheduler
  79. ILPListDAGScheduler("list-ilp",
  80. "Bottom-up register pressure aware list scheduling "
  81. "which tries to balance ILP and register pressure",
  82. createILPListDAGScheduler);
  83. static cl::opt<bool> DisableSchedCycles(
  84. "disable-sched-cycles", cl::Hidden, cl::init(false),
  85. cl::desc("Disable cycle-level precision during preRA scheduling"));
  86. // Temporary sched=list-ilp flags until the heuristics are robust.
  87. // Some options are also available under sched=list-hybrid.
  88. static cl::opt<bool> DisableSchedRegPressure(
  89. "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
  90. cl::desc("Disable regpressure priority in sched=list-ilp"));
  91. static cl::opt<bool> DisableSchedLiveUses(
  92. "disable-sched-live-uses", cl::Hidden, cl::init(true),
  93. cl::desc("Disable live use priority in sched=list-ilp"));
  94. static cl::opt<bool> DisableSchedVRegCycle(
  95. "disable-sched-vrcycle", cl::Hidden, cl::init(false),
  96. cl::desc("Disable virtual register cycle interference checks"));
  97. static cl::opt<bool> DisableSchedPhysRegJoin(
  98. "disable-sched-physreg-join", cl::Hidden, cl::init(false),
  99. cl::desc("Disable physreg def-use affinity"));
  100. static cl::opt<bool> DisableSchedStalls(
  101. "disable-sched-stalls", cl::Hidden, cl::init(true),
  102. cl::desc("Disable no-stall priority in sched=list-ilp"));
  103. static cl::opt<bool> DisableSchedCriticalPath(
  104. "disable-sched-critical-path", cl::Hidden, cl::init(false),
  105. cl::desc("Disable critical path priority in sched=list-ilp"));
  106. static cl::opt<bool> DisableSchedHeight(
  107. "disable-sched-height", cl::Hidden, cl::init(false),
  108. cl::desc("Disable scheduled-height priority in sched=list-ilp"));
  109. static cl::opt<bool> Disable2AddrHack(
  110. "disable-2addr-hack", cl::Hidden, cl::init(true),
  111. cl::desc("Disable scheduler's two-address hack"));
  112. static cl::opt<int> MaxReorderWindow(
  113. "max-sched-reorder", cl::Hidden, cl::init(6),
  114. cl::desc("Number of instructions to allow ahead of the critical path "
  115. "in sched=list-ilp"));
  116. static cl::opt<unsigned> AvgIPC(
  117. "sched-avg-ipc", cl::Hidden, cl::init(1),
  118. cl::desc("Average inst/cycle whan no target itinerary exists."));
  119. namespace {
  120. //===----------------------------------------------------------------------===//
  121. /// ScheduleDAGRRList - The actual register reduction list scheduler
  122. /// implementation. This supports both top-down and bottom-up scheduling.
  123. ///
  124. class ScheduleDAGRRList : public ScheduleDAGSDNodes {
  125. private:
  126. /// NeedLatency - True if the scheduler will make use of latency information.
  127. bool NeedLatency;
  128. /// AvailableQueue - The priority queue to use for the available SUnits.
  129. SchedulingPriorityQueue *AvailableQueue;
  130. /// PendingQueue - This contains all of the instructions whose operands have
  131. /// been issued, but their results are not ready yet (due to the latency of
  132. /// the operation). Once the operands becomes available, the instruction is
  133. /// added to the AvailableQueue.
  134. std::vector<SUnit *> PendingQueue;
  135. /// HazardRec - The hazard recognizer to use.
  136. ScheduleHazardRecognizer *HazardRec;
  137. /// CurCycle - The current scheduler state corresponds to this cycle.
  138. unsigned CurCycle = 0;
  139. /// MinAvailableCycle - Cycle of the soonest available instruction.
  140. unsigned MinAvailableCycle;
  141. /// IssueCount - Count instructions issued in this cycle
  142. /// Currently valid only for bottom-up scheduling.
  143. unsigned IssueCount;
  144. /// LiveRegDefs - A set of physical registers and their definition
  145. /// that are "live". These nodes must be scheduled before any other nodes that
  146. /// modifies the registers can be scheduled.
  147. unsigned NumLiveRegs;
  148. std::unique_ptr<SUnit*[]> LiveRegDefs;
  149. std::unique_ptr<SUnit*[]> LiveRegGens;
  150. // Collect interferences between physical register use/defs.
  151. // Each interference is an SUnit and set of physical registers.
  152. SmallVector<SUnit*, 4> Interferences;
  153. using LRegsMapT = DenseMap<SUnit *, SmallVector<unsigned, 4>>;
  154. LRegsMapT LRegsMap;
  155. /// Topo - A topological ordering for SUnits which permits fast IsReachable
  156. /// and similar queries.
  157. ScheduleDAGTopologicalSort Topo;
  158. // Hack to keep track of the inverse of FindCallSeqStart without more crazy
  159. // DAG crawling.
  160. DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
  161. public:
  162. ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
  163. SchedulingPriorityQueue *availqueue,
  164. CodeGenOpt::Level OptLevel)
  165. : ScheduleDAGSDNodes(mf),
  166. NeedLatency(needlatency), AvailableQueue(availqueue),
  167. Topo(SUnits, nullptr) {
  168. const TargetSubtargetInfo &STI = mf.getSubtarget();
  169. if (DisableSchedCycles || !NeedLatency)
  170. HazardRec = new ScheduleHazardRecognizer();
  171. else
  172. HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
  173. }
  174. ~ScheduleDAGRRList() override {
  175. delete HazardRec;
  176. delete AvailableQueue;
  177. }
  178. void Schedule() override;
  179. ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
  180. /// IsReachable - Checks if SU is reachable from TargetSU.
  181. bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
  182. return Topo.IsReachable(SU, TargetSU);
  183. }
  184. /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
  185. /// create a cycle.
  186. bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
  187. return Topo.WillCreateCycle(SU, TargetSU);
  188. }
  189. /// AddPredQueued - Queues and update to add a predecessor edge to SUnit SU.
  190. /// This returns true if this is a new predecessor.
  191. /// Does *NOT* update the topological ordering! It just queues an update.
  192. void AddPredQueued(SUnit *SU, const SDep &D) {
  193. Topo.AddPredQueued(SU, D.getSUnit());
  194. SU->addPred(D);
  195. }
  196. /// AddPred - adds a predecessor edge to SUnit SU.
  197. /// This returns true if this is a new predecessor.
  198. /// Updates the topological ordering if required.
  199. void AddPred(SUnit *SU, const SDep &D) {
  200. Topo.AddPred(SU, D.getSUnit());
  201. SU->addPred(D);
  202. }
  203. /// RemovePred - removes a predecessor edge from SUnit SU.
  204. /// This returns true if an edge was removed.
  205. /// Updates the topological ordering if required.
  206. void RemovePred(SUnit *SU, const SDep &D) {
  207. Topo.RemovePred(SU, D.getSUnit());
  208. SU->removePred(D);
  209. }
  210. private:
  211. bool isReady(SUnit *SU) {
  212. return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
  213. AvailableQueue->isReady(SU);
  214. }
  215. void ReleasePred(SUnit *SU, const SDep *PredEdge);
  216. void ReleasePredecessors(SUnit *SU);
  217. void ReleasePending();
  218. void AdvanceToCycle(unsigned NextCycle);
  219. void AdvancePastStalls(SUnit *SU);
  220. void EmitNode(SUnit *SU);
  221. void ScheduleNodeBottomUp(SUnit*);
  222. void CapturePred(SDep *PredEdge);
  223. void UnscheduleNodeBottomUp(SUnit*);
  224. void RestoreHazardCheckerBottomUp();
  225. void BacktrackBottomUp(SUnit*, SUnit*);
  226. SUnit *TryUnfoldSU(SUnit *);
  227. SUnit *CopyAndMoveSuccessors(SUnit*);
  228. void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
  229. const TargetRegisterClass*,
  230. const TargetRegisterClass*,
  231. SmallVectorImpl<SUnit*>&);
  232. bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
  233. void releaseInterferences(unsigned Reg = 0);
  234. SUnit *PickNodeToScheduleBottomUp();
  235. void ListScheduleBottomUp();
  236. /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
  237. SUnit *CreateNewSUnit(SDNode *N) {
  238. unsigned NumSUnits = SUnits.size();
  239. SUnit *NewNode = newSUnit(N);
  240. // Update the topological ordering.
  241. if (NewNode->NodeNum >= NumSUnits)
  242. Topo.MarkDirty();
  243. return NewNode;
  244. }
  245. /// CreateClone - Creates a new SUnit from an existing one.
  246. SUnit *CreateClone(SUnit *N) {
  247. unsigned NumSUnits = SUnits.size();
  248. SUnit *NewNode = Clone(N);
  249. // Update the topological ordering.
  250. if (NewNode->NodeNum >= NumSUnits)
  251. Topo.MarkDirty();
  252. return NewNode;
  253. }
  254. /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
  255. /// need actual latency information but the hybrid scheduler does.
  256. bool forceUnitLatencies() const override {
  257. return !NeedLatency;
  258. }
  259. };
  260. } // end anonymous namespace
  261. /// GetCostForDef - Looks up the register class and cost for a given definition.
  262. /// Typically this just means looking up the representative register class,
  263. /// but for untyped values (MVT::Untyped) it means inspecting the node's
  264. /// opcode to determine what register class is being generated.
  265. static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
  266. const TargetLowering *TLI,
  267. const TargetInstrInfo *TII,
  268. const TargetRegisterInfo *TRI,
  269. unsigned &RegClass, unsigned &Cost,
  270. const MachineFunction &MF) {
  271. MVT VT = RegDefPos.GetValue();
  272. // Special handling for untyped values. These values can only come from
  273. // the expansion of custom DAG-to-DAG patterns.
  274. if (VT == MVT::Untyped) {
  275. const SDNode *Node = RegDefPos.GetNode();
  276. // Special handling for CopyFromReg of untyped values.
  277. if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
  278. unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
  279. const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
  280. RegClass = RC->getID();
  281. Cost = 1;
  282. return;
  283. }
  284. unsigned Opcode = Node->getMachineOpcode();
  285. if (Opcode == TargetOpcode::REG_SEQUENCE) {
  286. unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
  287. const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
  288. RegClass = RC->getID();
  289. Cost = 1;
  290. return;
  291. }
  292. unsigned Idx = RegDefPos.GetIdx();
  293. const MCInstrDesc Desc = TII->get(Opcode);
  294. const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
  295. RegClass = RC->getID();
  296. // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
  297. // better way to determine it.
  298. Cost = 1;
  299. } else {
  300. RegClass = TLI->getRepRegClassFor(VT)->getID();
  301. Cost = TLI->getRepRegClassCostFor(VT);
  302. }
  303. }
  304. /// Schedule - Schedule the DAG using list scheduling.
  305. void ScheduleDAGRRList::Schedule() {
  306. LLVM_DEBUG(dbgs() << "********** List Scheduling " << printMBBReference(*BB)
  307. << " '" << BB->getName() << "' **********\n");
  308. CurCycle = 0;
  309. IssueCount = 0;
  310. MinAvailableCycle =
  311. DisableSchedCycles ? 0 : std::numeric_limits<unsigned>::max();
  312. NumLiveRegs = 0;
  313. // Allocate slots for each physical register, plus one for a special register
  314. // to track the virtual resource of a calling sequence.
  315. LiveRegDefs.reset(new SUnit*[TRI->getNumRegs() + 1]());
  316. LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]());
  317. CallSeqEndForStart.clear();
  318. assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
  319. // Build the scheduling graph.
  320. BuildSchedGraph(nullptr);
  321. LLVM_DEBUG(dump());
  322. Topo.MarkDirty();
  323. AvailableQueue->initNodes(SUnits);
  324. HazardRec->Reset();
  325. // Execute the actual scheduling loop.
  326. ListScheduleBottomUp();
  327. AvailableQueue->releaseState();
  328. LLVM_DEBUG({
  329. dbgs() << "*** Final schedule ***\n";
  330. dumpSchedule();
  331. dbgs() << '\n';
  332. });
  333. }
  334. //===----------------------------------------------------------------------===//
  335. // Bottom-Up Scheduling
  336. //===----------------------------------------------------------------------===//
  337. /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
  338. /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
  339. void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
  340. SUnit *PredSU = PredEdge->getSUnit();
  341. #ifndef NDEBUG
  342. if (PredSU->NumSuccsLeft == 0) {
  343. dbgs() << "*** Scheduling failed! ***\n";
  344. dumpNode(*PredSU);
  345. dbgs() << " has been released too many times!\n";
  346. llvm_unreachable(nullptr);
  347. }
  348. #endif
  349. --PredSU->NumSuccsLeft;
  350. if (!forceUnitLatencies()) {
  351. // Updating predecessor's height. This is now the cycle when the
  352. // predecessor can be scheduled without causing a pipeline stall.
  353. PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
  354. }
  355. // If all the node's successors are scheduled, this node is ready
  356. // to be scheduled. Ignore the special EntrySU node.
  357. if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
  358. PredSU->isAvailable = true;
  359. unsigned Height = PredSU->getHeight();
  360. if (Height < MinAvailableCycle)
  361. MinAvailableCycle = Height;
  362. if (isReady(PredSU)) {
  363. AvailableQueue->push(PredSU);
  364. }
  365. // CapturePred and others may have left the node in the pending queue, avoid
  366. // adding it twice.
  367. else if (!PredSU->isPending) {
  368. PredSU->isPending = true;
  369. PendingQueue.push_back(PredSU);
  370. }
  371. }
  372. }
  373. /// IsChainDependent - Test if Outer is reachable from Inner through
  374. /// chain dependencies.
  375. static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
  376. unsigned NestLevel,
  377. const TargetInstrInfo *TII) {
  378. SDNode *N = Outer;
  379. while (true) {
  380. if (N == Inner)
  381. return true;
  382. // For a TokenFactor, examine each operand. There may be multiple ways
  383. // to get to the CALLSEQ_BEGIN, but we need to find the path with the
  384. // most nesting in order to ensure that we find the corresponding match.
  385. if (N->getOpcode() == ISD::TokenFactor) {
  386. for (const SDValue &Op : N->op_values())
  387. if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII))
  388. return true;
  389. return false;
  390. }
  391. // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
  392. if (N->isMachineOpcode()) {
  393. if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  394. ++NestLevel;
  395. } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  396. if (NestLevel == 0)
  397. return false;
  398. --NestLevel;
  399. }
  400. }
  401. // Otherwise, find the chain and continue climbing.
  402. for (const SDValue &Op : N->op_values())
  403. if (Op.getValueType() == MVT::Other) {
  404. N = Op.getNode();
  405. goto found_chain_operand;
  406. }
  407. return false;
  408. found_chain_operand:;
  409. if (N->getOpcode() == ISD::EntryToken)
  410. return false;
  411. }
  412. }
  413. /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
  414. /// the corresponding (lowered) CALLSEQ_BEGIN node.
  415. ///
  416. /// NestLevel and MaxNested are used in recursion to indcate the current level
  417. /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
  418. /// level seen so far.
  419. ///
  420. /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
  421. /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
  422. static SDNode *
  423. FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
  424. const TargetInstrInfo *TII) {
  425. while (true) {
  426. // For a TokenFactor, examine each operand. There may be multiple ways
  427. // to get to the CALLSEQ_BEGIN, but we need to find the path with the
  428. // most nesting in order to ensure that we find the corresponding match.
  429. if (N->getOpcode() == ISD::TokenFactor) {
  430. SDNode *Best = nullptr;
  431. unsigned BestMaxNest = MaxNest;
  432. for (const SDValue &Op : N->op_values()) {
  433. unsigned MyNestLevel = NestLevel;
  434. unsigned MyMaxNest = MaxNest;
  435. if (SDNode *New = FindCallSeqStart(Op.getNode(),
  436. MyNestLevel, MyMaxNest, TII))
  437. if (!Best || (MyMaxNest > BestMaxNest)) {
  438. Best = New;
  439. BestMaxNest = MyMaxNest;
  440. }
  441. }
  442. assert(Best);
  443. MaxNest = BestMaxNest;
  444. return Best;
  445. }
  446. // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
  447. if (N->isMachineOpcode()) {
  448. if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  449. ++NestLevel;
  450. MaxNest = std::max(MaxNest, NestLevel);
  451. } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  452. assert(NestLevel != 0);
  453. --NestLevel;
  454. if (NestLevel == 0)
  455. return N;
  456. }
  457. }
  458. // Otherwise, find the chain and continue climbing.
  459. for (const SDValue &Op : N->op_values())
  460. if (Op.getValueType() == MVT::Other) {
  461. N = Op.getNode();
  462. goto found_chain_operand;
  463. }
  464. return nullptr;
  465. found_chain_operand:;
  466. if (N->getOpcode() == ISD::EntryToken)
  467. return nullptr;
  468. }
  469. }
  470. /// Call ReleasePred for each predecessor, then update register live def/gen.
  471. /// Always update LiveRegDefs for a register dependence even if the current SU
  472. /// also defines the register. This effectively create one large live range
  473. /// across a sequence of two-address node. This is important because the
  474. /// entire chain must be scheduled together. Example:
  475. ///
  476. /// flags = (3) add
  477. /// flags = (2) addc flags
  478. /// flags = (1) addc flags
  479. ///
  480. /// results in
  481. ///
  482. /// LiveRegDefs[flags] = 3
  483. /// LiveRegGens[flags] = 1
  484. ///
  485. /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
  486. /// interference on flags.
  487. void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
  488. // Bottom up: release predecessors
  489. for (SDep &Pred : SU->Preds) {
  490. ReleasePred(SU, &Pred);
  491. if (Pred.isAssignedRegDep()) {
  492. // This is a physical register dependency and it's impossible or
  493. // expensive to copy the register. Make sure nothing that can
  494. // clobber the register is scheduled between the predecessor and
  495. // this node.
  496. SUnit *RegDef = LiveRegDefs[Pred.getReg()]; (void)RegDef;
  497. assert((!RegDef || RegDef == SU || RegDef == Pred.getSUnit()) &&
  498. "interference on register dependence");
  499. LiveRegDefs[Pred.getReg()] = Pred.getSUnit();
  500. if (!LiveRegGens[Pred.getReg()]) {
  501. ++NumLiveRegs;
  502. LiveRegGens[Pred.getReg()] = SU;
  503. }
  504. }
  505. }
  506. // If we're scheduling a lowered CALLSEQ_END, find the corresponding
  507. // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
  508. // these nodes, to prevent other calls from being interscheduled with them.
  509. unsigned CallResource = TRI->getNumRegs();
  510. if (!LiveRegDefs[CallResource])
  511. for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
  512. if (Node->isMachineOpcode() &&
  513. Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  514. unsigned NestLevel = 0;
  515. unsigned MaxNest = 0;
  516. SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
  517. assert(N && "Must find call sequence start");
  518. SUnit *Def = &SUnits[N->getNodeId()];
  519. CallSeqEndForStart[Def] = SU;
  520. ++NumLiveRegs;
  521. LiveRegDefs[CallResource] = Def;
  522. LiveRegGens[CallResource] = SU;
  523. break;
  524. }
  525. }
  526. /// Check to see if any of the pending instructions are ready to issue. If
  527. /// so, add them to the available queue.
  528. void ScheduleDAGRRList::ReleasePending() {
  529. if (DisableSchedCycles) {
  530. assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
  531. return;
  532. }
  533. // If the available queue is empty, it is safe to reset MinAvailableCycle.
  534. if (AvailableQueue->empty())
  535. MinAvailableCycle = std::numeric_limits<unsigned>::max();
  536. // Check to see if any of the pending instructions are ready to issue. If
  537. // so, add them to the available queue.
  538. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  539. unsigned ReadyCycle = PendingQueue[i]->getHeight();
  540. if (ReadyCycle < MinAvailableCycle)
  541. MinAvailableCycle = ReadyCycle;
  542. if (PendingQueue[i]->isAvailable) {
  543. if (!isReady(PendingQueue[i]))
  544. continue;
  545. AvailableQueue->push(PendingQueue[i]);
  546. }
  547. PendingQueue[i]->isPending = false;
  548. PendingQueue[i] = PendingQueue.back();
  549. PendingQueue.pop_back();
  550. --i; --e;
  551. }
  552. }
  553. /// Move the scheduler state forward by the specified number of Cycles.
  554. void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
  555. if (NextCycle <= CurCycle)
  556. return;
  557. IssueCount = 0;
  558. AvailableQueue->setCurCycle(NextCycle);
  559. if (!HazardRec->isEnabled()) {
  560. // Bypass lots of virtual calls in case of long latency.
  561. CurCycle = NextCycle;
  562. }
  563. else {
  564. for (; CurCycle != NextCycle; ++CurCycle) {
  565. HazardRec->RecedeCycle();
  566. }
  567. }
  568. // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
  569. // available Q to release pending nodes at least once before popping.
  570. ReleasePending();
  571. }
  572. /// Move the scheduler state forward until the specified node's dependents are
  573. /// ready and can be scheduled with no resource conflicts.
  574. void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
  575. if (DisableSchedCycles)
  576. return;
  577. // FIXME: Nodes such as CopyFromReg probably should not advance the current
  578. // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
  579. // has predecessors the cycle will be advanced when they are scheduled.
  580. // But given the crude nature of modeling latency though such nodes, we
  581. // currently need to treat these nodes like real instructions.
  582. // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
  583. unsigned ReadyCycle = SU->getHeight();
  584. // Bump CurCycle to account for latency. We assume the latency of other
  585. // available instructions may be hidden by the stall (not a full pipe stall).
  586. // This updates the hazard recognizer's cycle before reserving resources for
  587. // this instruction.
  588. AdvanceToCycle(ReadyCycle);
  589. // Calls are scheduled in their preceding cycle, so don't conflict with
  590. // hazards from instructions after the call. EmitNode will reset the
  591. // scoreboard state before emitting the call.
  592. if (SU->isCall)
  593. return;
  594. // FIXME: For resource conflicts in very long non-pipelined stages, we
  595. // should probably skip ahead here to avoid useless scoreboard checks.
  596. int Stalls = 0;
  597. while (true) {
  598. ScheduleHazardRecognizer::HazardType HT =
  599. HazardRec->getHazardType(SU, -Stalls);
  600. if (HT == ScheduleHazardRecognizer::NoHazard)
  601. break;
  602. ++Stalls;
  603. }
  604. AdvanceToCycle(CurCycle + Stalls);
  605. }
  606. /// Record this SUnit in the HazardRecognizer.
  607. /// Does not update CurCycle.
  608. void ScheduleDAGRRList::EmitNode(SUnit *SU) {
  609. if (!HazardRec->isEnabled())
  610. return;
  611. // Check for phys reg copy.
  612. if (!SU->getNode())
  613. return;
  614. switch (SU->getNode()->getOpcode()) {
  615. default:
  616. assert(SU->getNode()->isMachineOpcode() &&
  617. "This target-independent node should not be scheduled.");
  618. break;
  619. case ISD::MERGE_VALUES:
  620. case ISD::TokenFactor:
  621. case ISD::LIFETIME_START:
  622. case ISD::LIFETIME_END:
  623. case ISD::CopyToReg:
  624. case ISD::CopyFromReg:
  625. case ISD::EH_LABEL:
  626. // Noops don't affect the scoreboard state. Copies are likely to be
  627. // removed.
  628. return;
  629. case ISD::INLINEASM:
  630. case ISD::INLINEASM_BR:
  631. // For inline asm, clear the pipeline state.
  632. HazardRec->Reset();
  633. return;
  634. }
  635. if (SU->isCall) {
  636. // Calls are scheduled with their preceding instructions. For bottom-up
  637. // scheduling, clear the pipeline state before emitting.
  638. HazardRec->Reset();
  639. }
  640. HazardRec->EmitInstruction(SU);
  641. }
  642. static void resetVRegCycle(SUnit *SU);
  643. /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
  644. /// count of its predecessors. If a predecessor pending count is zero, add it to
  645. /// the Available queue.
  646. void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
  647. LLVM_DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
  648. LLVM_DEBUG(dumpNode(*SU));
  649. #ifndef NDEBUG
  650. if (CurCycle < SU->getHeight())
  651. LLVM_DEBUG(dbgs() << " Height [" << SU->getHeight()
  652. << "] pipeline stall!\n");
  653. #endif
  654. // FIXME: Do not modify node height. It may interfere with
  655. // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
  656. // node its ready cycle can aid heuristics, and after scheduling it can
  657. // indicate the scheduled cycle.
  658. SU->setHeightToAtLeast(CurCycle);
  659. // Reserve resources for the scheduled instruction.
  660. EmitNode(SU);
  661. Sequence.push_back(SU);
  662. AvailableQueue->scheduledNode(SU);
  663. // If HazardRec is disabled, and each inst counts as one cycle, then
  664. // advance CurCycle before ReleasePredecessors to avoid useless pushes to
  665. // PendingQueue for schedulers that implement HasReadyFilter.
  666. if (!HazardRec->isEnabled() && AvgIPC < 2)
  667. AdvanceToCycle(CurCycle + 1);
  668. // Update liveness of predecessors before successors to avoid treating a
  669. // two-address node as a live range def.
  670. ReleasePredecessors(SU);
  671. // Release all the implicit physical register defs that are live.
  672. for (SDep &Succ : SU->Succs) {
  673. // LiveRegDegs[Succ.getReg()] != SU when SU is a two-address node.
  674. if (Succ.isAssignedRegDep() && LiveRegDefs[Succ.getReg()] == SU) {
  675. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  676. --NumLiveRegs;
  677. LiveRegDefs[Succ.getReg()] = nullptr;
  678. LiveRegGens[Succ.getReg()] = nullptr;
  679. releaseInterferences(Succ.getReg());
  680. }
  681. }
  682. // Release the special call resource dependence, if this is the beginning
  683. // of a call.
  684. unsigned CallResource = TRI->getNumRegs();
  685. if (LiveRegDefs[CallResource] == SU)
  686. for (const SDNode *SUNode = SU->getNode(); SUNode;
  687. SUNode = SUNode->getGluedNode()) {
  688. if (SUNode->isMachineOpcode() &&
  689. SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  690. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  691. --NumLiveRegs;
  692. LiveRegDefs[CallResource] = nullptr;
  693. LiveRegGens[CallResource] = nullptr;
  694. releaseInterferences(CallResource);
  695. }
  696. }
  697. resetVRegCycle(SU);
  698. SU->isScheduled = true;
  699. // Conditions under which the scheduler should eagerly advance the cycle:
  700. // (1) No available instructions
  701. // (2) All pipelines full, so available instructions must have hazards.
  702. //
  703. // If HazardRec is disabled, the cycle was pre-advanced before calling
  704. // ReleasePredecessors. In that case, IssueCount should remain 0.
  705. //
  706. // Check AvailableQueue after ReleasePredecessors in case of zero latency.
  707. if (HazardRec->isEnabled() || AvgIPC > 1) {
  708. if (SU->getNode() && SU->getNode()->isMachineOpcode())
  709. ++IssueCount;
  710. if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
  711. || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
  712. AdvanceToCycle(CurCycle + 1);
  713. }
  714. }
  715. /// CapturePred - This does the opposite of ReleasePred. Since SU is being
  716. /// unscheduled, increase the succ left count of its predecessors. Remove
  717. /// them from AvailableQueue if necessary.
  718. void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
  719. SUnit *PredSU = PredEdge->getSUnit();
  720. if (PredSU->isAvailable) {
  721. PredSU->isAvailable = false;
  722. if (!PredSU->isPending)
  723. AvailableQueue->remove(PredSU);
  724. }
  725. assert(PredSU->NumSuccsLeft < std::numeric_limits<unsigned>::max() &&
  726. "NumSuccsLeft will overflow!");
  727. ++PredSU->NumSuccsLeft;
  728. }
  729. /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
  730. /// its predecessor states to reflect the change.
  731. void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
  732. LLVM_DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
  733. LLVM_DEBUG(dumpNode(*SU));
  734. for (SDep &Pred : SU->Preds) {
  735. CapturePred(&Pred);
  736. if (Pred.isAssignedRegDep() && SU == LiveRegGens[Pred.getReg()]){
  737. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  738. assert(LiveRegDefs[Pred.getReg()] == Pred.getSUnit() &&
  739. "Physical register dependency violated?");
  740. --NumLiveRegs;
  741. LiveRegDefs[Pred.getReg()] = nullptr;
  742. LiveRegGens[Pred.getReg()] = nullptr;
  743. releaseInterferences(Pred.getReg());
  744. }
  745. }
  746. // Reclaim the special call resource dependence, if this is the beginning
  747. // of a call.
  748. unsigned CallResource = TRI->getNumRegs();
  749. for (const SDNode *SUNode = SU->getNode(); SUNode;
  750. SUNode = SUNode->getGluedNode()) {
  751. if (SUNode->isMachineOpcode() &&
  752. SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  753. SUnit *SeqEnd = CallSeqEndForStart[SU];
  754. assert(SeqEnd && "Call sequence start/end must be known");
  755. assert(!LiveRegDefs[CallResource]);
  756. assert(!LiveRegGens[CallResource]);
  757. ++NumLiveRegs;
  758. LiveRegDefs[CallResource] = SU;
  759. LiveRegGens[CallResource] = SeqEnd;
  760. }
  761. }
  762. // Release the special call resource dependence, if this is the end
  763. // of a call.
  764. if (LiveRegGens[CallResource] == SU)
  765. for (const SDNode *SUNode = SU->getNode(); SUNode;
  766. SUNode = SUNode->getGluedNode()) {
  767. if (SUNode->isMachineOpcode() &&
  768. SUNode->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  769. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  770. assert(LiveRegDefs[CallResource]);
  771. assert(LiveRegGens[CallResource]);
  772. --NumLiveRegs;
  773. LiveRegDefs[CallResource] = nullptr;
  774. LiveRegGens[CallResource] = nullptr;
  775. releaseInterferences(CallResource);
  776. }
  777. }
  778. for (auto &Succ : SU->Succs) {
  779. if (Succ.isAssignedRegDep()) {
  780. auto Reg = Succ.getReg();
  781. if (!LiveRegDefs[Reg])
  782. ++NumLiveRegs;
  783. // This becomes the nearest def. Note that an earlier def may still be
  784. // pending if this is a two-address node.
  785. LiveRegDefs[Reg] = SU;
  786. // Update LiveRegGen only if was empty before this unscheduling.
  787. // This is to avoid incorrect updating LiveRegGen set in previous run.
  788. if (!LiveRegGens[Reg]) {
  789. // Find the successor with the lowest height.
  790. LiveRegGens[Reg] = Succ.getSUnit();
  791. for (auto &Succ2 : SU->Succs) {
  792. if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
  793. Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight())
  794. LiveRegGens[Reg] = Succ2.getSUnit();
  795. }
  796. }
  797. }
  798. }
  799. if (SU->getHeight() < MinAvailableCycle)
  800. MinAvailableCycle = SU->getHeight();
  801. SU->setHeightDirty();
  802. SU->isScheduled = false;
  803. SU->isAvailable = true;
  804. if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
  805. // Don't make available until backtracking is complete.
  806. SU->isPending = true;
  807. PendingQueue.push_back(SU);
  808. }
  809. else {
  810. AvailableQueue->push(SU);
  811. }
  812. AvailableQueue->unscheduledNode(SU);
  813. }
  814. /// After backtracking, the hazard checker needs to be restored to a state
  815. /// corresponding the current cycle.
  816. void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
  817. HazardRec->Reset();
  818. unsigned LookAhead = std::min((unsigned)Sequence.size(),
  819. HazardRec->getMaxLookAhead());
  820. if (LookAhead == 0)
  821. return;
  822. std::vector<SUnit *>::const_iterator I = (Sequence.end() - LookAhead);
  823. unsigned HazardCycle = (*I)->getHeight();
  824. for (auto E = Sequence.end(); I != E; ++I) {
  825. SUnit *SU = *I;
  826. for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
  827. HazardRec->RecedeCycle();
  828. }
  829. EmitNode(SU);
  830. }
  831. }
  832. /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
  833. /// BTCycle in order to schedule a specific node.
  834. void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
  835. SUnit *OldSU = Sequence.back();
  836. while (true) {
  837. Sequence.pop_back();
  838. // FIXME: use ready cycle instead of height
  839. CurCycle = OldSU->getHeight();
  840. UnscheduleNodeBottomUp(OldSU);
  841. AvailableQueue->setCurCycle(CurCycle);
  842. if (OldSU == BtSU)
  843. break;
  844. OldSU = Sequence.back();
  845. }
  846. assert(!SU->isSucc(OldSU) && "Something is wrong!");
  847. RestoreHazardCheckerBottomUp();
  848. ReleasePending();
  849. ++NumBacktracks;
  850. }
  851. static bool isOperandOf(const SUnit *SU, SDNode *N) {
  852. for (const SDNode *SUNode = SU->getNode(); SUNode;
  853. SUNode = SUNode->getGluedNode()) {
  854. if (SUNode->isOperandOf(N))
  855. return true;
  856. }
  857. return false;
  858. }
  859. /// TryUnfold - Attempt to unfold
  860. SUnit *ScheduleDAGRRList::TryUnfoldSU(SUnit *SU) {
  861. SDNode *N = SU->getNode();
  862. // Use while over if to ease fall through.
  863. SmallVector<SDNode *, 2> NewNodes;
  864. if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
  865. return nullptr;
  866. // unfolding an x86 DEC64m operation results in store, dec, load which
  867. // can't be handled here so quit
  868. if (NewNodes.size() == 3)
  869. return nullptr;
  870. assert(NewNodes.size() == 2 && "Expected a load folding node!");
  871. N = NewNodes[1];
  872. SDNode *LoadNode = NewNodes[0];
  873. unsigned NumVals = N->getNumValues();
  874. unsigned OldNumVals = SU->getNode()->getNumValues();
  875. // LoadNode may already exist. This can happen when there is another
  876. // load from the same location and producing the same type of value
  877. // but it has different alignment or volatileness.
  878. bool isNewLoad = true;
  879. SUnit *LoadSU;
  880. if (LoadNode->getNodeId() != -1) {
  881. LoadSU = &SUnits[LoadNode->getNodeId()];
  882. // If LoadSU has already been scheduled, we should clone it but
  883. // this would negate the benefit to unfolding so just return SU.
  884. if (LoadSU->isScheduled)
  885. return SU;
  886. isNewLoad = false;
  887. } else {
  888. LoadSU = CreateNewSUnit(LoadNode);
  889. LoadNode->setNodeId(LoadSU->NodeNum);
  890. InitNumRegDefsLeft(LoadSU);
  891. computeLatency(LoadSU);
  892. }
  893. bool isNewN = true;
  894. SUnit *NewSU;
  895. // This can only happen when isNewLoad is false.
  896. if (N->getNodeId() != -1) {
  897. NewSU = &SUnits[N->getNodeId()];
  898. // If NewSU has already been scheduled, we need to clone it, but this
  899. // negates the benefit to unfolding so just return SU.
  900. if (NewSU->isScheduled) {
  901. return SU;
  902. }
  903. isNewN = false;
  904. } else {
  905. NewSU = CreateNewSUnit(N);
  906. N->setNodeId(NewSU->NodeNum);
  907. const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
  908. for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
  909. if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
  910. NewSU->isTwoAddress = true;
  911. break;
  912. }
  913. }
  914. if (MCID.isCommutable())
  915. NewSU->isCommutable = true;
  916. InitNumRegDefsLeft(NewSU);
  917. computeLatency(NewSU);
  918. }
  919. LLVM_DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
  920. // Now that we are committed to unfolding replace DAG Uses.
  921. for (unsigned i = 0; i != NumVals; ++i)
  922. DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
  923. DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals - 1),
  924. SDValue(LoadNode, 1));
  925. // Record all the edges to and from the old SU, by category.
  926. SmallVector<SDep, 4> ChainPreds;
  927. SmallVector<SDep, 4> ChainSuccs;
  928. SmallVector<SDep, 4> LoadPreds;
  929. SmallVector<SDep, 4> NodePreds;
  930. SmallVector<SDep, 4> NodeSuccs;
  931. for (SDep &Pred : SU->Preds) {
  932. if (Pred.isCtrl())
  933. ChainPreds.push_back(Pred);
  934. else if (isOperandOf(Pred.getSUnit(), LoadNode))
  935. LoadPreds.push_back(Pred);
  936. else
  937. NodePreds.push_back(Pred);
  938. }
  939. for (SDep &Succ : SU->Succs) {
  940. if (Succ.isCtrl())
  941. ChainSuccs.push_back(Succ);
  942. else
  943. NodeSuccs.push_back(Succ);
  944. }
  945. // Now assign edges to the newly-created nodes.
  946. for (const SDep &Pred : ChainPreds) {
  947. RemovePred(SU, Pred);
  948. if (isNewLoad)
  949. AddPredQueued(LoadSU, Pred);
  950. }
  951. for (const SDep &Pred : LoadPreds) {
  952. RemovePred(SU, Pred);
  953. if (isNewLoad)
  954. AddPredQueued(LoadSU, Pred);
  955. }
  956. for (const SDep &Pred : NodePreds) {
  957. RemovePred(SU, Pred);
  958. AddPredQueued(NewSU, Pred);
  959. }
  960. for (SDep D : NodeSuccs) {
  961. SUnit *SuccDep = D.getSUnit();
  962. D.setSUnit(SU);
  963. RemovePred(SuccDep, D);
  964. D.setSUnit(NewSU);
  965. AddPredQueued(SuccDep, D);
  966. // Balance register pressure.
  967. if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled &&
  968. !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
  969. --NewSU->NumRegDefsLeft;
  970. }
  971. for (SDep D : ChainSuccs) {
  972. SUnit *SuccDep = D.getSUnit();
  973. D.setSUnit(SU);
  974. RemovePred(SuccDep, D);
  975. if (isNewLoad) {
  976. D.setSUnit(LoadSU);
  977. AddPredQueued(SuccDep, D);
  978. }
  979. }
  980. // Add a data dependency to reflect that NewSU reads the value defined
  981. // by LoadSU.
  982. SDep D(LoadSU, SDep::Data, 0);
  983. D.setLatency(LoadSU->Latency);
  984. AddPredQueued(NewSU, D);
  985. if (isNewLoad)
  986. AvailableQueue->addNode(LoadSU);
  987. if (isNewN)
  988. AvailableQueue->addNode(NewSU);
  989. ++NumUnfolds;
  990. if (NewSU->NumSuccsLeft == 0)
  991. NewSU->isAvailable = true;
  992. return NewSU;
  993. }
  994. /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
  995. /// successors to the newly created node.
  996. SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
  997. SDNode *N = SU->getNode();
  998. if (!N)
  999. return nullptr;
  1000. LLVM_DEBUG(dbgs() << "Considering duplicating the SU\n");
  1001. LLVM_DEBUG(dumpNode(*SU));
  1002. if (N->getGluedNode() &&
  1003. !TII->canCopyGluedNodeDuringSchedule(N)) {
  1004. LLVM_DEBUG(
  1005. dbgs()
  1006. << "Giving up because it has incoming glue and the target does not "
  1007. "want to copy it\n");
  1008. return nullptr;
  1009. }
  1010. SUnit *NewSU;
  1011. bool TryUnfold = false;
  1012. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
  1013. MVT VT = N->getSimpleValueType(i);
  1014. if (VT == MVT::Glue) {
  1015. LLVM_DEBUG(dbgs() << "Giving up because it has outgoing glue\n");
  1016. return nullptr;
  1017. } else if (VT == MVT::Other)
  1018. TryUnfold = true;
  1019. }
  1020. for (const SDValue &Op : N->op_values()) {
  1021. MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
  1022. if (VT == MVT::Glue && !TII->canCopyGluedNodeDuringSchedule(N)) {
  1023. LLVM_DEBUG(
  1024. dbgs() << "Giving up because it one of the operands is glue and "
  1025. "the target does not want to copy it\n");
  1026. return nullptr;
  1027. }
  1028. }
  1029. // If possible unfold instruction.
  1030. if (TryUnfold) {
  1031. SUnit *UnfoldSU = TryUnfoldSU(SU);
  1032. if (!UnfoldSU)
  1033. return nullptr;
  1034. SU = UnfoldSU;
  1035. N = SU->getNode();
  1036. // If this can be scheduled don't bother duplicating and just return
  1037. if (SU->NumSuccsLeft == 0)
  1038. return SU;
  1039. }
  1040. LLVM_DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
  1041. NewSU = CreateClone(SU);
  1042. // New SUnit has the exact same predecessors.
  1043. for (SDep &Pred : SU->Preds)
  1044. if (!Pred.isArtificial())
  1045. AddPredQueued(NewSU, Pred);
  1046. // Only copy scheduled successors. Cut them from old node's successor
  1047. // list and move them over.
  1048. SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
  1049. for (SDep &Succ : SU->Succs) {
  1050. if (Succ.isArtificial())
  1051. continue;
  1052. SUnit *SuccSU = Succ.getSUnit();
  1053. if (SuccSU->isScheduled) {
  1054. SDep D = Succ;
  1055. D.setSUnit(NewSU);
  1056. AddPredQueued(SuccSU, D);
  1057. D.setSUnit(SU);
  1058. DelDeps.push_back(std::make_pair(SuccSU, D));
  1059. }
  1060. }
  1061. for (auto &DelDep : DelDeps)
  1062. RemovePred(DelDep.first, DelDep.second);
  1063. AvailableQueue->updateNode(SU);
  1064. AvailableQueue->addNode(NewSU);
  1065. ++NumDups;
  1066. return NewSU;
  1067. }
  1068. /// InsertCopiesAndMoveSuccs - Insert register copies and move all
  1069. /// scheduled successors of the given SUnit to the last copy.
  1070. void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
  1071. const TargetRegisterClass *DestRC,
  1072. const TargetRegisterClass *SrcRC,
  1073. SmallVectorImpl<SUnit*> &Copies) {
  1074. SUnit *CopyFromSU = CreateNewSUnit(nullptr);
  1075. CopyFromSU->CopySrcRC = SrcRC;
  1076. CopyFromSU->CopyDstRC = DestRC;
  1077. SUnit *CopyToSU = CreateNewSUnit(nullptr);
  1078. CopyToSU->CopySrcRC = DestRC;
  1079. CopyToSU->CopyDstRC = SrcRC;
  1080. // Only copy scheduled successors. Cut them from old node's successor
  1081. // list and move them over.
  1082. SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
  1083. for (SDep &Succ : SU->Succs) {
  1084. if (Succ.isArtificial())
  1085. continue;
  1086. SUnit *SuccSU = Succ.getSUnit();
  1087. if (SuccSU->isScheduled) {
  1088. SDep D = Succ;
  1089. D.setSUnit(CopyToSU);
  1090. AddPredQueued(SuccSU, D);
  1091. DelDeps.push_back(std::make_pair(SuccSU, Succ));
  1092. }
  1093. else {
  1094. // Avoid scheduling the def-side copy before other successors. Otherwise
  1095. // we could introduce another physreg interference on the copy and
  1096. // continue inserting copies indefinitely.
  1097. AddPredQueued(SuccSU, SDep(CopyFromSU, SDep::Artificial));
  1098. }
  1099. }
  1100. for (auto &DelDep : DelDeps)
  1101. RemovePred(DelDep.first, DelDep.second);
  1102. SDep FromDep(SU, SDep::Data, Reg);
  1103. FromDep.setLatency(SU->Latency);
  1104. AddPredQueued(CopyFromSU, FromDep);
  1105. SDep ToDep(CopyFromSU, SDep::Data, 0);
  1106. ToDep.setLatency(CopyFromSU->Latency);
  1107. AddPredQueued(CopyToSU, ToDep);
  1108. AvailableQueue->updateNode(SU);
  1109. AvailableQueue->addNode(CopyFromSU);
  1110. AvailableQueue->addNode(CopyToSU);
  1111. Copies.push_back(CopyFromSU);
  1112. Copies.push_back(CopyToSU);
  1113. ++NumPRCopies;
  1114. }
  1115. /// getPhysicalRegisterVT - Returns the ValueType of the physical register
  1116. /// definition of the specified node.
  1117. /// FIXME: Move to SelectionDAG?
  1118. static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
  1119. const TargetInstrInfo *TII) {
  1120. unsigned NumRes;
  1121. if (N->getOpcode() == ISD::CopyFromReg) {
  1122. // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
  1123. NumRes = 1;
  1124. } else {
  1125. const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
  1126. assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
  1127. NumRes = MCID.getNumDefs();
  1128. for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
  1129. if (Reg == *ImpDef)
  1130. break;
  1131. ++NumRes;
  1132. }
  1133. }
  1134. return N->getSimpleValueType(NumRes);
  1135. }
  1136. /// CheckForLiveRegDef - Return true and update live register vector if the
  1137. /// specified register def of the specified SUnit clobbers any "live" registers.
  1138. static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
  1139. SUnit **LiveRegDefs,
  1140. SmallSet<unsigned, 4> &RegAdded,
  1141. SmallVectorImpl<unsigned> &LRegs,
  1142. const TargetRegisterInfo *TRI) {
  1143. for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
  1144. // Check if Ref is live.
  1145. if (!LiveRegDefs[*AliasI]) continue;
  1146. // Allow multiple uses of the same def.
  1147. if (LiveRegDefs[*AliasI] == SU) continue;
  1148. // Add Reg to the set of interfering live regs.
  1149. if (RegAdded.insert(*AliasI).second) {
  1150. LRegs.push_back(*AliasI);
  1151. }
  1152. }
  1153. }
  1154. /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
  1155. /// by RegMask, and add them to LRegs.
  1156. static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
  1157. ArrayRef<SUnit*> LiveRegDefs,
  1158. SmallSet<unsigned, 4> &RegAdded,
  1159. SmallVectorImpl<unsigned> &LRegs) {
  1160. // Look at all live registers. Skip Reg0 and the special CallResource.
  1161. for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
  1162. if (!LiveRegDefs[i]) continue;
  1163. if (LiveRegDefs[i] == SU) continue;
  1164. if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
  1165. if (RegAdded.insert(i).second)
  1166. LRegs.push_back(i);
  1167. }
  1168. }
  1169. /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
  1170. static const uint32_t *getNodeRegMask(const SDNode *N) {
  1171. for (const SDValue &Op : N->op_values())
  1172. if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
  1173. return RegOp->getRegMask();
  1174. return nullptr;
  1175. }
  1176. /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
  1177. /// scheduling of the given node to satisfy live physical register dependencies.
  1178. /// If the specific node is the last one that's available to schedule, do
  1179. /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
  1180. bool ScheduleDAGRRList::
  1181. DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
  1182. if (NumLiveRegs == 0)
  1183. return false;
  1184. SmallSet<unsigned, 4> RegAdded;
  1185. // If this node would clobber any "live" register, then it's not ready.
  1186. //
  1187. // If SU is the currently live definition of the same register that it uses,
  1188. // then we are free to schedule it.
  1189. for (SDep &Pred : SU->Preds) {
  1190. if (Pred.isAssignedRegDep() && LiveRegDefs[Pred.getReg()] != SU)
  1191. CheckForLiveRegDef(Pred.getSUnit(), Pred.getReg(), LiveRegDefs.get(),
  1192. RegAdded, LRegs, TRI);
  1193. }
  1194. for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
  1195. if (Node->getOpcode() == ISD::INLINEASM ||
  1196. Node->getOpcode() == ISD::INLINEASM_BR) {
  1197. // Inline asm can clobber physical defs.
  1198. unsigned NumOps = Node->getNumOperands();
  1199. if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
  1200. --NumOps; // Ignore the glue operand.
  1201. for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
  1202. unsigned Flags =
  1203. cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
  1204. unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
  1205. ++i; // Skip the ID value.
  1206. if (InlineAsm::isRegDefKind(Flags) ||
  1207. InlineAsm::isRegDefEarlyClobberKind(Flags) ||
  1208. InlineAsm::isClobberKind(Flags)) {
  1209. // Check for def of register or earlyclobber register.
  1210. for (; NumVals; --NumVals, ++i) {
  1211. unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
  1212. if (Register::isPhysicalRegister(Reg))
  1213. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1214. }
  1215. } else
  1216. i += NumVals;
  1217. }
  1218. continue;
  1219. }
  1220. if (!Node->isMachineOpcode())
  1221. continue;
  1222. // If we're in the middle of scheduling a call, don't begin scheduling
  1223. // another call. Also, don't allow any physical registers to be live across
  1224. // the call.
  1225. if (Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  1226. // Check the special calling-sequence resource.
  1227. unsigned CallResource = TRI->getNumRegs();
  1228. if (LiveRegDefs[CallResource]) {
  1229. SDNode *Gen = LiveRegGens[CallResource]->getNode();
  1230. while (SDNode *Glued = Gen->getGluedNode())
  1231. Gen = Glued;
  1232. if (!IsChainDependent(Gen, Node, 0, TII) &&
  1233. RegAdded.insert(CallResource).second)
  1234. LRegs.push_back(CallResource);
  1235. }
  1236. }
  1237. if (const uint32_t *RegMask = getNodeRegMask(Node))
  1238. CheckForLiveRegDefMasked(SU, RegMask,
  1239. makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
  1240. RegAdded, LRegs);
  1241. const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
  1242. if (MCID.hasOptionalDef()) {
  1243. // Most ARM instructions have an OptionalDef for CPSR, to model the S-bit.
  1244. // This operand can be either a def of CPSR, if the S bit is set; or a use
  1245. // of %noreg. When the OptionalDef is set to a valid register, we need to
  1246. // handle it in the same way as an ImplicitDef.
  1247. for (unsigned i = 0; i < MCID.getNumDefs(); ++i)
  1248. if (MCID.OpInfo[i].isOptionalDef()) {
  1249. const SDValue &OptionalDef = Node->getOperand(i - Node->getNumValues());
  1250. unsigned Reg = cast<RegisterSDNode>(OptionalDef)->getReg();
  1251. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1252. }
  1253. }
  1254. if (!MCID.ImplicitDefs)
  1255. continue;
  1256. for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
  1257. CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1258. }
  1259. return !LRegs.empty();
  1260. }
  1261. void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
  1262. // Add the nodes that aren't ready back onto the available list.
  1263. for (unsigned i = Interferences.size(); i > 0; --i) {
  1264. SUnit *SU = Interferences[i-1];
  1265. LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
  1266. if (Reg) {
  1267. SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
  1268. if (!is_contained(LRegs, Reg))
  1269. continue;
  1270. }
  1271. SU->isPending = false;
  1272. // The interfering node may no longer be available due to backtracking.
  1273. // Furthermore, it may have been made available again, in which case it is
  1274. // now already in the AvailableQueue.
  1275. if (SU->isAvailable && !SU->NodeQueueId) {
  1276. LLVM_DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n');
  1277. AvailableQueue->push(SU);
  1278. }
  1279. if (i < Interferences.size())
  1280. Interferences[i-1] = Interferences.back();
  1281. Interferences.pop_back();
  1282. LRegsMap.erase(LRegsPos);
  1283. }
  1284. }
  1285. /// Return a node that can be scheduled in this cycle. Requirements:
  1286. /// (1) Ready: latency has been satisfied
  1287. /// (2) No Hazards: resources are available
  1288. /// (3) No Interferences: may unschedule to break register interferences.
  1289. SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
  1290. SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
  1291. auto FindAvailableNode = [&]() {
  1292. while (CurSU) {
  1293. SmallVector<unsigned, 4> LRegs;
  1294. if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
  1295. break;
  1296. LLVM_DEBUG(dbgs() << " Interfering reg ";
  1297. if (LRegs[0] == TRI->getNumRegs()) dbgs() << "CallResource";
  1298. else dbgs() << printReg(LRegs[0], TRI);
  1299. dbgs() << " SU #" << CurSU->NodeNum << '\n');
  1300. std::pair<LRegsMapT::iterator, bool> LRegsPair =
  1301. LRegsMap.insert(std::make_pair(CurSU, LRegs));
  1302. if (LRegsPair.second) {
  1303. CurSU->isPending = true; // This SU is not in AvailableQueue right now.
  1304. Interferences.push_back(CurSU);
  1305. }
  1306. else {
  1307. assert(CurSU->isPending && "Interferences are pending");
  1308. // Update the interference with current live regs.
  1309. LRegsPair.first->second = LRegs;
  1310. }
  1311. CurSU = AvailableQueue->pop();
  1312. }
  1313. };
  1314. FindAvailableNode();
  1315. if (CurSU)
  1316. return CurSU;
  1317. // We query the topological order in the loop body, so make sure outstanding
  1318. // updates are applied before entering it (we only enter the loop if there
  1319. // are some interferences). If we make changes to the ordering, we exit
  1320. // the loop.
  1321. // All candidates are delayed due to live physical reg dependencies.
  1322. // Try backtracking, code duplication, or inserting cross class copies
  1323. // to resolve it.
  1324. for (SUnit *TrySU : Interferences) {
  1325. SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
  1326. // Try unscheduling up to the point where it's safe to schedule
  1327. // this node.
  1328. SUnit *BtSU = nullptr;
  1329. unsigned LiveCycle = std::numeric_limits<unsigned>::max();
  1330. for (unsigned Reg : LRegs) {
  1331. if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
  1332. BtSU = LiveRegGens[Reg];
  1333. LiveCycle = BtSU->getHeight();
  1334. }
  1335. }
  1336. if (!WillCreateCycle(TrySU, BtSU)) {
  1337. // BacktrackBottomUp mutates Interferences!
  1338. BacktrackBottomUp(TrySU, BtSU);
  1339. // Force the current node to be scheduled before the node that
  1340. // requires the physical reg dep.
  1341. if (BtSU->isAvailable) {
  1342. BtSU->isAvailable = false;
  1343. if (!BtSU->isPending)
  1344. AvailableQueue->remove(BtSU);
  1345. }
  1346. LLVM_DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum
  1347. << ") to SU(" << TrySU->NodeNum << ")\n");
  1348. AddPredQueued(TrySU, SDep(BtSU, SDep::Artificial));
  1349. // If one or more successors has been unscheduled, then the current
  1350. // node is no longer available.
  1351. if (!TrySU->isAvailable || !TrySU->NodeQueueId) {
  1352. LLVM_DEBUG(dbgs() << "TrySU not available; choosing node from queue\n");
  1353. CurSU = AvailableQueue->pop();
  1354. } else {
  1355. LLVM_DEBUG(dbgs() << "TrySU available\n");
  1356. // Available and in AvailableQueue
  1357. AvailableQueue->remove(TrySU);
  1358. CurSU = TrySU;
  1359. }
  1360. FindAvailableNode();
  1361. // Interferences has been mutated. We must break.
  1362. break;
  1363. }
  1364. }
  1365. if (!CurSU) {
  1366. // Can't backtrack. If it's too expensive to copy the value, then try
  1367. // duplicate the nodes that produces these "too expensive to copy"
  1368. // values to break the dependency. In case even that doesn't work,
  1369. // insert cross class copies.
  1370. // If it's not too expensive, i.e. cost != -1, issue copies.
  1371. SUnit *TrySU = Interferences[0];
  1372. SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
  1373. assert(LRegs.size() == 1 && "Can't handle this yet!");
  1374. unsigned Reg = LRegs[0];
  1375. SUnit *LRDef = LiveRegDefs[Reg];
  1376. MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
  1377. const TargetRegisterClass *RC =
  1378. TRI->getMinimalPhysRegClass(Reg, VT);
  1379. const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
  1380. // If cross copy register class is the same as RC, then it must be possible
  1381. // copy the value directly. Do not try duplicate the def.
  1382. // If cross copy register class is not the same as RC, then it's possible to
  1383. // copy the value but it require cross register class copies and it is
  1384. // expensive.
  1385. // If cross copy register class is null, then it's not possible to copy
  1386. // the value at all.
  1387. SUnit *NewDef = nullptr;
  1388. if (DestRC != RC) {
  1389. NewDef = CopyAndMoveSuccessors(LRDef);
  1390. if (!DestRC && !NewDef)
  1391. report_fatal_error("Can't handle live physical register dependency!");
  1392. }
  1393. if (!NewDef) {
  1394. // Issue copies, these can be expensive cross register class copies.
  1395. SmallVector<SUnit*, 2> Copies;
  1396. InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
  1397. LLVM_DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
  1398. << " to SU #" << Copies.front()->NodeNum << "\n");
  1399. AddPredQueued(TrySU, SDep(Copies.front(), SDep::Artificial));
  1400. NewDef = Copies.back();
  1401. }
  1402. LLVM_DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
  1403. << " to SU #" << TrySU->NodeNum << "\n");
  1404. LiveRegDefs[Reg] = NewDef;
  1405. AddPredQueued(NewDef, SDep(TrySU, SDep::Artificial));
  1406. TrySU->isAvailable = false;
  1407. CurSU = NewDef;
  1408. }
  1409. assert(CurSU && "Unable to resolve live physical register dependencies!");
  1410. return CurSU;
  1411. }
  1412. /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
  1413. /// schedulers.
  1414. void ScheduleDAGRRList::ListScheduleBottomUp() {
  1415. // Release any predecessors of the special Exit node.
  1416. ReleasePredecessors(&ExitSU);
  1417. // Add root to Available queue.
  1418. if (!SUnits.empty()) {
  1419. SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
  1420. assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
  1421. RootSU->isAvailable = true;
  1422. AvailableQueue->push(RootSU);
  1423. }
  1424. // While Available queue is not empty, grab the node with the highest
  1425. // priority. If it is not ready put it back. Schedule the node.
  1426. Sequence.reserve(SUnits.size());
  1427. while (!AvailableQueue->empty() || !Interferences.empty()) {
  1428. LLVM_DEBUG(dbgs() << "\nExamining Available:\n";
  1429. AvailableQueue->dump(this));
  1430. // Pick the best node to schedule taking all constraints into
  1431. // consideration.
  1432. SUnit *SU = PickNodeToScheduleBottomUp();
  1433. AdvancePastStalls(SU);
  1434. ScheduleNodeBottomUp(SU);
  1435. while (AvailableQueue->empty() && !PendingQueue.empty()) {
  1436. // Advance the cycle to free resources. Skip ahead to the next ready SU.
  1437. assert(MinAvailableCycle < std::numeric_limits<unsigned>::max() &&
  1438. "MinAvailableCycle uninitialized");
  1439. AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
  1440. }
  1441. }
  1442. // Reverse the order if it is bottom up.
  1443. std::reverse(Sequence.begin(), Sequence.end());
  1444. #ifndef NDEBUG
  1445. VerifyScheduledSequence(/*isBottomUp=*/true);
  1446. #endif
  1447. }
  1448. namespace {
  1449. class RegReductionPQBase;
  1450. struct queue_sort {
  1451. bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
  1452. };
  1453. #ifndef NDEBUG
  1454. template<class SF>
  1455. struct reverse_sort : public queue_sort {
  1456. SF &SortFunc;
  1457. reverse_sort(SF &sf) : SortFunc(sf) {}
  1458. bool operator()(SUnit* left, SUnit* right) const {
  1459. // reverse left/right rather than simply !SortFunc(left, right)
  1460. // to expose different paths in the comparison logic.
  1461. return SortFunc(right, left);
  1462. }
  1463. };
  1464. #endif // NDEBUG
  1465. /// bu_ls_rr_sort - Priority function for bottom up register pressure
  1466. // reduction scheduler.
  1467. struct bu_ls_rr_sort : public queue_sort {
  1468. enum {
  1469. IsBottomUp = true,
  1470. HasReadyFilter = false
  1471. };
  1472. RegReductionPQBase *SPQ;
  1473. bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1474. bool operator()(SUnit* left, SUnit* right) const;
  1475. };
  1476. // src_ls_rr_sort - Priority function for source order scheduler.
  1477. struct src_ls_rr_sort : public queue_sort {
  1478. enum {
  1479. IsBottomUp = true,
  1480. HasReadyFilter = false
  1481. };
  1482. RegReductionPQBase *SPQ;
  1483. src_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1484. bool operator()(SUnit* left, SUnit* right) const;
  1485. };
  1486. // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
  1487. struct hybrid_ls_rr_sort : public queue_sort {
  1488. enum {
  1489. IsBottomUp = true,
  1490. HasReadyFilter = false
  1491. };
  1492. RegReductionPQBase *SPQ;
  1493. hybrid_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1494. bool isReady(SUnit *SU, unsigned CurCycle) const;
  1495. bool operator()(SUnit* left, SUnit* right) const;
  1496. };
  1497. // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
  1498. // scheduler.
  1499. struct ilp_ls_rr_sort : public queue_sort {
  1500. enum {
  1501. IsBottomUp = true,
  1502. HasReadyFilter = false
  1503. };
  1504. RegReductionPQBase *SPQ;
  1505. ilp_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1506. bool isReady(SUnit *SU, unsigned CurCycle) const;
  1507. bool operator()(SUnit* left, SUnit* right) const;
  1508. };
  1509. class RegReductionPQBase : public SchedulingPriorityQueue {
  1510. protected:
  1511. std::vector<SUnit *> Queue;
  1512. unsigned CurQueueId = 0;
  1513. bool TracksRegPressure;
  1514. bool SrcOrder;
  1515. // SUnits - The SUnits for the current graph.
  1516. std::vector<SUnit> *SUnits;
  1517. MachineFunction &MF;
  1518. const TargetInstrInfo *TII;
  1519. const TargetRegisterInfo *TRI;
  1520. const TargetLowering *TLI;
  1521. ScheduleDAGRRList *scheduleDAG = nullptr;
  1522. // SethiUllmanNumbers - The SethiUllman number for each node.
  1523. std::vector<unsigned> SethiUllmanNumbers;
  1524. /// RegPressure - Tracking current reg pressure per register class.
  1525. std::vector<unsigned> RegPressure;
  1526. /// RegLimit - Tracking the number of allocatable registers per register
  1527. /// class.
  1528. std::vector<unsigned> RegLimit;
  1529. public:
  1530. RegReductionPQBase(MachineFunction &mf,
  1531. bool hasReadyFilter,
  1532. bool tracksrp,
  1533. bool srcorder,
  1534. const TargetInstrInfo *tii,
  1535. const TargetRegisterInfo *tri,
  1536. const TargetLowering *tli)
  1537. : SchedulingPriorityQueue(hasReadyFilter), TracksRegPressure(tracksrp),
  1538. SrcOrder(srcorder), MF(mf), TII(tii), TRI(tri), TLI(tli) {
  1539. if (TracksRegPressure) {
  1540. unsigned NumRC = TRI->getNumRegClasses();
  1541. RegLimit.resize(NumRC);
  1542. RegPressure.resize(NumRC);
  1543. std::fill(RegLimit.begin(), RegLimit.end(), 0);
  1544. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  1545. for (const TargetRegisterClass *RC : TRI->regclasses())
  1546. RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF);
  1547. }
  1548. }
  1549. void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
  1550. scheduleDAG = scheduleDag;
  1551. }
  1552. ScheduleHazardRecognizer* getHazardRec() {
  1553. return scheduleDAG->getHazardRec();
  1554. }
  1555. void initNodes(std::vector<SUnit> &sunits) override;
  1556. void addNode(const SUnit *SU) override;
  1557. void updateNode(const SUnit *SU) override;
  1558. void releaseState() override {
  1559. SUnits = nullptr;
  1560. SethiUllmanNumbers.clear();
  1561. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  1562. }
  1563. unsigned getNodePriority(const SUnit *SU) const;
  1564. unsigned getNodeOrdering(const SUnit *SU) const {
  1565. if (!SU->getNode()) return 0;
  1566. return SU->getNode()->getIROrder();
  1567. }
  1568. bool empty() const override { return Queue.empty(); }
  1569. void push(SUnit *U) override {
  1570. assert(!U->NodeQueueId && "Node in the queue already");
  1571. U->NodeQueueId = ++CurQueueId;
  1572. Queue.push_back(U);
  1573. }
  1574. void remove(SUnit *SU) override {
  1575. assert(!Queue.empty() && "Queue is empty!");
  1576. assert(SU->NodeQueueId != 0 && "Not in queue!");
  1577. std::vector<SUnit *>::iterator I = llvm::find(Queue, SU);
  1578. if (I != std::prev(Queue.end()))
  1579. std::swap(*I, Queue.back());
  1580. Queue.pop_back();
  1581. SU->NodeQueueId = 0;
  1582. }
  1583. bool tracksRegPressure() const override { return TracksRegPressure; }
  1584. void dumpRegPressure() const;
  1585. bool HighRegPressure(const SUnit *SU) const;
  1586. bool MayReduceRegPressure(SUnit *SU) const;
  1587. int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
  1588. void scheduledNode(SUnit *SU) override;
  1589. void unscheduledNode(SUnit *SU) override;
  1590. protected:
  1591. bool canClobber(const SUnit *SU, const SUnit *Op);
  1592. void AddPseudoTwoAddrDeps();
  1593. void PrescheduleNodesWithMultipleUses();
  1594. void CalculateSethiUllmanNumbers();
  1595. };
  1596. template<class SF>
  1597. static SUnit *popFromQueueImpl(std::vector<SUnit *> &Q, SF &Picker) {
  1598. std::vector<SUnit *>::iterator Best = Q.begin();
  1599. for (auto I = std::next(Q.begin()), E = Q.end(); I != E; ++I)
  1600. if (Picker(*Best, *I))
  1601. Best = I;
  1602. SUnit *V = *Best;
  1603. if (Best != std::prev(Q.end()))
  1604. std::swap(*Best, Q.back());
  1605. Q.pop_back();
  1606. return V;
  1607. }
  1608. template<class SF>
  1609. SUnit *popFromQueue(std::vector<SUnit *> &Q, SF &Picker, ScheduleDAG *DAG) {
  1610. #ifndef NDEBUG
  1611. if (DAG->StressSched) {
  1612. reverse_sort<SF> RPicker(Picker);
  1613. return popFromQueueImpl(Q, RPicker);
  1614. }
  1615. #endif
  1616. (void)DAG;
  1617. return popFromQueueImpl(Q, Picker);
  1618. }
  1619. //===----------------------------------------------------------------------===//
  1620. // RegReductionPriorityQueue Definition
  1621. //===----------------------------------------------------------------------===//
  1622. //
  1623. // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
  1624. // to reduce register pressure.
  1625. //
  1626. template<class SF>
  1627. class RegReductionPriorityQueue : public RegReductionPQBase {
  1628. SF Picker;
  1629. public:
  1630. RegReductionPriorityQueue(MachineFunction &mf,
  1631. bool tracksrp,
  1632. bool srcorder,
  1633. const TargetInstrInfo *tii,
  1634. const TargetRegisterInfo *tri,
  1635. const TargetLowering *tli)
  1636. : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
  1637. tii, tri, tli),
  1638. Picker(this) {}
  1639. bool isBottomUp() const override { return SF::IsBottomUp; }
  1640. bool isReady(SUnit *U) const override {
  1641. return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
  1642. }
  1643. SUnit *pop() override {
  1644. if (Queue.empty()) return nullptr;
  1645. SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
  1646. V->NodeQueueId = 0;
  1647. return V;
  1648. }
  1649. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1650. LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
  1651. // Emulate pop() without clobbering NodeQueueIds.
  1652. std::vector<SUnit *> DumpQueue = Queue;
  1653. SF DumpPicker = Picker;
  1654. while (!DumpQueue.empty()) {
  1655. SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
  1656. dbgs() << "Height " << SU->getHeight() << ": ";
  1657. DAG->dumpNode(*SU);
  1658. }
  1659. }
  1660. #endif
  1661. };
  1662. using BURegReductionPriorityQueue = RegReductionPriorityQueue<bu_ls_rr_sort>;
  1663. using SrcRegReductionPriorityQueue = RegReductionPriorityQueue<src_ls_rr_sort>;
  1664. using HybridBURRPriorityQueue = RegReductionPriorityQueue<hybrid_ls_rr_sort>;
  1665. using ILPBURRPriorityQueue = RegReductionPriorityQueue<ilp_ls_rr_sort>;
  1666. } // end anonymous namespace
  1667. //===----------------------------------------------------------------------===//
  1668. // Static Node Priority for Register Pressure Reduction
  1669. //===----------------------------------------------------------------------===//
  1670. // Check for special nodes that bypass scheduling heuristics.
  1671. // Currently this pushes TokenFactor nodes down, but may be used for other
  1672. // pseudo-ops as well.
  1673. //
  1674. // Return -1 to schedule right above left, 1 for left above right.
  1675. // Return 0 if no bias exists.
  1676. static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
  1677. bool LSchedLow = left->isScheduleLow;
  1678. bool RSchedLow = right->isScheduleLow;
  1679. if (LSchedLow != RSchedLow)
  1680. return LSchedLow < RSchedLow ? 1 : -1;
  1681. return 0;
  1682. }
  1683. /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
  1684. /// Smaller number is the higher priority.
  1685. static unsigned
  1686. CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
  1687. if (SUNumbers[SU->NodeNum] != 0)
  1688. return SUNumbers[SU->NodeNum];
  1689. // Use WorkList to avoid stack overflow on excessively large IRs.
  1690. struct WorkState {
  1691. WorkState(const SUnit *SU) : SU(SU) {}
  1692. const SUnit *SU;
  1693. unsigned PredsProcessed = 0;
  1694. };
  1695. SmallVector<WorkState, 16> WorkList;
  1696. WorkList.push_back(SU);
  1697. while (!WorkList.empty()) {
  1698. auto &Temp = WorkList.back();
  1699. auto *TempSU = Temp.SU;
  1700. bool AllPredsKnown = true;
  1701. // Try to find a non-evaluated pred and push it into the processing stack.
  1702. for (unsigned P = Temp.PredsProcessed; P < TempSU->Preds.size(); ++P) {
  1703. auto &Pred = TempSU->Preds[P];
  1704. if (Pred.isCtrl()) continue; // ignore chain preds
  1705. SUnit *PredSU = Pred.getSUnit();
  1706. if (SUNumbers[PredSU->NodeNum] == 0) {
  1707. #ifndef NDEBUG
  1708. // In debug mode, check that we don't have such element in the stack.
  1709. for (auto It : WorkList)
  1710. assert(It.SU != PredSU && "Trying to push an element twice?");
  1711. #endif
  1712. // Next time start processing this one starting from the next pred.
  1713. Temp.PredsProcessed = P + 1;
  1714. WorkList.push_back(PredSU);
  1715. AllPredsKnown = false;
  1716. break;
  1717. }
  1718. }
  1719. if (!AllPredsKnown)
  1720. continue;
  1721. // Once all preds are known, we can calculate the answer for this one.
  1722. unsigned SethiUllmanNumber = 0;
  1723. unsigned Extra = 0;
  1724. for (const SDep &Pred : TempSU->Preds) {
  1725. if (Pred.isCtrl()) continue; // ignore chain preds
  1726. SUnit *PredSU = Pred.getSUnit();
  1727. unsigned PredSethiUllman = SUNumbers[PredSU->NodeNum];
  1728. assert(PredSethiUllman > 0 && "We should have evaluated this pred!");
  1729. if (PredSethiUllman > SethiUllmanNumber) {
  1730. SethiUllmanNumber = PredSethiUllman;
  1731. Extra = 0;
  1732. } else if (PredSethiUllman == SethiUllmanNumber)
  1733. ++Extra;
  1734. }
  1735. SethiUllmanNumber += Extra;
  1736. if (SethiUllmanNumber == 0)
  1737. SethiUllmanNumber = 1;
  1738. SUNumbers[TempSU->NodeNum] = SethiUllmanNumber;
  1739. WorkList.pop_back();
  1740. }
  1741. assert(SUNumbers[SU->NodeNum] > 0 && "SethiUllman should never be zero!");
  1742. return SUNumbers[SU->NodeNum];
  1743. }
  1744. /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
  1745. /// scheduling units.
  1746. void RegReductionPQBase::CalculateSethiUllmanNumbers() {
  1747. SethiUllmanNumbers.assign(SUnits->size(), 0);
  1748. for (const SUnit &SU : *SUnits)
  1749. CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
  1750. }
  1751. void RegReductionPQBase::addNode(const SUnit *SU) {
  1752. unsigned SUSize = SethiUllmanNumbers.size();
  1753. if (SUnits->size() > SUSize)
  1754. SethiUllmanNumbers.resize(SUSize*2, 0);
  1755. CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
  1756. }
  1757. void RegReductionPQBase::updateNode(const SUnit *SU) {
  1758. SethiUllmanNumbers[SU->NodeNum] = 0;
  1759. CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
  1760. }
  1761. // Lower priority means schedule further down. For bottom-up scheduling, lower
  1762. // priority SUs are scheduled before higher priority SUs.
  1763. unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
  1764. assert(SU->NodeNum < SethiUllmanNumbers.size());
  1765. unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
  1766. if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
  1767. // CopyToReg should be close to its uses to facilitate coalescing and
  1768. // avoid spilling.
  1769. return 0;
  1770. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  1771. Opc == TargetOpcode::SUBREG_TO_REG ||
  1772. Opc == TargetOpcode::INSERT_SUBREG)
  1773. // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
  1774. // close to their uses to facilitate coalescing.
  1775. return 0;
  1776. if (SU->NumSuccs == 0 && SU->NumPreds != 0)
  1777. // If SU does not have a register use, i.e. it doesn't produce a value
  1778. // that would be consumed (e.g. store), then it terminates a chain of
  1779. // computation. Give it a large SethiUllman number so it will be
  1780. // scheduled right before its predecessors that it doesn't lengthen
  1781. // their live ranges.
  1782. return 0xffff;
  1783. if (SU->NumPreds == 0 && SU->NumSuccs != 0)
  1784. // If SU does not have a register def, schedule it close to its uses
  1785. // because it does not lengthen any live ranges.
  1786. return 0;
  1787. #if 1
  1788. return SethiUllmanNumbers[SU->NodeNum];
  1789. #else
  1790. unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
  1791. if (SU->isCallOp) {
  1792. // FIXME: This assumes all of the defs are used as call operands.
  1793. int NP = (int)Priority - SU->getNode()->getNumValues();
  1794. return (NP > 0) ? NP : 0;
  1795. }
  1796. return Priority;
  1797. #endif
  1798. }
  1799. //===----------------------------------------------------------------------===//
  1800. // Register Pressure Tracking
  1801. //===----------------------------------------------------------------------===//
  1802. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1803. LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
  1804. for (const TargetRegisterClass *RC : TRI->regclasses()) {
  1805. unsigned Id = RC->getID();
  1806. unsigned RP = RegPressure[Id];
  1807. if (!RP) continue;
  1808. LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
  1809. << RegLimit[Id] << '\n');
  1810. }
  1811. }
  1812. #endif
  1813. bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
  1814. if (!TLI)
  1815. return false;
  1816. for (const SDep &Pred : SU->Preds) {
  1817. if (Pred.isCtrl())
  1818. continue;
  1819. SUnit *PredSU = Pred.getSUnit();
  1820. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1821. // to cover the number of registers defined (they are all live).
  1822. if (PredSU->NumRegDefsLeft == 0) {
  1823. continue;
  1824. }
  1825. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1826. RegDefPos.IsValid(); RegDefPos.Advance()) {
  1827. unsigned RCId, Cost;
  1828. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1829. if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
  1830. return true;
  1831. }
  1832. }
  1833. return false;
  1834. }
  1835. bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
  1836. const SDNode *N = SU->getNode();
  1837. if (!N->isMachineOpcode() || !SU->NumSuccs)
  1838. return false;
  1839. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  1840. for (unsigned i = 0; i != NumDefs; ++i) {
  1841. MVT VT = N->getSimpleValueType(i);
  1842. if (!N->hasAnyUseOfValue(i))
  1843. continue;
  1844. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1845. if (RegPressure[RCId] >= RegLimit[RCId])
  1846. return true;
  1847. }
  1848. return false;
  1849. }
  1850. // Compute the register pressure contribution by this instruction by count up
  1851. // for uses that are not live and down for defs. Only count register classes
  1852. // that are already under high pressure. As a side effect, compute the number of
  1853. // uses of registers that are already live.
  1854. //
  1855. // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
  1856. // so could probably be factored.
  1857. int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
  1858. LiveUses = 0;
  1859. int PDiff = 0;
  1860. for (const SDep &Pred : SU->Preds) {
  1861. if (Pred.isCtrl())
  1862. continue;
  1863. SUnit *PredSU = Pred.getSUnit();
  1864. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1865. // to cover the number of registers defined (they are all live).
  1866. if (PredSU->NumRegDefsLeft == 0) {
  1867. if (PredSU->getNode()->isMachineOpcode())
  1868. ++LiveUses;
  1869. continue;
  1870. }
  1871. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1872. RegDefPos.IsValid(); RegDefPos.Advance()) {
  1873. MVT VT = RegDefPos.GetValue();
  1874. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1875. if (RegPressure[RCId] >= RegLimit[RCId])
  1876. ++PDiff;
  1877. }
  1878. }
  1879. const SDNode *N = SU->getNode();
  1880. if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
  1881. return PDiff;
  1882. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  1883. for (unsigned i = 0; i != NumDefs; ++i) {
  1884. MVT VT = N->getSimpleValueType(i);
  1885. if (!N->hasAnyUseOfValue(i))
  1886. continue;
  1887. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1888. if (RegPressure[RCId] >= RegLimit[RCId])
  1889. --PDiff;
  1890. }
  1891. return PDiff;
  1892. }
  1893. void RegReductionPQBase::scheduledNode(SUnit *SU) {
  1894. if (!TracksRegPressure)
  1895. return;
  1896. if (!SU->getNode())
  1897. return;
  1898. for (const SDep &Pred : SU->Preds) {
  1899. if (Pred.isCtrl())
  1900. continue;
  1901. SUnit *PredSU = Pred.getSUnit();
  1902. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1903. // to cover the number of registers defined (they are all live).
  1904. if (PredSU->NumRegDefsLeft == 0) {
  1905. continue;
  1906. }
  1907. // FIXME: The ScheduleDAG currently loses information about which of a
  1908. // node's values is consumed by each dependence. Consequently, if the node
  1909. // defines multiple register classes, we don't know which to pressurize
  1910. // here. Instead the following loop consumes the register defs in an
  1911. // arbitrary order. At least it handles the common case of clustered loads
  1912. // to the same class. For precise liveness, each SDep needs to indicate the
  1913. // result number. But that tightly couples the ScheduleDAG with the
  1914. // SelectionDAG making updates tricky. A simpler hack would be to attach a
  1915. // value type or register class to SDep.
  1916. //
  1917. // The most important aspect of register tracking is balancing the increase
  1918. // here with the reduction further below. Note that this SU may use multiple
  1919. // defs in PredSU. The can't be determined here, but we've already
  1920. // compensated by reducing NumRegDefsLeft in PredSU during
  1921. // ScheduleDAGSDNodes::AddSchedEdges.
  1922. --PredSU->NumRegDefsLeft;
  1923. unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
  1924. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1925. RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
  1926. if (SkipRegDefs)
  1927. continue;
  1928. unsigned RCId, Cost;
  1929. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1930. RegPressure[RCId] += Cost;
  1931. break;
  1932. }
  1933. }
  1934. // We should have this assert, but there may be dead SDNodes that never
  1935. // materialize as SUnits, so they don't appear to generate liveness.
  1936. //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
  1937. int SkipRegDefs = (int)SU->NumRegDefsLeft;
  1938. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
  1939. RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
  1940. if (SkipRegDefs > 0)
  1941. continue;
  1942. unsigned RCId, Cost;
  1943. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1944. if (RegPressure[RCId] < Cost) {
  1945. // Register pressure tracking is imprecise. This can happen. But we try
  1946. // hard not to let it happen because it likely results in poor scheduling.
  1947. LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum
  1948. << ") has too many regdefs\n");
  1949. RegPressure[RCId] = 0;
  1950. }
  1951. else {
  1952. RegPressure[RCId] -= Cost;
  1953. }
  1954. }
  1955. LLVM_DEBUG(dumpRegPressure());
  1956. }
  1957. void RegReductionPQBase::unscheduledNode(SUnit *SU) {
  1958. if (!TracksRegPressure)
  1959. return;
  1960. const SDNode *N = SU->getNode();
  1961. if (!N) return;
  1962. if (!N->isMachineOpcode()) {
  1963. if (N->getOpcode() != ISD::CopyToReg)
  1964. return;
  1965. } else {
  1966. unsigned Opc = N->getMachineOpcode();
  1967. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  1968. Opc == TargetOpcode::INSERT_SUBREG ||
  1969. Opc == TargetOpcode::SUBREG_TO_REG ||
  1970. Opc == TargetOpcode::REG_SEQUENCE ||
  1971. Opc == TargetOpcode::IMPLICIT_DEF)
  1972. return;
  1973. }
  1974. for (const SDep &Pred : SU->Preds) {
  1975. if (Pred.isCtrl())
  1976. continue;
  1977. SUnit *PredSU = Pred.getSUnit();
  1978. // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
  1979. // counts data deps.
  1980. if (PredSU->NumSuccsLeft != PredSU->Succs.size())
  1981. continue;
  1982. const SDNode *PN = PredSU->getNode();
  1983. if (!PN->isMachineOpcode()) {
  1984. if (PN->getOpcode() == ISD::CopyFromReg) {
  1985. MVT VT = PN->getSimpleValueType(0);
  1986. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1987. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  1988. }
  1989. continue;
  1990. }
  1991. unsigned POpc = PN->getMachineOpcode();
  1992. if (POpc == TargetOpcode::IMPLICIT_DEF)
  1993. continue;
  1994. if (POpc == TargetOpcode::EXTRACT_SUBREG ||
  1995. POpc == TargetOpcode::INSERT_SUBREG ||
  1996. POpc == TargetOpcode::SUBREG_TO_REG) {
  1997. MVT VT = PN->getSimpleValueType(0);
  1998. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1999. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  2000. continue;
  2001. }
  2002. unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
  2003. for (unsigned i = 0; i != NumDefs; ++i) {
  2004. MVT VT = PN->getSimpleValueType(i);
  2005. if (!PN->hasAnyUseOfValue(i))
  2006. continue;
  2007. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2008. if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
  2009. // Register pressure tracking is imprecise. This can happen.
  2010. RegPressure[RCId] = 0;
  2011. else
  2012. RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
  2013. }
  2014. }
  2015. // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
  2016. // may transfer data dependencies to CopyToReg.
  2017. if (SU->NumSuccs && N->isMachineOpcode()) {
  2018. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  2019. for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
  2020. MVT VT = N->getSimpleValueType(i);
  2021. if (VT == MVT::Glue || VT == MVT::Other)
  2022. continue;
  2023. if (!N->hasAnyUseOfValue(i))
  2024. continue;
  2025. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2026. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  2027. }
  2028. }
  2029. LLVM_DEBUG(dumpRegPressure());
  2030. }
  2031. //===----------------------------------------------------------------------===//
  2032. // Dynamic Node Priority for Register Pressure Reduction
  2033. //===----------------------------------------------------------------------===//
  2034. /// closestSucc - Returns the scheduled cycle of the successor which is
  2035. /// closest to the current cycle.
  2036. static unsigned closestSucc(const SUnit *SU) {
  2037. unsigned MaxHeight = 0;
  2038. for (const SDep &Succ : SU->Succs) {
  2039. if (Succ.isCtrl()) continue; // ignore chain succs
  2040. unsigned Height = Succ.getSUnit()->getHeight();
  2041. // If there are bunch of CopyToRegs stacked up, they should be considered
  2042. // to be at the same position.
  2043. if (Succ.getSUnit()->getNode() &&
  2044. Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
  2045. Height = closestSucc(Succ.getSUnit())+1;
  2046. if (Height > MaxHeight)
  2047. MaxHeight = Height;
  2048. }
  2049. return MaxHeight;
  2050. }
  2051. /// calcMaxScratches - Returns an cost estimate of the worse case requirement
  2052. /// for scratch registers, i.e. number of data dependencies.
  2053. static unsigned calcMaxScratches(const SUnit *SU) {
  2054. unsigned Scratches = 0;
  2055. for (const SDep &Pred : SU->Preds) {
  2056. if (Pred.isCtrl()) continue; // ignore chain preds
  2057. Scratches++;
  2058. }
  2059. return Scratches;
  2060. }
  2061. /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
  2062. /// CopyFromReg from a virtual register.
  2063. static bool hasOnlyLiveInOpers(const SUnit *SU) {
  2064. bool RetVal = false;
  2065. for (const SDep &Pred : SU->Preds) {
  2066. if (Pred.isCtrl()) continue;
  2067. const SUnit *PredSU = Pred.getSUnit();
  2068. if (PredSU->getNode() &&
  2069. PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
  2070. unsigned Reg =
  2071. cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
  2072. if (Register::isVirtualRegister(Reg)) {
  2073. RetVal = true;
  2074. continue;
  2075. }
  2076. }
  2077. return false;
  2078. }
  2079. return RetVal;
  2080. }
  2081. /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
  2082. /// CopyToReg to a virtual register. This SU def is probably a liveout and
  2083. /// it has no other use. It should be scheduled closer to the terminator.
  2084. static bool hasOnlyLiveOutUses(const SUnit *SU) {
  2085. bool RetVal = false;
  2086. for (const SDep &Succ : SU->Succs) {
  2087. if (Succ.isCtrl()) continue;
  2088. const SUnit *SuccSU = Succ.getSUnit();
  2089. if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
  2090. unsigned Reg =
  2091. cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
  2092. if (Register::isVirtualRegister(Reg)) {
  2093. RetVal = true;
  2094. continue;
  2095. }
  2096. }
  2097. return false;
  2098. }
  2099. return RetVal;
  2100. }
  2101. // Set isVRegCycle for a node with only live in opers and live out uses. Also
  2102. // set isVRegCycle for its CopyFromReg operands.
  2103. //
  2104. // This is only relevant for single-block loops, in which case the VRegCycle
  2105. // node is likely an induction variable in which the operand and target virtual
  2106. // registers should be coalesced (e.g. pre/post increment values). Setting the
  2107. // isVRegCycle flag helps the scheduler prioritize other uses of the same
  2108. // CopyFromReg so that this node becomes the virtual register "kill". This
  2109. // avoids interference between the values live in and out of the block and
  2110. // eliminates a copy inside the loop.
  2111. static void initVRegCycle(SUnit *SU) {
  2112. if (DisableSchedVRegCycle)
  2113. return;
  2114. if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
  2115. return;
  2116. LLVM_DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
  2117. SU->isVRegCycle = true;
  2118. for (const SDep &Pred : SU->Preds) {
  2119. if (Pred.isCtrl()) continue;
  2120. Pred.getSUnit()->isVRegCycle = true;
  2121. }
  2122. }
  2123. // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
  2124. // CopyFromReg operands. We should no longer penalize other uses of this VReg.
  2125. static void resetVRegCycle(SUnit *SU) {
  2126. if (!SU->isVRegCycle)
  2127. return;
  2128. for (const SDep &Pred : SU->Preds) {
  2129. if (Pred.isCtrl()) continue; // ignore chain preds
  2130. SUnit *PredSU = Pred.getSUnit();
  2131. if (PredSU->isVRegCycle) {
  2132. assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
  2133. "VRegCycle def must be CopyFromReg");
  2134. Pred.getSUnit()->isVRegCycle = false;
  2135. }
  2136. }
  2137. }
  2138. // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
  2139. // means a node that defines the VRegCycle has not been scheduled yet.
  2140. static bool hasVRegCycleUse(const SUnit *SU) {
  2141. // If this SU also defines the VReg, don't hoist it as a "use".
  2142. if (SU->isVRegCycle)
  2143. return false;
  2144. for (const SDep &Pred : SU->Preds) {
  2145. if (Pred.isCtrl()) continue; // ignore chain preds
  2146. if (Pred.getSUnit()->isVRegCycle &&
  2147. Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
  2148. LLVM_DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
  2149. return true;
  2150. }
  2151. }
  2152. return false;
  2153. }
  2154. // Check for either a dependence (latency) or resource (hazard) stall.
  2155. //
  2156. // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
  2157. static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
  2158. if ((int)SPQ->getCurCycle() < Height) return true;
  2159. if (SPQ->getHazardRec()->getHazardType(SU, 0)
  2160. != ScheduleHazardRecognizer::NoHazard)
  2161. return true;
  2162. return false;
  2163. }
  2164. // Return -1 if left has higher priority, 1 if right has higher priority.
  2165. // Return 0 if latency-based priority is equivalent.
  2166. static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
  2167. RegReductionPQBase *SPQ) {
  2168. // Scheduling an instruction that uses a VReg whose postincrement has not yet
  2169. // been scheduled will induce a copy. Model this as an extra cycle of latency.
  2170. int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
  2171. int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
  2172. int LHeight = (int)left->getHeight() + LPenalty;
  2173. int RHeight = (int)right->getHeight() + RPenalty;
  2174. bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
  2175. BUHasStall(left, LHeight, SPQ);
  2176. bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
  2177. BUHasStall(right, RHeight, SPQ);
  2178. // If scheduling one of the node will cause a pipeline stall, delay it.
  2179. // If scheduling either one of the node will cause a pipeline stall, sort
  2180. // them according to their height.
  2181. if (LStall) {
  2182. if (!RStall)
  2183. return 1;
  2184. if (LHeight != RHeight)
  2185. return LHeight > RHeight ? 1 : -1;
  2186. } else if (RStall)
  2187. return -1;
  2188. // If either node is scheduling for latency, sort them by height/depth
  2189. // and latency.
  2190. if (!checkPref || (left->SchedulingPref == Sched::ILP ||
  2191. right->SchedulingPref == Sched::ILP)) {
  2192. // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
  2193. // is enabled, grouping instructions by cycle, then its height is already
  2194. // covered so only its depth matters. We also reach this point if both stall
  2195. // but have the same height.
  2196. if (!SPQ->getHazardRec()->isEnabled()) {
  2197. if (LHeight != RHeight)
  2198. return LHeight > RHeight ? 1 : -1;
  2199. }
  2200. int LDepth = left->getDepth() - LPenalty;
  2201. int RDepth = right->getDepth() - RPenalty;
  2202. if (LDepth != RDepth) {
  2203. LLVM_DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
  2204. << ") depth " << LDepth << " vs SU (" << right->NodeNum
  2205. << ") depth " << RDepth << "\n");
  2206. return LDepth < RDepth ? 1 : -1;
  2207. }
  2208. if (left->Latency != right->Latency)
  2209. return left->Latency > right->Latency ? 1 : -1;
  2210. }
  2211. return 0;
  2212. }
  2213. static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
  2214. // Schedule physical register definitions close to their use. This is
  2215. // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
  2216. // long as shortening physreg live ranges is generally good, we can defer
  2217. // creating a subtarget hook.
  2218. if (!DisableSchedPhysRegJoin) {
  2219. bool LHasPhysReg = left->hasPhysRegDefs;
  2220. bool RHasPhysReg = right->hasPhysRegDefs;
  2221. if (LHasPhysReg != RHasPhysReg) {
  2222. #ifndef NDEBUG
  2223. static const char *const PhysRegMsg[] = { " has no physreg",
  2224. " defines a physreg" };
  2225. #endif
  2226. LLVM_DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
  2227. << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum
  2228. << ") " << PhysRegMsg[RHasPhysReg] << "\n");
  2229. return LHasPhysReg < RHasPhysReg;
  2230. }
  2231. }
  2232. // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
  2233. unsigned LPriority = SPQ->getNodePriority(left);
  2234. unsigned RPriority = SPQ->getNodePriority(right);
  2235. // Be really careful about hoisting call operands above previous calls.
  2236. // Only allows it if it would reduce register pressure.
  2237. if (left->isCall && right->isCallOp) {
  2238. unsigned RNumVals = right->getNode()->getNumValues();
  2239. RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
  2240. }
  2241. if (right->isCall && left->isCallOp) {
  2242. unsigned LNumVals = left->getNode()->getNumValues();
  2243. LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
  2244. }
  2245. if (LPriority != RPriority)
  2246. return LPriority > RPriority;
  2247. // One or both of the nodes are calls and their sethi-ullman numbers are the
  2248. // same, then keep source order.
  2249. if (left->isCall || right->isCall) {
  2250. unsigned LOrder = SPQ->getNodeOrdering(left);
  2251. unsigned ROrder = SPQ->getNodeOrdering(right);
  2252. // Prefer an ordering where the lower the non-zero order number, the higher
  2253. // the preference.
  2254. if ((LOrder || ROrder) && LOrder != ROrder)
  2255. return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
  2256. }
  2257. // Try schedule def + use closer when Sethi-Ullman numbers are the same.
  2258. // e.g.
  2259. // t1 = op t2, c1
  2260. // t3 = op t4, c2
  2261. //
  2262. // and the following instructions are both ready.
  2263. // t2 = op c3
  2264. // t4 = op c4
  2265. //
  2266. // Then schedule t2 = op first.
  2267. // i.e.
  2268. // t4 = op c4
  2269. // t2 = op c3
  2270. // t1 = op t2, c1
  2271. // t3 = op t4, c2
  2272. //
  2273. // This creates more short live intervals.
  2274. unsigned LDist = closestSucc(left);
  2275. unsigned RDist = closestSucc(right);
  2276. if (LDist != RDist)
  2277. return LDist < RDist;
  2278. // How many registers becomes live when the node is scheduled.
  2279. unsigned LScratch = calcMaxScratches(left);
  2280. unsigned RScratch = calcMaxScratches(right);
  2281. if (LScratch != RScratch)
  2282. return LScratch > RScratch;
  2283. // Comparing latency against a call makes little sense unless the node
  2284. // is register pressure-neutral.
  2285. if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
  2286. return (left->NodeQueueId > right->NodeQueueId);
  2287. // Do not compare latencies when one or both of the nodes are calls.
  2288. if (!DisableSchedCycles &&
  2289. !(left->isCall || right->isCall)) {
  2290. int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
  2291. if (result != 0)
  2292. return result > 0;
  2293. }
  2294. else {
  2295. if (left->getHeight() != right->getHeight())
  2296. return left->getHeight() > right->getHeight();
  2297. if (left->getDepth() != right->getDepth())
  2298. return left->getDepth() < right->getDepth();
  2299. }
  2300. assert(left->NodeQueueId && right->NodeQueueId &&
  2301. "NodeQueueId cannot be zero");
  2302. return (left->NodeQueueId > right->NodeQueueId);
  2303. }
  2304. // Bottom up
  2305. bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2306. if (int res = checkSpecialNodes(left, right))
  2307. return res > 0;
  2308. return BURRSort(left, right, SPQ);
  2309. }
  2310. // Source order, otherwise bottom up.
  2311. bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2312. if (int res = checkSpecialNodes(left, right))
  2313. return res > 0;
  2314. unsigned LOrder = SPQ->getNodeOrdering(left);
  2315. unsigned ROrder = SPQ->getNodeOrdering(right);
  2316. // Prefer an ordering where the lower the non-zero order number, the higher
  2317. // the preference.
  2318. if ((LOrder || ROrder) && LOrder != ROrder)
  2319. return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
  2320. return BURRSort(left, right, SPQ);
  2321. }
  2322. // If the time between now and when the instruction will be ready can cover
  2323. // the spill code, then avoid adding it to the ready queue. This gives long
  2324. // stalls highest priority and allows hoisting across calls. It should also
  2325. // speed up processing the available queue.
  2326. bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
  2327. static const unsigned ReadyDelay = 3;
  2328. if (SPQ->MayReduceRegPressure(SU)) return true;
  2329. if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
  2330. if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
  2331. != ScheduleHazardRecognizer::NoHazard)
  2332. return false;
  2333. return true;
  2334. }
  2335. // Return true if right should be scheduled with higher priority than left.
  2336. bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2337. if (int res = checkSpecialNodes(left, right))
  2338. return res > 0;
  2339. if (left->isCall || right->isCall)
  2340. // No way to compute latency of calls.
  2341. return BURRSort(left, right, SPQ);
  2342. bool LHigh = SPQ->HighRegPressure(left);
  2343. bool RHigh = SPQ->HighRegPressure(right);
  2344. // Avoid causing spills. If register pressure is high, schedule for
  2345. // register pressure reduction.
  2346. if (LHigh && !RHigh) {
  2347. LLVM_DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
  2348. << right->NodeNum << ")\n");
  2349. return true;
  2350. }
  2351. else if (!LHigh && RHigh) {
  2352. LLVM_DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
  2353. << left->NodeNum << ")\n");
  2354. return false;
  2355. }
  2356. if (!LHigh && !RHigh) {
  2357. int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
  2358. if (result != 0)
  2359. return result > 0;
  2360. }
  2361. return BURRSort(left, right, SPQ);
  2362. }
  2363. // Schedule as many instructions in each cycle as possible. So don't make an
  2364. // instruction available unless it is ready in the current cycle.
  2365. bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
  2366. if (SU->getHeight() > CurCycle) return false;
  2367. if (SPQ->getHazardRec()->getHazardType(SU, 0)
  2368. != ScheduleHazardRecognizer::NoHazard)
  2369. return false;
  2370. return true;
  2371. }
  2372. static bool canEnableCoalescing(SUnit *SU) {
  2373. unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
  2374. if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
  2375. // CopyToReg should be close to its uses to facilitate coalescing and
  2376. // avoid spilling.
  2377. return true;
  2378. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  2379. Opc == TargetOpcode::SUBREG_TO_REG ||
  2380. Opc == TargetOpcode::INSERT_SUBREG)
  2381. // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
  2382. // close to their uses to facilitate coalescing.
  2383. return true;
  2384. if (SU->NumPreds == 0 && SU->NumSuccs != 0)
  2385. // If SU does not have a register def, schedule it close to its uses
  2386. // because it does not lengthen any live ranges.
  2387. return true;
  2388. return false;
  2389. }
  2390. // list-ilp is currently an experimental scheduler that allows various
  2391. // heuristics to be enabled prior to the normal register reduction logic.
  2392. bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2393. if (int res = checkSpecialNodes(left, right))
  2394. return res > 0;
  2395. if (left->isCall || right->isCall)
  2396. // No way to compute latency of calls.
  2397. return BURRSort(left, right, SPQ);
  2398. unsigned LLiveUses = 0, RLiveUses = 0;
  2399. int LPDiff = 0, RPDiff = 0;
  2400. if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
  2401. LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
  2402. RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
  2403. }
  2404. if (!DisableSchedRegPressure && LPDiff != RPDiff) {
  2405. LLVM_DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum
  2406. << "): " << LPDiff << " != SU(" << right->NodeNum
  2407. << "): " << RPDiff << "\n");
  2408. return LPDiff > RPDiff;
  2409. }
  2410. if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
  2411. bool LReduce = canEnableCoalescing(left);
  2412. bool RReduce = canEnableCoalescing(right);
  2413. if (LReduce && !RReduce) return false;
  2414. if (RReduce && !LReduce) return true;
  2415. }
  2416. if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
  2417. LLVM_DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
  2418. << " != SU(" << right->NodeNum << "): " << RLiveUses
  2419. << "\n");
  2420. return LLiveUses < RLiveUses;
  2421. }
  2422. if (!DisableSchedStalls) {
  2423. bool LStall = BUHasStall(left, left->getHeight(), SPQ);
  2424. bool RStall = BUHasStall(right, right->getHeight(), SPQ);
  2425. if (LStall != RStall)
  2426. return left->getHeight() > right->getHeight();
  2427. }
  2428. if (!DisableSchedCriticalPath) {
  2429. int spread = (int)left->getDepth() - (int)right->getDepth();
  2430. if (std::abs(spread) > MaxReorderWindow) {
  2431. LLVM_DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
  2432. << left->getDepth() << " != SU(" << right->NodeNum
  2433. << "): " << right->getDepth() << "\n");
  2434. return left->getDepth() < right->getDepth();
  2435. }
  2436. }
  2437. if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
  2438. int spread = (int)left->getHeight() - (int)right->getHeight();
  2439. if (std::abs(spread) > MaxReorderWindow)
  2440. return left->getHeight() > right->getHeight();
  2441. }
  2442. return BURRSort(left, right, SPQ);
  2443. }
  2444. void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
  2445. SUnits = &sunits;
  2446. // Add pseudo dependency edges for two-address nodes.
  2447. if (!Disable2AddrHack)
  2448. AddPseudoTwoAddrDeps();
  2449. // Reroute edges to nodes with multiple uses.
  2450. if (!TracksRegPressure && !SrcOrder)
  2451. PrescheduleNodesWithMultipleUses();
  2452. // Calculate node priorities.
  2453. CalculateSethiUllmanNumbers();
  2454. // For single block loops, mark nodes that look like canonical IV increments.
  2455. if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
  2456. for (SUnit &SU : sunits)
  2457. initVRegCycle(&SU);
  2458. }
  2459. //===----------------------------------------------------------------------===//
  2460. // Preschedule for Register Pressure
  2461. //===----------------------------------------------------------------------===//
  2462. bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
  2463. if (SU->isTwoAddress) {
  2464. unsigned Opc = SU->getNode()->getMachineOpcode();
  2465. const MCInstrDesc &MCID = TII->get(Opc);
  2466. unsigned NumRes = MCID.getNumDefs();
  2467. unsigned NumOps = MCID.getNumOperands() - NumRes;
  2468. for (unsigned i = 0; i != NumOps; ++i) {
  2469. if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
  2470. SDNode *DU = SU->getNode()->getOperand(i).getNode();
  2471. if (DU->getNodeId() != -1 &&
  2472. Op->OrigNode == &(*SUnits)[DU->getNodeId()])
  2473. return true;
  2474. }
  2475. }
  2476. }
  2477. return false;
  2478. }
  2479. /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
  2480. /// successor's explicit physregs whose definition can reach DepSU.
  2481. /// i.e. DepSU should not be scheduled above SU.
  2482. static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
  2483. ScheduleDAGRRList *scheduleDAG,
  2484. const TargetInstrInfo *TII,
  2485. const TargetRegisterInfo *TRI) {
  2486. const MCPhysReg *ImpDefs
  2487. = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
  2488. const uint32_t *RegMask = getNodeRegMask(SU->getNode());
  2489. if(!ImpDefs && !RegMask)
  2490. return false;
  2491. for (const SDep &Succ : SU->Succs) {
  2492. SUnit *SuccSU = Succ.getSUnit();
  2493. for (const SDep &SuccPred : SuccSU->Preds) {
  2494. if (!SuccPred.isAssignedRegDep())
  2495. continue;
  2496. if (RegMask &&
  2497. MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
  2498. scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
  2499. return true;
  2500. if (ImpDefs)
  2501. for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
  2502. // Return true if SU clobbers this physical register use and the
  2503. // definition of the register reaches from DepSU. IsReachable queries
  2504. // a topological forward sort of the DAG (following the successors).
  2505. if (TRI->regsOverlap(*ImpDef, SuccPred.getReg()) &&
  2506. scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
  2507. return true;
  2508. }
  2509. }
  2510. return false;
  2511. }
  2512. /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
  2513. /// physical register defs.
  2514. static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
  2515. const TargetInstrInfo *TII,
  2516. const TargetRegisterInfo *TRI) {
  2517. SDNode *N = SuccSU->getNode();
  2518. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  2519. const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
  2520. assert(ImpDefs && "Caller should check hasPhysRegDefs");
  2521. for (const SDNode *SUNode = SU->getNode(); SUNode;
  2522. SUNode = SUNode->getGluedNode()) {
  2523. if (!SUNode->isMachineOpcode())
  2524. continue;
  2525. const MCPhysReg *SUImpDefs =
  2526. TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
  2527. const uint32_t *SURegMask = getNodeRegMask(SUNode);
  2528. if (!SUImpDefs && !SURegMask)
  2529. continue;
  2530. for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
  2531. MVT VT = N->getSimpleValueType(i);
  2532. if (VT == MVT::Glue || VT == MVT::Other)
  2533. continue;
  2534. if (!N->hasAnyUseOfValue(i))
  2535. continue;
  2536. unsigned Reg = ImpDefs[i - NumDefs];
  2537. if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
  2538. return true;
  2539. if (!SUImpDefs)
  2540. continue;
  2541. for (;*SUImpDefs; ++SUImpDefs) {
  2542. unsigned SUReg = *SUImpDefs;
  2543. if (TRI->regsOverlap(Reg, SUReg))
  2544. return true;
  2545. }
  2546. }
  2547. }
  2548. return false;
  2549. }
  2550. /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
  2551. /// are not handled well by the general register pressure reduction
  2552. /// heuristics. When presented with code like this:
  2553. ///
  2554. /// N
  2555. /// / |
  2556. /// / |
  2557. /// U store
  2558. /// |
  2559. /// ...
  2560. ///
  2561. /// the heuristics tend to push the store up, but since the
  2562. /// operand of the store has another use (U), this would increase
  2563. /// the length of that other use (the U->N edge).
  2564. ///
  2565. /// This function transforms code like the above to route U's
  2566. /// dependence through the store when possible, like this:
  2567. ///
  2568. /// N
  2569. /// ||
  2570. /// ||
  2571. /// store
  2572. /// |
  2573. /// U
  2574. /// |
  2575. /// ...
  2576. ///
  2577. /// This results in the store being scheduled immediately
  2578. /// after N, which shortens the U->N live range, reducing
  2579. /// register pressure.
  2580. void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
  2581. // Visit all the nodes in topological order, working top-down.
  2582. for (SUnit &SU : *SUnits) {
  2583. // For now, only look at nodes with no data successors, such as stores.
  2584. // These are especially important, due to the heuristics in
  2585. // getNodePriority for nodes with no data successors.
  2586. if (SU.NumSuccs != 0)
  2587. continue;
  2588. // For now, only look at nodes with exactly one data predecessor.
  2589. if (SU.NumPreds != 1)
  2590. continue;
  2591. // Avoid prescheduling copies to virtual registers, which don't behave
  2592. // like other nodes from the perspective of scheduling heuristics.
  2593. if (SDNode *N = SU.getNode())
  2594. if (N->getOpcode() == ISD::CopyToReg &&
  2595. Register::isVirtualRegister(
  2596. cast<RegisterSDNode>(N->getOperand(1))->getReg()))
  2597. continue;
  2598. SDNode *PredFrameSetup = nullptr;
  2599. for (const SDep &Pred : SU.Preds)
  2600. if (Pred.isCtrl() && Pred.getSUnit()) {
  2601. // Find the predecessor which is not data dependence.
  2602. SDNode *PredND = Pred.getSUnit()->getNode();
  2603. // If PredND is FrameSetup, we should not pre-scheduled the node,
  2604. // or else, when bottom up scheduling, ADJCALLSTACKDOWN and
  2605. // ADJCALLSTACKUP may hold CallResource too long and make other
  2606. // calls can't be scheduled. If there's no other available node
  2607. // to schedule, the schedular will try to rename the register by
  2608. // creating copy to avoid the conflict which will fail because
  2609. // CallResource is not a real physical register.
  2610. if (PredND && PredND->isMachineOpcode() &&
  2611. (PredND->getMachineOpcode() == TII->getCallFrameSetupOpcode())) {
  2612. PredFrameSetup = PredND;
  2613. break;
  2614. }
  2615. }
  2616. // Skip the node has FrameSetup parent.
  2617. if (PredFrameSetup != nullptr)
  2618. continue;
  2619. // Locate the single data predecessor.
  2620. SUnit *PredSU = nullptr;
  2621. for (const SDep &Pred : SU.Preds)
  2622. if (!Pred.isCtrl()) {
  2623. PredSU = Pred.getSUnit();
  2624. break;
  2625. }
  2626. assert(PredSU);
  2627. // Don't rewrite edges that carry physregs, because that requires additional
  2628. // support infrastructure.
  2629. if (PredSU->hasPhysRegDefs)
  2630. continue;
  2631. // Short-circuit the case where SU is PredSU's only data successor.
  2632. if (PredSU->NumSuccs == 1)
  2633. continue;
  2634. // Avoid prescheduling to copies from virtual registers, which don't behave
  2635. // like other nodes from the perspective of scheduling heuristics.
  2636. if (SDNode *N = SU.getNode())
  2637. if (N->getOpcode() == ISD::CopyFromReg &&
  2638. Register::isVirtualRegister(
  2639. cast<RegisterSDNode>(N->getOperand(1))->getReg()))
  2640. continue;
  2641. // Perform checks on the successors of PredSU.
  2642. for (const SDep &PredSucc : PredSU->Succs) {
  2643. SUnit *PredSuccSU = PredSucc.getSUnit();
  2644. if (PredSuccSU == &SU) continue;
  2645. // If PredSU has another successor with no data successors, for
  2646. // now don't attempt to choose either over the other.
  2647. if (PredSuccSU->NumSuccs == 0)
  2648. goto outer_loop_continue;
  2649. // Don't break physical register dependencies.
  2650. if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
  2651. if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
  2652. goto outer_loop_continue;
  2653. // Don't introduce graph cycles.
  2654. if (scheduleDAG->IsReachable(&SU, PredSuccSU))
  2655. goto outer_loop_continue;
  2656. }
  2657. // Ok, the transformation is safe and the heuristics suggest it is
  2658. // profitable. Update the graph.
  2659. LLVM_DEBUG(
  2660. dbgs() << " Prescheduling SU #" << SU.NodeNum << " next to PredSU #"
  2661. << PredSU->NodeNum
  2662. << " to guide scheduling in the presence of multiple uses\n");
  2663. for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
  2664. SDep Edge = PredSU->Succs[i];
  2665. assert(!Edge.isAssignedRegDep());
  2666. SUnit *SuccSU = Edge.getSUnit();
  2667. if (SuccSU != &SU) {
  2668. Edge.setSUnit(PredSU);
  2669. scheduleDAG->RemovePred(SuccSU, Edge);
  2670. scheduleDAG->AddPredQueued(&SU, Edge);
  2671. Edge.setSUnit(&SU);
  2672. scheduleDAG->AddPredQueued(SuccSU, Edge);
  2673. --i;
  2674. }
  2675. }
  2676. outer_loop_continue:;
  2677. }
  2678. }
  2679. /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
  2680. /// it as a def&use operand. Add a pseudo control edge from it to the other
  2681. /// node (if it won't create a cycle) so the two-address one will be scheduled
  2682. /// first (lower in the schedule). If both nodes are two-address, favor the
  2683. /// one that has a CopyToReg use (more likely to be a loop induction update).
  2684. /// If both are two-address, but one is commutable while the other is not
  2685. /// commutable, favor the one that's not commutable.
  2686. void RegReductionPQBase::AddPseudoTwoAddrDeps() {
  2687. for (SUnit &SU : *SUnits) {
  2688. if (!SU.isTwoAddress)
  2689. continue;
  2690. SDNode *Node = SU.getNode();
  2691. if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
  2692. continue;
  2693. bool isLiveOut = hasOnlyLiveOutUses(&SU);
  2694. unsigned Opc = Node->getMachineOpcode();
  2695. const MCInstrDesc &MCID = TII->get(Opc);
  2696. unsigned NumRes = MCID.getNumDefs();
  2697. unsigned NumOps = MCID.getNumOperands() - NumRes;
  2698. for (unsigned j = 0; j != NumOps; ++j) {
  2699. if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
  2700. continue;
  2701. SDNode *DU = SU.getNode()->getOperand(j).getNode();
  2702. if (DU->getNodeId() == -1)
  2703. continue;
  2704. const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
  2705. if (!DUSU)
  2706. continue;
  2707. for (const SDep &Succ : DUSU->Succs) {
  2708. if (Succ.isCtrl())
  2709. continue;
  2710. SUnit *SuccSU = Succ.getSUnit();
  2711. if (SuccSU == &SU)
  2712. continue;
  2713. // Be conservative. Ignore if nodes aren't at roughly the same
  2714. // depth and height.
  2715. if (SuccSU->getHeight() < SU.getHeight() &&
  2716. (SU.getHeight() - SuccSU->getHeight()) > 1)
  2717. continue;
  2718. // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
  2719. // constrains whatever is using the copy, instead of the copy
  2720. // itself. In the case that the copy is coalesced, this
  2721. // preserves the intent of the pseudo two-address heurietics.
  2722. while (SuccSU->Succs.size() == 1 &&
  2723. SuccSU->getNode()->isMachineOpcode() &&
  2724. SuccSU->getNode()->getMachineOpcode() ==
  2725. TargetOpcode::COPY_TO_REGCLASS)
  2726. SuccSU = SuccSU->Succs.front().getSUnit();
  2727. // Don't constrain non-instruction nodes.
  2728. if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
  2729. continue;
  2730. // Don't constrain nodes with physical register defs if the
  2731. // predecessor can clobber them.
  2732. if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
  2733. if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
  2734. continue;
  2735. }
  2736. // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
  2737. // these may be coalesced away. We want them close to their uses.
  2738. unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
  2739. if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
  2740. SuccOpc == TargetOpcode::INSERT_SUBREG ||
  2741. SuccOpc == TargetOpcode::SUBREG_TO_REG)
  2742. continue;
  2743. if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
  2744. (!canClobber(SuccSU, DUSU) ||
  2745. (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
  2746. (!SU.isCommutable && SuccSU->isCommutable)) &&
  2747. !scheduleDAG->IsReachable(SuccSU, &SU)) {
  2748. LLVM_DEBUG(dbgs()
  2749. << " Adding a pseudo-two-addr edge from SU #"
  2750. << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
  2751. scheduleDAG->AddPredQueued(&SU, SDep(SuccSU, SDep::Artificial));
  2752. }
  2753. }
  2754. }
  2755. }
  2756. }
  2757. //===----------------------------------------------------------------------===//
  2758. // Public Constructor Functions
  2759. //===----------------------------------------------------------------------===//
  2760. ScheduleDAGSDNodes *
  2761. llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
  2762. CodeGenOpt::Level OptLevel) {
  2763. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2764. const TargetInstrInfo *TII = STI.getInstrInfo();
  2765. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2766. BURegReductionPriorityQueue *PQ =
  2767. new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
  2768. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
  2769. PQ->setScheduleDAG(SD);
  2770. return SD;
  2771. }
  2772. ScheduleDAGSDNodes *
  2773. llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
  2774. CodeGenOpt::Level OptLevel) {
  2775. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2776. const TargetInstrInfo *TII = STI.getInstrInfo();
  2777. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2778. SrcRegReductionPriorityQueue *PQ =
  2779. new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
  2780. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
  2781. PQ->setScheduleDAG(SD);
  2782. return SD;
  2783. }
  2784. ScheduleDAGSDNodes *
  2785. llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
  2786. CodeGenOpt::Level OptLevel) {
  2787. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2788. const TargetInstrInfo *TII = STI.getInstrInfo();
  2789. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2790. const TargetLowering *TLI = IS->TLI;
  2791. HybridBURRPriorityQueue *PQ =
  2792. new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
  2793. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
  2794. PQ->setScheduleDAG(SD);
  2795. return SD;
  2796. }
  2797. ScheduleDAGSDNodes *
  2798. llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
  2799. CodeGenOpt::Level OptLevel) {
  2800. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2801. const TargetInstrInfo *TII = STI.getInstrInfo();
  2802. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2803. const TargetLowering *TLI = IS->TLI;
  2804. ILPBURRPriorityQueue *PQ =
  2805. new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
  2806. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
  2807. PQ->setScheduleDAG(SD);
  2808. return SD;
  2809. }