rgobj.pas 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102
  1. {
  2. Copyright (c) 1998-2012 by the Free Pascal team
  3. This unit implements the base class for the register allocator
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. {$i fpcdefs.inc}
  18. { $define DEBUG_REGALLOC}
  19. { $define DEBUG_SPILLCOALESCE}
  20. { $define DEBUG_REGISTERLIFE}
  21. { Allow duplicate allocations, can be used to get the .s file written }
  22. { $define ALLOWDUPREG}
  23. {$ifdef DEBUG_REGALLOC}
  24. {$define EXTDEBUG}
  25. {$endif DEBUG_REGALLOC}
  26. unit rgobj;
  27. interface
  28. uses
  29. cutils, cpubase,
  30. aasmtai,aasmdata,aasmsym,aasmcpu,
  31. cclasses,globtype,cgbase,cgutils;
  32. const
  33. interferenceBitmap2Size = 256;
  34. type
  35. {
  36. The interference bitmap contains of 2 layers:
  37. layer 1 - 256*256 blocks with pointers to layer 2 blocks
  38. layer 2 - blocks of 32*256 (32 bytes = 256 bits)
  39. }
  40. Tinterferencebitmap2 = array of set of byte;
  41. Tinterferencebitmap1 = array[byte] of Tinterferencebitmap2;
  42. tinterferencebitmap1Array = array of tinterferencebitmap1;
  43. Tinterferencebitmap=class
  44. private
  45. maxx1,
  46. maxy1 : byte;
  47. fbitmap : tinterferencebitmap1Array;
  48. function getbitmap(x,y:tsuperregister):boolean;
  49. procedure setbitmap(x,y:tsuperregister;b:boolean);
  50. public
  51. constructor create;
  52. destructor destroy;override;
  53. property bitmap[x,y:tsuperregister]:boolean read getbitmap write setbitmap;default;
  54. end;
  55. {In the register allocator we keep track of move instructions.
  56. These instructions are moved between five linked lists. There
  57. is also a linked list per register to keep track about the moves
  58. it is associated with. Because we need to determine quickly in
  59. which of the five lists it is we add anu enumeradtion to each
  60. move instruction.}
  61. Tmoveset=(ms_coalesced_moves,ms_constrained_moves,ms_frozen_moves,
  62. ms_worklist_moves,ms_active_moves);
  63. Tmoveins=class(Tlinkedlistitem)
  64. moveset:Tmoveset;
  65. x,y:Tsuperregister;
  66. id:longint;
  67. end;
  68. Tmovelistheader=record
  69. count,
  70. maxcount,
  71. sorted_until : cardinal;
  72. end;
  73. Tmovelist=record
  74. header : Tmovelistheader;
  75. data : array[tsuperregister] of Tmoveins;
  76. end;
  77. Pmovelist=^Tmovelist;
  78. Treginfoflag=(
  79. ri_coalesced, { the register is coalesced with other register }
  80. ri_selected, { the register is put to selectstack }
  81. ri_spill_helper, { the register contains a value of a previously spilled register }
  82. ri_has_initial_loc { the register has the initial memory location (e.g. a parameter in the stack) }
  83. );
  84. Treginfoflagset=set of Treginfoflag;
  85. Treginfo=record
  86. live_start,
  87. live_end : Tai;
  88. subreg : tsubregister;
  89. alias : Tsuperregister;
  90. { The register allocator assigns each register a colour }
  91. colour : Tsuperregister;
  92. movelist : Pmovelist;
  93. adjlist : Psuperregisterworklist;
  94. degree : TSuperregister;
  95. flags : Treginfoflagset;
  96. weight : longint;
  97. {$ifdef llvm}
  98. def : pointer;
  99. {$endif llvm}
  100. count_uses : longint;
  101. total_interferences : longint;
  102. real_reg_interferences: word;
  103. end;
  104. // Preginfo=^TReginfo;
  105. TReginfoArray = Array of TReginfo;
  106. tspillreginfo = record
  107. { a single register may appear more than once in an instruction,
  108. but with different subregister types -> store all subregister types
  109. that occur, so we can add the necessary constraints for the inline
  110. register that will have to replace it }
  111. spillregconstraints : set of TSubRegister;
  112. orgreg : tsuperregister;
  113. loadreg,
  114. storereg: tregister;
  115. regread, regwritten, mustbespilled: boolean;
  116. end;
  117. tspillregsinfo = record
  118. spillreginfocount: longint;
  119. spillreginfo: array[0..3] of tspillreginfo;
  120. end;
  121. // Pspill_temp_list=^Tspill_temp_list;
  122. Tspill_temp_list = array of Treference;
  123. { used to store where a register is spilled and what interferences it has at the point of being spilled }
  124. tspillinfo = record
  125. spilllocation : treference;
  126. spilled : boolean;
  127. interferences : Tinterferencebitmap;
  128. end;
  129. {#------------------------------------------------------------------
  130. This class implements the default register allocator. It is used by the
  131. code generator to allocate and free registers which might be valid
  132. across nodes. It also contains utility routines related to registers.
  133. Some of the methods in this class should be overridden
  134. by cpu-specific implementations.
  135. --------------------------------------------------------------------}
  136. trgobj=class
  137. preserved_by_proc : tcpuregisterset;
  138. used_in_proc : tcpuregisterset;
  139. { generate SSA code? }
  140. ssa_safe: boolean;
  141. constructor create(Aregtype:Tregistertype;
  142. Adefaultsub:Tsubregister;
  143. const Ausable:array of tsuperregister;
  144. Afirst_imaginary:Tsuperregister;
  145. Apreserved_by_proc:Tcpuregisterset);
  146. destructor destroy;override;
  147. { Allocate a register. An internalerror will be generated if there is
  148. no more free registers which can be allocated.}
  149. function getregister(list:TAsmList;subreg:Tsubregister):Tregister;virtual;
  150. { Get the register specified.}
  151. procedure getcpuregister(list:TAsmList;r:Tregister);virtual;
  152. procedure ungetcpuregister(list:TAsmList;r:Tregister);virtual;
  153. { Get multiple registers specified.}
  154. procedure alloccpuregisters(list:TAsmList;const r:Tcpuregisterset);virtual;
  155. { Free multiple registers specified.}
  156. procedure dealloccpuregisters(list:TAsmList;const r:Tcpuregisterset);virtual;
  157. function uses_registers:boolean;virtual;
  158. procedure add_reg_instruction(instr:Tai;r:tregister;aweight:longint);
  159. {$if max_operands>1}
  160. procedure add_move_instruction(instr:Taicpu);
  161. {$endif max_operands>1}
  162. { Do the register allocation.}
  163. procedure do_register_allocation(list:TAsmList;headertai:tai);virtual;
  164. { Adds an interference edge.
  165. don't move this to the protected section, the arm cg requires to access this (FK) }
  166. procedure add_edge(u,v:Tsuperregister);
  167. { translates a single given imaginary register to it's real register }
  168. procedure translate_register(var reg : tregister);
  169. { sets the initial memory location of the register }
  170. procedure set_reg_initial_location(reg: tregister; const ref: treference);
  171. protected
  172. maxreginfo,
  173. maxreginfoinc,
  174. maxreg : Tsuperregister;
  175. regtype : Tregistertype;
  176. { default subregister used }
  177. defaultsub : tsubregister;
  178. live_registers:Tsuperregisterworklist;
  179. spillednodes: tsuperregisterworklist;
  180. { can be overridden to add cpu specific interferences }
  181. procedure add_cpu_interferences(p : tai);virtual;
  182. procedure add_constraints(reg:Tregister);virtual;
  183. function getregisterinline(list:TAsmList;const subregconstraints:Tsubregisterset):Tregister;
  184. procedure ungetregisterinline(list:TAsmList;r:Tregister);
  185. function get_spill_subreg(r : tregister) : tsubregister;virtual;
  186. function do_spill_replace(list:TAsmList;instr:tai_cpu_abstract_sym;orgreg:tsuperregister;const spilltemp:treference):boolean;virtual;
  187. { the orgrsupeg parameter is only here for the llvm target, so it can
  188. discover the def to use for the load }
  189. procedure do_spill_read(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);virtual;
  190. procedure do_spill_written(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);virtual;
  191. function addreginfo(var spregs: tspillregsinfo; const r: tsuperregisterset; reg: tregister; operation: topertype): boolean;
  192. function instr_get_oper_spilling_info(var spregs: tspillregsinfo; const r: tsuperregisterset; instr: tai_cpu_abstract_sym; opidx: longint): boolean; virtual;
  193. procedure substitute_spilled_registers(const spregs: tspillregsinfo; instr: tai_cpu_abstract_sym; opidx: longint); virtual;
  194. procedure try_replace_reg(const spregs: tspillregsinfo; var reg: tregister; useloadreg: boolean);
  195. function instr_spill_register(list:TAsmList;
  196. instr:tai_cpu_abstract_sym;
  197. const r:Tsuperregisterset;
  198. const spilltemplist:Tspill_temp_list): boolean;virtual;
  199. procedure insert_regalloc_info_all(list:TAsmList);
  200. procedure determine_spill_registers(list:TAsmList;headertail:tai); virtual;
  201. procedure get_spill_temp(list:TAsmlist;spill_temps: Tspill_temp_list; supreg: tsuperregister);virtual;
  202. strict protected
  203. { Highest register allocated until now.}
  204. reginfo : TReginfoArray;
  205. usable_registers_cnt : word;
  206. private
  207. int_live_range_direction: TRADirection;
  208. { First imaginary register.}
  209. first_imaginary : Tsuperregister;
  210. usable_registers : array[0..maxcpuregister] of tsuperregister;
  211. usable_register_set : tcpuregisterset;
  212. ibitmap : Tinterferencebitmap;
  213. simplifyworklist,
  214. freezeworklist,
  215. spillworklist,
  216. coalescednodes,
  217. selectstack : tsuperregisterworklist;
  218. worklist_moves,
  219. active_moves,
  220. frozen_moves,
  221. coalesced_moves,
  222. constrained_moves,
  223. { in this list we collect all moveins which should be disposed after register allocation finishes,
  224. we still need the moves for spill coalesce for the whole register allocation process, so they cannot be
  225. released as soon as they are frozen or whatever }
  226. move_garbage : Tlinkedlist;
  227. extended_backwards,
  228. backwards_was_first : tbitset;
  229. has_usedmarks: boolean;
  230. has_directalloc: boolean;
  231. spillinfo : array of tspillinfo;
  232. moveins_id_counter: longint;
  233. { Disposes of the reginfo array.}
  234. procedure dispose_reginfo;
  235. { Prepare the register colouring.}
  236. procedure prepare_colouring;
  237. { Clean up after register colouring.}
  238. procedure epilogue_colouring;
  239. { Colour the registers; that is do the register allocation.}
  240. procedure colour_registers;
  241. procedure insert_regalloc_info(list:TAsmList;u:tsuperregister);
  242. procedure generate_interference_graph(list:TAsmList;headertai:tai);
  243. { sort spilled nodes by increasing number of interferences }
  244. procedure sort_spillednodes;
  245. { translates the registers in the given assembler list }
  246. procedure translate_registers(list:TAsmList);
  247. function spill_registers(list:TAsmList;headertai:tai):boolean;virtual;
  248. function getnewreg(subreg:tsubregister):tsuperregister;
  249. procedure add_edges_used(u:Tsuperregister);
  250. procedure add_to_movelist(u:Tsuperregister;ins:Tmoveins);
  251. function move_related(n:Tsuperregister):boolean;
  252. procedure make_work_list;
  253. procedure sort_simplify_worklist;
  254. procedure enable_moves(n:Tsuperregister);
  255. procedure decrement_degree(m:Tsuperregister);
  256. procedure simplify;
  257. procedure add_worklist(u:Tsuperregister);
  258. function adjacent_ok(u,v:Tsuperregister):boolean;
  259. function conservative(u,v:Tsuperregister):boolean;
  260. procedure coalesce;
  261. procedure freeze_moves(u:Tsuperregister);
  262. procedure freeze;
  263. procedure select_spill;
  264. procedure assign_colours;
  265. procedure clear_interferences(u:Tsuperregister);
  266. procedure set_live_range_direction(dir: TRADirection);
  267. procedure set_live_start(reg : tsuperregister;t : tai);
  268. function get_live_start(reg : tsuperregister) : tai;
  269. procedure set_live_end(reg : tsuperregister;t : tai);
  270. function get_live_end(reg : tsuperregister) : tai;
  271. procedure alloc_spillinfo(max_reg: Tsuperregister);
  272. { Remove p from the list and set p to the next element in the list }
  273. procedure remove_ai(list:TAsmList; var p:Tai);
  274. {$ifdef DEBUG_SPILLCOALESCE}
  275. procedure write_spill_stats;
  276. {$endif DEBUG_SPILLCOALESCE}
  277. public
  278. {$ifdef EXTDEBUG}
  279. procedure writegraph(loopidx:longint);
  280. {$endif EXTDEBUG}
  281. procedure combine(u,v:Tsuperregister);
  282. { set v as an alias for u }
  283. procedure set_alias(u,v:Tsuperregister);
  284. function get_alias(n:Tsuperregister):Tsuperregister;
  285. property live_range_direction: TRADirection read int_live_range_direction write set_live_range_direction;
  286. property live_start[reg : tsuperregister]: tai read get_live_start write set_live_start;
  287. property live_end[reg : tsuperregister]: tai read get_live_end write set_live_end;
  288. end;
  289. const
  290. first_reg = 0;
  291. last_reg = high(tsuperregister)-1;
  292. maxspillingcounter = 20;
  293. implementation
  294. uses
  295. sysutils,
  296. globals,
  297. verbose,tgobj,procinfo,cgobj;
  298. procedure sort_movelist(ml:Pmovelist);
  299. var h,i,p:longword;
  300. t:Tmoveins;
  301. begin
  302. with ml^ do
  303. begin
  304. if header.count<2 then
  305. exit;
  306. p:=longword(1) shl BsrDWord(header.count-1);
  307. repeat
  308. for h:=p to header.count-1 do
  309. begin
  310. i:=h;
  311. t:=data[i];
  312. repeat
  313. if data[i-p].id<=t.id then
  314. break;
  315. data[i]:=data[i-p];
  316. dec(i,p);
  317. until i<p;
  318. data[i]:=t;
  319. end;
  320. p:=p shr 1;
  321. until p=0;
  322. header.sorted_until:=header.count-1;
  323. end;
  324. end;
  325. {******************************************************************************
  326. tinterferencebitmap
  327. ******************************************************************************}
  328. constructor tinterferencebitmap.create;
  329. begin
  330. inherited create;
  331. maxx1:=1;
  332. SetLength(fbitmap,2);
  333. end;
  334. destructor tinterferencebitmap.destroy;
  335. var i,j:byte;
  336. begin
  337. for i:=0 to maxx1 do
  338. for j:=0 to maxy1 do
  339. if assigned(fbitmap[i,j]) then
  340. fbitmap[i,j]:=nil;
  341. fbitmap:=nil;
  342. end;
  343. function tinterferencebitmap.getbitmap(x,y:tsuperregister):boolean;
  344. var
  345. page : TInterferencebitmap2;
  346. begin
  347. result:=false;
  348. if (x shr 8>maxx1) then
  349. exit;
  350. page:=fbitmap[x shr 8,y shr 8];
  351. result:=assigned(page) and
  352. ((x and $ff) in page[y and $ff]);
  353. end;
  354. procedure tinterferencebitmap.setbitmap(x,y:tsuperregister;b:boolean);
  355. var
  356. x1,y1 : byte;
  357. begin
  358. x1:=x shr 8;
  359. y1:=y shr 8;
  360. if x1>maxx1 then
  361. begin
  362. Setlength(fbitmap,x1+1);
  363. maxx1:=x1;
  364. end;
  365. if not assigned(fbitmap[x1,y1]) then
  366. begin
  367. if y1>maxy1 then
  368. maxy1:=y1;
  369. SetLength(fbitmap[x1,y1],interferenceBitmap2Size);
  370. end;
  371. if b then
  372. include(fbitmap[x1,y1][y and $ff],(x and $ff))
  373. else
  374. exclude(fbitmap[x1,y1][y and $ff],(x and $ff));
  375. end;
  376. {******************************************************************************
  377. trgobj
  378. ******************************************************************************}
  379. constructor trgobj.create(Aregtype:Tregistertype;
  380. Adefaultsub:Tsubregister;
  381. const Ausable:array of tsuperregister;
  382. Afirst_imaginary:Tsuperregister;
  383. Apreserved_by_proc:Tcpuregisterset);
  384. var
  385. i : cardinal;
  386. begin
  387. { empty super register sets can cause very strange problems }
  388. if high(Ausable)=-1 then
  389. internalerror(200210181);
  390. live_range_direction:=rad_forward;
  391. first_imaginary:=Afirst_imaginary;
  392. maxreg:=Afirst_imaginary;
  393. regtype:=Aregtype;
  394. defaultsub:=Adefaultsub;
  395. preserved_by_proc:=Apreserved_by_proc;
  396. // default values set by newinstance
  397. // used_in_proc:=[];
  398. // ssa_safe:=false;
  399. live_registers.init;
  400. { Get reginfo for CPU registers }
  401. maxreginfo:=first_imaginary;
  402. maxreginfoinc:=16;
  403. moveins_id_counter:=0;
  404. worklist_moves:=Tlinkedlist.create;
  405. move_garbage:=TLinkedList.Create;
  406. SetLength(reginfo,first_imaginary);
  407. for i:=0 to first_imaginary-1 do
  408. begin
  409. reginfo[i].degree:=high(tsuperregister);
  410. reginfo[i].alias:=RS_INVALID;
  411. end;
  412. { Usable registers }
  413. // default value set by constructor
  414. // fillchar(usable_registers,sizeof(usable_registers),0);
  415. for i:=low(Ausable) to high(Ausable) do
  416. begin
  417. usable_registers[i]:=Ausable[i];
  418. include(usable_register_set,Ausable[i]);
  419. end;
  420. usable_registers_cnt:=high(Ausable)+1;
  421. { Initialize Worklists }
  422. spillednodes.init;
  423. simplifyworklist.init;
  424. freezeworklist.init;
  425. spillworklist.init;
  426. coalescednodes.init;
  427. selectstack.init;
  428. end;
  429. destructor trgobj.destroy;
  430. begin
  431. spillednodes.done;
  432. simplifyworklist.done;
  433. freezeworklist.done;
  434. spillworklist.done;
  435. coalescednodes.done;
  436. selectstack.done;
  437. live_registers.done;
  438. move_garbage.free;
  439. worklist_moves.free;
  440. dispose_reginfo;
  441. extended_backwards.free;
  442. backwards_was_first.free;
  443. end;
  444. procedure Trgobj.dispose_reginfo;
  445. var
  446. i : cardinal;
  447. begin
  448. if reginfo<>nil then
  449. begin
  450. for i:=0 to maxreg-1 do
  451. with reginfo[i] do
  452. begin
  453. if adjlist<>nil then
  454. dispose(adjlist,done);
  455. if movelist<>nil then
  456. dispose(movelist);
  457. end;
  458. reginfo:=nil;
  459. end;
  460. end;
  461. function trgobj.getnewreg(subreg:tsubregister):tsuperregister;
  462. var
  463. oldmaxreginfo : tsuperregister;
  464. begin
  465. result:=maxreg;
  466. inc(maxreg);
  467. if maxreg>=last_reg then
  468. Message(parser_f_too_complex_proc);
  469. if maxreg>=maxreginfo then
  470. begin
  471. oldmaxreginfo:=maxreginfo;
  472. { Prevent overflow }
  473. if maxreginfoinc>last_reg-maxreginfo then
  474. maxreginfo:=last_reg
  475. else
  476. begin
  477. inc(maxreginfo,maxreginfoinc);
  478. if maxreginfoinc<256 then
  479. maxreginfoinc:=maxreginfoinc*2;
  480. end;
  481. SetLength(reginfo,maxreginfo);
  482. end;
  483. reginfo[result].subreg:=subreg;
  484. end;
  485. function trgobj.getregister(list:TAsmList;subreg:Tsubregister):Tregister;
  486. begin
  487. {$ifdef EXTDEBUG}
  488. if reginfo=nil then
  489. InternalError(2004020901);
  490. {$endif EXTDEBUG}
  491. if defaultsub=R_SUBNONE then
  492. result:=newreg(regtype,getnewreg(R_SUBNONE),R_SUBNONE)
  493. else
  494. result:=newreg(regtype,getnewreg(subreg),subreg);
  495. end;
  496. function trgobj.uses_registers:boolean;
  497. begin
  498. result:=(maxreg>first_imaginary) or has_usedmarks or has_directalloc;
  499. end;
  500. procedure trgobj.ungetcpuregister(list:TAsmList;r:Tregister);
  501. begin
  502. if (getsupreg(r)>=first_imaginary) then
  503. InternalError(2004020902);
  504. list.concat(Tai_regalloc.dealloc(r,nil));
  505. end;
  506. procedure trgobj.getcpuregister(list:TAsmList;r:Tregister);
  507. var
  508. supreg:Tsuperregister;
  509. begin
  510. supreg:=getsupreg(r);
  511. if supreg>=first_imaginary then
  512. internalerror(2003121503);
  513. include(used_in_proc,supreg);
  514. has_directalloc:=true;
  515. list.concat(Tai_regalloc.alloc(r,nil));
  516. end;
  517. procedure trgobj.alloccpuregisters(list:TAsmList;const r:Tcpuregisterset);
  518. var i:cardinal;
  519. begin
  520. for i:=0 to first_imaginary-1 do
  521. if i in r then
  522. getcpuregister(list,newreg(regtype,i,defaultsub));
  523. end;
  524. procedure trgobj.dealloccpuregisters(list:TAsmList;const r:Tcpuregisterset);
  525. var i:cardinal;
  526. begin
  527. for i:=0 to first_imaginary-1 do
  528. if i in r then
  529. ungetcpuregister(list,newreg(regtype,i,defaultsub));
  530. end;
  531. const
  532. rtindex : longint = 0;
  533. procedure trgobj.do_register_allocation(list:TAsmList;headertai:tai);
  534. var
  535. spillingcounter:longint;
  536. endspill:boolean;
  537. i : Longint;
  538. begin
  539. { Insert regalloc info for imaginary registers }
  540. insert_regalloc_info_all(list);
  541. ibitmap:=tinterferencebitmap.create;
  542. generate_interference_graph(list,headertai);
  543. {$ifdef DEBUG_SPILLCOALESCE}
  544. if maxreg>first_imaginary then
  545. writeln(current_procinfo.procdef.mangledname, ': register allocation [',regtype,']');
  546. {$endif DEBUG_SPILLCOALESCE}
  547. {$ifdef DEBUG_REGALLOC}
  548. if maxreg>first_imaginary then
  549. writegraph(rtindex);
  550. {$endif DEBUG_REGALLOC}
  551. inc(rtindex);
  552. { Don't do the real allocation when -sr is passed }
  553. if (cs_no_regalloc in current_settings.globalswitches) then
  554. exit;
  555. { Spill registers which interfere with all usable real registers.
  556. It is pointless to keep them for further processing. Also it may
  557. cause endless spilling.
  558. This can happen when compiling for very constrained CPUs such as
  559. i8086 where indexed memory access instructions allow only
  560. few registers as arguments and additionally the calling convention
  561. provides no general purpose volatile registers.
  562. Also spill registers which have the initial memory location
  563. and are used only once. This allows to access the memory location
  564. directly, without preloading it to a register.
  565. }
  566. for i:=first_imaginary to maxreg-1 do
  567. with reginfo[i] do
  568. if (real_reg_interferences>=usable_registers_cnt) or
  569. { also spill registers which have the initial memory location
  570. and are used only once }
  571. ((ri_has_initial_loc in flags) and (weight<=200)) then
  572. spillednodes.add(i);
  573. if spillednodes.length<>0 then
  574. begin
  575. spill_registers(list,headertai);
  576. spillednodes.clear;
  577. end;
  578. {Do register allocation.}
  579. spillingcounter:=0;
  580. repeat
  581. determine_spill_registers(list,headertai);
  582. endspill:=true;
  583. if spillednodes.length<>0 then
  584. begin
  585. inc(spillingcounter);
  586. if spillingcounter>maxspillingcounter then
  587. begin
  588. {$ifdef EXTDEBUG}
  589. { Only exit here so the .s file is still generated. Assembling
  590. the file will still trigger an error }
  591. exit;
  592. {$else}
  593. internalerror(200309041);
  594. {$endif}
  595. end;
  596. endspill:=not spill_registers(list,headertai);
  597. end;
  598. until endspill;
  599. ibitmap.free;
  600. translate_registers(list);
  601. {$ifdef DEBUG_SPILLCOALESCE}
  602. write_spill_stats;
  603. {$endif DEBUG_SPILLCOALESCE}
  604. { we need the translation table for debugging info and verbose assembler output,
  605. so not dispose them yet (FK)
  606. }
  607. for i:=0 to High(spillinfo) do
  608. spillinfo[i].interferences.Free;
  609. spillinfo:=nil;
  610. end;
  611. procedure trgobj.add_constraints(reg:Tregister);
  612. begin
  613. end;
  614. procedure trgobj.add_edge(u,v:Tsuperregister);
  615. {This procedure will add an edge to the virtual interference graph.}
  616. procedure addadj(u,v:Tsuperregister);
  617. begin
  618. {$ifdef EXTDEBUG}
  619. if (u>=maxreginfo) then
  620. internalerror(2012101901);
  621. {$endif}
  622. with reginfo[u] do
  623. begin
  624. if adjlist=nil then
  625. new(adjlist,init);
  626. adjlist^.add(v);
  627. if (v<first_imaginary) and
  628. (v in usable_register_set) then
  629. inc(real_reg_interferences);
  630. end;
  631. end;
  632. begin
  633. if (u<>v) and not(ibitmap[v,u]) then
  634. begin
  635. ibitmap[v,u]:=true;
  636. ibitmap[u,v]:=true;
  637. {Precoloured nodes are not stored in the interference graph.}
  638. if (u>=first_imaginary) then
  639. addadj(u,v);
  640. if (v>=first_imaginary) then
  641. addadj(v,u);
  642. end;
  643. end;
  644. procedure trgobj.add_edges_used(u:Tsuperregister);
  645. var i:cardinal;
  646. begin
  647. with live_registers do
  648. if length>0 then
  649. for i:=0 to length-1 do
  650. add_edge(u,get_alias(buf[i]));
  651. end;
  652. {$ifdef EXTDEBUG}
  653. procedure trgobj.writegraph(loopidx:longint);
  654. {This procedure writes out the current interference graph in the
  655. register allocator.}
  656. var f:text;
  657. i,j:cardinal;
  658. begin
  659. assign(f,outputunitdir+current_procinfo.procdef.mangledname+'_igraph'+tostr(loopidx));
  660. rewrite(f);
  661. writeln(f,'Interference graph of ',current_procinfo.procdef.fullprocname(true));
  662. writeln(f,'Register type: ',regtype,', First imaginary register is ',first_imaginary,' ($',hexstr(first_imaginary,2),')');
  663. writeln(f);
  664. write(f,' ');
  665. for i:=0 to maxreg div 16 do
  666. for j:=0 to 15 do
  667. write(f,hexstr(i,1));
  668. writeln(f);
  669. write(f,'Weight Degree Uses IntfCnt ');
  670. for i:=0 to maxreg div 16 do
  671. write(f,'0123456789ABCDEF');
  672. writeln(f);
  673. for i:=0 to maxreg-1 do
  674. begin
  675. write(f,reginfo[i].weight:5,' ',reginfo[i].degree:5,' ',reginfo[i].count_uses:5,' ',reginfo[i].total_interferences:5,' ');
  676. if (i<first_imaginary) and
  677. (findreg_by_number(newreg(regtype,TSuperRegister(i),defaultsub))<>0) then
  678. write(f,std_regname(newreg(regtype,TSuperRegister(i),defaultsub))+':'+hexstr(i,2):7)
  679. else
  680. write(f,' ',hexstr(i,2):4);
  681. for j:=0 to maxreg-1 do
  682. if ibitmap[i,j] then
  683. write(f,'*')
  684. else
  685. write(f,'-');
  686. writeln(f);
  687. end;
  688. close(f);
  689. end;
  690. {$endif EXTDEBUG}
  691. procedure trgobj.add_to_movelist(u:Tsuperregister;ins:Tmoveins);
  692. begin
  693. {$ifdef EXTDEBUG}
  694. if (u>=maxreginfo) then
  695. internalerror(2012101902);
  696. {$endif}
  697. with reginfo[u] do
  698. begin
  699. if movelist=nil then
  700. begin
  701. { don't use sizeof(tmovelistheader), because that ignores alignment }
  702. getmem(movelist,ptruint(@movelist^.data)-ptruint(movelist)+16*sizeof(pointer));
  703. movelist^.header.maxcount:=16;
  704. movelist^.header.count:=0;
  705. movelist^.header.sorted_until:=0;
  706. end
  707. else
  708. begin
  709. if movelist^.header.count>=movelist^.header.maxcount then
  710. begin
  711. movelist^.header.maxcount:=movelist^.header.maxcount*2;
  712. { don't use sizeof(tmovelistheader), because that ignores alignment }
  713. reallocmem(movelist,ptruint(@movelist^.data)-ptruint(movelist)+movelist^.header.maxcount*sizeof(pointer));
  714. end;
  715. end;
  716. movelist^.data[movelist^.header.count]:=ins;
  717. inc(movelist^.header.count);
  718. end;
  719. end;
  720. procedure trgobj.set_live_range_direction(dir: TRADirection);
  721. begin
  722. if (dir in [rad_backwards,rad_backwards_reinit]) then
  723. begin
  724. if not assigned(extended_backwards) then
  725. begin
  726. { create expects a "size", not a "max bit" parameter -> +1 }
  727. backwards_was_first:=tbitset.create(maxreg+1);
  728. extended_backwards:=tbitset.create(maxreg+1);
  729. end
  730. else
  731. begin
  732. if (dir=rad_backwards_reinit) then
  733. extended_backwards.clear;
  734. backwards_was_first.clear;
  735. end;
  736. int_live_range_direction:=rad_backwards;
  737. end
  738. else
  739. int_live_range_direction:=rad_forward;
  740. end;
  741. procedure trgobj.set_live_start(reg: tsuperregister; t: tai);
  742. begin
  743. reginfo[reg].live_start:=t;
  744. end;
  745. function trgobj.get_live_start(reg: tsuperregister): tai;
  746. begin
  747. result:=reginfo[reg].live_start;
  748. end;
  749. procedure trgobj.set_live_end(reg: tsuperregister; t: tai);
  750. begin
  751. reginfo[reg].live_end:=t;
  752. end;
  753. function trgobj.get_live_end(reg: tsuperregister): tai;
  754. begin
  755. result:=reginfo[reg].live_end;
  756. end;
  757. procedure trgobj.alloc_spillinfo(max_reg: Tsuperregister);
  758. var
  759. j: longint;
  760. begin
  761. if Length(spillinfo)<max_reg then
  762. begin
  763. j:=Length(spillinfo);
  764. SetLength(spillinfo,max_reg);
  765. fillchar(spillinfo[j],sizeof(spillinfo[0])*(Length(spillinfo)-j),0);
  766. end;
  767. end;
  768. procedure trgobj.add_reg_instruction(instr:Tai;r:tregister;aweight:longint);
  769. var
  770. supreg : tsuperregister;
  771. begin
  772. supreg:=getsupreg(r);
  773. {$ifdef extdebug}
  774. if not (cs_no_regalloc in current_settings.globalswitches) and
  775. (supreg>=maxreginfo) then
  776. internalerror(200411061);
  777. {$endif extdebug}
  778. if supreg>=first_imaginary then
  779. with reginfo[supreg] do
  780. begin
  781. { avoid overflow }
  782. if high(weight)-aweight<weight then
  783. weight:=high(weight)
  784. else
  785. inc(weight,aweight);
  786. if (live_range_direction=rad_forward) then
  787. begin
  788. if not assigned(live_start) then
  789. live_start:=instr;
  790. live_end:=instr;
  791. end
  792. else
  793. begin
  794. if not extended_backwards.isset(supreg) then
  795. begin
  796. extended_backwards.include(supreg);
  797. live_start := instr;
  798. if not assigned(live_end) then
  799. begin
  800. backwards_was_first.include(supreg);
  801. live_end := instr;
  802. end;
  803. end
  804. else
  805. begin
  806. if backwards_was_first.isset(supreg) then
  807. live_end := instr;
  808. end
  809. end
  810. end;
  811. end;
  812. {$if max_operands>1}
  813. procedure trgobj.add_move_instruction(instr:Taicpu);
  814. {This procedure notifies a certain as a move instruction so the
  815. register allocator can try to eliminate it.}
  816. var i:Tmoveins;
  817. sreg, dreg : Tregister;
  818. ssupreg,dsupreg:Tsuperregister;
  819. begin
  820. {$ifdef extdebug}
  821. if (instr.oper[O_MOV_SOURCE]^.typ<>top_reg) or
  822. (instr.oper[O_MOV_DEST]^.typ<>top_reg) then
  823. internalerror(200311291);
  824. {$endif}
  825. sreg:=instr.oper[O_MOV_SOURCE]^.reg;
  826. dreg:=instr.oper[O_MOV_DEST]^.reg;
  827. { How should we handle m68k move %d0,%a0? }
  828. if (getregtype(sreg)<>getregtype(dreg)) then
  829. exit;
  830. if moveins_id_counter=high(moveins_id_counter) then
  831. internalerror(2021112701);
  832. inc(moveins_id_counter);
  833. i:=Tmoveins.create;
  834. i.id:=moveins_id_counter;
  835. i.moveset:=ms_worklist_moves;
  836. worklist_moves.insert(i);
  837. ssupreg:=getsupreg(sreg);
  838. add_to_movelist(ssupreg,i);
  839. dsupreg:=getsupreg(dreg);
  840. { On m68k move can mix address and integer registers,
  841. this leads to problems ... PM }
  842. if (ssupreg<>dsupreg) {and (getregtype(sreg)=getregtype(dreg))} then
  843. {Avoid adding the same move instruction twice to a single register.}
  844. add_to_movelist(dsupreg,i);
  845. i.x:=ssupreg;
  846. i.y:=dsupreg;
  847. end;
  848. {$endif max_operands>1}
  849. function trgobj.move_related(n:Tsuperregister):boolean;
  850. var i:cardinal;
  851. begin
  852. move_related:=false;
  853. with reginfo[n] do
  854. if movelist<>nil then
  855. with movelist^ do
  856. for i:=0 to header.count-1 do
  857. if Tmoveins(data[i]).moveset in [ms_worklist_moves,ms_active_moves] then
  858. begin
  859. move_related:=true;
  860. break;
  861. end;
  862. end;
  863. procedure Trgobj.sort_simplify_worklist;
  864. {Sorts the simplifyworklist by the number of interferences the
  865. registers in it cause. This allows simplify to execute in
  866. constant time.
  867. Sort the list in the descending order, since items of simplifyworklist
  868. are retrieved from end to start and then items are added to selectstack.
  869. The selectstack list is also processed from end to start.
  870. Such way nodes with most interferences will get their colors first.
  871. Since degree of nodes in simplifyworklist before sorting is always
  872. less than the number of usable registers this should not trigger spilling
  873. and should lead to a better register allocation in some cases.
  874. }
  875. var p,h,i,leni,lent:longword;
  876. t:Tsuperregister;
  877. adji,adjt:Psuperregisterworklist;
  878. begin
  879. with simplifyworklist do
  880. begin
  881. if length<2 then
  882. exit;
  883. p:=longword(1) shl BsrDWord(length-1);
  884. repeat
  885. for h:=p to length-1 do
  886. begin
  887. i:=h;
  888. t:=buf[i];
  889. adjt:=reginfo[buf[i]].adjlist;
  890. lent:=0;
  891. if adjt<>nil then
  892. lent:=adjt^.length;
  893. repeat
  894. adji:=reginfo[buf[i-p]].adjlist;
  895. leni:=0;
  896. if adji<>nil then
  897. leni:=adji^.length;
  898. if leni>=lent then
  899. break;
  900. buf[i]:=buf[i-p];
  901. dec(i,p)
  902. until i<p;
  903. buf[i]:=t;
  904. end;
  905. p:=p shr 1;
  906. until p=0;
  907. end;
  908. end;
  909. { sort spilled nodes by increasing number of interferences }
  910. procedure Trgobj.sort_spillednodes;
  911. var
  912. p,h,i,leni,lent:longword;
  913. t:Tsuperregister;
  914. adji,adjt:Psuperregisterworklist;
  915. begin
  916. with spillednodes do
  917. begin
  918. if length<2 then
  919. exit;
  920. p:=longword(1) shl BsrDWord(length-1);
  921. repeat
  922. for h:=p to length-1 do
  923. begin
  924. i:=h;
  925. t:=buf[i];
  926. adjt:=reginfo[buf[i]].adjlist;
  927. lent:=0;
  928. if adjt<>nil then
  929. lent:=adjt^.length;
  930. repeat
  931. adji:=reginfo[buf[i-p]].adjlist;
  932. leni:=0;
  933. if adji<>nil then
  934. leni:=adji^.length;
  935. if leni<=lent then
  936. break;
  937. buf[i]:=buf[i-p];
  938. dec(i,p)
  939. until i<p;
  940. buf[i]:=t;
  941. end;
  942. p:=p shr 1;
  943. until p=0;
  944. end;
  945. end;
  946. procedure trgobj.make_work_list;
  947. var n:cardinal;
  948. begin
  949. {If we have 7 cpu registers, and the degree of a node >= 7, we cannot
  950. assign it to any of the registers, thus it is significant.}
  951. for n:=first_imaginary to maxreg-1 do
  952. with reginfo[n] do
  953. begin
  954. if adjlist=nil then
  955. degree:=0
  956. else
  957. degree:=adjlist^.length;
  958. if degree>=usable_registers_cnt then
  959. spillworklist.add(n)
  960. else if move_related(n) then
  961. freezeworklist.add(n)
  962. else if not(ri_coalesced in flags) then
  963. simplifyworklist.add(n);
  964. end;
  965. sort_simplify_worklist;
  966. end;
  967. procedure trgobj.prepare_colouring;
  968. begin
  969. make_work_list;
  970. active_moves:=Tlinkedlist.create;
  971. frozen_moves:=Tlinkedlist.create;
  972. coalesced_moves:=Tlinkedlist.create;
  973. constrained_moves:=Tlinkedlist.create;
  974. selectstack.clear;
  975. end;
  976. procedure trgobj.enable_moves(n:Tsuperregister);
  977. var m:Tlinkedlistitem;
  978. i:cardinal;
  979. begin
  980. with reginfo[n] do
  981. if movelist<>nil then
  982. for i:=0 to movelist^.header.count-1 do
  983. begin
  984. m:=movelist^.data[i];
  985. if Tmoveins(m).moveset=ms_active_moves then
  986. begin
  987. {Move m from the set active_moves to the set worklist_moves.}
  988. active_moves.remove(m);
  989. Tmoveins(m).moveset:=ms_worklist_moves;
  990. worklist_moves.concat(m);
  991. end;
  992. end;
  993. end;
  994. procedure Trgobj.decrement_degree(m:Tsuperregister);
  995. var adj : Psuperregisterworklist;
  996. n : tsuperregister;
  997. d,i : cardinal;
  998. begin
  999. with reginfo[m] do
  1000. begin
  1001. d:=degree;
  1002. if d=0 then
  1003. internalerror(200312151);
  1004. dec(degree);
  1005. if d=usable_registers_cnt then
  1006. begin
  1007. {Enable moves for m.}
  1008. enable_moves(m);
  1009. {Enable moves for adjacent.}
  1010. adj:=adjlist;
  1011. if adj<>nil then
  1012. for i:=1 to adj^.length do
  1013. begin
  1014. n:=adj^.buf[i-1];
  1015. if reginfo[n].flags*[ri_selected,ri_coalesced]<>[] then
  1016. enable_moves(n);
  1017. end;
  1018. {Remove the node from the spillworklist.}
  1019. if not spillworklist.delete(m) then
  1020. internalerror(200310145);
  1021. if move_related(m) then
  1022. freezeworklist.add(m)
  1023. else
  1024. simplifyworklist.add(m);
  1025. end;
  1026. end;
  1027. end;
  1028. procedure trgobj.simplify;
  1029. var adj : Psuperregisterworklist;
  1030. m,n : Tsuperregister;
  1031. i : cardinal;
  1032. begin
  1033. {We take the element with the least interferences out of the
  1034. simplifyworklist. Since the simplifyworklist is now sorted, we
  1035. no longer need to search, but we can simply take the first element.}
  1036. m:=simplifyworklist.get;
  1037. {Push it on the selectstack.}
  1038. selectstack.add(m);
  1039. with reginfo[m] do
  1040. begin
  1041. include(flags,ri_selected);
  1042. adj:=adjlist;
  1043. end;
  1044. if adj<>nil then
  1045. for i:=1 to adj^.length do
  1046. begin
  1047. n:=adj^.buf[i-1];
  1048. if (n>=first_imaginary) and
  1049. (reginfo[n].flags*[ri_selected,ri_coalesced]=[]) then
  1050. decrement_degree(n);
  1051. end;
  1052. end;
  1053. function trgobj.get_alias(n:Tsuperregister):Tsuperregister;
  1054. begin
  1055. if n>=maxreg then
  1056. internalerror(2021121201);
  1057. while ri_coalesced in reginfo[n].flags do
  1058. n:=reginfo[n].alias;
  1059. get_alias:=n;
  1060. end;
  1061. procedure trgobj.add_worklist(u:Tsuperregister);
  1062. begin
  1063. if (u>=first_imaginary) and
  1064. (not move_related(u)) and
  1065. (reginfo[u].degree<usable_registers_cnt) then
  1066. begin
  1067. if not freezeworklist.delete(u) then
  1068. internalerror(200308161); {must be found}
  1069. simplifyworklist.add(u);
  1070. end;
  1071. end;
  1072. function trgobj.adjacent_ok(u,v:Tsuperregister):boolean;
  1073. {Check wether u and v should be coalesced. u is precoloured.}
  1074. function ok(t,r:Tsuperregister):boolean;
  1075. begin
  1076. ok:=(t<first_imaginary) or
  1077. (reginfo[t].degree<usable_registers_cnt) or
  1078. ibitmap[r,t];
  1079. end;
  1080. var adj : Psuperregisterworklist;
  1081. i : cardinal;
  1082. n : tsuperregister;
  1083. begin
  1084. with reginfo[v] do
  1085. begin
  1086. adjacent_ok:=true;
  1087. adj:=adjlist;
  1088. if adj<>nil then
  1089. for i:=1 to adj^.length do
  1090. begin
  1091. n:=adj^.buf[i-1];
  1092. if (reginfo[n].flags*[ri_coalesced]=[]) and not ok(n,u) then
  1093. begin
  1094. adjacent_ok:=false;
  1095. break;
  1096. end;
  1097. end;
  1098. end;
  1099. end;
  1100. function trgobj.conservative(u,v:Tsuperregister):boolean;
  1101. var adj : Psuperregisterworklist;
  1102. done : Tsuperregisterset; {To prevent that we count nodes twice.}
  1103. i,k:cardinal;
  1104. n : tsuperregister;
  1105. begin
  1106. k:=0;
  1107. supregset_reset(done,false,maxreg);
  1108. with reginfo[u] do
  1109. begin
  1110. adj:=adjlist;
  1111. if adj<>nil then
  1112. for i:=1 to adj^.length do
  1113. begin
  1114. n:=adj^.buf[i-1];
  1115. if reginfo[n].flags*[ri_coalesced,ri_selected]=[] then
  1116. begin
  1117. supregset_include(done,n);
  1118. if reginfo[n].degree>=usable_registers_cnt then
  1119. inc(k);
  1120. end;
  1121. end;
  1122. end;
  1123. adj:=reginfo[v].adjlist;
  1124. if adj<>nil then
  1125. for i:=1 to adj^.length do
  1126. begin
  1127. n:=adj^.buf[i-1];
  1128. if (u<first_imaginary) and
  1129. (n>=first_imaginary) and
  1130. not ibitmap[u,n] and
  1131. (usable_registers_cnt-reginfo[n].real_reg_interferences<=1) then
  1132. begin
  1133. { Do not coalesce if 'u' is the last usable real register available
  1134. for imaginary register 'n'. }
  1135. conservative:=false;
  1136. exit;
  1137. end;
  1138. if not supregset_in(done,n) and
  1139. (reginfo[n].degree>=usable_registers_cnt) and
  1140. (reginfo[n].flags*[ri_coalesced,ri_selected]=[]) then
  1141. inc(k);
  1142. end;
  1143. conservative:=(k<usable_registers_cnt);
  1144. end;
  1145. procedure trgobj.set_alias(u,v:Tsuperregister);
  1146. begin
  1147. { don't make registers that the register allocator shouldn't touch (such
  1148. as stack and frame pointers) be aliases for other registers, because
  1149. then it can propagate them and even start changing them if the aliased
  1150. register gets changed }
  1151. if ((u<first_imaginary) and
  1152. not(u in usable_register_set)) or
  1153. ((v<first_imaginary) and
  1154. not(v in usable_register_set)) then
  1155. exit;
  1156. include(reginfo[v].flags,ri_coalesced);
  1157. if reginfo[v].alias<>0 then
  1158. internalerror(200712291);
  1159. reginfo[v].alias:=get_alias(u);
  1160. coalescednodes.add(v);
  1161. end;
  1162. procedure trgobj.combine(u,v:Tsuperregister);
  1163. var adj : Psuperregisterworklist;
  1164. original_u_count, i,n,p,q:cardinal;
  1165. t : tsuperregister;
  1166. searched:Tmoveins;
  1167. found : boolean;
  1168. begin
  1169. if not freezeworklist.delete(v) then
  1170. spillworklist.delete(v);
  1171. coalescednodes.add(v);
  1172. include(reginfo[v].flags,ri_coalesced);
  1173. reginfo[v].alias:=u;
  1174. {Combine both movelists. Since the movelists are sets, only add
  1175. elements that are not already present. The movelists cannot be
  1176. empty by definition; nodes are only coalesced if there is a move
  1177. between them. To prevent quadratic time blowup (movelists of
  1178. especially machine registers can get very large because of moves
  1179. generated during calls) we need to go into disgusting complexity.
  1180. (See webtbs/tw2242 for an example that stresses this.)
  1181. We want to sort the movelist to be able to search logarithmically.
  1182. Unfortunately, sorting the movelist every time before searching
  1183. is counter-productive, since the movelist usually grows with a few
  1184. items at a time. Therefore, we split the movelist into a sorted
  1185. and an unsorted part and search through both. If the unsorted part
  1186. becomes too large, we sort.}
  1187. if assigned(reginfo[u].movelist) then
  1188. begin
  1189. {We have to weigh the cost of sorting the list against searching
  1190. the cost of the unsorted part. I use factor of 8 here; if the
  1191. number of items is less than 8 times the numer of unsorted items,
  1192. we'll sort the list.}
  1193. with reginfo[u].movelist^ do
  1194. if header.count<8*(header.count-header.sorted_until) then
  1195. sort_movelist(reginfo[u].movelist);
  1196. if assigned(reginfo[v].movelist) then
  1197. begin
  1198. original_u_count:=reginfo[u].movelist^.header.count;
  1199. for n:=0 to reginfo[v].movelist^.header.count-1 do
  1200. begin
  1201. {Binary search the sorted part of the list.}
  1202. searched:=reginfo[v].movelist^.data[n];
  1203. p:=0;
  1204. q:=reginfo[u].movelist^.header.sorted_until;
  1205. i:=0;
  1206. if q<>0 then
  1207. repeat
  1208. i:=(p+q) shr 1;
  1209. if searched.id>reginfo[u].movelist^.data[i].id then
  1210. p:=i+1
  1211. else
  1212. q:=i;
  1213. until p=q;
  1214. with reginfo[u].movelist^ do
  1215. if searched<>data[i] then
  1216. begin
  1217. {Linear search the unsorted part of the list.}
  1218. found:=false;
  1219. { no need to search the instructions we've already added
  1220. from v, we know we won't find a match there }
  1221. for i:=header.sorted_until+1 to original_u_count-1 do
  1222. if searched.id=data[i].id then
  1223. begin
  1224. found:=true;
  1225. break;
  1226. end;
  1227. if not found then
  1228. add_to_movelist(u,searched);
  1229. end;
  1230. end;
  1231. end;
  1232. end;
  1233. enable_moves(v);
  1234. adj:=reginfo[v].adjlist;
  1235. if adj<>nil then
  1236. for i:=1 to adj^.length do
  1237. begin
  1238. t:=adj^.buf[i-1];
  1239. with reginfo[t] do
  1240. if not(ri_coalesced in flags) then
  1241. begin
  1242. {t has a connection to v. Since we are adding v to u, we
  1243. need to connect t to u. However, beware if t was already
  1244. connected to u...}
  1245. if (ibitmap[t,u]) and not (ri_selected in flags) then
  1246. begin
  1247. {... because in that case, we are actually removing an edge
  1248. and the degree of t decreases.}
  1249. decrement_degree(t);
  1250. { if v is combined with a real register, retry
  1251. coalescing of interfering nodes since it may succeed now. }
  1252. if (u<first_imaginary) and
  1253. (adj^.length>=usable_registers_cnt) and
  1254. (reginfo[t].degree>usable_registers_cnt) then
  1255. enable_moves(t);
  1256. end
  1257. else
  1258. begin
  1259. add_edge(t,u);
  1260. {We have added an edge to t and u. So their degree increases.
  1261. However, v is added to u. That means its neighbours will
  1262. no longer point to v, but to u instead. Therefore, only the
  1263. degree of u increases.}
  1264. if (u>=first_imaginary) and not (ri_selected in flags) then
  1265. inc(reginfo[u].degree);
  1266. end;
  1267. end;
  1268. end;
  1269. if (reginfo[u].degree>=usable_registers_cnt) and freezeworklist.delete(u) then
  1270. spillworklist.add(u);
  1271. end;
  1272. procedure trgobj.coalesce;
  1273. var m:Tmoveins;
  1274. x,y,u,v:cardinal;
  1275. begin
  1276. m:=Tmoveins(worklist_moves.getfirst);
  1277. x:=get_alias(m.x);
  1278. y:=get_alias(m.y);
  1279. if (y<first_imaginary) then
  1280. begin
  1281. u:=y;
  1282. v:=x;
  1283. end
  1284. else
  1285. begin
  1286. u:=x;
  1287. v:=y;
  1288. end;
  1289. if (u=v) then
  1290. begin
  1291. m.moveset:=ms_coalesced_moves; {Already coalesced.}
  1292. coalesced_moves.insert(m);
  1293. add_worklist(u);
  1294. end
  1295. {Do u and v interfere? In that case the move is constrained. Two
  1296. precoloured nodes interfere allways. If v is precoloured, by the above
  1297. code u is precoloured, thus interference...}
  1298. else if (v<first_imaginary) or ibitmap[u,v] then
  1299. begin
  1300. m.moveset:=ms_constrained_moves; {Cannot coalesce yet...}
  1301. constrained_moves.insert(m);
  1302. add_worklist(u);
  1303. add_worklist(v);
  1304. end
  1305. {Next test: is it possible and a good idea to coalesce?? Note: don't
  1306. coalesce registers that should not be touched by the register allocator,
  1307. such as stack/framepointers, because otherwise they can be changed }
  1308. else if (((u<first_imaginary) and adjacent_ok(u,v)) or
  1309. conservative(u,v)) and
  1310. ((u>=first_imaginary) or
  1311. (u in usable_register_set)) and
  1312. ((v>=first_imaginary) or
  1313. (v in usable_register_set)) then
  1314. begin
  1315. m.moveset:=ms_coalesced_moves; {Move coalesced!}
  1316. coalesced_moves.insert(m);
  1317. combine(u,v);
  1318. add_worklist(u);
  1319. end
  1320. else
  1321. begin
  1322. m.moveset:=ms_active_moves;
  1323. active_moves.insert(m);
  1324. end;
  1325. end;
  1326. procedure trgobj.freeze_moves(u:Tsuperregister);
  1327. var i:cardinal;
  1328. m:Tlinkedlistitem;
  1329. v,x,y:Tsuperregister;
  1330. begin
  1331. if reginfo[u].movelist<>nil then
  1332. for i:=0 to reginfo[u].movelist^.header.count-1 do
  1333. begin
  1334. m:=reginfo[u].movelist^.data[i];
  1335. if Tmoveins(m).moveset in [ms_worklist_moves,ms_active_moves] then
  1336. begin
  1337. x:=Tmoveins(m).x;
  1338. y:=Tmoveins(m).y;
  1339. if get_alias(y)=get_alias(u) then
  1340. v:=get_alias(x)
  1341. else
  1342. v:=get_alias(y);
  1343. {Move m from active_moves/worklist_moves to frozen_moves.}
  1344. if Tmoveins(m).moveset=ms_active_moves then
  1345. active_moves.remove(m)
  1346. else
  1347. worklist_moves.remove(m);
  1348. Tmoveins(m).moveset:=ms_frozen_moves;
  1349. frozen_moves.insert(m);
  1350. if (v>=first_imaginary) and not(move_related(v)) and
  1351. (reginfo[v].degree<usable_registers_cnt) then
  1352. begin
  1353. freezeworklist.delete(v);
  1354. simplifyworklist.add(v);
  1355. end;
  1356. end;
  1357. end;
  1358. end;
  1359. procedure trgobj.freeze;
  1360. var n:Tsuperregister;
  1361. begin
  1362. { We need to take a random element out of the freezeworklist. We take
  1363. the last element. Dirty code! }
  1364. n:=freezeworklist.get;
  1365. {Add it to the simplifyworklist.}
  1366. simplifyworklist.add(n);
  1367. freeze_moves(n);
  1368. end;
  1369. { The spilling approach selected by SPILLING_NEW does not work well for AVR as it eploits apparently the problem of the current
  1370. reg. allocator with AVR. The current reg. allocator is not aware of the fact that r1-r15 and r16-r31 are not equal on AVR }
  1371. {$if defined(AVR)}
  1372. {$define SPILLING_OLD}
  1373. {$else defined(AVR)}
  1374. { $define SPILLING_NEW}
  1375. {$endif defined(AVR)}
  1376. {$ifndef SPILLING_NEW}
  1377. {$define SPILLING_OLD}
  1378. {$endif SPILLING_NEW}
  1379. procedure trgobj.select_spill;
  1380. var
  1381. n : tsuperregister;
  1382. adj : psuperregisterworklist;
  1383. maxlength,minlength,p,i :word;
  1384. minweight: longint;
  1385. {$ifdef SPILLING_NEW}
  1386. dist: Double;
  1387. {$endif}
  1388. begin
  1389. {$ifdef SPILLING_NEW}
  1390. { This new approach for selecting the next spill candidate takes care of the weight of a register:
  1391. It spills the register with the lowest weight but only if it is expected that it results in convergence of
  1392. register allocation. Convergence is expected if a register is spilled where the average of the active interferences
  1393. - active interference means that the register is used in an instruction - is lower than
  1394. the degree.
  1395. Example (modify means read and the write):
  1396. modify reg1
  1397. loop:
  1398. modify reg2
  1399. modify reg3
  1400. modify reg4
  1401. modify reg5
  1402. modify reg6
  1403. modify reg7
  1404. modify reg1
  1405. In this example, all register have the same degree. However, spilling reg1 is most benefical as it is used least. Furthermore,
  1406. spilling reg1 is a step toward solving the coloring problem as the registers used during spilling will have a lower degree
  1407. as no register are in use at the location where reg1 is spilled.
  1408. }
  1409. minweight:=high(longint);
  1410. p:=0;
  1411. with spillworklist do
  1412. begin
  1413. { Safe: This procedure is only called if length<>0 }
  1414. for i:=0 to length-1 do
  1415. begin
  1416. adj:=reginfo[buf^[i]].adjlist;
  1417. dist:=adj^.length-reginfo[buf^[i]].total_interferences/reginfo[buf^[i]].count_uses;
  1418. if assigned(adj) and
  1419. (reginfo[buf^[i]].weight<minweight) and
  1420. (dist>=1) and
  1421. (reginfo[buf^[i]].weight>0) then
  1422. begin
  1423. p:=i;
  1424. minweight:=reginfo[buf^[i]].weight;
  1425. end;
  1426. end;
  1427. n:=buf^[p];
  1428. deleteidx(p);
  1429. end;
  1430. {$endif SPILLING_NEW}
  1431. {$ifdef SPILLING_OLD}
  1432. { We must look for the element with the most interferences in the
  1433. spillworklist. This is required because those registers are creating
  1434. the most conflicts and keeping them in a register will not reduce the
  1435. complexity and even can cause the help registers for the spilling code
  1436. to get too much conflicts with the result that the spilling code
  1437. will never converge (PFV)
  1438. We need a special processing for nodes with the ri_spill_helper flag set.
  1439. These nodes contain a value of a previously spilled node.
  1440. We need to avoid another spilling of ri_spill_helper nodes, since it will
  1441. likely lead to an endless loop and the register allocation will fail.
  1442. }
  1443. maxlength:=0;
  1444. minweight:=high(longint);
  1445. p:=high(p);
  1446. with spillworklist do
  1447. begin
  1448. {Safe: This procedure is only called if length<>0}
  1449. { Search for a candidate to be spilled, ignoring nodes with the ri_spill_helper flag set. }
  1450. for i:=0 to length-1 do
  1451. if not(ri_spill_helper in reginfo[buf[i]].flags) then
  1452. begin
  1453. adj:=reginfo[buf[i]].adjlist;
  1454. if assigned(adj) and
  1455. (
  1456. (adj^.length>maxlength) or
  1457. ((adj^.length=maxlength) and (reginfo[buf[i]].weight<minweight))
  1458. ) then
  1459. begin
  1460. p:=i;
  1461. maxlength:=adj^.length;
  1462. minweight:=reginfo[buf[i]].weight;
  1463. end;
  1464. end;
  1465. if p=high(p) then
  1466. begin
  1467. { If no normal nodes found, then only ri_spill_helper nodes are present
  1468. in the list. Finding the node with the least interferences and
  1469. the least weight.
  1470. This allows us to put the most restricted ri_spill_helper nodes
  1471. to the top of selectstack so they will be the first to get
  1472. a color assigned.
  1473. }
  1474. minlength:=high(maxlength);
  1475. minweight:=high(minweight);
  1476. p:=0;
  1477. for i:=0 to length-1 do
  1478. begin
  1479. adj:=reginfo[buf[i]].adjlist;
  1480. if assigned(adj) and
  1481. (
  1482. (adj^.length<minlength) or
  1483. ((adj^.length=minlength) and (reginfo[buf[i]].weight<minweight))
  1484. ) then
  1485. begin
  1486. p:=i;
  1487. minlength:=adj^.length;
  1488. minweight:=reginfo[buf[i]].weight;
  1489. end;
  1490. end;
  1491. end;
  1492. n:=buf[p];
  1493. deleteidx(p);
  1494. end;
  1495. {$endif SPILLING_OLD}
  1496. simplifyworklist.add(n);
  1497. freeze_moves(n);
  1498. end;
  1499. procedure trgobj.assign_colours;
  1500. {Assign_colours assigns the actual colours to the registers.}
  1501. var
  1502. colourednodes : Tsuperregisterset;
  1503. procedure reset_colours;
  1504. var
  1505. n : Tsuperregister;
  1506. begin
  1507. spillednodes.clear;
  1508. {Reset colours}
  1509. for n:=0 to maxreg-1 do
  1510. reginfo[n].colour:=n;
  1511. {Colour the cpu registers...}
  1512. supregset_reset(colourednodes,false,maxreg);
  1513. for n:=0 to first_imaginary-1 do
  1514. supregset_include(colourednodes,n);
  1515. end;
  1516. function colour_register(n : Tsuperregister) : boolean;
  1517. var
  1518. j,k : cardinal;
  1519. adj : Psuperregisterworklist;
  1520. adj_colours:set of 0..255;
  1521. a,c : Tsuperregister;
  1522. {$if declared(RS_STACK_POINTER_REG) and (RS_STACK_POINTER_REG<>RS_INVALID)}
  1523. tmpr: tregister;
  1524. {$endif}
  1525. begin
  1526. {Create a list of colours that we cannot assign to n.}
  1527. adj_colours:=[];
  1528. adj:=reginfo[n].adjlist;
  1529. if adj<>nil then
  1530. for j:=0 to adj^.length-1 do
  1531. begin
  1532. a:=get_alias(adj^.buf[j]);
  1533. if supregset_in(colourednodes,a) and (reginfo[a].colour<=255) then
  1534. include(adj_colours,reginfo[a].colour);
  1535. end;
  1536. { e.g. AVR does not have a stack pointer register }
  1537. {$if declared(RS_STACK_POINTER_REG) and (RS_STACK_POINTER_REG<>RS_INVALID)}
  1538. { FIXME: temp variable r is needed here to avoid Internal error 20060521 }
  1539. { while compiling the compiler. }
  1540. tmpr:=NR_STACK_POINTER_REG;
  1541. if (regtype=getregtype(tmpr)) then
  1542. include(adj_colours,RS_STACK_POINTER_REG);
  1543. {$ifend}
  1544. {Assume a spill by default...}
  1545. result:=false;
  1546. {Search for a colour not in this list.}
  1547. for k:=0 to usable_registers_cnt-1 do
  1548. begin
  1549. c:=usable_registers[k];
  1550. if not(c in adj_colours) then
  1551. begin
  1552. reginfo[n].colour:=c;
  1553. result:=true;
  1554. supregset_include(colourednodes,n);
  1555. break;
  1556. end;
  1557. end;
  1558. if not result then
  1559. spillednodes.add(n);
  1560. end;
  1561. var
  1562. i,k : cardinal;
  1563. n : Tsuperregister;
  1564. spill_loop : boolean;
  1565. begin
  1566. reset_colours;
  1567. {Now colour the imaginary registers on the select-stack.}
  1568. spill_loop:=false;
  1569. for i:=selectstack.length downto 1 do
  1570. begin
  1571. n:=selectstack.buf[i-1];
  1572. if not colour_register(n) and
  1573. (ri_spill_helper in reginfo[n].flags) then
  1574. begin
  1575. { Register n is a helper register which holds the value
  1576. of a previously spilled register. Register n must never
  1577. be spilled. Report the spilling loop and break. }
  1578. spill_loop:=true;
  1579. break;
  1580. end;
  1581. end;
  1582. if spill_loop then
  1583. begin
  1584. { Spilling loop is detected when colouring registers using the select-stack order.
  1585. Trying to eliminte this by using a different colouring order. }
  1586. reset_colours;
  1587. { To prevent spilling of helper registers it is needed to assign colours to them first. }
  1588. for i:=selectstack.length downto 1 do
  1589. begin
  1590. n:=selectstack.buf[i-1];
  1591. if ri_spill_helper in reginfo[n].flags then
  1592. if not colour_register(n) then
  1593. { Can't colour the spill helper register n.
  1594. This can happen only when the code generator produces invalid code
  1595. or sue to incorrect node coalescing. }
  1596. internalerror(2021091001);
  1597. end;
  1598. { Assign colours for the rest of the registers }
  1599. for i:=selectstack.length downto 1 do
  1600. begin
  1601. n:=selectstack.buf[i-1];
  1602. if not (ri_spill_helper in reginfo[n].flags) then
  1603. colour_register(n);
  1604. end;
  1605. end;
  1606. {Finally colour the nodes that were coalesced.}
  1607. for i:=1 to coalescednodes.length do
  1608. begin
  1609. n:=coalescednodes.buf[i-1];
  1610. k:=get_alias(n);
  1611. reginfo[n].colour:=reginfo[k].colour;
  1612. end;
  1613. end;
  1614. procedure trgobj.colour_registers;
  1615. begin
  1616. repeat
  1617. if simplifyworklist.length<>0 then
  1618. simplify
  1619. else if not(worklist_moves.empty) then
  1620. coalesce
  1621. else if freezeworklist.length<>0 then
  1622. freeze
  1623. else if spillworklist.length<>0 then
  1624. select_spill;
  1625. until (simplifyworklist.length=0) and
  1626. worklist_moves.empty and
  1627. (freezeworklist.length=0) and
  1628. (spillworklist.length=0);
  1629. assign_colours;
  1630. end;
  1631. procedure trgobj.epilogue_colouring;
  1632. begin
  1633. { remove all items from the worklists, but do not free them, they are still needed for spill coalesce }
  1634. move_garbage.concatList(worklist_moves);
  1635. move_garbage.concatList(active_moves);
  1636. active_moves.Free;
  1637. active_moves:=nil;
  1638. move_garbage.concatList(frozen_moves);
  1639. frozen_moves.Free;
  1640. frozen_moves:=nil;
  1641. move_garbage.concatList(coalesced_moves);
  1642. coalesced_moves.Free;
  1643. coalesced_moves:=nil;
  1644. move_garbage.concatList(constrained_moves);
  1645. constrained_moves.Free;
  1646. constrained_moves:=nil;
  1647. end;
  1648. procedure trgobj.clear_interferences(u:Tsuperregister);
  1649. {Remove node u from the interference graph and remove all collected
  1650. move instructions it is associated with.}
  1651. var i : word;
  1652. v : Tsuperregister;
  1653. adj,adj2 : Psuperregisterworklist;
  1654. begin
  1655. adj:=reginfo[u].adjlist;
  1656. if adj<>nil then
  1657. begin
  1658. for i:=1 to adj^.length do
  1659. begin
  1660. v:=adj^.buf[i-1];
  1661. {Remove (u,v) and (v,u) from bitmap.}
  1662. ibitmap[u,v]:=false;
  1663. ibitmap[v,u]:=false;
  1664. {Remove (v,u) from adjacency list.}
  1665. adj2:=reginfo[v].adjlist;
  1666. if adj2<>nil then
  1667. begin
  1668. adj2^.delete(u);
  1669. if adj2^.length=0 then
  1670. begin
  1671. dispose(adj2,done);
  1672. reginfo[v].adjlist:=nil;
  1673. end;
  1674. end;
  1675. end;
  1676. {Remove ( u,* ) from adjacency list.}
  1677. dispose(adj,done);
  1678. reginfo[u].adjlist:=nil;
  1679. end;
  1680. end;
  1681. function trgobj.getregisterinline(list:TAsmList;const subregconstraints:Tsubregisterset):Tregister;
  1682. var
  1683. p : Tsuperregister;
  1684. subreg: tsubregister;
  1685. begin
  1686. for subreg:=high(tsubregister) downto low(tsubregister) do
  1687. if subreg in subregconstraints then
  1688. break;
  1689. p:=getnewreg(subreg);
  1690. live_registers.add(p);
  1691. result:=newreg(regtype,p,subreg);
  1692. add_edges_used(p);
  1693. add_constraints(result);
  1694. { also add constraints for other sizes used for this register }
  1695. if subreg<>low(tsubregister) then
  1696. for subreg:=pred(subreg) downto low(tsubregister) do
  1697. if subreg in subregconstraints then
  1698. add_constraints(newreg(regtype,getsupreg(result),subreg));
  1699. end;
  1700. procedure trgobj.ungetregisterinline(list:TAsmList;r:Tregister);
  1701. var
  1702. supreg:Tsuperregister;
  1703. begin
  1704. supreg:=getsupreg(r);
  1705. live_registers.delete(supreg);
  1706. insert_regalloc_info(list,supreg);
  1707. end;
  1708. procedure trgobj.insert_regalloc_info(list:TAsmList;u:tsuperregister);
  1709. var
  1710. p : tai;
  1711. r : tregister;
  1712. palloc,
  1713. pdealloc : tai_regalloc;
  1714. begin
  1715. { Insert regallocs for all imaginary registers }
  1716. with reginfo[u] do
  1717. begin
  1718. r:=newreg(regtype,u,subreg);
  1719. if assigned(live_start) then
  1720. begin
  1721. { Generate regalloc and bind it to an instruction, this
  1722. is needed to find all live registers belonging to an
  1723. instruction during the spilling }
  1724. if live_start.typ=ait_instruction then
  1725. palloc:=tai_regalloc.alloc(r,live_start)
  1726. else
  1727. palloc:=tai_regalloc.alloc(r,nil);
  1728. if assigned(live_end) and (live_end.typ=ait_instruction) then
  1729. pdealloc:=tai_regalloc.dealloc(r,live_end)
  1730. else
  1731. pdealloc:=tai_regalloc.dealloc(r,nil);
  1732. { Insert live start allocation before the instruction/reg_a_sync }
  1733. list.insertbefore(palloc,live_start);
  1734. { Insert live end deallocation before reg allocations
  1735. to reduce conflicts }
  1736. p:=live_end;
  1737. if assigned(p) then
  1738. begin
  1739. while assigned(p.previous) and
  1740. (
  1741. (
  1742. (tai(p.previous).typ=ait_regalloc) and
  1743. (
  1744. (
  1745. (tai_regalloc(p.previous).ratype=ra_alloc) and
  1746. (tai_regalloc(p.previous).reg<>r)
  1747. ) or (
  1748. (tai_regalloc(p.previous).ratype=ra_resize)
  1749. { Don't worry if a resize for the same supreg as
  1750. r appears - it won't cause issues in the end
  1751. since it's stripped out anyway and the deallocs
  1752. are adjusted after graph colouring }
  1753. )
  1754. )
  1755. ) or
  1756. (tai(p.previous).typ in [ait_comment,ait_tempalloc,ait_varloc])
  1757. ) do
  1758. p:=tai(p.previous);
  1759. { , but add release after a reg_a_sync }
  1760. if (p.typ=ait_regalloc) and
  1761. (tai_regalloc(p).ratype=ra_sync) then
  1762. p:=tai(p.next);
  1763. end;
  1764. if assigned(p) then
  1765. list.insertbefore(pdealloc,p)
  1766. else
  1767. list.concat(pdealloc);
  1768. end;
  1769. end;
  1770. end;
  1771. procedure trgobj.insert_regalloc_info_all(list:TAsmList);
  1772. var
  1773. supreg : tsuperregister;
  1774. begin
  1775. { Insert regallocs for all imaginary registers }
  1776. for supreg:=first_imaginary to maxreg-1 do
  1777. insert_regalloc_info(list,supreg);
  1778. end;
  1779. procedure trgobj.determine_spill_registers(list: TAsmList; headertail: tai);
  1780. begin
  1781. prepare_colouring;
  1782. colour_registers;
  1783. epilogue_colouring;
  1784. end;
  1785. procedure trgobj.get_spill_temp(list: TAsmlist; spill_temps: Tspill_temp_list; supreg: tsuperregister);
  1786. var
  1787. size: ptrint;
  1788. begin
  1789. {Get a temp for the spilled register, the size must at least equal a complete register,
  1790. take also care of the fact that subreg can be larger than a single register like doubles
  1791. that occupy 2 registers }
  1792. { only force the whole register in case of integers. Storing a register that contains
  1793. a single precision value as a double can cause conversion errors on e.g. ARM VFP }
  1794. if (regtype=R_INTREGISTER) then
  1795. size:=max(tcgsize2size[reg_cgsize(newreg(regtype,supreg,R_SUBWHOLE))],
  1796. tcgsize2size[reg_cgsize(newreg(regtype,supreg,reginfo[supreg].subreg))])
  1797. else
  1798. size:=tcgsize2size[reg_cgsize(newreg(regtype,supreg,reginfo[supreg].subreg))];
  1799. tg.gettemp(list,
  1800. size,size,
  1801. tt_noreuse,spill_temps[supreg]);
  1802. end;
  1803. procedure trgobj.add_cpu_interferences(p : tai);
  1804. begin
  1805. end;
  1806. procedure trgobj.generate_interference_graph(list:TAsmList;headertai:tai);
  1807. procedure RecordUse(var r : Treginfo);
  1808. begin
  1809. inc(r.total_interferences,live_registers.length);
  1810. inc(r.count_uses);
  1811. end;
  1812. var
  1813. p : tai;
  1814. i : integer;
  1815. supreg, u: tsuperregister;
  1816. {$ifdef arm}
  1817. so: pshifterop;
  1818. {$endif arm}
  1819. begin
  1820. { All allocations are available. Now we can generate the
  1821. interference graph. Walk through all instructions, we can
  1822. start with the headertai, because before the header tai is
  1823. only symbols. }
  1824. live_registers.clear;
  1825. p:=headertai;
  1826. while assigned(p) do
  1827. begin
  1828. prefetch(pointer(p.next)^);
  1829. case p.typ of
  1830. ait_instruction:
  1831. with Taicpu(p) do
  1832. begin
  1833. current_filepos:=fileinfo;
  1834. {For speed reasons, get_alias isn't used here, instead,
  1835. assign_colours will also set the colour of coalesced nodes.
  1836. If there are registers with colour=0, then the coalescednodes
  1837. list probably doesn't contain these registers, causing
  1838. assign_colours not to do this properly.}
  1839. for i:=0 to ops-1 do
  1840. with oper[i]^ do
  1841. case typ of
  1842. top_reg:
  1843. if (getregtype(reg)=regtype) then
  1844. begin
  1845. u:=getsupreg(reg);
  1846. {$ifdef EXTDEBUG}
  1847. if (u>=maxreginfo) then
  1848. internalerror(2018111701);
  1849. {$endif}
  1850. RecordUse(reginfo[u]);
  1851. end;
  1852. top_ref:
  1853. begin
  1854. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  1855. with ref^ do
  1856. begin
  1857. if (base<>NR_NO) and
  1858. (getregtype(base)=regtype) then
  1859. begin
  1860. u:=getsupreg(base);
  1861. {$ifdef EXTDEBUG}
  1862. if (u>=maxreginfo) then
  1863. internalerror(2018111702);
  1864. {$endif}
  1865. RecordUse(reginfo[u]);
  1866. end;
  1867. if (index<>NR_NO) and
  1868. (getregtype(index)=regtype) then
  1869. begin
  1870. u:=getsupreg(index);
  1871. {$ifdef EXTDEBUG}
  1872. if (u>=maxreginfo) then
  1873. internalerror(2018111703);
  1874. {$endif}
  1875. RecordUse(reginfo[u]);
  1876. end;
  1877. {$if defined(x86)}
  1878. if (segment<>NR_NO) and
  1879. (getregtype(segment)=regtype) then
  1880. begin
  1881. u:=getsupreg(segment);
  1882. {$ifdef EXTDEBUG}
  1883. if (u>=maxreginfo) then
  1884. internalerror(2018111704);
  1885. {$endif}
  1886. RecordUse(reginfo[u]);
  1887. end;
  1888. {$endif defined(x86)}
  1889. end;
  1890. end;
  1891. {$ifdef arm}
  1892. Top_shifterop:
  1893. begin
  1894. if regtype=R_INTREGISTER then
  1895. begin
  1896. so:=shifterop;
  1897. if (so^.rs<>NR_NO) and
  1898. (getregtype(so^.rs)=regtype) then
  1899. RecordUse(reginfo[getsupreg(so^.rs)]);
  1900. end;
  1901. end;
  1902. {$endif arm}
  1903. else
  1904. ;
  1905. end;
  1906. end;
  1907. ait_regalloc:
  1908. with Tai_regalloc(p) do
  1909. begin
  1910. if (getregtype(reg)=regtype) then
  1911. begin
  1912. supreg:=getsupreg(reg);
  1913. case ratype of
  1914. ra_alloc :
  1915. begin
  1916. live_registers.add(supreg);
  1917. {$ifdef DEBUG_REGISTERLIFE}
  1918. write(live_registers.length,' ');
  1919. for i:=0 to live_registers.length-1 do
  1920. write(std_regname(newreg(regtype,live_registers.buf[i],defaultsub)),' ');
  1921. writeln;
  1922. {$endif DEBUG_REGISTERLIFE}
  1923. add_edges_used(supreg);
  1924. end;
  1925. ra_dealloc :
  1926. begin
  1927. live_registers.delete(supreg);
  1928. {$ifdef DEBUG_REGISTERLIFE}
  1929. write(live_registers.length,' ');
  1930. for i:=0 to live_registers.length-1 do
  1931. write(std_regname(newreg(regtype,live_registers.buf[i],defaultsub)),' ');
  1932. writeln;
  1933. {$endif DEBUG_REGISTERLIFE}
  1934. add_edges_used(supreg);
  1935. end;
  1936. ra_markused :
  1937. if (supreg<first_imaginary) then
  1938. begin
  1939. include(used_in_proc,supreg);
  1940. has_usedmarks:=true;
  1941. end;
  1942. else
  1943. ;
  1944. end;
  1945. { constraints needs always to be updated }
  1946. add_constraints(reg);
  1947. end;
  1948. end;
  1949. else
  1950. ;
  1951. end;
  1952. add_cpu_interferences(p);
  1953. p:=Tai(p.next);
  1954. end;
  1955. {$ifdef EXTDEBUG}
  1956. if live_registers.length>0 then
  1957. begin
  1958. for i:=0 to live_registers.length-1 do
  1959. begin
  1960. { Only report for imaginary registers }
  1961. if live_registers.buf[i]>=first_imaginary then
  1962. Comment(V_Warning,'Register '+std_regname(newreg(regtype,live_registers.buf[i],defaultsub))+' not released');
  1963. end;
  1964. end;
  1965. {$endif}
  1966. end;
  1967. procedure trgobj.translate_register(var reg : tregister);
  1968. begin
  1969. if (getregtype(reg)=regtype) then
  1970. setsupreg(reg,reginfo[getsupreg(reg)].colour)
  1971. else
  1972. internalerror(200602021);
  1973. end;
  1974. procedure trgobj.set_reg_initial_location(reg: tregister; const ref: treference);
  1975. var
  1976. supreg: TSuperRegister;
  1977. begin
  1978. supreg:=getsupreg(reg);
  1979. if (supreg<first_imaginary) or (supreg>=maxreg) then
  1980. internalerror(2020090501);
  1981. alloc_spillinfo(supreg+1);
  1982. spillinfo[supreg].spilllocation:=ref;
  1983. include(reginfo[supreg].flags,ri_has_initial_loc);
  1984. end;
  1985. procedure trgobj.translate_registers(list: TAsmList);
  1986. function get_reg_name_full(r: tregister; include_prefix: boolean): string;
  1987. var
  1988. rr:tregister;
  1989. sr:TSuperRegister;
  1990. begin
  1991. sr:=getsupreg(r);
  1992. if reginfo[sr].live_start=nil then
  1993. begin
  1994. result:='';
  1995. exit;
  1996. end;
  1997. if (sr<length(spillinfo)) and spillinfo[sr].spilled then
  1998. with spillinfo[sr].spilllocation do
  1999. begin
  2000. result:='['+std_regname(base);
  2001. if offset>=0 then
  2002. result:=result+'+';
  2003. result:=result+IntToStr(offset)+']';
  2004. if include_prefix then
  2005. result:='stack '+result;
  2006. end
  2007. else
  2008. begin
  2009. rr:=r;
  2010. setsupreg(rr,reginfo[sr].colour);
  2011. result:=std_regname(rr);
  2012. if include_prefix then
  2013. result:='register '+result;
  2014. end;
  2015. {$if defined(cpu8bitalu) or defined(cpu16bitalu)}
  2016. if (sr>=first_int_imreg) and cg.has_next_reg[sr] then
  2017. result:=result+':'+get_reg_name_full(cg.GetNextReg(r),false);
  2018. {$endif defined(cpu8bitalu) or defined(cpu16bitalu)}
  2019. end;
  2020. var
  2021. hp,p:Tai;
  2022. i:shortint;
  2023. u:longint;
  2024. s:string;
  2025. {$ifdef arm}
  2026. so:pshifterop;
  2027. {$endif arm}
  2028. begin
  2029. { Leave when no imaginary registers are used }
  2030. if maxreg<=first_imaginary then
  2031. exit;
  2032. p:=Tai(list.first);
  2033. while assigned(p) do
  2034. begin
  2035. prefetch(pointer(p.next)^);
  2036. case p.typ of
  2037. ait_regalloc:
  2038. with Tai_regalloc(p) do
  2039. begin
  2040. if (getregtype(reg)=regtype) then
  2041. begin
  2042. { Only alloc/dealloc is needed for the optimizer, remove
  2043. other regalloc }
  2044. if not(ratype in [ra_alloc,ra_dealloc]) then
  2045. begin
  2046. remove_ai(list,p);
  2047. continue;
  2048. end
  2049. else
  2050. begin
  2051. u:=reginfo[getsupreg(reg)].colour;
  2052. include(used_in_proc,u);
  2053. {$ifdef DEBUG_SPILLCOALESCE}
  2054. if (ratype=ra_alloc) and (ri_coalesced in reginfo[getsupreg(reg)].flags) then
  2055. begin
  2056. hp:=Tai_comment.Create(strpnew('Coalesced '+std_regname(reg)+'->'+
  2057. std_regname(newreg(regtype,reginfo[getsupreg(reg)].alias,reginfo[getsupreg(reg)].subreg))+
  2058. ' ('+std_regname(newreg(regtype,u,reginfo[getsupreg(reg)].subreg))+')'));
  2059. list.insertafter(hp,p);
  2060. end;
  2061. {$endif DEBUG_SPILLCOALESCE}
  2062. {$ifdef EXTDEBUG}
  2063. if u>=maxreginfo then
  2064. internalerror(2015040501);
  2065. {$endif}
  2066. setsupreg(reg,u);
  2067. end;
  2068. end;
  2069. end;
  2070. ait_varloc:
  2071. begin
  2072. if (getregtype(tai_varloc(p).newlocation)=regtype) then
  2073. begin
  2074. if (cs_asm_source in current_settings.globalswitches) then
  2075. begin
  2076. s:=get_reg_name_full(tai_varloc(p).newlocation,tai_varloc(p).newlocationhi=NR_NO);
  2077. if s<>'' then
  2078. begin
  2079. if tai_varloc(p).newlocationhi<>NR_NO then
  2080. s:=get_reg_name_full(tai_varloc(p).newlocationhi,true)+':'+s;
  2081. hp:=Tai_comment.Create(strpnew('Var '+tai_varloc(p).varsym.realname+' located in '+s));
  2082. list.insertafter(hp,p);
  2083. end;
  2084. setsupreg(tai_varloc(p).newlocation,reginfo[getsupreg(tai_varloc(p).newlocation)].colour);
  2085. if tai_varloc(p).newlocationhi<>NR_NO then
  2086. setsupreg(tai_varloc(p).newlocationhi,reginfo[getsupreg(tai_varloc(p).newlocationhi)].colour);
  2087. end;
  2088. remove_ai(list,p);
  2089. continue;
  2090. end;
  2091. end;
  2092. ait_instruction:
  2093. with Taicpu(p) do
  2094. begin
  2095. current_filepos:=fileinfo;
  2096. {For speed reasons, get_alias isn't used here, instead,
  2097. assign_colours will also set the colour of coalesced nodes.
  2098. If there are registers with colour=0, then the coalescednodes
  2099. list probably doesn't contain these registers, causing
  2100. assign_colours not to do this properly.}
  2101. for i:=0 to ops-1 do
  2102. with oper[i]^ do
  2103. case typ of
  2104. Top_reg:
  2105. if (getregtype(reg)=regtype) then
  2106. begin
  2107. u:=getsupreg(reg);
  2108. {$ifdef EXTDEBUG}
  2109. if (u>=maxreginfo) then
  2110. internalerror(2012101903);
  2111. {$endif}
  2112. setsupreg(reg,reginfo[u].colour);
  2113. end;
  2114. Top_ref:
  2115. begin
  2116. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2117. with ref^ do
  2118. begin
  2119. if (base<>NR_NO) and
  2120. (getregtype(base)=regtype) then
  2121. begin
  2122. u:=getsupreg(base);
  2123. {$ifdef EXTDEBUG}
  2124. if (u>=maxreginfo) then
  2125. internalerror(2012101904);
  2126. {$endif}
  2127. setsupreg(base,reginfo[u].colour);
  2128. end;
  2129. if (index<>NR_NO) and
  2130. (getregtype(index)=regtype) then
  2131. begin
  2132. u:=getsupreg(index);
  2133. {$ifdef EXTDEBUG}
  2134. if (u>=maxreginfo) then
  2135. internalerror(2012101905);
  2136. {$endif}
  2137. setsupreg(index,reginfo[u].colour);
  2138. end;
  2139. {$if defined(x86)}
  2140. if (segment<>NR_NO) and
  2141. (getregtype(segment)=regtype) then
  2142. begin
  2143. u:=getsupreg(segment);
  2144. {$ifdef EXTDEBUG}
  2145. if (u>=maxreginfo) then
  2146. internalerror(2013052401);
  2147. {$endif}
  2148. setsupreg(segment,reginfo[u].colour);
  2149. end;
  2150. {$endif defined(x86)}
  2151. end;
  2152. end;
  2153. {$ifdef arm}
  2154. Top_shifterop:
  2155. begin
  2156. if regtype=R_INTREGISTER then
  2157. begin
  2158. so:=shifterop;
  2159. if (so^.rs<>NR_NO) and
  2160. (getregtype(so^.rs)=regtype) then
  2161. setsupreg(so^.rs,reginfo[getsupreg(so^.rs)].colour);
  2162. end;
  2163. end;
  2164. {$endif arm}
  2165. else
  2166. ;
  2167. end;
  2168. { Maybe the operation can be removed when
  2169. it is a move and both arguments are the same }
  2170. if is_same_reg_move(regtype) then
  2171. begin
  2172. { Be careful of dangling pointers in previous reg_allocs,
  2173. ss these can confuse the register allocator }
  2174. hp:=tai(p.previous);
  2175. while Assigned(hp) do
  2176. begin
  2177. if (hp.typ in [ait_comment,ait_tempalloc,ait_varloc]) then
  2178. { Do nothing, but pass control flow to
  2179. "hp:=tai(hp.previous)" and continue the loop }
  2180. else if (hp.typ=ait_regalloc) then
  2181. begin
  2182. if tai_regalloc(hp).instr=p then
  2183. tai_regalloc(hp).instr:=nil;
  2184. end
  2185. else
  2186. Break;
  2187. hp:=tai(hp.previous);
  2188. end;
  2189. remove_ai(list,p);
  2190. continue;
  2191. end;
  2192. end;
  2193. else
  2194. ;
  2195. end;
  2196. p:=Tai(p.next);
  2197. end;
  2198. current_filepos:=current_procinfo.exitpos;
  2199. end;
  2200. function trgobj.spill_registers(list:TAsmList;headertai:tai):boolean;
  2201. { Returns true if any help registers have been used }
  2202. var
  2203. i : cardinal;
  2204. t : tsuperregister;
  2205. p : Tai;
  2206. regs_to_spill_set:Tsuperregisterset;
  2207. spill_temps : Tspill_temp_list;
  2208. supreg,x,y : tsuperregister;
  2209. templist : TAsmList;
  2210. j : Longint;
  2211. getnewspillloc : Boolean;
  2212. begin
  2213. spill_registers:=false;
  2214. live_registers.clear;
  2215. { spilling should start with the node with the highest number of interferences, so we can coalesce as
  2216. much as possible spilled nodes (coalesce in case of spilled node means they share the same memory location) }
  2217. sort_spillednodes;
  2218. for i:=first_imaginary to maxreg-1 do
  2219. exclude(reginfo[i].flags,ri_selected);
  2220. SetLength(spill_temps,maxreg);
  2221. supregset_reset(regs_to_spill_set,false,$ffff);
  2222. {$ifdef DEBUG_SPILLCOALESCE}
  2223. writeln('trgobj.spill_registers: Got maxreg ',maxreg);
  2224. writeln('trgobj.spill_registers: Spilling ',spillednodes.length,' nodes');
  2225. {$endif DEBUG_SPILLCOALESCE}
  2226. { after each round of spilling, more registers could be used due to allocations for spilling }
  2227. alloc_spillinfo(maxreg);
  2228. { Allocate temps and insert in front of the list }
  2229. templist:=TAsmList.create;
  2230. { Safe: this procedure is only called if there are spilled nodes. }
  2231. with spillednodes do
  2232. { the node with the highest interferences is the last one }
  2233. for i:=length-1 downto 0 do
  2234. begin
  2235. t:=buf[i];
  2236. {$ifdef DEBUG_SPILLCOALESCE}
  2237. writeln('trgobj.spill_registers: Spilling ',t);
  2238. {$endif DEBUG_SPILLCOALESCE}
  2239. spillinfo[t].interferences:=Tinterferencebitmap.create;
  2240. { copy interferences }
  2241. for j:=0 to maxreg-1 do
  2242. spillinfo[t].interferences[0,j]:=ibitmap[t,j];
  2243. { Alternative representation. }
  2244. supregset_include(regs_to_spill_set,t);
  2245. { Clear all interferences of the spilled register. }
  2246. clear_interferences(t);
  2247. getnewspillloc:=not (ri_has_initial_loc in reginfo[t].flags);
  2248. if not getnewspillloc then
  2249. spill_temps[t]:=spillinfo[t].spilllocation;
  2250. { check if we can "coalesce" spilled nodes. To do so, it is required that they do not
  2251. interfere but are connected by a move instruction
  2252. doing so might save some mem->mem moves }
  2253. if (cs_opt_level3 in current_settings.optimizerswitches) and
  2254. getnewspillloc and
  2255. assigned(reginfo[t].movelist) then
  2256. for j:=0 to reginfo[t].movelist^.header.count-1 do
  2257. begin
  2258. x:=Tmoveins(reginfo[t].movelist^.data[j]).x;
  2259. y:=Tmoveins(reginfo[t].movelist^.data[j]).y;
  2260. if (x=t) and
  2261. (spillinfo[get_alias(y)].spilled) and
  2262. not(spillinfo[get_alias(y)].interferences[0,t]) then
  2263. begin
  2264. spill_temps[t]:=spillinfo[get_alias(y)].spilllocation;
  2265. {$ifdef DEBUG_SPILLCOALESCE}
  2266. writeln('trgobj.spill_registers: Spill coalesce ',t,' to ',y);
  2267. {$endif DEBUG_SPILLCOALESCE}
  2268. getnewspillloc:=false;
  2269. break;
  2270. end
  2271. else if (y=t) and
  2272. (spillinfo[get_alias(x)].spilled) and
  2273. not(spillinfo[get_alias(x)].interferences[0,t]) then
  2274. begin
  2275. {$ifdef DEBUG_SPILLCOALESCE}
  2276. writeln('trgobj.spill_registers: Spill coalesce ',t,' to ',x);
  2277. {$endif DEBUG_SPILLCOALESCE}
  2278. spill_temps[t]:=spillinfo[get_alias(x)].spilllocation;
  2279. getnewspillloc:=false;
  2280. break;
  2281. end;
  2282. end;
  2283. if getnewspillloc then
  2284. get_spill_temp(templist,spill_temps,t);
  2285. {$ifdef DEBUG_SPILLCOALESCE}
  2286. writeln('trgobj.spill_registers: Spill temp: ',getsupreg(spill_temps[t].base),'+',spill_temps[t].offset);
  2287. {$endif DEBUG_SPILLCOALESCE}
  2288. { set spilled only as soon as a temp is assigned, else a mov iregX,iregX results in a spill coalesce with itself }
  2289. spillinfo[t].spilled:=true;
  2290. spillinfo[t].spilllocation:=spill_temps[t];
  2291. end;
  2292. list.insertlistafter(headertai,templist);
  2293. templist.free;
  2294. { Walk through all instructions, we can start with the headertai,
  2295. because before the header tai is only symbols }
  2296. p:=headertai;
  2297. while assigned(p) do
  2298. begin
  2299. case p.typ of
  2300. ait_regalloc:
  2301. with Tai_regalloc(p) do
  2302. begin
  2303. if (getregtype(reg)=regtype) then
  2304. begin
  2305. {A register allocation of the spilled register (and all coalesced registers)
  2306. must be removed.}
  2307. supreg:=get_alias(getsupreg(reg));
  2308. if supregset_in(regs_to_spill_set,supreg) then
  2309. begin
  2310. { Remove loading of the register from its initial memory location
  2311. (e.g. load of a stack parameter to the register). }
  2312. if (ratype=ra_alloc) and
  2313. (ri_has_initial_loc in reginfo[supreg].flags) and
  2314. (instr<>nil) then
  2315. begin
  2316. list.remove(instr);
  2317. FreeAndNil(instr);
  2318. dec(reginfo[supreg].weight,100);
  2319. end;
  2320. { Remove the regalloc }
  2321. remove_ai(list,p);
  2322. continue;
  2323. end
  2324. else
  2325. begin
  2326. case ratype of
  2327. ra_alloc :
  2328. live_registers.add(supreg);
  2329. ra_dealloc :
  2330. live_registers.delete(supreg);
  2331. else
  2332. ;
  2333. end;
  2334. end;
  2335. end;
  2336. end;
  2337. {$ifdef llvm}
  2338. ait_llvmins,
  2339. {$endif llvm}
  2340. ait_instruction:
  2341. with tai_cpu_abstract_sym(p) do
  2342. begin
  2343. // writeln(gas_op2str[tai_cpu_abstract_sym(p).opcode]);
  2344. current_filepos:=fileinfo;
  2345. if instr_spill_register(list,tai_cpu_abstract_sym(p),regs_to_spill_set,spill_temps) then
  2346. spill_registers:=true;
  2347. end;
  2348. else
  2349. ;
  2350. end;
  2351. p:=Tai(p.next);
  2352. end;
  2353. current_filepos:=current_procinfo.exitpos;
  2354. {Safe: this procedure is only called if there are spilled nodes.}
  2355. with spillednodes do
  2356. for i:=0 to length-1 do
  2357. begin
  2358. j:=buf[i];
  2359. if tg.istemp(spill_temps[j]) then
  2360. tg.ungettemp(list,spill_temps[j]);
  2361. end;
  2362. spill_temps:=nil;
  2363. end;
  2364. function trgobj.do_spill_replace(list:TAsmList;instr:tai_cpu_abstract_sym;orgreg:tsuperregister;const spilltemp:treference):boolean;
  2365. begin
  2366. result:=false;
  2367. end;
  2368. procedure trgobj.do_spill_read(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);
  2369. var
  2370. ins:tai_cpu_abstract_sym;
  2371. begin
  2372. ins:=spilling_create_load(spilltemp,tempreg);
  2373. add_cpu_interferences(ins);
  2374. list.insertafter(ins,pos);
  2375. {$ifdef DEBUG_SPILLING}
  2376. list.Insertbefore(tai_comment.Create(strpnew('Spilling: Spill Read')),ins);
  2377. {$endif}
  2378. end;
  2379. procedure Trgobj.do_spill_written(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);
  2380. var
  2381. ins:tai_cpu_abstract_sym;
  2382. begin
  2383. ins:=spilling_create_store(tempreg,spilltemp);
  2384. add_cpu_interferences(ins);
  2385. list.insertafter(ins,pos);
  2386. {$ifdef DEBUG_SPILLING}
  2387. list.Insertbefore(tai_comment.Create(strpnew('Spilling: Spill Write')),ins);
  2388. {$endif}
  2389. end;
  2390. function trgobj.get_spill_subreg(r : tregister) : tsubregister;
  2391. begin
  2392. result:=defaultsub;
  2393. end;
  2394. function trgobj.addreginfo(var spregs: tspillregsinfo; const r: tsuperregisterset; reg: tregister; operation: topertype): boolean;
  2395. var
  2396. i, tmpindex: longint;
  2397. supreg: tsuperregister;
  2398. begin
  2399. result:=false;
  2400. tmpindex := spregs.spillreginfocount;
  2401. supreg := get_alias(getsupreg(reg));
  2402. { did we already encounter this register? }
  2403. for i := 0 to pred(spregs.spillreginfocount) do
  2404. if (spregs.spillreginfo[i].orgreg = supreg) then
  2405. begin
  2406. tmpindex := i;
  2407. break;
  2408. end;
  2409. if tmpindex > high(spregs.spillreginfo) then
  2410. internalerror(2003120301);
  2411. spregs.spillreginfo[tmpindex].orgreg := supreg;
  2412. include(spregs.spillreginfo[tmpindex].spillregconstraints,get_spill_subreg(reg));
  2413. if supregset_in(r,supreg) then
  2414. begin
  2415. { add/update info on this register }
  2416. spregs.spillreginfo[tmpindex].mustbespilled := true;
  2417. case operation of
  2418. operand_read:
  2419. spregs.spillreginfo[tmpindex].regread := true;
  2420. operand_write:
  2421. spregs.spillreginfo[tmpindex].regwritten := true;
  2422. operand_readwrite:
  2423. begin
  2424. spregs.spillreginfo[tmpindex].regread := true;
  2425. spregs.spillreginfo[tmpindex].regwritten := true;
  2426. end;
  2427. end;
  2428. result:=true;
  2429. end;
  2430. inc(spregs.spillreginfocount,ord(spregs.spillreginfocount=tmpindex));
  2431. end;
  2432. function trgobj.instr_get_oper_spilling_info(var spregs: tspillregsinfo; const r: tsuperregisterset; instr: tai_cpu_abstract_sym; opidx: longint): boolean;
  2433. begin
  2434. result:=false;
  2435. with instr.oper[opidx]^ do
  2436. begin
  2437. case typ of
  2438. top_reg:
  2439. begin
  2440. if (getregtype(reg) = regtype) then
  2441. result:=addreginfo(spregs,r,reg,instr.spilling_get_operation_type(opidx));
  2442. end;
  2443. top_ref:
  2444. begin
  2445. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2446. with ref^ do
  2447. begin
  2448. if (base <> NR_NO) and
  2449. (getregtype(base)=regtype) then
  2450. result:=addreginfo(spregs,r,base,instr.spilling_get_operation_type_ref(opidx,base));
  2451. if (index <> NR_NO) and
  2452. (getregtype(index)=regtype) then
  2453. result:=addreginfo(spregs,r,index,instr.spilling_get_operation_type_ref(opidx,index)) or result;
  2454. {$if defined(x86)}
  2455. if (segment <> NR_NO) and
  2456. (getregtype(segment)=regtype) then
  2457. result:=addreginfo(spregs,r,segment,instr.spilling_get_operation_type_ref(opidx,segment)) or result;
  2458. {$endif defined(x86)}
  2459. end;
  2460. end;
  2461. {$ifdef ARM}
  2462. top_shifterop:
  2463. begin
  2464. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2465. if shifterop^.rs<>NR_NO then
  2466. result:=addreginfo(spregs,r,shifterop^.rs,operand_read);
  2467. end;
  2468. {$endif ARM}
  2469. else
  2470. ;
  2471. end;
  2472. end;
  2473. end;
  2474. procedure trgobj.try_replace_reg(const spregs: tspillregsinfo; var reg: tregister; useloadreg: boolean);
  2475. var
  2476. i: longint;
  2477. supreg: tsuperregister;
  2478. begin
  2479. supreg:=get_alias(getsupreg(reg));
  2480. for i:=0 to pred(spregs.spillreginfocount) do
  2481. if (spregs.spillreginfo[i].mustbespilled) and
  2482. (spregs.spillreginfo[i].orgreg=supreg) then
  2483. begin
  2484. { Only replace supreg }
  2485. if useloadreg then
  2486. setsupreg(reg, getsupreg(spregs.spillreginfo[i].loadreg))
  2487. else
  2488. setsupreg(reg, getsupreg(spregs.spillreginfo[i].storereg));
  2489. break;
  2490. end;
  2491. end;
  2492. procedure trgobj.substitute_spilled_registers(const spregs: tspillregsinfo; instr: tai_cpu_abstract_sym; opidx: longint);
  2493. begin
  2494. with instr.oper[opidx]^ do
  2495. case typ of
  2496. top_reg:
  2497. begin
  2498. if (getregtype(reg) = regtype) then
  2499. try_replace_reg(spregs, reg, not ssa_safe or
  2500. (instr.spilling_get_operation_type(opidx)=operand_read));
  2501. end;
  2502. top_ref:
  2503. begin
  2504. if regtype in [R_INTREGISTER, R_ADDRESSREGISTER] then
  2505. begin
  2506. if (ref^.base <> NR_NO) and
  2507. (getregtype(ref^.base)=regtype) then
  2508. try_replace_reg(spregs, ref^.base,
  2509. not ssa_safe or (instr.spilling_get_operation_type_ref(opidx, ref^.base)=operand_read));
  2510. if (ref^.index <> NR_NO) and
  2511. (getregtype(ref^.index)=regtype) then
  2512. try_replace_reg(spregs, ref^.index,
  2513. not ssa_safe or (instr.spilling_get_operation_type_ref(opidx, ref^.index)=operand_read));
  2514. {$if defined(x86)}
  2515. if (ref^.segment <> NR_NO) and
  2516. (getregtype(ref^.segment)=regtype) then
  2517. try_replace_reg(spregs, ref^.segment, true { always read-only });
  2518. {$endif defined(x86)}
  2519. end;
  2520. end;
  2521. {$ifdef ARM}
  2522. top_shifterop:
  2523. begin
  2524. if regtype in [R_INTREGISTER, R_ADDRESSREGISTER] then
  2525. try_replace_reg(spregs, shifterop^.rs, true { always read-only });
  2526. end;
  2527. {$endif ARM}
  2528. else
  2529. ;
  2530. end;
  2531. end;
  2532. function trgobj.instr_spill_register(list:TAsmList;
  2533. instr:tai_cpu_abstract_sym;
  2534. const r:Tsuperregisterset;
  2535. const spilltemplist:Tspill_temp_list): boolean;
  2536. var
  2537. counter: longint;
  2538. spregs: tspillregsinfo;
  2539. spilled: boolean;
  2540. var
  2541. loadpos,
  2542. storepos : tai;
  2543. oldlive_registers : tsuperregisterworklist;
  2544. begin
  2545. result := false;
  2546. fillchar(spregs,sizeof(spregs),0);
  2547. for counter := low(spregs.spillreginfo) to high(spregs.spillreginfo) do
  2548. begin
  2549. spregs.spillreginfo[counter].orgreg := RS_INVALID;
  2550. spregs.spillreginfo[counter].loadreg := NR_INVALID;
  2551. spregs.spillreginfo[counter].storereg := NR_INVALID;
  2552. end;
  2553. spilled := false;
  2554. { check whether and if so which and how (read/written) this instructions contains
  2555. registers that must be spilled }
  2556. for counter := 0 to instr.ops-1 do
  2557. spilled:=instr_get_oper_spilling_info(spregs,r,instr,counter) or spilled;
  2558. { if no spilling for this instruction we can leave }
  2559. if not spilled then
  2560. exit;
  2561. {$if max_operands>1}
  2562. { Check if the instruction is "OP reg1,reg2" and reg1 is coalesced with reg2 }
  2563. if (spregs.spillreginfocount=1) and (instr.ops=2) and
  2564. (instr.oper[0]^.typ=top_reg) and (instr.oper[1]^.typ=top_reg) and
  2565. (getregtype(instr.oper[0]^.reg)=getregtype(instr.oper[1]^.reg)) then
  2566. begin
  2567. { Set both registers in the instruction to the same register }
  2568. setsupreg(instr.oper[0]^.reg, spregs.spillreginfo[0].orgreg);
  2569. setsupreg(instr.oper[1]^.reg, spregs.spillreginfo[0].orgreg);
  2570. { In case of MOV reg,reg no spilling is needed.
  2571. This MOV will be removed later in translate_registers() }
  2572. if instr.is_same_reg_move(regtype) then
  2573. exit;
  2574. end;
  2575. {$endif max_operands>1}
  2576. {$if defined(x86) or defined(mips) or defined(sparcgen) or defined(arm) or defined(m68k)}
  2577. { Try replacing the register with the spilltemp. This is useful only
  2578. for the i386,x86_64 that support memory locations for several instructions
  2579. For non-x86 it is nevertheless possible to replace moves to/from the register
  2580. with loads/stores to spilltemp (Sergei) }
  2581. for counter := 0 to pred(spregs.spillreginfocount) do
  2582. with spregs.spillreginfo[counter] do
  2583. begin
  2584. if mustbespilled then
  2585. begin
  2586. if do_spill_replace(list,instr,orgreg,spilltemplist[orgreg]) then
  2587. mustbespilled:=false;
  2588. end;
  2589. end;
  2590. {$endif defined(x86) or defined(mips) or defined(sparcgen) or defined(arm) or defined(m68k)}
  2591. {
  2592. There are registers that need are spilled. We generate the
  2593. following code for it. The used positions where code need
  2594. to be inserted are marked using #. Note that code is always inserted
  2595. before the positions using pos.previous. This way the position is always
  2596. the same since pos doesn't change, but pos.previous is modified everytime
  2597. new code is inserted.
  2598. [
  2599. - reg_allocs load spills
  2600. - load spills
  2601. ]
  2602. [#loadpos
  2603. - reg_deallocs
  2604. - reg_allocs
  2605. ]
  2606. [
  2607. - reg_deallocs for load-only spills
  2608. - reg_allocs for store-only spills
  2609. ]
  2610. [#instr
  2611. - original instruction
  2612. ]
  2613. [
  2614. - store spills
  2615. - reg_deallocs store spills
  2616. ]
  2617. [#storepos
  2618. ]
  2619. }
  2620. result := true;
  2621. oldlive_registers.copyfrom(live_registers);
  2622. { Process all tai_regallocs belonging to this instruction, ignore explicit
  2623. inserted regallocs. These can happend for example in i386:
  2624. mov ref,ireg26
  2625. <regdealloc ireg26, instr=taicpu of lea>
  2626. <regalloc edi, insrt=nil>
  2627. lea [ireg26+ireg17],edi
  2628. All released registers are also added to the live_registers because
  2629. they can't be used during the spilling }
  2630. loadpos:=tai(instr.previous);
  2631. while assigned(loadpos) and
  2632. (
  2633. (loadpos.typ in [ait_comment,ait_tempalloc,ait_varloc]) or
  2634. (
  2635. (loadpos.typ=ait_regalloc) and
  2636. (
  2637. (tai_regalloc(loadpos).instr=nil) or
  2638. (tai_regalloc(loadpos).instr=instr)
  2639. )
  2640. )
  2641. ) do
  2642. begin
  2643. { Only add deallocs belonging to the instruction. Explicit inserted deallocs
  2644. belong to the previous instruction and not the current instruction }
  2645. if (loadpos.typ=ait_regalloc) and
  2646. (tai_regalloc(loadpos).instr=instr) and
  2647. (tai_regalloc(loadpos).ratype=ra_dealloc) then
  2648. live_registers.add(get_alias(getsupreg(tai_regalloc(loadpos).reg)));
  2649. loadpos:=tai(loadpos.previous);
  2650. end;
  2651. loadpos:=tai(loadpos.next);
  2652. { Load the spilled registers }
  2653. for counter := 0 to pred(spregs.spillreginfocount) do
  2654. with spregs.spillreginfo[counter] do
  2655. begin
  2656. if mustbespilled and regread then
  2657. begin
  2658. loadreg:=getregisterinline(list,spregs.spillreginfo[counter].spillregconstraints);
  2659. do_spill_read(list,tai(loadpos.previous),spilltemplist[orgreg],loadreg,orgreg);
  2660. include(reginfo[getsupreg(loadreg)].flags,ri_spill_helper);
  2661. end;
  2662. end;
  2663. { Release temp registers of read-only registers, and add reference of the instruction
  2664. to the reginfo }
  2665. for counter := 0 to pred(spregs.spillreginfocount) do
  2666. with spregs.spillreginfo[counter] do
  2667. begin
  2668. if mustbespilled and regread and
  2669. (ssa_safe or
  2670. not regwritten) then
  2671. begin
  2672. { The original instruction will be the next that uses this register
  2673. set weigth of the newly allocated register higher than the old one,
  2674. so it will selected for spilling with a lower priority than
  2675. the original one, this prevents an endless spilling loop if orgreg
  2676. is short living, see e.g. tw25164.pp
  2677. the min trick is needed to avoid an overflow in case weight=high(weight which might happen }
  2678. add_reg_instruction(instr,loadreg,min(high(reginfo[orgreg].weight)-1,reginfo[orgreg].weight)+1);
  2679. ungetregisterinline(list,loadreg);
  2680. end;
  2681. end;
  2682. { Allocate temp registers of write-only registers, and add reference of the instruction
  2683. to the reginfo }
  2684. for counter := 0 to pred(spregs.spillreginfocount) do
  2685. with spregs.spillreginfo[counter] do
  2686. begin
  2687. if mustbespilled and regwritten then
  2688. begin
  2689. { When the register is also loaded there is already a register assigned }
  2690. if (not regread) or
  2691. ssa_safe then
  2692. begin
  2693. storereg:=getregisterinline(list,spregs.spillreginfo[counter].spillregconstraints);
  2694. include(reginfo[getsupreg(storereg)].flags,ri_spill_helper);
  2695. { we also use loadreg for store replacements in case we
  2696. don't have ensure ssa -> initialise loadreg even if
  2697. there are no reads }
  2698. if not regread then
  2699. loadreg:=storereg;
  2700. end
  2701. else
  2702. storereg:=loadreg;
  2703. { The original instruction will be the next that uses this register, this
  2704. also needs to be done for read-write registers,
  2705. set weigth of the newly allocated register higher than the old one,
  2706. so it will selected for spilling with a lower priority than
  2707. the original one, this prevents an endless spilling loop if orgreg
  2708. is short living, see e.g. tw25164.pp
  2709. the min trick is needed to avoid an overflow in case weight=high(weight which might happen }
  2710. add_reg_instruction(instr,storereg,min(high(reginfo[orgreg].weight)-1,reginfo[orgreg].weight)+1);
  2711. end;
  2712. end;
  2713. { store the spilled registers }
  2714. if not assigned(instr.next) then
  2715. list.concat(tai_marker.Create(mark_Position));
  2716. storepos:=tai(instr.next);
  2717. for counter := 0 to pred(spregs.spillreginfocount) do
  2718. with spregs.spillreginfo[counter] do
  2719. begin
  2720. if mustbespilled and regwritten then
  2721. begin
  2722. do_spill_written(list,tai(storepos.previous),spilltemplist[orgreg],storereg,orgreg);
  2723. ungetregisterinline(list,storereg);
  2724. end;
  2725. end;
  2726. { now all spilling code is generated we can restore the live registers. This
  2727. must be done after the store because the store can need an extra register
  2728. that also needs to conflict with the registers of the instruction }
  2729. live_registers.done;
  2730. live_registers:=oldlive_registers;
  2731. { substitute registers }
  2732. for counter:=0 to instr.ops-1 do
  2733. substitute_spilled_registers(spregs,instr,counter);
  2734. { We have modified the instruction; perhaps the new instruction has
  2735. certain constraints regarding which imaginary registers interfere
  2736. with certain physical registers. }
  2737. add_cpu_interferences(instr);
  2738. end;
  2739. procedure trgobj.remove_ai(list:TAsmList; var p:Tai);
  2740. var
  2741. q:Tai;
  2742. begin
  2743. q:=tai(p.next);
  2744. list.remove(p);
  2745. p.free;
  2746. p:=q;
  2747. end;
  2748. {$ifdef DEBUG_SPILLCOALESCE}
  2749. procedure trgobj.write_spill_stats;
  2750. { This procedure outputs spilling statistincs.
  2751. If no spilling has occurred, no output is provided.
  2752. NUM is the number of spilled registers.
  2753. EFF is efficiency of the spilling which is based on
  2754. weight and usage count of registers. Range 0-100%.
  2755. 0% means all imaginary registers have been spilled.
  2756. 100% means no imaginary registers have been spilled
  2757. (no output in this case).
  2758. Higher value is better.
  2759. }
  2760. var
  2761. i,j,spillingcounter,max_weight:longint;
  2762. all_weight,spill_weight,d: double;
  2763. begin
  2764. max_weight:=1;
  2765. for i:=first_imaginary to maxreg-1 do
  2766. with reginfo[i] do
  2767. if weight>max_weight then
  2768. max_weight:=weight;
  2769. spillingcounter:=0;
  2770. spill_weight:=0;
  2771. all_weight:=0;
  2772. for i:=first_imaginary to maxreg-1 do
  2773. with reginfo[i] do
  2774. if not (ri_spill_helper in flags) then
  2775. begin
  2776. d:=weight/max_weight;
  2777. all_weight:=all_weight+d;
  2778. if (ri_coalesced in flags) and (alias>=first_imaginary) then
  2779. j:=alias
  2780. else
  2781. j:=i;
  2782. if (reginfo[j].weight>100) and
  2783. (j<=high(spillinfo)) and
  2784. spillinfo[j].spilled then
  2785. begin
  2786. inc(spillingcounter);
  2787. spill_weight:=spill_weight+d;
  2788. end;
  2789. end;
  2790. if spillingcounter>0 then
  2791. begin
  2792. d:=(1.0-spill_weight/all_weight)*100.0;
  2793. writeln(current_procinfo.procdef.mangledname,' [',regtype,']: spill stats: NUM: ',spillingcounter, ', EFF: ',d:4:1,'%');
  2794. end;
  2795. end;
  2796. {$endif DEBUG_SPILLCOALESCE}
  2797. end.