rgobj.pas 109 KB

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