rgobj.pas 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055
  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. while assigned(p) and
  1734. assigned(p.previous) and
  1735. (tai(p.previous).typ=ait_regalloc) and
  1736. (tai_regalloc(p.previous).ratype=ra_alloc) and
  1737. (tai_regalloc(p.previous).reg<>r) do
  1738. p:=tai(p.previous);
  1739. { , but add release after a reg_a_sync }
  1740. if assigned(p) and
  1741. (p.typ=ait_regalloc) and
  1742. (tai_regalloc(p).ratype=ra_sync) then
  1743. p:=tai(p.next);
  1744. if assigned(p) then
  1745. list.insertbefore(pdealloc,p)
  1746. else
  1747. list.concat(pdealloc);
  1748. end;
  1749. end;
  1750. end;
  1751. procedure trgobj.insert_regalloc_info_all(list:TAsmList);
  1752. var
  1753. supreg : tsuperregister;
  1754. begin
  1755. { Insert regallocs for all imaginary registers }
  1756. for supreg:=first_imaginary to maxreg-1 do
  1757. insert_regalloc_info(list,supreg);
  1758. end;
  1759. procedure trgobj.determine_spill_registers(list: TAsmList; headertail: tai);
  1760. begin
  1761. prepare_colouring;
  1762. colour_registers;
  1763. epilogue_colouring;
  1764. end;
  1765. procedure trgobj.get_spill_temp(list: TAsmlist; spill_temps: Tspill_temp_list; supreg: tsuperregister);
  1766. var
  1767. size: ptrint;
  1768. begin
  1769. {Get a temp for the spilled register, the size must at least equal a complete register,
  1770. take also care of the fact that subreg can be larger than a single register like doubles
  1771. that occupy 2 registers }
  1772. { only force the whole register in case of integers. Storing a register that contains
  1773. a single precision value as a double can cause conversion errors on e.g. ARM VFP }
  1774. if (regtype=R_INTREGISTER) then
  1775. size:=max(tcgsize2size[reg_cgsize(newreg(regtype,supreg,R_SUBWHOLE))],
  1776. tcgsize2size[reg_cgsize(newreg(regtype,supreg,reginfo[supreg].subreg))])
  1777. else
  1778. size:=tcgsize2size[reg_cgsize(newreg(regtype,supreg,reginfo[supreg].subreg))];
  1779. tg.gettemp(list,
  1780. size,size,
  1781. tt_noreuse,spill_temps[supreg]);
  1782. end;
  1783. procedure trgobj.add_cpu_interferences(p : tai);
  1784. begin
  1785. end;
  1786. procedure trgobj.generate_interference_graph(list:TAsmList;headertai:tai);
  1787. procedure RecordUse(var r : Treginfo);
  1788. begin
  1789. inc(r.total_interferences,live_registers.length);
  1790. inc(r.count_uses);
  1791. end;
  1792. var
  1793. p : tai;
  1794. i : integer;
  1795. supreg, u: tsuperregister;
  1796. {$ifdef arm}
  1797. so: pshifterop;
  1798. {$endif arm}
  1799. begin
  1800. { All allocations are available. Now we can generate the
  1801. interference graph. Walk through all instructions, we can
  1802. start with the headertai, because before the header tai is
  1803. only symbols. }
  1804. live_registers.clear;
  1805. p:=headertai;
  1806. while assigned(p) do
  1807. begin
  1808. prefetch(pointer(p.next)^);
  1809. case p.typ of
  1810. ait_instruction:
  1811. with Taicpu(p) do
  1812. begin
  1813. current_filepos:=fileinfo;
  1814. {For speed reasons, get_alias isn't used here, instead,
  1815. assign_colours will also set the colour of coalesced nodes.
  1816. If there are registers with colour=0, then the coalescednodes
  1817. list probably doesn't contain these registers, causing
  1818. assign_colours not to do this properly.}
  1819. for i:=0 to ops-1 do
  1820. with oper[i]^ do
  1821. case typ of
  1822. top_reg:
  1823. if (getregtype(reg)=regtype) then
  1824. begin
  1825. u:=getsupreg(reg);
  1826. {$ifdef EXTDEBUG}
  1827. if (u>=maxreginfo) then
  1828. internalerror(2018111701);
  1829. {$endif}
  1830. RecordUse(reginfo[u]);
  1831. end;
  1832. top_ref:
  1833. begin
  1834. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  1835. with ref^ do
  1836. begin
  1837. if (base<>NR_NO) and
  1838. (getregtype(base)=regtype) then
  1839. begin
  1840. u:=getsupreg(base);
  1841. {$ifdef EXTDEBUG}
  1842. if (u>=maxreginfo) then
  1843. internalerror(2018111702);
  1844. {$endif}
  1845. RecordUse(reginfo[u]);
  1846. end;
  1847. if (index<>NR_NO) and
  1848. (getregtype(index)=regtype) then
  1849. begin
  1850. u:=getsupreg(index);
  1851. {$ifdef EXTDEBUG}
  1852. if (u>=maxreginfo) then
  1853. internalerror(2018111703);
  1854. {$endif}
  1855. RecordUse(reginfo[u]);
  1856. end;
  1857. {$if defined(x86)}
  1858. if (segment<>NR_NO) and
  1859. (getregtype(segment)=regtype) then
  1860. begin
  1861. u:=getsupreg(segment);
  1862. {$ifdef EXTDEBUG}
  1863. if (u>=maxreginfo) then
  1864. internalerror(2018111704);
  1865. {$endif}
  1866. RecordUse(reginfo[u]);
  1867. end;
  1868. {$endif defined(x86)}
  1869. end;
  1870. end;
  1871. {$ifdef arm}
  1872. Top_shifterop:
  1873. begin
  1874. if regtype=R_INTREGISTER then
  1875. begin
  1876. so:=shifterop;
  1877. if (so^.rs<>NR_NO) and
  1878. (getregtype(so^.rs)=regtype) then
  1879. RecordUse(reginfo[getsupreg(so^.rs)]);
  1880. end;
  1881. end;
  1882. {$endif arm}
  1883. else
  1884. ;
  1885. end;
  1886. end;
  1887. ait_regalloc:
  1888. with Tai_regalloc(p) do
  1889. begin
  1890. if (getregtype(reg)=regtype) then
  1891. begin
  1892. supreg:=getsupreg(reg);
  1893. case ratype of
  1894. ra_alloc :
  1895. begin
  1896. live_registers.add(supreg);
  1897. {$ifdef DEBUG_REGISTERLIFE}
  1898. write(live_registers.length,' ');
  1899. for i:=0 to live_registers.length-1 do
  1900. write(std_regname(newreg(regtype,live_registers.buf^[i],defaultsub)),' ');
  1901. writeln;
  1902. {$endif DEBUG_REGISTERLIFE}
  1903. add_edges_used(supreg);
  1904. end;
  1905. ra_dealloc :
  1906. begin
  1907. live_registers.delete(supreg);
  1908. {$ifdef DEBUG_REGISTERLIFE}
  1909. write(live_registers.length,' ');
  1910. for i:=0 to live_registers.length-1 do
  1911. write(std_regname(newreg(regtype,live_registers.buf^[i],defaultsub)),' ');
  1912. writeln;
  1913. {$endif DEBUG_REGISTERLIFE}
  1914. add_edges_used(supreg);
  1915. end;
  1916. ra_markused :
  1917. if (supreg<first_imaginary) then
  1918. begin
  1919. include(used_in_proc,supreg);
  1920. has_usedmarks:=true;
  1921. end;
  1922. else
  1923. ;
  1924. end;
  1925. { constraints needs always to be updated }
  1926. add_constraints(reg);
  1927. end;
  1928. end;
  1929. else
  1930. ;
  1931. end;
  1932. add_cpu_interferences(p);
  1933. p:=Tai(p.next);
  1934. end;
  1935. {$ifdef EXTDEBUG}
  1936. if live_registers.length>0 then
  1937. begin
  1938. for i:=0 to live_registers.length-1 do
  1939. begin
  1940. { Only report for imaginary registers }
  1941. if live_registers.buf[i]>=first_imaginary then
  1942. Comment(V_Warning,'Register '+std_regname(newreg(regtype,live_registers.buf[i],defaultsub))+' not released');
  1943. end;
  1944. end;
  1945. {$endif}
  1946. end;
  1947. procedure trgobj.translate_register(var reg : tregister);
  1948. begin
  1949. if (getregtype(reg)=regtype) then
  1950. setsupreg(reg,reginfo[getsupreg(reg)].colour)
  1951. else
  1952. internalerror(200602021);
  1953. end;
  1954. procedure trgobj.set_reg_initial_location(reg: tregister; const ref: treference);
  1955. var
  1956. supreg: TSuperRegister;
  1957. begin
  1958. supreg:=getsupreg(reg);
  1959. if (supreg<first_imaginary) or (supreg>=maxreg) then
  1960. internalerror(2020090501);
  1961. alloc_spillinfo(supreg+1);
  1962. spillinfo[supreg].spilllocation:=ref;
  1963. include(reginfo[supreg].flags,ri_has_initial_loc);
  1964. end;
  1965. procedure trgobj.translate_registers(list: TAsmList);
  1966. function get_reg_name_full(r: tregister; include_prefix: boolean): string;
  1967. var
  1968. rr:tregister;
  1969. sr:TSuperRegister;
  1970. begin
  1971. sr:=getsupreg(r);
  1972. if reginfo[sr].live_start=nil then
  1973. begin
  1974. result:='';
  1975. exit;
  1976. end;
  1977. if (sr<length(spillinfo)) and spillinfo[sr].spilled then
  1978. with spillinfo[sr].spilllocation do
  1979. begin
  1980. result:='['+std_regname(base);
  1981. if offset>=0 then
  1982. result:=result+'+';
  1983. result:=result+IntToStr(offset)+']';
  1984. if include_prefix then
  1985. result:='stack '+result;
  1986. end
  1987. else
  1988. begin
  1989. rr:=r;
  1990. setsupreg(rr,reginfo[sr].colour);
  1991. result:=std_regname(rr);
  1992. if include_prefix then
  1993. result:='register '+result;
  1994. end;
  1995. {$if defined(cpu8bitalu) or defined(cpu16bitalu)}
  1996. if (sr>=first_int_imreg) and cg.has_next_reg[sr] then
  1997. result:=result+':'+get_reg_name_full(cg.GetNextReg(r),false);
  1998. {$endif defined(cpu8bitalu) or defined(cpu16bitalu)}
  1999. end;
  2000. var
  2001. hp,p:Tai;
  2002. i:shortint;
  2003. u:longint;
  2004. s:string;
  2005. {$ifdef arm}
  2006. so:pshifterop;
  2007. {$endif arm}
  2008. begin
  2009. { Leave when no imaginary registers are used }
  2010. if maxreg<=first_imaginary then
  2011. exit;
  2012. p:=Tai(list.first);
  2013. while assigned(p) do
  2014. begin
  2015. prefetch(pointer(p.next)^);
  2016. case p.typ of
  2017. ait_regalloc:
  2018. with Tai_regalloc(p) do
  2019. begin
  2020. if (getregtype(reg)=regtype) then
  2021. begin
  2022. { Only alloc/dealloc is needed for the optimizer, remove
  2023. other regalloc }
  2024. if not(ratype in [ra_alloc,ra_dealloc]) then
  2025. begin
  2026. remove_ai(list,p);
  2027. continue;
  2028. end
  2029. else
  2030. begin
  2031. u:=reginfo[getsupreg(reg)].colour;
  2032. include(used_in_proc,u);
  2033. {$ifdef DEBUG_SPILLCOALESCE}
  2034. if (ratype=ra_alloc) and (ri_coalesced in reginfo[getsupreg(reg)].flags) then
  2035. begin
  2036. hp:=Tai_comment.Create(strpnew('Coalesced '+std_regname(reg)+'->'+
  2037. std_regname(newreg(regtype,reginfo[getsupreg(reg)].alias,reginfo[getsupreg(reg)].subreg))+
  2038. ' ('+std_regname(newreg(regtype,u,reginfo[getsupreg(reg)].subreg))+')'));
  2039. list.insertafter(hp,p);
  2040. end;
  2041. {$endif DEBUG_SPILLCOALESCE}
  2042. {$ifdef EXTDEBUG}
  2043. if u>=maxreginfo then
  2044. internalerror(2015040501);
  2045. {$endif}
  2046. setsupreg(reg,u);
  2047. end;
  2048. end;
  2049. end;
  2050. ait_varloc:
  2051. begin
  2052. if (getregtype(tai_varloc(p).newlocation)=regtype) then
  2053. begin
  2054. if (cs_asm_source in current_settings.globalswitches) then
  2055. begin
  2056. s:=get_reg_name_full(tai_varloc(p).newlocation,tai_varloc(p).newlocationhi=NR_NO);
  2057. if s<>'' then
  2058. begin
  2059. if tai_varloc(p).newlocationhi<>NR_NO then
  2060. s:=get_reg_name_full(tai_varloc(p).newlocationhi,true)+':'+s;
  2061. hp:=Tai_comment.Create(strpnew('Var '+tai_varloc(p).varsym.realname+' located in '+s));
  2062. list.insertafter(hp,p);
  2063. end;
  2064. setsupreg(tai_varloc(p).newlocation,reginfo[getsupreg(tai_varloc(p).newlocation)].colour);
  2065. if tai_varloc(p).newlocationhi<>NR_NO then
  2066. setsupreg(tai_varloc(p).newlocationhi,reginfo[getsupreg(tai_varloc(p).newlocationhi)].colour);
  2067. end;
  2068. remove_ai(list,p);
  2069. continue;
  2070. end;
  2071. end;
  2072. ait_instruction:
  2073. with Taicpu(p) do
  2074. begin
  2075. current_filepos:=fileinfo;
  2076. {For speed reasons, get_alias isn't used here, instead,
  2077. assign_colours will also set the colour of coalesced nodes.
  2078. If there are registers with colour=0, then the coalescednodes
  2079. list probably doesn't contain these registers, causing
  2080. assign_colours not to do this properly.}
  2081. for i:=0 to ops-1 do
  2082. with oper[i]^ do
  2083. case typ of
  2084. Top_reg:
  2085. if (getregtype(reg)=regtype) then
  2086. begin
  2087. u:=getsupreg(reg);
  2088. {$ifdef EXTDEBUG}
  2089. if (u>=maxreginfo) then
  2090. internalerror(2012101903);
  2091. {$endif}
  2092. setsupreg(reg,reginfo[u].colour);
  2093. end;
  2094. Top_ref:
  2095. begin
  2096. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2097. with ref^ do
  2098. begin
  2099. if (base<>NR_NO) and
  2100. (getregtype(base)=regtype) then
  2101. begin
  2102. u:=getsupreg(base);
  2103. {$ifdef EXTDEBUG}
  2104. if (u>=maxreginfo) then
  2105. internalerror(2012101904);
  2106. {$endif}
  2107. setsupreg(base,reginfo[u].colour);
  2108. end;
  2109. if (index<>NR_NO) and
  2110. (getregtype(index)=regtype) then
  2111. begin
  2112. u:=getsupreg(index);
  2113. {$ifdef EXTDEBUG}
  2114. if (u>=maxreginfo) then
  2115. internalerror(2012101905);
  2116. {$endif}
  2117. setsupreg(index,reginfo[u].colour);
  2118. end;
  2119. {$if defined(x86)}
  2120. if (segment<>NR_NO) and
  2121. (getregtype(segment)=regtype) then
  2122. begin
  2123. u:=getsupreg(segment);
  2124. {$ifdef EXTDEBUG}
  2125. if (u>=maxreginfo) then
  2126. internalerror(2013052401);
  2127. {$endif}
  2128. setsupreg(segment,reginfo[u].colour);
  2129. end;
  2130. {$endif defined(x86)}
  2131. end;
  2132. end;
  2133. {$ifdef arm}
  2134. Top_shifterop:
  2135. begin
  2136. if regtype=R_INTREGISTER then
  2137. begin
  2138. so:=shifterop;
  2139. if (so^.rs<>NR_NO) and
  2140. (getregtype(so^.rs)=regtype) then
  2141. setsupreg(so^.rs,reginfo[getsupreg(so^.rs)].colour);
  2142. end;
  2143. end;
  2144. {$endif arm}
  2145. else
  2146. ;
  2147. end;
  2148. { Maybe the operation can be removed when
  2149. it is a move and both arguments are the same }
  2150. if is_same_reg_move(regtype) then
  2151. begin
  2152. remove_ai(list,p);
  2153. continue;
  2154. end;
  2155. end;
  2156. else
  2157. ;
  2158. end;
  2159. p:=Tai(p.next);
  2160. end;
  2161. current_filepos:=current_procinfo.exitpos;
  2162. end;
  2163. function trgobj.spill_registers(list:TAsmList;headertai:tai):boolean;
  2164. { Returns true if any help registers have been used }
  2165. var
  2166. i : cardinal;
  2167. t : tsuperregister;
  2168. p : Tai;
  2169. regs_to_spill_set:Tsuperregisterset;
  2170. spill_temps : Tspill_temp_list;
  2171. supreg,x,y : tsuperregister;
  2172. templist : TAsmList;
  2173. j : Longint;
  2174. getnewspillloc : Boolean;
  2175. begin
  2176. spill_registers:=false;
  2177. live_registers.clear;
  2178. { spilling should start with the node with the highest number of interferences, so we can coalesce as
  2179. much as possible spilled nodes (coalesce in case of spilled node means they share the same memory location) }
  2180. sort_spillednodes;
  2181. for i:=first_imaginary to maxreg-1 do
  2182. exclude(reginfo[i].flags,ri_selected);
  2183. SetLength(spill_temps,maxreg);
  2184. supregset_reset(regs_to_spill_set,false,$ffff);
  2185. {$ifdef DEBUG_SPILLCOALESCE}
  2186. writeln('trgobj.spill_registers: Got maxreg ',maxreg);
  2187. writeln('trgobj.spill_registers: Spilling ',spillednodes.length,' nodes');
  2188. {$endif DEBUG_SPILLCOALESCE}
  2189. { after each round of spilling, more registers could be used due to allocations for spilling }
  2190. alloc_spillinfo(maxreg);
  2191. { Allocate temps and insert in front of the list }
  2192. templist:=TAsmList.create;
  2193. { Safe: this procedure is only called if there are spilled nodes. }
  2194. with spillednodes do
  2195. { the node with the highest interferences is the last one }
  2196. for i:=length-1 downto 0 do
  2197. begin
  2198. t:=buf[i];
  2199. {$ifdef DEBUG_SPILLCOALESCE}
  2200. writeln('trgobj.spill_registers: Spilling ',t);
  2201. {$endif DEBUG_SPILLCOALESCE}
  2202. spillinfo[t].interferences:=Tinterferencebitmap.create;
  2203. { copy interferences }
  2204. for j:=0 to maxreg-1 do
  2205. spillinfo[t].interferences[0,j]:=ibitmap[t,j];
  2206. { Alternative representation. }
  2207. supregset_include(regs_to_spill_set,t);
  2208. { Clear all interferences of the spilled register. }
  2209. clear_interferences(t);
  2210. getnewspillloc:=not (ri_has_initial_loc in reginfo[t].flags);
  2211. if not getnewspillloc then
  2212. spill_temps[t]:=spillinfo[t].spilllocation;
  2213. { check if we can "coalesce" spilled nodes. To do so, it is required that they do not
  2214. interfere but are connected by a move instruction
  2215. doing so might save some mem->mem moves }
  2216. if (cs_opt_level3 in current_settings.optimizerswitches) and
  2217. getnewspillloc and
  2218. assigned(reginfo[t].movelist) then
  2219. for j:=0 to reginfo[t].movelist^.header.count-1 do
  2220. begin
  2221. x:=Tmoveins(reginfo[t].movelist^.data[j]).x;
  2222. y:=Tmoveins(reginfo[t].movelist^.data[j]).y;
  2223. if (x=t) and
  2224. (spillinfo[get_alias(y)].spilled) and
  2225. not(spillinfo[get_alias(y)].interferences[0,t]) then
  2226. begin
  2227. spill_temps[t]:=spillinfo[get_alias(y)].spilllocation;
  2228. {$ifdef DEBUG_SPILLCOALESCE}
  2229. writeln('trgobj.spill_registers: Spill coalesce ',t,' to ',y);
  2230. {$endif DEBUG_SPILLCOALESCE}
  2231. getnewspillloc:=false;
  2232. break;
  2233. end
  2234. else if (y=t) and
  2235. (spillinfo[get_alias(x)].spilled) and
  2236. not(spillinfo[get_alias(x)].interferences[0,t]) then
  2237. begin
  2238. {$ifdef DEBUG_SPILLCOALESCE}
  2239. writeln('trgobj.spill_registers: Spill coalesce ',t,' to ',x);
  2240. {$endif DEBUG_SPILLCOALESCE}
  2241. spill_temps[t]:=spillinfo[get_alias(x)].spilllocation;
  2242. getnewspillloc:=false;
  2243. break;
  2244. end;
  2245. end;
  2246. if getnewspillloc then
  2247. get_spill_temp(templist,spill_temps,t);
  2248. {$ifdef DEBUG_SPILLCOALESCE}
  2249. writeln('trgobj.spill_registers: Spill temp: ',getsupreg(spill_temps[t].base),'+',spill_temps[t].offset);
  2250. {$endif DEBUG_SPILLCOALESCE}
  2251. { set spilled only as soon as a temp is assigned, else a mov iregX,iregX results in a spill coalesce with itself }
  2252. spillinfo[t].spilled:=true;
  2253. spillinfo[t].spilllocation:=spill_temps[t];
  2254. end;
  2255. list.insertlistafter(headertai,templist);
  2256. templist.free;
  2257. { Walk through all instructions, we can start with the headertai,
  2258. because before the header tai is only symbols }
  2259. p:=headertai;
  2260. while assigned(p) do
  2261. begin
  2262. case p.typ of
  2263. ait_regalloc:
  2264. with Tai_regalloc(p) do
  2265. begin
  2266. if (getregtype(reg)=regtype) then
  2267. begin
  2268. {A register allocation of the spilled register (and all coalesced registers)
  2269. must be removed.}
  2270. supreg:=get_alias(getsupreg(reg));
  2271. if supregset_in(regs_to_spill_set,supreg) then
  2272. begin
  2273. { Remove loading of the register from its initial memory location
  2274. (e.g. load of a stack parameter to the register). }
  2275. if (ratype=ra_alloc) and
  2276. (ri_has_initial_loc in reginfo[supreg].flags) and
  2277. (instr<>nil) then
  2278. begin
  2279. list.remove(instr);
  2280. FreeAndNil(instr);
  2281. dec(reginfo[supreg].weight,100);
  2282. end;
  2283. { Remove the regalloc }
  2284. remove_ai(list,p);
  2285. continue;
  2286. end
  2287. else
  2288. begin
  2289. case ratype of
  2290. ra_alloc :
  2291. live_registers.add(supreg);
  2292. ra_dealloc :
  2293. live_registers.delete(supreg);
  2294. else
  2295. ;
  2296. end;
  2297. end;
  2298. end;
  2299. end;
  2300. {$ifdef llvm}
  2301. ait_llvmins,
  2302. {$endif llvm}
  2303. ait_instruction:
  2304. with tai_cpu_abstract_sym(p) do
  2305. begin
  2306. // writeln(gas_op2str[tai_cpu_abstract_sym(p).opcode]);
  2307. current_filepos:=fileinfo;
  2308. if instr_spill_register(list,tai_cpu_abstract_sym(p),regs_to_spill_set,spill_temps) then
  2309. spill_registers:=true;
  2310. end;
  2311. else
  2312. ;
  2313. end;
  2314. p:=Tai(p.next);
  2315. end;
  2316. current_filepos:=current_procinfo.exitpos;
  2317. {Safe: this procedure is only called if there are spilled nodes.}
  2318. with spillednodes do
  2319. for i:=0 to length-1 do
  2320. begin
  2321. j:=buf[i];
  2322. if tg.istemp(spill_temps[j]) then
  2323. tg.ungettemp(list,spill_temps[j]);
  2324. end;
  2325. spill_temps:=nil;
  2326. end;
  2327. function trgobj.do_spill_replace(list:TAsmList;instr:tai_cpu_abstract_sym;orgreg:tsuperregister;const spilltemp:treference):boolean;
  2328. begin
  2329. result:=false;
  2330. end;
  2331. procedure trgobj.do_spill_read(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);
  2332. var
  2333. ins:tai_cpu_abstract_sym;
  2334. begin
  2335. ins:=spilling_create_load(spilltemp,tempreg);
  2336. add_cpu_interferences(ins);
  2337. list.insertafter(ins,pos);
  2338. {$ifdef DEBUG_SPILLING}
  2339. list.Insertbefore(tai_comment.Create(strpnew('Spilling: Spill Read')),ins);
  2340. {$endif}
  2341. end;
  2342. procedure Trgobj.do_spill_written(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);
  2343. var
  2344. ins:tai_cpu_abstract_sym;
  2345. begin
  2346. ins:=spilling_create_store(tempreg,spilltemp);
  2347. add_cpu_interferences(ins);
  2348. list.insertafter(ins,pos);
  2349. {$ifdef DEBUG_SPILLING}
  2350. list.Insertbefore(tai_comment.Create(strpnew('Spilling: Spill Write')),ins);
  2351. {$endif}
  2352. end;
  2353. function trgobj.get_spill_subreg(r : tregister) : tsubregister;
  2354. begin
  2355. result:=defaultsub;
  2356. end;
  2357. function trgobj.addreginfo(var spregs: tspillregsinfo; const r: tsuperregisterset; reg: tregister; operation: topertype): boolean;
  2358. var
  2359. i, tmpindex: longint;
  2360. supreg: tsuperregister;
  2361. begin
  2362. result:=false;
  2363. tmpindex := spregs.spillreginfocount;
  2364. supreg := get_alias(getsupreg(reg));
  2365. { did we already encounter this register? }
  2366. for i := 0 to pred(spregs.spillreginfocount) do
  2367. if (spregs.spillreginfo[i].orgreg = supreg) then
  2368. begin
  2369. tmpindex := i;
  2370. break;
  2371. end;
  2372. if tmpindex > high(spregs.spillreginfo) then
  2373. internalerror(2003120301);
  2374. spregs.spillreginfo[tmpindex].orgreg := supreg;
  2375. include(spregs.spillreginfo[tmpindex].spillregconstraints,get_spill_subreg(reg));
  2376. if supregset_in(r,supreg) then
  2377. begin
  2378. { add/update info on this register }
  2379. spregs.spillreginfo[tmpindex].mustbespilled := true;
  2380. case operation of
  2381. operand_read:
  2382. spregs.spillreginfo[tmpindex].regread := true;
  2383. operand_write:
  2384. spregs.spillreginfo[tmpindex].regwritten := true;
  2385. operand_readwrite:
  2386. begin
  2387. spregs.spillreginfo[tmpindex].regread := true;
  2388. spregs.spillreginfo[tmpindex].regwritten := true;
  2389. end;
  2390. end;
  2391. result:=true;
  2392. end;
  2393. inc(spregs.spillreginfocount,ord(spregs.spillreginfocount=tmpindex));
  2394. end;
  2395. function trgobj.instr_get_oper_spilling_info(var spregs: tspillregsinfo; const r: tsuperregisterset; instr: tai_cpu_abstract_sym; opidx: longint): boolean;
  2396. begin
  2397. result:=false;
  2398. with instr.oper[opidx]^ do
  2399. begin
  2400. case typ of
  2401. top_reg:
  2402. begin
  2403. if (getregtype(reg) = regtype) then
  2404. result:=addreginfo(spregs,r,reg,instr.spilling_get_operation_type(opidx));
  2405. end;
  2406. top_ref:
  2407. begin
  2408. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2409. with ref^ do
  2410. begin
  2411. if (base <> NR_NO) and
  2412. (getregtype(base)=regtype) then
  2413. result:=addreginfo(spregs,r,base,instr.spilling_get_operation_type_ref(opidx,base));
  2414. if (index <> NR_NO) and
  2415. (getregtype(index)=regtype) then
  2416. result:=addreginfo(spregs,r,index,instr.spilling_get_operation_type_ref(opidx,index)) or result;
  2417. {$if defined(x86)}
  2418. if (segment <> NR_NO) and
  2419. (getregtype(segment)=regtype) then
  2420. result:=addreginfo(spregs,r,segment,instr.spilling_get_operation_type_ref(opidx,segment)) or result;
  2421. {$endif defined(x86)}
  2422. end;
  2423. end;
  2424. {$ifdef ARM}
  2425. top_shifterop:
  2426. begin
  2427. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2428. if shifterop^.rs<>NR_NO then
  2429. result:=addreginfo(spregs,r,shifterop^.rs,operand_read);
  2430. end;
  2431. {$endif ARM}
  2432. else
  2433. ;
  2434. end;
  2435. end;
  2436. end;
  2437. procedure trgobj.try_replace_reg(const spregs: tspillregsinfo; var reg: tregister; useloadreg: boolean);
  2438. var
  2439. i: longint;
  2440. supreg: tsuperregister;
  2441. begin
  2442. supreg:=get_alias(getsupreg(reg));
  2443. for i:=0 to pred(spregs.spillreginfocount) do
  2444. if (spregs.spillreginfo[i].mustbespilled) and
  2445. (spregs.spillreginfo[i].orgreg=supreg) then
  2446. begin
  2447. { Only replace supreg }
  2448. if useloadreg then
  2449. setsupreg(reg, getsupreg(spregs.spillreginfo[i].loadreg))
  2450. else
  2451. setsupreg(reg, getsupreg(spregs.spillreginfo[i].storereg));
  2452. break;
  2453. end;
  2454. end;
  2455. procedure trgobj.substitute_spilled_registers(const spregs: tspillregsinfo; instr: tai_cpu_abstract_sym; opidx: longint);
  2456. begin
  2457. with instr.oper[opidx]^ do
  2458. case typ of
  2459. top_reg:
  2460. begin
  2461. if (getregtype(reg) = regtype) then
  2462. try_replace_reg(spregs, reg, not ssa_safe or
  2463. (instr.spilling_get_operation_type(opidx)=operand_read));
  2464. end;
  2465. top_ref:
  2466. begin
  2467. if regtype in [R_INTREGISTER, R_ADDRESSREGISTER] then
  2468. begin
  2469. if (ref^.base <> NR_NO) and
  2470. (getregtype(ref^.base)=regtype) then
  2471. try_replace_reg(spregs, ref^.base,
  2472. not ssa_safe or (instr.spilling_get_operation_type_ref(opidx, ref^.base)=operand_read));
  2473. if (ref^.index <> NR_NO) and
  2474. (getregtype(ref^.index)=regtype) then
  2475. try_replace_reg(spregs, ref^.index,
  2476. not ssa_safe or (instr.spilling_get_operation_type_ref(opidx, ref^.index)=operand_read));
  2477. {$if defined(x86)}
  2478. if (ref^.segment <> NR_NO) and
  2479. (getregtype(ref^.segment)=regtype) then
  2480. try_replace_reg(spregs, ref^.segment, true { always read-only });
  2481. {$endif defined(x86)}
  2482. end;
  2483. end;
  2484. {$ifdef ARM}
  2485. top_shifterop:
  2486. begin
  2487. if regtype in [R_INTREGISTER, R_ADDRESSREGISTER] then
  2488. try_replace_reg(spregs, shifterop^.rs, true { always read-only });
  2489. end;
  2490. {$endif ARM}
  2491. else
  2492. ;
  2493. end;
  2494. end;
  2495. function trgobj.instr_spill_register(list:TAsmList;
  2496. instr:tai_cpu_abstract_sym;
  2497. const r:Tsuperregisterset;
  2498. const spilltemplist:Tspill_temp_list): boolean;
  2499. var
  2500. counter: longint;
  2501. spregs: tspillregsinfo;
  2502. spilled: boolean;
  2503. var
  2504. loadpos,
  2505. storepos : tai;
  2506. oldlive_registers : tsuperregisterworklist;
  2507. begin
  2508. result := false;
  2509. fillchar(spregs,sizeof(spregs),0);
  2510. for counter := low(spregs.spillreginfo) to high(spregs.spillreginfo) do
  2511. begin
  2512. spregs.spillreginfo[counter].orgreg := RS_INVALID;
  2513. spregs.spillreginfo[counter].loadreg := NR_INVALID;
  2514. spregs.spillreginfo[counter].storereg := NR_INVALID;
  2515. end;
  2516. spilled := false;
  2517. { check whether and if so which and how (read/written) this instructions contains
  2518. registers that must be spilled }
  2519. for counter := 0 to instr.ops-1 do
  2520. spilled:=instr_get_oper_spilling_info(spregs,r,instr,counter) or spilled;
  2521. { if no spilling for this instruction we can leave }
  2522. if not spilled then
  2523. exit;
  2524. { Check if the instruction is "OP reg1,reg2" and reg1 is coalesced with reg2 }
  2525. if (spregs.spillreginfocount=1) and (instr.ops=2) and
  2526. (instr.oper[0]^.typ=top_reg) and (instr.oper[1]^.typ=top_reg) and
  2527. (getregtype(instr.oper[0]^.reg)=getregtype(instr.oper[1]^.reg)) then
  2528. begin
  2529. { Set both registers in the instruction to the same register }
  2530. setsupreg(instr.oper[0]^.reg, spregs.spillreginfo[0].orgreg);
  2531. setsupreg(instr.oper[1]^.reg, spregs.spillreginfo[0].orgreg);
  2532. { In case of MOV reg,reg no spilling is needed.
  2533. This MOV will be removed later in translate_registers() }
  2534. if instr.is_same_reg_move(regtype) then
  2535. exit;
  2536. end;
  2537. {$if defined(x86) or defined(mips) or defined(sparcgen) or defined(arm) or defined(m68k)}
  2538. { Try replacing the register with the spilltemp. This is useful only
  2539. for the i386,x86_64 that support memory locations for several instructions
  2540. For non-x86 it is nevertheless possible to replace moves to/from the register
  2541. with loads/stores to spilltemp (Sergei) }
  2542. for counter := 0 to pred(spregs.spillreginfocount) do
  2543. with spregs.spillreginfo[counter] do
  2544. begin
  2545. if mustbespilled then
  2546. begin
  2547. if do_spill_replace(list,instr,orgreg,spilltemplist[orgreg]) then
  2548. mustbespilled:=false;
  2549. end;
  2550. end;
  2551. {$endif defined(x86) or defined(mips) or defined(sparcgen) or defined(arm) or defined(m68k)}
  2552. {
  2553. There are registers that need are spilled. We generate the
  2554. following code for it. The used positions where code need
  2555. to be inserted are marked using #. Note that code is always inserted
  2556. before the positions using pos.previous. This way the position is always
  2557. the same since pos doesn't change, but pos.previous is modified everytime
  2558. new code is inserted.
  2559. [
  2560. - reg_allocs load spills
  2561. - load spills
  2562. ]
  2563. [#loadpos
  2564. - reg_deallocs
  2565. - reg_allocs
  2566. ]
  2567. [
  2568. - reg_deallocs for load-only spills
  2569. - reg_allocs for store-only spills
  2570. ]
  2571. [#instr
  2572. - original instruction
  2573. ]
  2574. [
  2575. - store spills
  2576. - reg_deallocs store spills
  2577. ]
  2578. [#storepos
  2579. ]
  2580. }
  2581. result := true;
  2582. oldlive_registers.copyfrom(live_registers);
  2583. { Process all tai_regallocs belonging to this instruction, ignore explicit
  2584. inserted regallocs. These can happend for example in i386:
  2585. mov ref,ireg26
  2586. <regdealloc ireg26, instr=taicpu of lea>
  2587. <regalloc edi, insrt=nil>
  2588. lea [ireg26+ireg17],edi
  2589. All released registers are also added to the live_registers because
  2590. they can't be used during the spilling }
  2591. loadpos:=tai(instr.previous);
  2592. while assigned(loadpos) and
  2593. (loadpos.typ=ait_regalloc) and
  2594. ((tai_regalloc(loadpos).instr=nil) or
  2595. (tai_regalloc(loadpos).instr=instr)) do
  2596. begin
  2597. { Only add deallocs belonging to the instruction. Explicit inserted deallocs
  2598. belong to the previous instruction and not the current instruction }
  2599. if (tai_regalloc(loadpos).instr=instr) and
  2600. (tai_regalloc(loadpos).ratype=ra_dealloc) then
  2601. live_registers.add(get_alias(getsupreg(tai_regalloc(loadpos).reg)));
  2602. loadpos:=tai(loadpos.previous);
  2603. end;
  2604. loadpos:=tai(loadpos.next);
  2605. { Load the spilled registers }
  2606. for counter := 0 to pred(spregs.spillreginfocount) do
  2607. with spregs.spillreginfo[counter] do
  2608. begin
  2609. if mustbespilled and regread then
  2610. begin
  2611. loadreg:=getregisterinline(list,spregs.spillreginfo[counter].spillregconstraints);
  2612. do_spill_read(list,tai(loadpos.previous),spilltemplist[orgreg],loadreg,orgreg);
  2613. include(reginfo[getsupreg(loadreg)].flags,ri_spill_helper);
  2614. end;
  2615. end;
  2616. { Release temp registers of read-only registers, and add reference of the instruction
  2617. to the reginfo }
  2618. for counter := 0 to pred(spregs.spillreginfocount) do
  2619. with spregs.spillreginfo[counter] do
  2620. begin
  2621. if mustbespilled and regread and
  2622. (ssa_safe or
  2623. not regwritten) then
  2624. begin
  2625. { The original instruction will be the next that uses this register
  2626. set weigth of the newly allocated register higher than the old one,
  2627. so it will selected for spilling with a lower priority than
  2628. the original one, this prevents an endless spilling loop if orgreg
  2629. is short living, see e.g. tw25164.pp
  2630. the min trick is needed to avoid an overflow in case weight=high(weight which might happen }
  2631. add_reg_instruction(instr,loadreg,min(high(reginfo[orgreg].weight)-1,reginfo[orgreg].weight)+1);
  2632. ungetregisterinline(list,loadreg);
  2633. end;
  2634. end;
  2635. { Allocate temp registers of write-only registers, and add reference of the instruction
  2636. to the reginfo }
  2637. for counter := 0 to pred(spregs.spillreginfocount) do
  2638. with spregs.spillreginfo[counter] do
  2639. begin
  2640. if mustbespilled and regwritten then
  2641. begin
  2642. { When the register is also loaded there is already a register assigned }
  2643. if (not regread) or
  2644. ssa_safe then
  2645. begin
  2646. storereg:=getregisterinline(list,spregs.spillreginfo[counter].spillregconstraints);
  2647. include(reginfo[getsupreg(storereg)].flags,ri_spill_helper);
  2648. { we also use loadreg for store replacements in case we
  2649. don't have ensure ssa -> initialise loadreg even if
  2650. there are no reads }
  2651. if not regread then
  2652. loadreg:=storereg;
  2653. end
  2654. else
  2655. storereg:=loadreg;
  2656. { The original instruction will be the next that uses this register, this
  2657. also needs to be done for read-write registers,
  2658. set weigth of the newly allocated register higher than the old one,
  2659. so it will selected for spilling with a lower priority than
  2660. the original one, this prevents an endless spilling loop if orgreg
  2661. is short living, see e.g. tw25164.pp
  2662. the min trick is needed to avoid an overflow in case weight=high(weight which might happen }
  2663. add_reg_instruction(instr,storereg,min(high(reginfo[orgreg].weight)-1,reginfo[orgreg].weight)+1);
  2664. end;
  2665. end;
  2666. { store the spilled registers }
  2667. if not assigned(instr.next) then
  2668. list.concat(tai_marker.Create(mark_Position));
  2669. storepos:=tai(instr.next);
  2670. for counter := 0 to pred(spregs.spillreginfocount) do
  2671. with spregs.spillreginfo[counter] do
  2672. begin
  2673. if mustbespilled and regwritten then
  2674. begin
  2675. do_spill_written(list,tai(storepos.previous),spilltemplist[orgreg],storereg,orgreg);
  2676. ungetregisterinline(list,storereg);
  2677. end;
  2678. end;
  2679. { now all spilling code is generated we can restore the live registers. This
  2680. must be done after the store because the store can need an extra register
  2681. that also needs to conflict with the registers of the instruction }
  2682. live_registers.done;
  2683. live_registers:=oldlive_registers;
  2684. { substitute registers }
  2685. for counter:=0 to instr.ops-1 do
  2686. substitute_spilled_registers(spregs,instr,counter);
  2687. { We have modified the instruction; perhaps the new instruction has
  2688. certain constraints regarding which imaginary registers interfere
  2689. with certain physical registers. }
  2690. add_cpu_interferences(instr);
  2691. end;
  2692. procedure trgobj.remove_ai(list:TAsmList; var p:Tai);
  2693. var
  2694. q:Tai;
  2695. begin
  2696. q:=tai(p.next);
  2697. list.remove(p);
  2698. p.free;
  2699. p:=q;
  2700. end;
  2701. {$ifdef DEBUG_SPILLCOALESCE}
  2702. procedure trgobj.write_spill_stats;
  2703. { This procedure outputs spilling statistincs.
  2704. If no spilling has occurred, no output is provided.
  2705. NUM is the number of spilled registers.
  2706. EFF is efficiency of the spilling which is based on
  2707. weight and usage count of registers. Range 0-100%.
  2708. 0% means all imaginary registers have been spilled.
  2709. 100% means no imaginary registers have been spilled
  2710. (no output in this case).
  2711. Higher value is better.
  2712. }
  2713. var
  2714. i,j,spillingcounter,max_weight:longint;
  2715. all_weight,spill_weight,d: double;
  2716. begin
  2717. max_weight:=1;
  2718. for i:=first_imaginary to maxreg-1 do
  2719. with reginfo[i] do
  2720. if weight>max_weight then
  2721. max_weight:=weight;
  2722. spillingcounter:=0;
  2723. spill_weight:=0;
  2724. all_weight:=0;
  2725. for i:=first_imaginary to maxreg-1 do
  2726. with reginfo[i] do
  2727. if not (ri_spill_helper in flags) then
  2728. begin
  2729. d:=weight/max_weight;
  2730. all_weight:=all_weight+d;
  2731. if (ri_coalesced in flags) and (alias>=first_imaginary) then
  2732. j:=alias
  2733. else
  2734. j:=i;
  2735. if (reginfo[j].weight>100) and
  2736. (j<=high(spillinfo)) and
  2737. spillinfo[j].spilled then
  2738. begin
  2739. inc(spillingcounter);
  2740. spill_weight:=spill_weight+d;
  2741. end;
  2742. end;
  2743. if spillingcounter>0 then
  2744. begin
  2745. d:=(1.0-spill_weight/all_weight)*100.0;
  2746. writeln(current_procinfo.procdef.mangledname,' [',regtype,']: spill stats: NUM: ',spillingcounter, ', EFF: ',d:4:1,'%');
  2747. end;
  2748. end;
  2749. {$endif DEBUG_SPILLCOALESCE}
  2750. end.