rgobj.pas 105 KB

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