ScheduleDAGRRList.cpp 107 KB

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