rgobj.pas 109 KB

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