rgobj.pas 111 KB

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