ScheduleDAGRRList.cpp 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191
  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.AddSUnitWithoutPredecessors(NewNode);
  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.AddSUnitWithoutPredecessors(NewNode);
  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. // Make sure the clone comes after the original. (InstrEmitter assumes
  1047. // this ordering.)
  1048. AddPredQueued(NewSU, SDep(SU, SDep::Artificial));
  1049. // Only copy scheduled successors. Cut them from old node's successor
  1050. // list and move them over.
  1051. SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
  1052. for (SDep &Succ : SU->Succs) {
  1053. if (Succ.isArtificial())
  1054. continue;
  1055. SUnit *SuccSU = Succ.getSUnit();
  1056. if (SuccSU->isScheduled) {
  1057. SDep D = Succ;
  1058. D.setSUnit(NewSU);
  1059. AddPredQueued(SuccSU, D);
  1060. D.setSUnit(SU);
  1061. DelDeps.push_back(std::make_pair(SuccSU, D));
  1062. }
  1063. }
  1064. for (auto &DelDep : DelDeps)
  1065. RemovePred(DelDep.first, DelDep.second);
  1066. AvailableQueue->updateNode(SU);
  1067. AvailableQueue->addNode(NewSU);
  1068. ++NumDups;
  1069. return NewSU;
  1070. }
  1071. /// InsertCopiesAndMoveSuccs - Insert register copies and move all
  1072. /// scheduled successors of the given SUnit to the last copy.
  1073. void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
  1074. const TargetRegisterClass *DestRC,
  1075. const TargetRegisterClass *SrcRC,
  1076. SmallVectorImpl<SUnit*> &Copies) {
  1077. SUnit *CopyFromSU = CreateNewSUnit(nullptr);
  1078. CopyFromSU->CopySrcRC = SrcRC;
  1079. CopyFromSU->CopyDstRC = DestRC;
  1080. SUnit *CopyToSU = CreateNewSUnit(nullptr);
  1081. CopyToSU->CopySrcRC = DestRC;
  1082. CopyToSU->CopyDstRC = SrcRC;
  1083. // Only copy scheduled successors. Cut them from old node's successor
  1084. // list and move them over.
  1085. SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
  1086. for (SDep &Succ : SU->Succs) {
  1087. if (Succ.isArtificial())
  1088. continue;
  1089. SUnit *SuccSU = Succ.getSUnit();
  1090. if (SuccSU->isScheduled) {
  1091. SDep D = Succ;
  1092. D.setSUnit(CopyToSU);
  1093. AddPredQueued(SuccSU, D);
  1094. DelDeps.push_back(std::make_pair(SuccSU, Succ));
  1095. }
  1096. else {
  1097. // Avoid scheduling the def-side copy before other successors. Otherwise
  1098. // we could introduce another physreg interference on the copy and
  1099. // continue inserting copies indefinitely.
  1100. AddPredQueued(SuccSU, SDep(CopyFromSU, SDep::Artificial));
  1101. }
  1102. }
  1103. for (auto &DelDep : DelDeps)
  1104. RemovePred(DelDep.first, DelDep.second);
  1105. SDep FromDep(SU, SDep::Data, Reg);
  1106. FromDep.setLatency(SU->Latency);
  1107. AddPredQueued(CopyFromSU, FromDep);
  1108. SDep ToDep(CopyFromSU, SDep::Data, 0);
  1109. ToDep.setLatency(CopyFromSU->Latency);
  1110. AddPredQueued(CopyToSU, ToDep);
  1111. AvailableQueue->updateNode(SU);
  1112. AvailableQueue->addNode(CopyFromSU);
  1113. AvailableQueue->addNode(CopyToSU);
  1114. Copies.push_back(CopyFromSU);
  1115. Copies.push_back(CopyToSU);
  1116. ++NumPRCopies;
  1117. }
  1118. /// getPhysicalRegisterVT - Returns the ValueType of the physical register
  1119. /// definition of the specified node.
  1120. /// FIXME: Move to SelectionDAG?
  1121. static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
  1122. const TargetInstrInfo *TII) {
  1123. unsigned NumRes;
  1124. if (N->getOpcode() == ISD::CopyFromReg) {
  1125. // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
  1126. NumRes = 1;
  1127. } else {
  1128. const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
  1129. assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
  1130. NumRes = MCID.getNumDefs();
  1131. for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
  1132. if (Reg == *ImpDef)
  1133. break;
  1134. ++NumRes;
  1135. }
  1136. }
  1137. return N->getSimpleValueType(NumRes);
  1138. }
  1139. /// CheckForLiveRegDef - Return true and update live register vector if the
  1140. /// specified register def of the specified SUnit clobbers any "live" registers.
  1141. static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
  1142. SUnit **LiveRegDefs,
  1143. SmallSet<unsigned, 4> &RegAdded,
  1144. SmallVectorImpl<unsigned> &LRegs,
  1145. const TargetRegisterInfo *TRI) {
  1146. for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
  1147. // Check if Ref is live.
  1148. if (!LiveRegDefs[*AliasI]) continue;
  1149. // Allow multiple uses of the same def.
  1150. if (LiveRegDefs[*AliasI] == SU) continue;
  1151. // Add Reg to the set of interfering live regs.
  1152. if (RegAdded.insert(*AliasI).second) {
  1153. LRegs.push_back(*AliasI);
  1154. }
  1155. }
  1156. }
  1157. /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
  1158. /// by RegMask, and add them to LRegs.
  1159. static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
  1160. ArrayRef<SUnit*> LiveRegDefs,
  1161. SmallSet<unsigned, 4> &RegAdded,
  1162. SmallVectorImpl<unsigned> &LRegs) {
  1163. // Look at all live registers. Skip Reg0 and the special CallResource.
  1164. for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
  1165. if (!LiveRegDefs[i]) continue;
  1166. if (LiveRegDefs[i] == SU) continue;
  1167. if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
  1168. if (RegAdded.insert(i).second)
  1169. LRegs.push_back(i);
  1170. }
  1171. }
  1172. /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
  1173. static const uint32_t *getNodeRegMask(const SDNode *N) {
  1174. for (const SDValue &Op : N->op_values())
  1175. if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
  1176. return RegOp->getRegMask();
  1177. return nullptr;
  1178. }
  1179. /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
  1180. /// scheduling of the given node to satisfy live physical register dependencies.
  1181. /// If the specific node is the last one that's available to schedule, do
  1182. /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
  1183. bool ScheduleDAGRRList::
  1184. DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
  1185. if (NumLiveRegs == 0)
  1186. return false;
  1187. SmallSet<unsigned, 4> RegAdded;
  1188. // If this node would clobber any "live" register, then it's not ready.
  1189. //
  1190. // If SU is the currently live definition of the same register that it uses,
  1191. // then we are free to schedule it.
  1192. for (SDep &Pred : SU->Preds) {
  1193. if (Pred.isAssignedRegDep() && LiveRegDefs[Pred.getReg()] != SU)
  1194. CheckForLiveRegDef(Pred.getSUnit(), Pred.getReg(), LiveRegDefs.get(),
  1195. RegAdded, LRegs, TRI);
  1196. }
  1197. for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
  1198. if (Node->getOpcode() == ISD::INLINEASM ||
  1199. Node->getOpcode() == ISD::INLINEASM_BR) {
  1200. // Inline asm can clobber physical defs.
  1201. unsigned NumOps = Node->getNumOperands();
  1202. if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
  1203. --NumOps; // Ignore the glue operand.
  1204. for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
  1205. unsigned Flags =
  1206. cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
  1207. unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
  1208. ++i; // Skip the ID value.
  1209. if (InlineAsm::isRegDefKind(Flags) ||
  1210. InlineAsm::isRegDefEarlyClobberKind(Flags) ||
  1211. InlineAsm::isClobberKind(Flags)) {
  1212. // Check for def of register or earlyclobber register.
  1213. for (; NumVals; --NumVals, ++i) {
  1214. unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
  1215. if (Register::isPhysicalRegister(Reg))
  1216. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1217. }
  1218. } else
  1219. i += NumVals;
  1220. }
  1221. continue;
  1222. }
  1223. if (!Node->isMachineOpcode())
  1224. continue;
  1225. // If we're in the middle of scheduling a call, don't begin scheduling
  1226. // another call. Also, don't allow any physical registers to be live across
  1227. // the call.
  1228. if (Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  1229. // Check the special calling-sequence resource.
  1230. unsigned CallResource = TRI->getNumRegs();
  1231. if (LiveRegDefs[CallResource]) {
  1232. SDNode *Gen = LiveRegGens[CallResource]->getNode();
  1233. while (SDNode *Glued = Gen->getGluedNode())
  1234. Gen = Glued;
  1235. if (!IsChainDependent(Gen, Node, 0, TII) &&
  1236. RegAdded.insert(CallResource).second)
  1237. LRegs.push_back(CallResource);
  1238. }
  1239. }
  1240. if (const uint32_t *RegMask = getNodeRegMask(Node))
  1241. CheckForLiveRegDefMasked(SU, RegMask,
  1242. makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
  1243. RegAdded, LRegs);
  1244. const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
  1245. if (MCID.hasOptionalDef()) {
  1246. // Most ARM instructions have an OptionalDef for CPSR, to model the S-bit.
  1247. // This operand can be either a def of CPSR, if the S bit is set; or a use
  1248. // of %noreg. When the OptionalDef is set to a valid register, we need to
  1249. // handle it in the same way as an ImplicitDef.
  1250. for (unsigned i = 0; i < MCID.getNumDefs(); ++i)
  1251. if (MCID.OpInfo[i].isOptionalDef()) {
  1252. const SDValue &OptionalDef = Node->getOperand(i - Node->getNumValues());
  1253. unsigned Reg = cast<RegisterSDNode>(OptionalDef)->getReg();
  1254. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1255. }
  1256. }
  1257. if (!MCID.ImplicitDefs)
  1258. continue;
  1259. for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
  1260. CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1261. }
  1262. return !LRegs.empty();
  1263. }
  1264. void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
  1265. // Add the nodes that aren't ready back onto the available list.
  1266. for (unsigned i = Interferences.size(); i > 0; --i) {
  1267. SUnit *SU = Interferences[i-1];
  1268. LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
  1269. if (Reg) {
  1270. SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
  1271. if (!is_contained(LRegs, Reg))
  1272. continue;
  1273. }
  1274. SU->isPending = false;
  1275. // The interfering node may no longer be available due to backtracking.
  1276. // Furthermore, it may have been made available again, in which case it is
  1277. // now already in the AvailableQueue.
  1278. if (SU->isAvailable && !SU->NodeQueueId) {
  1279. LLVM_DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n');
  1280. AvailableQueue->push(SU);
  1281. }
  1282. if (i < Interferences.size())
  1283. Interferences[i-1] = Interferences.back();
  1284. Interferences.pop_back();
  1285. LRegsMap.erase(LRegsPos);
  1286. }
  1287. }
  1288. /// Return a node that can be scheduled in this cycle. Requirements:
  1289. /// (1) Ready: latency has been satisfied
  1290. /// (2) No Hazards: resources are available
  1291. /// (3) No Interferences: may unschedule to break register interferences.
  1292. SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
  1293. SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
  1294. auto FindAvailableNode = [&]() {
  1295. while (CurSU) {
  1296. SmallVector<unsigned, 4> LRegs;
  1297. if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
  1298. break;
  1299. LLVM_DEBUG(dbgs() << " Interfering reg ";
  1300. if (LRegs[0] == TRI->getNumRegs()) dbgs() << "CallResource";
  1301. else dbgs() << printReg(LRegs[0], TRI);
  1302. dbgs() << " SU #" << CurSU->NodeNum << '\n');
  1303. std::pair<LRegsMapT::iterator, bool> LRegsPair =
  1304. LRegsMap.insert(std::make_pair(CurSU, LRegs));
  1305. if (LRegsPair.second) {
  1306. CurSU->isPending = true; // This SU is not in AvailableQueue right now.
  1307. Interferences.push_back(CurSU);
  1308. }
  1309. else {
  1310. assert(CurSU->isPending && "Interferences are pending");
  1311. // Update the interference with current live regs.
  1312. LRegsPair.first->second = LRegs;
  1313. }
  1314. CurSU = AvailableQueue->pop();
  1315. }
  1316. };
  1317. FindAvailableNode();
  1318. if (CurSU)
  1319. return CurSU;
  1320. // We query the topological order in the loop body, so make sure outstanding
  1321. // updates are applied before entering it (we only enter the loop if there
  1322. // are some interferences). If we make changes to the ordering, we exit
  1323. // the loop.
  1324. // All candidates are delayed due to live physical reg dependencies.
  1325. // Try backtracking, code duplication, or inserting cross class copies
  1326. // to resolve it.
  1327. for (SUnit *TrySU : Interferences) {
  1328. SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
  1329. // Try unscheduling up to the point where it's safe to schedule
  1330. // this node.
  1331. SUnit *BtSU = nullptr;
  1332. unsigned LiveCycle = std::numeric_limits<unsigned>::max();
  1333. for (unsigned Reg : LRegs) {
  1334. if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
  1335. BtSU = LiveRegGens[Reg];
  1336. LiveCycle = BtSU->getHeight();
  1337. }
  1338. }
  1339. if (!WillCreateCycle(TrySU, BtSU)) {
  1340. // BacktrackBottomUp mutates Interferences!
  1341. BacktrackBottomUp(TrySU, BtSU);
  1342. // Force the current node to be scheduled before the node that
  1343. // requires the physical reg dep.
  1344. if (BtSU->isAvailable) {
  1345. BtSU->isAvailable = false;
  1346. if (!BtSU->isPending)
  1347. AvailableQueue->remove(BtSU);
  1348. }
  1349. LLVM_DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum
  1350. << ") to SU(" << TrySU->NodeNum << ")\n");
  1351. AddPredQueued(TrySU, SDep(BtSU, SDep::Artificial));
  1352. // If one or more successors has been unscheduled, then the current
  1353. // node is no longer available.
  1354. if (!TrySU->isAvailable || !TrySU->NodeQueueId) {
  1355. LLVM_DEBUG(dbgs() << "TrySU not available; choosing node from queue\n");
  1356. CurSU = AvailableQueue->pop();
  1357. } else {
  1358. LLVM_DEBUG(dbgs() << "TrySU available\n");
  1359. // Available and in AvailableQueue
  1360. AvailableQueue->remove(TrySU);
  1361. CurSU = TrySU;
  1362. }
  1363. FindAvailableNode();
  1364. // Interferences has been mutated. We must break.
  1365. break;
  1366. }
  1367. }
  1368. if (!CurSU) {
  1369. // Can't backtrack. If it's too expensive to copy the value, then try
  1370. // duplicate the nodes that produces these "too expensive to copy"
  1371. // values to break the dependency. In case even that doesn't work,
  1372. // insert cross class copies.
  1373. // If it's not too expensive, i.e. cost != -1, issue copies.
  1374. SUnit *TrySU = Interferences[0];
  1375. SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
  1376. assert(LRegs.size() == 1 && "Can't handle this yet!");
  1377. unsigned Reg = LRegs[0];
  1378. SUnit *LRDef = LiveRegDefs[Reg];
  1379. MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
  1380. const TargetRegisterClass *RC =
  1381. TRI->getMinimalPhysRegClass(Reg, VT);
  1382. const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
  1383. // If cross copy register class is the same as RC, then it must be possible
  1384. // copy the value directly. Do not try duplicate the def.
  1385. // If cross copy register class is not the same as RC, then it's possible to
  1386. // copy the value but it require cross register class copies and it is
  1387. // expensive.
  1388. // If cross copy register class is null, then it's not possible to copy
  1389. // the value at all.
  1390. SUnit *NewDef = nullptr;
  1391. if (DestRC != RC) {
  1392. NewDef = CopyAndMoveSuccessors(LRDef);
  1393. if (!DestRC && !NewDef)
  1394. report_fatal_error("Can't handle live physical register dependency!");
  1395. }
  1396. if (!NewDef) {
  1397. // Issue copies, these can be expensive cross register class copies.
  1398. SmallVector<SUnit*, 2> Copies;
  1399. InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
  1400. LLVM_DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
  1401. << " to SU #" << Copies.front()->NodeNum << "\n");
  1402. AddPredQueued(TrySU, SDep(Copies.front(), SDep::Artificial));
  1403. NewDef = Copies.back();
  1404. }
  1405. LLVM_DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
  1406. << " to SU #" << TrySU->NodeNum << "\n");
  1407. LiveRegDefs[Reg] = NewDef;
  1408. AddPredQueued(NewDef, SDep(TrySU, SDep::Artificial));
  1409. TrySU->isAvailable = false;
  1410. CurSU = NewDef;
  1411. }
  1412. assert(CurSU && "Unable to resolve live physical register dependencies!");
  1413. return CurSU;
  1414. }
  1415. /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
  1416. /// schedulers.
  1417. void ScheduleDAGRRList::ListScheduleBottomUp() {
  1418. // Release any predecessors of the special Exit node.
  1419. ReleasePredecessors(&ExitSU);
  1420. // Add root to Available queue.
  1421. if (!SUnits.empty()) {
  1422. SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
  1423. assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
  1424. RootSU->isAvailable = true;
  1425. AvailableQueue->push(RootSU);
  1426. }
  1427. // While Available queue is not empty, grab the node with the highest
  1428. // priority. If it is not ready put it back. Schedule the node.
  1429. Sequence.reserve(SUnits.size());
  1430. while (!AvailableQueue->empty() || !Interferences.empty()) {
  1431. LLVM_DEBUG(dbgs() << "\nExamining Available:\n";
  1432. AvailableQueue->dump(this));
  1433. // Pick the best node to schedule taking all constraints into
  1434. // consideration.
  1435. SUnit *SU = PickNodeToScheduleBottomUp();
  1436. AdvancePastStalls(SU);
  1437. ScheduleNodeBottomUp(SU);
  1438. while (AvailableQueue->empty() && !PendingQueue.empty()) {
  1439. // Advance the cycle to free resources. Skip ahead to the next ready SU.
  1440. assert(MinAvailableCycle < std::numeric_limits<unsigned>::max() &&
  1441. "MinAvailableCycle uninitialized");
  1442. AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
  1443. }
  1444. }
  1445. // Reverse the order if it is bottom up.
  1446. std::reverse(Sequence.begin(), Sequence.end());
  1447. #ifndef NDEBUG
  1448. VerifyScheduledSequence(/*isBottomUp=*/true);
  1449. #endif
  1450. }
  1451. namespace {
  1452. class RegReductionPQBase;
  1453. struct queue_sort {
  1454. bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
  1455. };
  1456. #ifndef NDEBUG
  1457. template<class SF>
  1458. struct reverse_sort : public queue_sort {
  1459. SF &SortFunc;
  1460. reverse_sort(SF &sf) : SortFunc(sf) {}
  1461. bool operator()(SUnit* left, SUnit* right) const {
  1462. // reverse left/right rather than simply !SortFunc(left, right)
  1463. // to expose different paths in the comparison logic.
  1464. return SortFunc(right, left);
  1465. }
  1466. };
  1467. #endif // NDEBUG
  1468. /// bu_ls_rr_sort - Priority function for bottom up register pressure
  1469. // reduction scheduler.
  1470. struct bu_ls_rr_sort : public queue_sort {
  1471. enum {
  1472. IsBottomUp = true,
  1473. HasReadyFilter = false
  1474. };
  1475. RegReductionPQBase *SPQ;
  1476. bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1477. bool operator()(SUnit* left, SUnit* right) const;
  1478. };
  1479. // src_ls_rr_sort - Priority function for source order scheduler.
  1480. struct src_ls_rr_sort : public queue_sort {
  1481. enum {
  1482. IsBottomUp = true,
  1483. HasReadyFilter = false
  1484. };
  1485. RegReductionPQBase *SPQ;
  1486. src_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1487. bool operator()(SUnit* left, SUnit* right) const;
  1488. };
  1489. // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
  1490. struct hybrid_ls_rr_sort : public queue_sort {
  1491. enum {
  1492. IsBottomUp = true,
  1493. HasReadyFilter = false
  1494. };
  1495. RegReductionPQBase *SPQ;
  1496. hybrid_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1497. bool isReady(SUnit *SU, unsigned CurCycle) const;
  1498. bool operator()(SUnit* left, SUnit* right) const;
  1499. };
  1500. // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
  1501. // scheduler.
  1502. struct ilp_ls_rr_sort : public queue_sort {
  1503. enum {
  1504. IsBottomUp = true,
  1505. HasReadyFilter = false
  1506. };
  1507. RegReductionPQBase *SPQ;
  1508. ilp_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1509. bool isReady(SUnit *SU, unsigned CurCycle) const;
  1510. bool operator()(SUnit* left, SUnit* right) const;
  1511. };
  1512. class RegReductionPQBase : public SchedulingPriorityQueue {
  1513. protected:
  1514. std::vector<SUnit *> Queue;
  1515. unsigned CurQueueId = 0;
  1516. bool TracksRegPressure;
  1517. bool SrcOrder;
  1518. // SUnits - The SUnits for the current graph.
  1519. std::vector<SUnit> *SUnits;
  1520. MachineFunction &MF;
  1521. const TargetInstrInfo *TII;
  1522. const TargetRegisterInfo *TRI;
  1523. const TargetLowering *TLI;
  1524. ScheduleDAGRRList *scheduleDAG = nullptr;
  1525. // SethiUllmanNumbers - The SethiUllman number for each node.
  1526. std::vector<unsigned> SethiUllmanNumbers;
  1527. /// RegPressure - Tracking current reg pressure per register class.
  1528. std::vector<unsigned> RegPressure;
  1529. /// RegLimit - Tracking the number of allocatable registers per register
  1530. /// class.
  1531. std::vector<unsigned> RegLimit;
  1532. public:
  1533. RegReductionPQBase(MachineFunction &mf,
  1534. bool hasReadyFilter,
  1535. bool tracksrp,
  1536. bool srcorder,
  1537. const TargetInstrInfo *tii,
  1538. const TargetRegisterInfo *tri,
  1539. const TargetLowering *tli)
  1540. : SchedulingPriorityQueue(hasReadyFilter), TracksRegPressure(tracksrp),
  1541. SrcOrder(srcorder), MF(mf), TII(tii), TRI(tri), TLI(tli) {
  1542. if (TracksRegPressure) {
  1543. unsigned NumRC = TRI->getNumRegClasses();
  1544. RegLimit.resize(NumRC);
  1545. RegPressure.resize(NumRC);
  1546. std::fill(RegLimit.begin(), RegLimit.end(), 0);
  1547. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  1548. for (const TargetRegisterClass *RC : TRI->regclasses())
  1549. RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF);
  1550. }
  1551. }
  1552. void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
  1553. scheduleDAG = scheduleDag;
  1554. }
  1555. ScheduleHazardRecognizer* getHazardRec() {
  1556. return scheduleDAG->getHazardRec();
  1557. }
  1558. void initNodes(std::vector<SUnit> &sunits) override;
  1559. void addNode(const SUnit *SU) override;
  1560. void updateNode(const SUnit *SU) override;
  1561. void releaseState() override {
  1562. SUnits = nullptr;
  1563. SethiUllmanNumbers.clear();
  1564. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  1565. }
  1566. unsigned getNodePriority(const SUnit *SU) const;
  1567. unsigned getNodeOrdering(const SUnit *SU) const {
  1568. if (!SU->getNode()) return 0;
  1569. return SU->getNode()->getIROrder();
  1570. }
  1571. bool empty() const override { return Queue.empty(); }
  1572. void push(SUnit *U) override {
  1573. assert(!U->NodeQueueId && "Node in the queue already");
  1574. U->NodeQueueId = ++CurQueueId;
  1575. Queue.push_back(U);
  1576. }
  1577. void remove(SUnit *SU) override {
  1578. assert(!Queue.empty() && "Queue is empty!");
  1579. assert(SU->NodeQueueId != 0 && "Not in queue!");
  1580. std::vector<SUnit *>::iterator I = llvm::find(Queue, SU);
  1581. if (I != std::prev(Queue.end()))
  1582. std::swap(*I, Queue.back());
  1583. Queue.pop_back();
  1584. SU->NodeQueueId = 0;
  1585. }
  1586. bool tracksRegPressure() const override { return TracksRegPressure; }
  1587. void dumpRegPressure() const;
  1588. bool HighRegPressure(const SUnit *SU) const;
  1589. bool MayReduceRegPressure(SUnit *SU) const;
  1590. int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
  1591. void scheduledNode(SUnit *SU) override;
  1592. void unscheduledNode(SUnit *SU) override;
  1593. protected:
  1594. bool canClobber(const SUnit *SU, const SUnit *Op);
  1595. void AddPseudoTwoAddrDeps();
  1596. void PrescheduleNodesWithMultipleUses();
  1597. void CalculateSethiUllmanNumbers();
  1598. };
  1599. template<class SF>
  1600. static SUnit *popFromQueueImpl(std::vector<SUnit *> &Q, SF &Picker) {
  1601. unsigned BestIdx = 0;
  1602. // Only compute the cost for the first 1000 items in the queue, to avoid
  1603. // excessive compile-times for very large queues.
  1604. for (unsigned I = 1, E = std::min(Q.size(), (decltype(Q.size()))1000); I != E;
  1605. I++)
  1606. if (Picker(Q[BestIdx], Q[I]))
  1607. BestIdx = I;
  1608. SUnit *V = Q[BestIdx];
  1609. if (BestIdx + 1 != Q.size())
  1610. std::swap(Q[BestIdx], Q.back());
  1611. Q.pop_back();
  1612. return V;
  1613. }
  1614. template<class SF>
  1615. SUnit *popFromQueue(std::vector<SUnit *> &Q, SF &Picker, ScheduleDAG *DAG) {
  1616. #ifndef NDEBUG
  1617. if (DAG->StressSched) {
  1618. reverse_sort<SF> RPicker(Picker);
  1619. return popFromQueueImpl(Q, RPicker);
  1620. }
  1621. #endif
  1622. (void)DAG;
  1623. return popFromQueueImpl(Q, Picker);
  1624. }
  1625. //===----------------------------------------------------------------------===//
  1626. // RegReductionPriorityQueue Definition
  1627. //===----------------------------------------------------------------------===//
  1628. //
  1629. // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
  1630. // to reduce register pressure.
  1631. //
  1632. template<class SF>
  1633. class RegReductionPriorityQueue : public RegReductionPQBase {
  1634. SF Picker;
  1635. public:
  1636. RegReductionPriorityQueue(MachineFunction &mf,
  1637. bool tracksrp,
  1638. bool srcorder,
  1639. const TargetInstrInfo *tii,
  1640. const TargetRegisterInfo *tri,
  1641. const TargetLowering *tli)
  1642. : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
  1643. tii, tri, tli),
  1644. Picker(this) {}
  1645. bool isBottomUp() const override { return SF::IsBottomUp; }
  1646. bool isReady(SUnit *U) const override {
  1647. return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
  1648. }
  1649. SUnit *pop() override {
  1650. if (Queue.empty()) return nullptr;
  1651. SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
  1652. V->NodeQueueId = 0;
  1653. return V;
  1654. }
  1655. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1656. LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
  1657. // Emulate pop() without clobbering NodeQueueIds.
  1658. std::vector<SUnit *> DumpQueue = Queue;
  1659. SF DumpPicker = Picker;
  1660. while (!DumpQueue.empty()) {
  1661. SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
  1662. dbgs() << "Height " << SU->getHeight() << ": ";
  1663. DAG->dumpNode(*SU);
  1664. }
  1665. }
  1666. #endif
  1667. };
  1668. using BURegReductionPriorityQueue = RegReductionPriorityQueue<bu_ls_rr_sort>;
  1669. using SrcRegReductionPriorityQueue = RegReductionPriorityQueue<src_ls_rr_sort>;
  1670. using HybridBURRPriorityQueue = RegReductionPriorityQueue<hybrid_ls_rr_sort>;
  1671. using ILPBURRPriorityQueue = RegReductionPriorityQueue<ilp_ls_rr_sort>;
  1672. } // end anonymous namespace
  1673. //===----------------------------------------------------------------------===//
  1674. // Static Node Priority for Register Pressure Reduction
  1675. //===----------------------------------------------------------------------===//
  1676. // Check for special nodes that bypass scheduling heuristics.
  1677. // Currently this pushes TokenFactor nodes down, but may be used for other
  1678. // pseudo-ops as well.
  1679. //
  1680. // Return -1 to schedule right above left, 1 for left above right.
  1681. // Return 0 if no bias exists.
  1682. static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
  1683. bool LSchedLow = left->isScheduleLow;
  1684. bool RSchedLow = right->isScheduleLow;
  1685. if (LSchedLow != RSchedLow)
  1686. return LSchedLow < RSchedLow ? 1 : -1;
  1687. return 0;
  1688. }
  1689. /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
  1690. /// Smaller number is the higher priority.
  1691. static unsigned
  1692. CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
  1693. if (SUNumbers[SU->NodeNum] != 0)
  1694. return SUNumbers[SU->NodeNum];
  1695. // Use WorkList to avoid stack overflow on excessively large IRs.
  1696. struct WorkState {
  1697. WorkState(const SUnit *SU) : SU(SU) {}
  1698. const SUnit *SU;
  1699. unsigned PredsProcessed = 0;
  1700. };
  1701. SmallVector<WorkState, 16> WorkList;
  1702. WorkList.push_back(SU);
  1703. while (!WorkList.empty()) {
  1704. auto &Temp = WorkList.back();
  1705. auto *TempSU = Temp.SU;
  1706. bool AllPredsKnown = true;
  1707. // Try to find a non-evaluated pred and push it into the processing stack.
  1708. for (unsigned P = Temp.PredsProcessed; P < TempSU->Preds.size(); ++P) {
  1709. auto &Pred = TempSU->Preds[P];
  1710. if (Pred.isCtrl()) continue; // ignore chain preds
  1711. SUnit *PredSU = Pred.getSUnit();
  1712. if (SUNumbers[PredSU->NodeNum] == 0) {
  1713. #ifndef NDEBUG
  1714. // In debug mode, check that we don't have such element in the stack.
  1715. for (auto It : WorkList)
  1716. assert(It.SU != PredSU && "Trying to push an element twice?");
  1717. #endif
  1718. // Next time start processing this one starting from the next pred.
  1719. Temp.PredsProcessed = P + 1;
  1720. WorkList.push_back(PredSU);
  1721. AllPredsKnown = false;
  1722. break;
  1723. }
  1724. }
  1725. if (!AllPredsKnown)
  1726. continue;
  1727. // Once all preds are known, we can calculate the answer for this one.
  1728. unsigned SethiUllmanNumber = 0;
  1729. unsigned Extra = 0;
  1730. for (const SDep &Pred : TempSU->Preds) {
  1731. if (Pred.isCtrl()) continue; // ignore chain preds
  1732. SUnit *PredSU = Pred.getSUnit();
  1733. unsigned PredSethiUllman = SUNumbers[PredSU->NodeNum];
  1734. assert(PredSethiUllman > 0 && "We should have evaluated this pred!");
  1735. if (PredSethiUllman > SethiUllmanNumber) {
  1736. SethiUllmanNumber = PredSethiUllman;
  1737. Extra = 0;
  1738. } else if (PredSethiUllman == SethiUllmanNumber)
  1739. ++Extra;
  1740. }
  1741. SethiUllmanNumber += Extra;
  1742. if (SethiUllmanNumber == 0)
  1743. SethiUllmanNumber = 1;
  1744. SUNumbers[TempSU->NodeNum] = SethiUllmanNumber;
  1745. WorkList.pop_back();
  1746. }
  1747. assert(SUNumbers[SU->NodeNum] > 0 && "SethiUllman should never be zero!");
  1748. return SUNumbers[SU->NodeNum];
  1749. }
  1750. /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
  1751. /// scheduling units.
  1752. void RegReductionPQBase::CalculateSethiUllmanNumbers() {
  1753. SethiUllmanNumbers.assign(SUnits->size(), 0);
  1754. for (const SUnit &SU : *SUnits)
  1755. CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
  1756. }
  1757. void RegReductionPQBase::addNode(const SUnit *SU) {
  1758. unsigned SUSize = SethiUllmanNumbers.size();
  1759. if (SUnits->size() > SUSize)
  1760. SethiUllmanNumbers.resize(SUSize*2, 0);
  1761. CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
  1762. }
  1763. void RegReductionPQBase::updateNode(const SUnit *SU) {
  1764. SethiUllmanNumbers[SU->NodeNum] = 0;
  1765. CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
  1766. }
  1767. // Lower priority means schedule further down. For bottom-up scheduling, lower
  1768. // priority SUs are scheduled before higher priority SUs.
  1769. unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
  1770. assert(SU->NodeNum < SethiUllmanNumbers.size());
  1771. unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
  1772. if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
  1773. // CopyToReg should be close to its uses to facilitate coalescing and
  1774. // avoid spilling.
  1775. return 0;
  1776. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  1777. Opc == TargetOpcode::SUBREG_TO_REG ||
  1778. Opc == TargetOpcode::INSERT_SUBREG)
  1779. // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
  1780. // close to their uses to facilitate coalescing.
  1781. return 0;
  1782. if (SU->NumSuccs == 0 && SU->NumPreds != 0)
  1783. // If SU does not have a register use, i.e. it doesn't produce a value
  1784. // that would be consumed (e.g. store), then it terminates a chain of
  1785. // computation. Give it a large SethiUllman number so it will be
  1786. // scheduled right before its predecessors that it doesn't lengthen
  1787. // their live ranges.
  1788. return 0xffff;
  1789. if (SU->NumPreds == 0 && SU->NumSuccs != 0)
  1790. // If SU does not have a register def, schedule it close to its uses
  1791. // because it does not lengthen any live ranges.
  1792. return 0;
  1793. #if 1
  1794. return SethiUllmanNumbers[SU->NodeNum];
  1795. #else
  1796. unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
  1797. if (SU->isCallOp) {
  1798. // FIXME: This assumes all of the defs are used as call operands.
  1799. int NP = (int)Priority - SU->getNode()->getNumValues();
  1800. return (NP > 0) ? NP : 0;
  1801. }
  1802. return Priority;
  1803. #endif
  1804. }
  1805. //===----------------------------------------------------------------------===//
  1806. // Register Pressure Tracking
  1807. //===----------------------------------------------------------------------===//
  1808. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1809. LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
  1810. for (const TargetRegisterClass *RC : TRI->regclasses()) {
  1811. unsigned Id = RC->getID();
  1812. unsigned RP = RegPressure[Id];
  1813. if (!RP) continue;
  1814. LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
  1815. << RegLimit[Id] << '\n');
  1816. }
  1817. }
  1818. #endif
  1819. bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
  1820. if (!TLI)
  1821. return false;
  1822. for (const SDep &Pred : SU->Preds) {
  1823. if (Pred.isCtrl())
  1824. continue;
  1825. SUnit *PredSU = Pred.getSUnit();
  1826. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1827. // to cover the number of registers defined (they are all live).
  1828. if (PredSU->NumRegDefsLeft == 0) {
  1829. continue;
  1830. }
  1831. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1832. RegDefPos.IsValid(); RegDefPos.Advance()) {
  1833. unsigned RCId, Cost;
  1834. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1835. if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
  1836. return true;
  1837. }
  1838. }
  1839. return false;
  1840. }
  1841. bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
  1842. const SDNode *N = SU->getNode();
  1843. if (!N->isMachineOpcode() || !SU->NumSuccs)
  1844. return false;
  1845. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  1846. for (unsigned i = 0; i != NumDefs; ++i) {
  1847. MVT VT = N->getSimpleValueType(i);
  1848. if (!N->hasAnyUseOfValue(i))
  1849. continue;
  1850. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1851. if (RegPressure[RCId] >= RegLimit[RCId])
  1852. return true;
  1853. }
  1854. return false;
  1855. }
  1856. // Compute the register pressure contribution by this instruction by count up
  1857. // for uses that are not live and down for defs. Only count register classes
  1858. // that are already under high pressure. As a side effect, compute the number of
  1859. // uses of registers that are already live.
  1860. //
  1861. // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
  1862. // so could probably be factored.
  1863. int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
  1864. LiveUses = 0;
  1865. int PDiff = 0;
  1866. for (const SDep &Pred : SU->Preds) {
  1867. if (Pred.isCtrl())
  1868. continue;
  1869. SUnit *PredSU = Pred.getSUnit();
  1870. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1871. // to cover the number of registers defined (they are all live).
  1872. if (PredSU->NumRegDefsLeft == 0) {
  1873. if (PredSU->getNode()->isMachineOpcode())
  1874. ++LiveUses;
  1875. continue;
  1876. }
  1877. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1878. RegDefPos.IsValid(); RegDefPos.Advance()) {
  1879. MVT VT = RegDefPos.GetValue();
  1880. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1881. if (RegPressure[RCId] >= RegLimit[RCId])
  1882. ++PDiff;
  1883. }
  1884. }
  1885. const SDNode *N = SU->getNode();
  1886. if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
  1887. return PDiff;
  1888. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  1889. for (unsigned i = 0; i != NumDefs; ++i) {
  1890. MVT VT = N->getSimpleValueType(i);
  1891. if (!N->hasAnyUseOfValue(i))
  1892. continue;
  1893. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1894. if (RegPressure[RCId] >= RegLimit[RCId])
  1895. --PDiff;
  1896. }
  1897. return PDiff;
  1898. }
  1899. void RegReductionPQBase::scheduledNode(SUnit *SU) {
  1900. if (!TracksRegPressure)
  1901. return;
  1902. if (!SU->getNode())
  1903. return;
  1904. for (const SDep &Pred : SU->Preds) {
  1905. if (Pred.isCtrl())
  1906. continue;
  1907. SUnit *PredSU = Pred.getSUnit();
  1908. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1909. // to cover the number of registers defined (they are all live).
  1910. if (PredSU->NumRegDefsLeft == 0) {
  1911. continue;
  1912. }
  1913. // FIXME: The ScheduleDAG currently loses information about which of a
  1914. // node's values is consumed by each dependence. Consequently, if the node
  1915. // defines multiple register classes, we don't know which to pressurize
  1916. // here. Instead the following loop consumes the register defs in an
  1917. // arbitrary order. At least it handles the common case of clustered loads
  1918. // to the same class. For precise liveness, each SDep needs to indicate the
  1919. // result number. But that tightly couples the ScheduleDAG with the
  1920. // SelectionDAG making updates tricky. A simpler hack would be to attach a
  1921. // value type or register class to SDep.
  1922. //
  1923. // The most important aspect of register tracking is balancing the increase
  1924. // here with the reduction further below. Note that this SU may use multiple
  1925. // defs in PredSU. The can't be determined here, but we've already
  1926. // compensated by reducing NumRegDefsLeft in PredSU during
  1927. // ScheduleDAGSDNodes::AddSchedEdges.
  1928. --PredSU->NumRegDefsLeft;
  1929. unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
  1930. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1931. RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
  1932. if (SkipRegDefs)
  1933. continue;
  1934. unsigned RCId, Cost;
  1935. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1936. RegPressure[RCId] += Cost;
  1937. break;
  1938. }
  1939. }
  1940. // We should have this assert, but there may be dead SDNodes that never
  1941. // materialize as SUnits, so they don't appear to generate liveness.
  1942. //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
  1943. int SkipRegDefs = (int)SU->NumRegDefsLeft;
  1944. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
  1945. RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
  1946. if (SkipRegDefs > 0)
  1947. continue;
  1948. unsigned RCId, Cost;
  1949. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1950. if (RegPressure[RCId] < Cost) {
  1951. // Register pressure tracking is imprecise. This can happen. But we try
  1952. // hard not to let it happen because it likely results in poor scheduling.
  1953. LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum
  1954. << ") has too many regdefs\n");
  1955. RegPressure[RCId] = 0;
  1956. }
  1957. else {
  1958. RegPressure[RCId] -= Cost;
  1959. }
  1960. }
  1961. LLVM_DEBUG(dumpRegPressure());
  1962. }
  1963. void RegReductionPQBase::unscheduledNode(SUnit *SU) {
  1964. if (!TracksRegPressure)
  1965. return;
  1966. const SDNode *N = SU->getNode();
  1967. if (!N) return;
  1968. if (!N->isMachineOpcode()) {
  1969. if (N->getOpcode() != ISD::CopyToReg)
  1970. return;
  1971. } else {
  1972. unsigned Opc = N->getMachineOpcode();
  1973. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  1974. Opc == TargetOpcode::INSERT_SUBREG ||
  1975. Opc == TargetOpcode::SUBREG_TO_REG ||
  1976. Opc == TargetOpcode::REG_SEQUENCE ||
  1977. Opc == TargetOpcode::IMPLICIT_DEF)
  1978. return;
  1979. }
  1980. for (const SDep &Pred : SU->Preds) {
  1981. if (Pred.isCtrl())
  1982. continue;
  1983. SUnit *PredSU = Pred.getSUnit();
  1984. // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
  1985. // counts data deps.
  1986. if (PredSU->NumSuccsLeft != PredSU->Succs.size())
  1987. continue;
  1988. const SDNode *PN = PredSU->getNode();
  1989. if (!PN->isMachineOpcode()) {
  1990. if (PN->getOpcode() == ISD::CopyFromReg) {
  1991. MVT VT = PN->getSimpleValueType(0);
  1992. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1993. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  1994. }
  1995. continue;
  1996. }
  1997. unsigned POpc = PN->getMachineOpcode();
  1998. if (POpc == TargetOpcode::IMPLICIT_DEF)
  1999. continue;
  2000. if (POpc == TargetOpcode::EXTRACT_SUBREG ||
  2001. POpc == TargetOpcode::INSERT_SUBREG ||
  2002. POpc == TargetOpcode::SUBREG_TO_REG) {
  2003. MVT VT = PN->getSimpleValueType(0);
  2004. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2005. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  2006. continue;
  2007. }
  2008. unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
  2009. for (unsigned i = 0; i != NumDefs; ++i) {
  2010. MVT VT = PN->getSimpleValueType(i);
  2011. if (!PN->hasAnyUseOfValue(i))
  2012. continue;
  2013. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2014. if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
  2015. // Register pressure tracking is imprecise. This can happen.
  2016. RegPressure[RCId] = 0;
  2017. else
  2018. RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
  2019. }
  2020. }
  2021. // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
  2022. // may transfer data dependencies to CopyToReg.
  2023. if (SU->NumSuccs && N->isMachineOpcode()) {
  2024. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  2025. for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
  2026. MVT VT = N->getSimpleValueType(i);
  2027. if (VT == MVT::Glue || VT == MVT::Other)
  2028. continue;
  2029. if (!N->hasAnyUseOfValue(i))
  2030. continue;
  2031. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2032. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  2033. }
  2034. }
  2035. LLVM_DEBUG(dumpRegPressure());
  2036. }
  2037. //===----------------------------------------------------------------------===//
  2038. // Dynamic Node Priority for Register Pressure Reduction
  2039. //===----------------------------------------------------------------------===//
  2040. /// closestSucc - Returns the scheduled cycle of the successor which is
  2041. /// closest to the current cycle.
  2042. static unsigned closestSucc(const SUnit *SU) {
  2043. unsigned MaxHeight = 0;
  2044. for (const SDep &Succ : SU->Succs) {
  2045. if (Succ.isCtrl()) continue; // ignore chain succs
  2046. unsigned Height = Succ.getSUnit()->getHeight();
  2047. // If there are bunch of CopyToRegs stacked up, they should be considered
  2048. // to be at the same position.
  2049. if (Succ.getSUnit()->getNode() &&
  2050. Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
  2051. Height = closestSucc(Succ.getSUnit())+1;
  2052. if (Height > MaxHeight)
  2053. MaxHeight = Height;
  2054. }
  2055. return MaxHeight;
  2056. }
  2057. /// calcMaxScratches - Returns an cost estimate of the worse case requirement
  2058. /// for scratch registers, i.e. number of data dependencies.
  2059. static unsigned calcMaxScratches(const SUnit *SU) {
  2060. unsigned Scratches = 0;
  2061. for (const SDep &Pred : SU->Preds) {
  2062. if (Pred.isCtrl()) continue; // ignore chain preds
  2063. Scratches++;
  2064. }
  2065. return Scratches;
  2066. }
  2067. /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
  2068. /// CopyFromReg from a virtual register.
  2069. static bool hasOnlyLiveInOpers(const SUnit *SU) {
  2070. bool RetVal = false;
  2071. for (const SDep &Pred : SU->Preds) {
  2072. if (Pred.isCtrl()) continue;
  2073. const SUnit *PredSU = Pred.getSUnit();
  2074. if (PredSU->getNode() &&
  2075. PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
  2076. unsigned Reg =
  2077. cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
  2078. if (Register::isVirtualRegister(Reg)) {
  2079. RetVal = true;
  2080. continue;
  2081. }
  2082. }
  2083. return false;
  2084. }
  2085. return RetVal;
  2086. }
  2087. /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
  2088. /// CopyToReg to a virtual register. This SU def is probably a liveout and
  2089. /// it has no other use. It should be scheduled closer to the terminator.
  2090. static bool hasOnlyLiveOutUses(const SUnit *SU) {
  2091. bool RetVal = false;
  2092. for (const SDep &Succ : SU->Succs) {
  2093. if (Succ.isCtrl()) continue;
  2094. const SUnit *SuccSU = Succ.getSUnit();
  2095. if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
  2096. unsigned Reg =
  2097. cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
  2098. if (Register::isVirtualRegister(Reg)) {
  2099. RetVal = true;
  2100. continue;
  2101. }
  2102. }
  2103. return false;
  2104. }
  2105. return RetVal;
  2106. }
  2107. // Set isVRegCycle for a node with only live in opers and live out uses. Also
  2108. // set isVRegCycle for its CopyFromReg operands.
  2109. //
  2110. // This is only relevant for single-block loops, in which case the VRegCycle
  2111. // node is likely an induction variable in which the operand and target virtual
  2112. // registers should be coalesced (e.g. pre/post increment values). Setting the
  2113. // isVRegCycle flag helps the scheduler prioritize other uses of the same
  2114. // CopyFromReg so that this node becomes the virtual register "kill". This
  2115. // avoids interference between the values live in and out of the block and
  2116. // eliminates a copy inside the loop.
  2117. static void initVRegCycle(SUnit *SU) {
  2118. if (DisableSchedVRegCycle)
  2119. return;
  2120. if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
  2121. return;
  2122. LLVM_DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
  2123. SU->isVRegCycle = true;
  2124. for (const SDep &Pred : SU->Preds) {
  2125. if (Pred.isCtrl()) continue;
  2126. Pred.getSUnit()->isVRegCycle = true;
  2127. }
  2128. }
  2129. // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
  2130. // CopyFromReg operands. We should no longer penalize other uses of this VReg.
  2131. static void resetVRegCycle(SUnit *SU) {
  2132. if (!SU->isVRegCycle)
  2133. return;
  2134. for (const SDep &Pred : SU->Preds) {
  2135. if (Pred.isCtrl()) continue; // ignore chain preds
  2136. SUnit *PredSU = Pred.getSUnit();
  2137. if (PredSU->isVRegCycle) {
  2138. assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
  2139. "VRegCycle def must be CopyFromReg");
  2140. Pred.getSUnit()->isVRegCycle = false;
  2141. }
  2142. }
  2143. }
  2144. // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
  2145. // means a node that defines the VRegCycle has not been scheduled yet.
  2146. static bool hasVRegCycleUse(const SUnit *SU) {
  2147. // If this SU also defines the VReg, don't hoist it as a "use".
  2148. if (SU->isVRegCycle)
  2149. return false;
  2150. for (const SDep &Pred : SU->Preds) {
  2151. if (Pred.isCtrl()) continue; // ignore chain preds
  2152. if (Pred.getSUnit()->isVRegCycle &&
  2153. Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
  2154. LLVM_DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
  2155. return true;
  2156. }
  2157. }
  2158. return false;
  2159. }
  2160. // Check for either a dependence (latency) or resource (hazard) stall.
  2161. //
  2162. // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
  2163. static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
  2164. if ((int)SPQ->getCurCycle() < Height) return true;
  2165. if (SPQ->getHazardRec()->getHazardType(SU, 0)
  2166. != ScheduleHazardRecognizer::NoHazard)
  2167. return true;
  2168. return false;
  2169. }
  2170. // Return -1 if left has higher priority, 1 if right has higher priority.
  2171. // Return 0 if latency-based priority is equivalent.
  2172. static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
  2173. RegReductionPQBase *SPQ) {
  2174. // Scheduling an instruction that uses a VReg whose postincrement has not yet
  2175. // been scheduled will induce a copy. Model this as an extra cycle of latency.
  2176. int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
  2177. int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
  2178. int LHeight = (int)left->getHeight() + LPenalty;
  2179. int RHeight = (int)right->getHeight() + RPenalty;
  2180. bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
  2181. BUHasStall(left, LHeight, SPQ);
  2182. bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
  2183. BUHasStall(right, RHeight, SPQ);
  2184. // If scheduling one of the node will cause a pipeline stall, delay it.
  2185. // If scheduling either one of the node will cause a pipeline stall, sort
  2186. // them according to their height.
  2187. if (LStall) {
  2188. if (!RStall)
  2189. return 1;
  2190. if (LHeight != RHeight)
  2191. return LHeight > RHeight ? 1 : -1;
  2192. } else if (RStall)
  2193. return -1;
  2194. // If either node is scheduling for latency, sort them by height/depth
  2195. // and latency.
  2196. if (!checkPref || (left->SchedulingPref == Sched::ILP ||
  2197. right->SchedulingPref == Sched::ILP)) {
  2198. // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
  2199. // is enabled, grouping instructions by cycle, then its height is already
  2200. // covered so only its depth matters. We also reach this point if both stall
  2201. // but have the same height.
  2202. if (!SPQ->getHazardRec()->isEnabled()) {
  2203. if (LHeight != RHeight)
  2204. return LHeight > RHeight ? 1 : -1;
  2205. }
  2206. int LDepth = left->getDepth() - LPenalty;
  2207. int RDepth = right->getDepth() - RPenalty;
  2208. if (LDepth != RDepth) {
  2209. LLVM_DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
  2210. << ") depth " << LDepth << " vs SU (" << right->NodeNum
  2211. << ") depth " << RDepth << "\n");
  2212. return LDepth < RDepth ? 1 : -1;
  2213. }
  2214. if (left->Latency != right->Latency)
  2215. return left->Latency > right->Latency ? 1 : -1;
  2216. }
  2217. return 0;
  2218. }
  2219. static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
  2220. // Schedule physical register definitions close to their use. This is
  2221. // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
  2222. // long as shortening physreg live ranges is generally good, we can defer
  2223. // creating a subtarget hook.
  2224. if (!DisableSchedPhysRegJoin) {
  2225. bool LHasPhysReg = left->hasPhysRegDefs;
  2226. bool RHasPhysReg = right->hasPhysRegDefs;
  2227. if (LHasPhysReg != RHasPhysReg) {
  2228. #ifndef NDEBUG
  2229. static const char *const PhysRegMsg[] = { " has no physreg",
  2230. " defines a physreg" };
  2231. #endif
  2232. LLVM_DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
  2233. << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum
  2234. << ") " << PhysRegMsg[RHasPhysReg] << "\n");
  2235. return LHasPhysReg < RHasPhysReg;
  2236. }
  2237. }
  2238. // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
  2239. unsigned LPriority = SPQ->getNodePriority(left);
  2240. unsigned RPriority = SPQ->getNodePriority(right);
  2241. // Be really careful about hoisting call operands above previous calls.
  2242. // Only allows it if it would reduce register pressure.
  2243. if (left->isCall && right->isCallOp) {
  2244. unsigned RNumVals = right->getNode()->getNumValues();
  2245. RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
  2246. }
  2247. if (right->isCall && left->isCallOp) {
  2248. unsigned LNumVals = left->getNode()->getNumValues();
  2249. LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
  2250. }
  2251. if (LPriority != RPriority)
  2252. return LPriority > RPriority;
  2253. // One or both of the nodes are calls and their sethi-ullman numbers are the
  2254. // same, then keep source order.
  2255. if (left->isCall || right->isCall) {
  2256. unsigned LOrder = SPQ->getNodeOrdering(left);
  2257. unsigned ROrder = SPQ->getNodeOrdering(right);
  2258. // Prefer an ordering where the lower the non-zero order number, the higher
  2259. // the preference.
  2260. if ((LOrder || ROrder) && LOrder != ROrder)
  2261. return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
  2262. }
  2263. // Try schedule def + use closer when Sethi-Ullman numbers are the same.
  2264. // e.g.
  2265. // t1 = op t2, c1
  2266. // t3 = op t4, c2
  2267. //
  2268. // and the following instructions are both ready.
  2269. // t2 = op c3
  2270. // t4 = op c4
  2271. //
  2272. // Then schedule t2 = op first.
  2273. // i.e.
  2274. // t4 = op c4
  2275. // t2 = op c3
  2276. // t1 = op t2, c1
  2277. // t3 = op t4, c2
  2278. //
  2279. // This creates more short live intervals.
  2280. unsigned LDist = closestSucc(left);
  2281. unsigned RDist = closestSucc(right);
  2282. if (LDist != RDist)
  2283. return LDist < RDist;
  2284. // How many registers becomes live when the node is scheduled.
  2285. unsigned LScratch = calcMaxScratches(left);
  2286. unsigned RScratch = calcMaxScratches(right);
  2287. if (LScratch != RScratch)
  2288. return LScratch > RScratch;
  2289. // Comparing latency against a call makes little sense unless the node
  2290. // is register pressure-neutral.
  2291. if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
  2292. return (left->NodeQueueId > right->NodeQueueId);
  2293. // Do not compare latencies when one or both of the nodes are calls.
  2294. if (!DisableSchedCycles &&
  2295. !(left->isCall || right->isCall)) {
  2296. int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
  2297. if (result != 0)
  2298. return result > 0;
  2299. }
  2300. else {
  2301. if (left->getHeight() != right->getHeight())
  2302. return left->getHeight() > right->getHeight();
  2303. if (left->getDepth() != right->getDepth())
  2304. return left->getDepth() < right->getDepth();
  2305. }
  2306. assert(left->NodeQueueId && right->NodeQueueId &&
  2307. "NodeQueueId cannot be zero");
  2308. return (left->NodeQueueId > right->NodeQueueId);
  2309. }
  2310. // Bottom up
  2311. bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2312. if (int res = checkSpecialNodes(left, right))
  2313. return res > 0;
  2314. return BURRSort(left, right, SPQ);
  2315. }
  2316. // Source order, otherwise bottom up.
  2317. bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2318. if (int res = checkSpecialNodes(left, right))
  2319. return res > 0;
  2320. unsigned LOrder = SPQ->getNodeOrdering(left);
  2321. unsigned ROrder = SPQ->getNodeOrdering(right);
  2322. // Prefer an ordering where the lower the non-zero order number, the higher
  2323. // the preference.
  2324. if ((LOrder || ROrder) && LOrder != ROrder)
  2325. return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
  2326. return BURRSort(left, right, SPQ);
  2327. }
  2328. // If the time between now and when the instruction will be ready can cover
  2329. // the spill code, then avoid adding it to the ready queue. This gives long
  2330. // stalls highest priority and allows hoisting across calls. It should also
  2331. // speed up processing the available queue.
  2332. bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
  2333. static const unsigned ReadyDelay = 3;
  2334. if (SPQ->MayReduceRegPressure(SU)) return true;
  2335. if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
  2336. if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
  2337. != ScheduleHazardRecognizer::NoHazard)
  2338. return false;
  2339. return true;
  2340. }
  2341. // Return true if right should be scheduled with higher priority than left.
  2342. bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2343. if (int res = checkSpecialNodes(left, right))
  2344. return res > 0;
  2345. if (left->isCall || right->isCall)
  2346. // No way to compute latency of calls.
  2347. return BURRSort(left, right, SPQ);
  2348. bool LHigh = SPQ->HighRegPressure(left);
  2349. bool RHigh = SPQ->HighRegPressure(right);
  2350. // Avoid causing spills. If register pressure is high, schedule for
  2351. // register pressure reduction.
  2352. if (LHigh && !RHigh) {
  2353. LLVM_DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
  2354. << right->NodeNum << ")\n");
  2355. return true;
  2356. }
  2357. else if (!LHigh && RHigh) {
  2358. LLVM_DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
  2359. << left->NodeNum << ")\n");
  2360. return false;
  2361. }
  2362. if (!LHigh && !RHigh) {
  2363. int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
  2364. if (result != 0)
  2365. return result > 0;
  2366. }
  2367. return BURRSort(left, right, SPQ);
  2368. }
  2369. // Schedule as many instructions in each cycle as possible. So don't make an
  2370. // instruction available unless it is ready in the current cycle.
  2371. bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
  2372. if (SU->getHeight() > CurCycle) return false;
  2373. if (SPQ->getHazardRec()->getHazardType(SU, 0)
  2374. != ScheduleHazardRecognizer::NoHazard)
  2375. return false;
  2376. return true;
  2377. }
  2378. static bool canEnableCoalescing(SUnit *SU) {
  2379. unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
  2380. if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
  2381. // CopyToReg should be close to its uses to facilitate coalescing and
  2382. // avoid spilling.
  2383. return true;
  2384. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  2385. Opc == TargetOpcode::SUBREG_TO_REG ||
  2386. Opc == TargetOpcode::INSERT_SUBREG)
  2387. // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
  2388. // close to their uses to facilitate coalescing.
  2389. return true;
  2390. if (SU->NumPreds == 0 && SU->NumSuccs != 0)
  2391. // If SU does not have a register def, schedule it close to its uses
  2392. // because it does not lengthen any live ranges.
  2393. return true;
  2394. return false;
  2395. }
  2396. // list-ilp is currently an experimental scheduler that allows various
  2397. // heuristics to be enabled prior to the normal register reduction logic.
  2398. bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2399. if (int res = checkSpecialNodes(left, right))
  2400. return res > 0;
  2401. if (left->isCall || right->isCall)
  2402. // No way to compute latency of calls.
  2403. return BURRSort(left, right, SPQ);
  2404. unsigned LLiveUses = 0, RLiveUses = 0;
  2405. int LPDiff = 0, RPDiff = 0;
  2406. if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
  2407. LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
  2408. RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
  2409. }
  2410. if (!DisableSchedRegPressure && LPDiff != RPDiff) {
  2411. LLVM_DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum
  2412. << "): " << LPDiff << " != SU(" << right->NodeNum
  2413. << "): " << RPDiff << "\n");
  2414. return LPDiff > RPDiff;
  2415. }
  2416. if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
  2417. bool LReduce = canEnableCoalescing(left);
  2418. bool RReduce = canEnableCoalescing(right);
  2419. if (LReduce && !RReduce) return false;
  2420. if (RReduce && !LReduce) return true;
  2421. }
  2422. if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
  2423. LLVM_DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
  2424. << " != SU(" << right->NodeNum << "): " << RLiveUses
  2425. << "\n");
  2426. return LLiveUses < RLiveUses;
  2427. }
  2428. if (!DisableSchedStalls) {
  2429. bool LStall = BUHasStall(left, left->getHeight(), SPQ);
  2430. bool RStall = BUHasStall(right, right->getHeight(), SPQ);
  2431. if (LStall != RStall)
  2432. return left->getHeight() > right->getHeight();
  2433. }
  2434. if (!DisableSchedCriticalPath) {
  2435. int spread = (int)left->getDepth() - (int)right->getDepth();
  2436. if (std::abs(spread) > MaxReorderWindow) {
  2437. LLVM_DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
  2438. << left->getDepth() << " != SU(" << right->NodeNum
  2439. << "): " << right->getDepth() << "\n");
  2440. return left->getDepth() < right->getDepth();
  2441. }
  2442. }
  2443. if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
  2444. int spread = (int)left->getHeight() - (int)right->getHeight();
  2445. if (std::abs(spread) > MaxReorderWindow)
  2446. return left->getHeight() > right->getHeight();
  2447. }
  2448. return BURRSort(left, right, SPQ);
  2449. }
  2450. void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
  2451. SUnits = &sunits;
  2452. // Add pseudo dependency edges for two-address nodes.
  2453. if (!Disable2AddrHack)
  2454. AddPseudoTwoAddrDeps();
  2455. // Reroute edges to nodes with multiple uses.
  2456. if (!TracksRegPressure && !SrcOrder)
  2457. PrescheduleNodesWithMultipleUses();
  2458. // Calculate node priorities.
  2459. CalculateSethiUllmanNumbers();
  2460. // For single block loops, mark nodes that look like canonical IV increments.
  2461. if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
  2462. for (SUnit &SU : sunits)
  2463. initVRegCycle(&SU);
  2464. }
  2465. //===----------------------------------------------------------------------===//
  2466. // Preschedule for Register Pressure
  2467. //===----------------------------------------------------------------------===//
  2468. bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
  2469. if (SU->isTwoAddress) {
  2470. unsigned Opc = SU->getNode()->getMachineOpcode();
  2471. const MCInstrDesc &MCID = TII->get(Opc);
  2472. unsigned NumRes = MCID.getNumDefs();
  2473. unsigned NumOps = MCID.getNumOperands() - NumRes;
  2474. for (unsigned i = 0; i != NumOps; ++i) {
  2475. if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
  2476. SDNode *DU = SU->getNode()->getOperand(i).getNode();
  2477. if (DU->getNodeId() != -1 &&
  2478. Op->OrigNode == &(*SUnits)[DU->getNodeId()])
  2479. return true;
  2480. }
  2481. }
  2482. }
  2483. return false;
  2484. }
  2485. /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
  2486. /// successor's explicit physregs whose definition can reach DepSU.
  2487. /// i.e. DepSU should not be scheduled above SU.
  2488. static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
  2489. ScheduleDAGRRList *scheduleDAG,
  2490. const TargetInstrInfo *TII,
  2491. const TargetRegisterInfo *TRI) {
  2492. const MCPhysReg *ImpDefs
  2493. = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
  2494. const uint32_t *RegMask = getNodeRegMask(SU->getNode());
  2495. if(!ImpDefs && !RegMask)
  2496. return false;
  2497. for (const SDep &Succ : SU->Succs) {
  2498. SUnit *SuccSU = Succ.getSUnit();
  2499. for (const SDep &SuccPred : SuccSU->Preds) {
  2500. if (!SuccPred.isAssignedRegDep())
  2501. continue;
  2502. if (RegMask &&
  2503. MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
  2504. scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
  2505. return true;
  2506. if (ImpDefs)
  2507. for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
  2508. // Return true if SU clobbers this physical register use and the
  2509. // definition of the register reaches from DepSU. IsReachable queries
  2510. // a topological forward sort of the DAG (following the successors).
  2511. if (TRI->regsOverlap(*ImpDef, SuccPred.getReg()) &&
  2512. scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
  2513. return true;
  2514. }
  2515. }
  2516. return false;
  2517. }
  2518. /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
  2519. /// physical register defs.
  2520. static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
  2521. const TargetInstrInfo *TII,
  2522. const TargetRegisterInfo *TRI) {
  2523. SDNode *N = SuccSU->getNode();
  2524. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  2525. const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
  2526. assert(ImpDefs && "Caller should check hasPhysRegDefs");
  2527. for (const SDNode *SUNode = SU->getNode(); SUNode;
  2528. SUNode = SUNode->getGluedNode()) {
  2529. if (!SUNode->isMachineOpcode())
  2530. continue;
  2531. const MCPhysReg *SUImpDefs =
  2532. TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
  2533. const uint32_t *SURegMask = getNodeRegMask(SUNode);
  2534. if (!SUImpDefs && !SURegMask)
  2535. continue;
  2536. for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
  2537. MVT VT = N->getSimpleValueType(i);
  2538. if (VT == MVT::Glue || VT == MVT::Other)
  2539. continue;
  2540. if (!N->hasAnyUseOfValue(i))
  2541. continue;
  2542. unsigned Reg = ImpDefs[i - NumDefs];
  2543. if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
  2544. return true;
  2545. if (!SUImpDefs)
  2546. continue;
  2547. for (;*SUImpDefs; ++SUImpDefs) {
  2548. unsigned SUReg = *SUImpDefs;
  2549. if (TRI->regsOverlap(Reg, SUReg))
  2550. return true;
  2551. }
  2552. }
  2553. }
  2554. return false;
  2555. }
  2556. /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
  2557. /// are not handled well by the general register pressure reduction
  2558. /// heuristics. When presented with code like this:
  2559. ///
  2560. /// N
  2561. /// / |
  2562. /// / |
  2563. /// U store
  2564. /// |
  2565. /// ...
  2566. ///
  2567. /// the heuristics tend to push the store up, but since the
  2568. /// operand of the store has another use (U), this would increase
  2569. /// the length of that other use (the U->N edge).
  2570. ///
  2571. /// This function transforms code like the above to route U's
  2572. /// dependence through the store when possible, like this:
  2573. ///
  2574. /// N
  2575. /// ||
  2576. /// ||
  2577. /// store
  2578. /// |
  2579. /// U
  2580. /// |
  2581. /// ...
  2582. ///
  2583. /// This results in the store being scheduled immediately
  2584. /// after N, which shortens the U->N live range, reducing
  2585. /// register pressure.
  2586. void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
  2587. // Visit all the nodes in topological order, working top-down.
  2588. for (SUnit &SU : *SUnits) {
  2589. // For now, only look at nodes with no data successors, such as stores.
  2590. // These are especially important, due to the heuristics in
  2591. // getNodePriority for nodes with no data successors.
  2592. if (SU.NumSuccs != 0)
  2593. continue;
  2594. // For now, only look at nodes with exactly one data predecessor.
  2595. if (SU.NumPreds != 1)
  2596. continue;
  2597. // Avoid prescheduling copies to virtual registers, which don't behave
  2598. // like other nodes from the perspective of scheduling heuristics.
  2599. if (SDNode *N = SU.getNode())
  2600. if (N->getOpcode() == ISD::CopyToReg &&
  2601. Register::isVirtualRegister(
  2602. cast<RegisterSDNode>(N->getOperand(1))->getReg()))
  2603. continue;
  2604. SDNode *PredFrameSetup = nullptr;
  2605. for (const SDep &Pred : SU.Preds)
  2606. if (Pred.isCtrl() && Pred.getSUnit()) {
  2607. // Find the predecessor which is not data dependence.
  2608. SDNode *PredND = Pred.getSUnit()->getNode();
  2609. // If PredND is FrameSetup, we should not pre-scheduled the node,
  2610. // or else, when bottom up scheduling, ADJCALLSTACKDOWN and
  2611. // ADJCALLSTACKUP may hold CallResource too long and make other
  2612. // calls can't be scheduled. If there's no other available node
  2613. // to schedule, the schedular will try to rename the register by
  2614. // creating copy to avoid the conflict which will fail because
  2615. // CallResource is not a real physical register.
  2616. if (PredND && PredND->isMachineOpcode() &&
  2617. (PredND->getMachineOpcode() == TII->getCallFrameSetupOpcode())) {
  2618. PredFrameSetup = PredND;
  2619. break;
  2620. }
  2621. }
  2622. // Skip the node has FrameSetup parent.
  2623. if (PredFrameSetup != nullptr)
  2624. continue;
  2625. // Locate the single data predecessor.
  2626. SUnit *PredSU = nullptr;
  2627. for (const SDep &Pred : SU.Preds)
  2628. if (!Pred.isCtrl()) {
  2629. PredSU = Pred.getSUnit();
  2630. break;
  2631. }
  2632. assert(PredSU);
  2633. // Don't rewrite edges that carry physregs, because that requires additional
  2634. // support infrastructure.
  2635. if (PredSU->hasPhysRegDefs)
  2636. continue;
  2637. // Short-circuit the case where SU is PredSU's only data successor.
  2638. if (PredSU->NumSuccs == 1)
  2639. continue;
  2640. // Avoid prescheduling to copies from virtual registers, which don't behave
  2641. // like other nodes from the perspective of scheduling heuristics.
  2642. if (SDNode *N = SU.getNode())
  2643. if (N->getOpcode() == ISD::CopyFromReg &&
  2644. Register::isVirtualRegister(
  2645. cast<RegisterSDNode>(N->getOperand(1))->getReg()))
  2646. continue;
  2647. // Perform checks on the successors of PredSU.
  2648. for (const SDep &PredSucc : PredSU->Succs) {
  2649. SUnit *PredSuccSU = PredSucc.getSUnit();
  2650. if (PredSuccSU == &SU) continue;
  2651. // If PredSU has another successor with no data successors, for
  2652. // now don't attempt to choose either over the other.
  2653. if (PredSuccSU->NumSuccs == 0)
  2654. goto outer_loop_continue;
  2655. // Don't break physical register dependencies.
  2656. if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
  2657. if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
  2658. goto outer_loop_continue;
  2659. // Don't introduce graph cycles.
  2660. if (scheduleDAG->IsReachable(&SU, PredSuccSU))
  2661. goto outer_loop_continue;
  2662. }
  2663. // Ok, the transformation is safe and the heuristics suggest it is
  2664. // profitable. Update the graph.
  2665. LLVM_DEBUG(
  2666. dbgs() << " Prescheduling SU #" << SU.NodeNum << " next to PredSU #"
  2667. << PredSU->NodeNum
  2668. << " to guide scheduling in the presence of multiple uses\n");
  2669. for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
  2670. SDep Edge = PredSU->Succs[i];
  2671. assert(!Edge.isAssignedRegDep());
  2672. SUnit *SuccSU = Edge.getSUnit();
  2673. if (SuccSU != &SU) {
  2674. Edge.setSUnit(PredSU);
  2675. scheduleDAG->RemovePred(SuccSU, Edge);
  2676. scheduleDAG->AddPredQueued(&SU, Edge);
  2677. Edge.setSUnit(&SU);
  2678. scheduleDAG->AddPredQueued(SuccSU, Edge);
  2679. --i;
  2680. }
  2681. }
  2682. outer_loop_continue:;
  2683. }
  2684. }
  2685. /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
  2686. /// it as a def&use operand. Add a pseudo control edge from it to the other
  2687. /// node (if it won't create a cycle) so the two-address one will be scheduled
  2688. /// first (lower in the schedule). If both nodes are two-address, favor the
  2689. /// one that has a CopyToReg use (more likely to be a loop induction update).
  2690. /// If both are two-address, but one is commutable while the other is not
  2691. /// commutable, favor the one that's not commutable.
  2692. void RegReductionPQBase::AddPseudoTwoAddrDeps() {
  2693. for (SUnit &SU : *SUnits) {
  2694. if (!SU.isTwoAddress)
  2695. continue;
  2696. SDNode *Node = SU.getNode();
  2697. if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
  2698. continue;
  2699. bool isLiveOut = hasOnlyLiveOutUses(&SU);
  2700. unsigned Opc = Node->getMachineOpcode();
  2701. const MCInstrDesc &MCID = TII->get(Opc);
  2702. unsigned NumRes = MCID.getNumDefs();
  2703. unsigned NumOps = MCID.getNumOperands() - NumRes;
  2704. for (unsigned j = 0; j != NumOps; ++j) {
  2705. if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
  2706. continue;
  2707. SDNode *DU = SU.getNode()->getOperand(j).getNode();
  2708. if (DU->getNodeId() == -1)
  2709. continue;
  2710. const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
  2711. if (!DUSU)
  2712. continue;
  2713. for (const SDep &Succ : DUSU->Succs) {
  2714. if (Succ.isCtrl())
  2715. continue;
  2716. SUnit *SuccSU = Succ.getSUnit();
  2717. if (SuccSU == &SU)
  2718. continue;
  2719. // Be conservative. Ignore if nodes aren't at roughly the same
  2720. // depth and height.
  2721. if (SuccSU->getHeight() < SU.getHeight() &&
  2722. (SU.getHeight() - SuccSU->getHeight()) > 1)
  2723. continue;
  2724. // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
  2725. // constrains whatever is using the copy, instead of the copy
  2726. // itself. In the case that the copy is coalesced, this
  2727. // preserves the intent of the pseudo two-address heurietics.
  2728. while (SuccSU->Succs.size() == 1 &&
  2729. SuccSU->getNode()->isMachineOpcode() &&
  2730. SuccSU->getNode()->getMachineOpcode() ==
  2731. TargetOpcode::COPY_TO_REGCLASS)
  2732. SuccSU = SuccSU->Succs.front().getSUnit();
  2733. // Don't constrain non-instruction nodes.
  2734. if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
  2735. continue;
  2736. // Don't constrain nodes with physical register defs if the
  2737. // predecessor can clobber them.
  2738. if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
  2739. if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
  2740. continue;
  2741. }
  2742. // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
  2743. // these may be coalesced away. We want them close to their uses.
  2744. unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
  2745. if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
  2746. SuccOpc == TargetOpcode::INSERT_SUBREG ||
  2747. SuccOpc == TargetOpcode::SUBREG_TO_REG)
  2748. continue;
  2749. if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
  2750. (!canClobber(SuccSU, DUSU) ||
  2751. (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
  2752. (!SU.isCommutable && SuccSU->isCommutable)) &&
  2753. !scheduleDAG->IsReachable(SuccSU, &SU)) {
  2754. LLVM_DEBUG(dbgs()
  2755. << " Adding a pseudo-two-addr edge from SU #"
  2756. << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
  2757. scheduleDAG->AddPredQueued(&SU, SDep(SuccSU, SDep::Artificial));
  2758. }
  2759. }
  2760. }
  2761. }
  2762. }
  2763. //===----------------------------------------------------------------------===//
  2764. // Public Constructor Functions
  2765. //===----------------------------------------------------------------------===//
  2766. ScheduleDAGSDNodes *
  2767. llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
  2768. CodeGenOpt::Level OptLevel) {
  2769. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2770. const TargetInstrInfo *TII = STI.getInstrInfo();
  2771. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2772. BURegReductionPriorityQueue *PQ =
  2773. new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
  2774. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
  2775. PQ->setScheduleDAG(SD);
  2776. return SD;
  2777. }
  2778. ScheduleDAGSDNodes *
  2779. llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
  2780. CodeGenOpt::Level OptLevel) {
  2781. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2782. const TargetInstrInfo *TII = STI.getInstrInfo();
  2783. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2784. SrcRegReductionPriorityQueue *PQ =
  2785. new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
  2786. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
  2787. PQ->setScheduleDAG(SD);
  2788. return SD;
  2789. }
  2790. ScheduleDAGSDNodes *
  2791. llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
  2792. CodeGenOpt::Level OptLevel) {
  2793. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2794. const TargetInstrInfo *TII = STI.getInstrInfo();
  2795. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2796. const TargetLowering *TLI = IS->TLI;
  2797. HybridBURRPriorityQueue *PQ =
  2798. new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
  2799. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
  2800. PQ->setScheduleDAG(SD);
  2801. return SD;
  2802. }
  2803. ScheduleDAGSDNodes *
  2804. llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
  2805. CodeGenOpt::Level OptLevel) {
  2806. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2807. const TargetInstrInfo *TII = STI.getInstrInfo();
  2808. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2809. const TargetLowering *TLI = IS->TLI;
  2810. ILPBURRPriorityQueue *PQ =
  2811. new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
  2812. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
  2813. PQ->setScheduleDAG(SD);
  2814. return SD;
  2815. }