rgobj.pas 111 KB

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