rgobj.pas 111 KB

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