aoptobj.pas 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900
  1. {
  2. Copyright (c) 1998-2004 by Jonas Maebe, member of the Free Pascal
  3. Development Team
  4. This unit contains the processor independent assembler optimizer
  5. object, base for the dataflow analyzer, peepholeoptimizer and
  6. common subexpression elimination objects.
  7. This program is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 2 of the License, or
  10. (at your option) any later version.
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License
  16. along with this program; if not, write to the Free Software
  17. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18. ****************************************************************************
  19. }
  20. Unit AoptObj;
  21. { $define DEBUG_AOPTOBJ}
  22. { $define DEBUG_JUMP}
  23. {$i fpcdefs.inc}
  24. {$if not defined(JVM) and not defined(WASM) and not defined(POWERPC) and not defined (POWERPC64)}
  25. {$define CPU_SUPPORTS_OPT_COND_JUMP}
  26. {$endif}
  27. { general, processor independent objects for use by the assembler optimizer }
  28. Interface
  29. uses
  30. globtype,
  31. aasmbase,aasmcpu,aasmtai,aasmdata,
  32. cclasses,
  33. cgbase,cgutils,
  34. cpubase,
  35. aoptbase,aoptcpub,aoptda;
  36. { ************************************************************************* }
  37. { ********************************* Constants ***************************** }
  38. { ************************************************************************* }
  39. Const
  40. {Possible register content types}
  41. con_Unknown = 0;
  42. con_ref = 1;
  43. con_const = 2;
  44. {***************** Types ****************}
  45. Type
  46. { ************************************************************************* }
  47. { ************************* Some general type definitions ***************** }
  48. { ************************************************************************* }
  49. TRefCompare = Function(const r1, r2: TReference): Boolean;
  50. //!!! FIXME
  51. TRegArray = Array[byte] of tsuperregister;
  52. TRegSet = tcpuregisterset;
  53. { possible actions on an operand: read, write or modify (= read & write) }
  54. TOpAction = (OpAct_Read, OpAct_Write, OpAct_Modify, OpAct_Unknown);
  55. { ************************************************************************* }
  56. { * Object to hold information on which regiters are in use and which not * }
  57. { ************************************************************************* }
  58. { TUsedRegs }
  59. TUsedRegs = class
  60. Constructor create(aTyp : TRegisterType);
  61. Constructor create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  62. Destructor Destroy;override;
  63. Procedure Clear;
  64. { update the info with the pairegalloc objects coming after
  65. p }
  66. procedure Update(p: Tai; IgnoreNewAllocs: Boolean=false);
  67. { is Reg currently in use }
  68. Function IsUsed(Reg: TRegister): Boolean; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  69. { get all the currently used registers }
  70. Function GetUsedRegs: TRegSet; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  71. { outputs the current set }
  72. Procedure Dump(var t : text);
  73. Private
  74. Typ : TRegisterType;
  75. UsedRegs: TRegSet;
  76. End;
  77. { ************************************************************************* }
  78. { ******************* Contents of the integer registers ******************* }
  79. { ************************************************************************* }
  80. { size of the integer that holds the state number of a register. Can be any }
  81. { integer type, so it can be changed to reduce the size of the TContent }
  82. { structure or to improve alignment }
  83. TStateInt = Byte;
  84. TContent = Record
  85. { start and end of block instructions that defines the }
  86. { content of this register. If Typ = con_const, then }
  87. { Longint(StartMod) = value of the constant) }
  88. StartMod: Tai;
  89. { starts at 0, gets increased everytime the register is }
  90. { written to }
  91. WState: TStateInt;
  92. { starts at 0, gets increased everytime the register is read }
  93. { from }
  94. RState: TStateInt;
  95. { how many instructions starting with StarMod does the block }
  96. { consist of }
  97. NrOfMods: Byte;
  98. { the type of the content of the register: unknown, memory }
  99. { (variable) or constant }
  100. Typ: Byte;
  101. End;
  102. //!!! FIXME
  103. TRegContent = Array[byte] Of TContent;
  104. { ************************************************************************** }
  105. { information object with the contents of every register. Every Tai object }
  106. { gets one of these assigned: a pointer to it is stored in the OptInfo field }
  107. { ************************************************************************** }
  108. { TPaiProp }
  109. TPaiProp = class(TAoptBaseCpu)
  110. Regs: TRegContent;
  111. { can this instruction be removed? }
  112. CanBeRemoved: Boolean;
  113. Constructor create; reintroduce;
  114. { checks the whole sequence of which (so regs[which].StartMod and and }
  115. { the next NrOfMods Tai objects) to see whether Reg is used somewhere, }
  116. { without it being loaded with something else first }
  117. Function RegInSequence(Reg, which: TRegister): Boolean;
  118. { destroy the contents of a register, as well as those whose contents }
  119. { are based on those of that register }
  120. Procedure DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  121. TInstrSinceLastMod);
  122. { if the contents of WhichReg (can be R_NO in case of a constant) are }
  123. { written to memory at the location Ref, the contents of the registers }
  124. { that depend on Ref have to be destroyed }
  125. Procedure DestroyRefs(Const Ref: TReference; WhichReg: TRegister; var
  126. InstrSinceLastMod: TInstrSinceLastMod);
  127. { an instruction reads from operand o }
  128. Procedure ReadOp(const o:toper);
  129. { an instruction reads from reference Ref }
  130. Procedure ReadRef(Ref: PReference);
  131. { an instruction reads from register Reg }
  132. Procedure ReadReg(Reg: TRegister);
  133. { an instruction writes/modifies operand o and this has special }
  134. { side-effects or modifies the contents in such a way that we can't }
  135. { simply add this instruction to the sequence of instructions that }
  136. { describe the contents of the operand, so destroy it }
  137. Procedure DestroyOp(const o:Toper; var InstrSinceLastMod:
  138. TInstrSinceLastMod);
  139. { destroy the contents of all registers }
  140. Procedure DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  141. { a register's contents are modified, but not destroyed (the new value
  142. depends on the old one) }
  143. Procedure ModifyReg(reg: TRegister; var InstrSinceLastMod:
  144. TInstrSinceLastMod);
  145. { an operand's contents are modified, but not destroyed (the new value
  146. depends on the old one) }
  147. Procedure ModifyOp(const oper: TOper; var InstrSinceLastMod:
  148. TInstrSinceLastMod);
  149. { increase the write state of a register (call every time a register is
  150. written to) }
  151. Procedure IncWState(Reg: TRegister);
  152. { increase the read state of a register (call every time a register is }
  153. { read from) }
  154. Procedure IncRState(Reg: TRegister);
  155. { get the write state of a register }
  156. Function GetWState(Reg: TRegister): TStateInt;
  157. { get the read state of a register }
  158. Function GetRState(Reg: TRegister): TStateInt;
  159. { get the type of contents of a register }
  160. Function GetRegContentType(Reg: TRegister): Byte;
  161. Destructor Done;
  162. Private
  163. Procedure IncState(var s: TStateInt);
  164. { returns whether the reference Ref is used somewhere in the loading }
  165. { sequence Content }
  166. class function RefInSequence(Const Ref: TReference; Content: TContent;
  167. RefsEq: TRefCompare): Boolean; static;
  168. { returns whether the instruction P reads from and/or writes }
  169. { to Reg }
  170. class function RefInInstruction(Const Ref: TReference; p: Tai;
  171. RefsEq: TRefCompare): Boolean; static;
  172. { returns whether two references with at least one pointing to an array }
  173. { may point to the same memory location }
  174. End;
  175. { ************************************************************************* }
  176. { ************************ Label information ****************************** }
  177. { ************************************************************************* }
  178. TLabelTableItem = Record
  179. PaiObj: Tai;
  180. End;
  181. TLabelTable = Array Of TLabelTableItem;
  182. PLabelInfo = ^TLabelInfo;
  183. TLabelInfo = Record
  184. { the highest and lowest label number occurring in the current code }
  185. { fragment }
  186. LowLabel, HighLabel: longint;
  187. LabelDif: cardinal;
  188. { table that contains the addresses of the Pai_Label objects associated
  189. with each label number }
  190. LabelTable: TLabelTable;
  191. End;
  192. { ************************************************************************* }
  193. { ********** General optimizer object, used to derive others from ********* }
  194. { ************************************************************************* }
  195. TAllUsedRegs = array[TRegisterType] of TUsedRegs;
  196. { TAOptObj }
  197. TAOptObj = class(TAoptBaseCpu)
  198. { the PAasmOutput list this optimizer instance works on }
  199. AsmL: TAsmList;
  200. { The labelinfo record contains the addresses of the Tai objects }
  201. { that are labels, how many labels there are and the min and max }
  202. { label numbers }
  203. LabelInfo: PLabelInfo;
  204. { Start and end of the block that is currently being optimized, and
  205. a selected start point after the start of the block }
  206. BlockStart, BlockEnd, StartPoint: Tai;
  207. DFA: TAOptDFA;
  208. UsedRegs: TAllUsedRegs;
  209. { _AsmL is the PAasmOutpout list that has to be optimized, }
  210. { _BlockStart and _BlockEnd the start and the end of the block }
  211. { that has to be optimized and _LabelInfo a pointer to a }
  212. { TLabelInfo record }
  213. Constructor create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  214. _LabelInfo: PLabelInfo); virtual; reintroduce;
  215. Destructor Destroy;override;
  216. { processor independent methods }
  217. Procedure CreateUsedRegs(var regs: TAllUsedRegs);
  218. Procedure ClearUsedRegs;
  219. Procedure UpdateUsedRegs(p : Tai); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  220. class procedure UpdateUsedRegs(var Regs: TAllUsedRegs; p: Tai); static;
  221. { UpdateUsedRegsBetween updates the given TUsedRegs from p1 to p2 exclusive, calling GetNextInstruction
  222. to move between instructions and sending p1.Next to UpdateUsedRegs }
  223. class procedure UpdateUsedRegsBetween(var Regs: TAllUsedRegs; p1, p2: Tai); static;
  224. { If UpdateUsedRegsAndOptimize has read ahead, the result is one before
  225. the next valid entry (so "p.Next" returns what's expected). If no
  226. reading ahead happened, then the result is equal to p. }
  227. function UpdateUsedRegsAndOptimize(p : Tai): Tai;
  228. Function CopyUsedRegs(var dest : TAllUsedRegs) : boolean;
  229. procedure RestoreUsedRegs(const Regs : TAllUsedRegs);
  230. procedure TransferUsedRegs(var dest: TAllUsedRegs);
  231. class procedure ReleaseUsedRegs(const regs : TAllUsedRegs); static;
  232. class function RegInUsedRegs(reg : TRegister;var regs : TAllUsedRegs) : boolean; static;
  233. class procedure IncludeRegInUsedRegs(reg : TRegister;var regs : TAllUsedRegs); static; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  234. class procedure ExcludeRegFromUsedRegs(reg: TRegister;var regs : TAllUsedRegs); static; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  235. class function GetAllocationString(const regs : TAllUsedRegs) : string; static;
  236. { returns true if the label L is found between hp and the next }
  237. { instruction }
  238. class function FindLabel(L: TasmLabel; Var hp: Tai): Boolean; static;
  239. { inserts new_one between prev and foll in AsmL }
  240. Procedure InsertLLItem(prev, foll, new_one: TLinkedListItem);
  241. { If P is a Tai object releveant to the optimizer, P is returned
  242. If it is not relevant tot he optimizer, the first object after P
  243. that is relevant is returned }
  244. class function SkipHead(P: Tai): Tai; static;
  245. { returns true if the operands o1 and o2 are completely equal }
  246. class function OpsEqual(const o1,o2:toper): Boolean; static;
  247. { Returns the next ait_alloc object with ratype ra_alloc for
  248. Reg is found in the block
  249. of Tai's starting with StartPai and ending with the next "real"
  250. instruction. If none is found, it returns
  251. nil
  252. }
  253. class function FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc; static;
  254. { Returns the last ait_alloc object with ratype ra_alloc for
  255. Reg is found in the block
  256. of Tai's starting with StartPai and ending with the next "real"
  257. instruction. If none is found, it returns
  258. nil
  259. }
  260. class function FindRegAllocBackward(Reg : TRegister; StartPai : Tai) : tai_regalloc; static;
  261. { Returns the next ait_alloc object with ratype ra_dealloc
  262. for Reg which is found in the block of Tai's starting with StartPai
  263. and ending with the next "real" instruction. If none is found, it returns
  264. nil }
  265. class function FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc; static;
  266. { allocates register reg between (and including) instructions p1 and p2
  267. the type of p1 and p2 must not be in SkipInstr }
  268. procedure AllocRegBetween(reg : tregister; p1,p2 : tai; var initialusedregs : TAllUsedRegs);
  269. { reg used after p? }
  270. function RegUsedAfterInstruction(reg: Tregister; p: tai; var AllUsedRegs: TAllUsedRegs): Boolean;
  271. { returns true if reg reaches it's end of life at p, this means it is either
  272. reloaded with a new value or it is deallocated afterwards }
  273. function RegEndOfLife(reg: TRegister;p: taicpu): boolean;
  274. { Returns the next ait_tempalloc object with allocation=false
  275. for Offset which is found in the block of Tai's starting with StartPai
  276. and ending with the next "real" instruction. If none is found, it returns
  277. nil }
  278. class function FindTempDeAlloc(Offset: ASizeInt; StartPai: Tai): tai_tempalloc;
  279. { removes p from asml, updates registers and replaces it by a valid value, if this is the case true is returned }
  280. function RemoveCurrentP(var p : tai): boolean;
  281. { removes p from asml, updates registers and replaces p with hp1 (if the next instruction was known beforehand) }
  282. procedure RemoveCurrentP(var p: tai; const hp1: tai); inline;
  283. { removes hp from asml then frees it }
  284. procedure RemoveInstruction(const hp: tai); inline;
  285. { traces sucessive jumps to their final destination and sets it, e.g.
  286. je l1 je l3
  287. <code> <code>
  288. l1: becomes l1:
  289. je l2 je l3
  290. <code> <code>
  291. l2: l2:
  292. jmp l3 jmp l3
  293. the level parameter denotes how deeep we have already followed the jump,
  294. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  295. function GetFinalDestination(hp: taicpu; level: longint): boolean;
  296. function getlabelwithsym(sym: tasmlabel): tai;
  297. { Removes an instruction following hp1 (possibly with reg.deallocations in between),
  298. if its opcode is A_NOP. }
  299. procedure RemoveDelaySlot(hp1: tai);
  300. { peephole optimizer }
  301. procedure PrePeepHoleOpts; virtual;
  302. procedure PeepHoleOptPass1; virtual;
  303. procedure PeepHoleOptPass2; virtual;
  304. procedure PostPeepHoleOpts; virtual;
  305. { processor dependent methods }
  306. // if it returns true, perform a "continue"
  307. function PrePeepHoleOptsCpu(var p: tai): boolean; virtual;
  308. function PeepHoleOptPass1Cpu(var p: tai): boolean; virtual;
  309. function PeepHoleOptPass2Cpu(var p: tai): boolean; virtual;
  310. function PostPeepHoleOptsCpu(var p: tai): boolean; virtual;
  311. { Output debug message to console - null function if EXTDEBUG is not defined }
  312. class procedure DebugWrite(Message: string); static; inline;
  313. { Converts a conditional jump into an unconditional jump. Only call this
  314. procedure on an instruction that you already know is a conditional jump }
  315. procedure MakeUnconditional(p: taicpu); virtual;
  316. { Removes all instructions between an unconditional jump and the next label.
  317. Returns True if a jump in between was removed (as it may open up new
  318. optimisations if the label appeared earlier in the stream) }
  319. function RemoveDeadCodeAfterJump(p: tai): Boolean;
  320. { If hp is a label, strip it if its reference count is zero. Repeat until
  321. a non-label is found, or a label with a non-zero reference count.
  322. True is returned if something was stripped }
  323. function StripDeadLabels(hp: tai; var NextValid: tai): Boolean;
  324. { Strips a label and any aligns that appear before it (if hp points to
  325. them rather than the label). Only call this procedure on a label that
  326. you already know is no longer referenced }
  327. procedure StripLabelFast(hp: tai);
  328. { Checks and removes "jmp @@lbl; @lbl". Returns True if the jump was removed }
  329. function CollapseZeroDistJump(var p: tai; ThisLabel: TAsmLabel): Boolean;
  330. { If a group of labels are clustered, change the jump to point to the last one that is still referenced }
  331. function CollapseLabelCluster(jump: tai; var lbltai: tai): TAsmLabel;
  332. {$ifdef CPU_SUPPORTS_OPT_COND_JUMP}
  333. function OptimizeConditionalJump(CJLabel: TAsmLabel; var p: tai; hp1: tai; var stoploop: Boolean): Boolean;
  334. {$endif}
  335. { Function to determine if the jump optimisations can be performed }
  336. function CanDoJumpOpts: Boolean; virtual;
  337. { Jump/label optimisation entry method }
  338. function DoJumpOptimizations(var p: tai; var stoploop: Boolean): Boolean;
  339. { Attempts to reconfigure the Regallocs and Regdeallocs before p1 and
  340. after p2 so Reg is no longer allocated between them. Returns True if
  341. the register is no longer allocated at p1 }
  342. function TryRemoveRegAlloc(const Reg: TRegister; p1, p2: tai): Boolean;
  343. { insert debug comments about which registers are read and written by
  344. each instruction. Useful for debugging the InstructionLoadsFromReg and
  345. other similar functions. }
  346. procedure Debug_InsertInstrRegisterDependencyInfo; virtual;
  347. protected
  348. { Set to True if this is the second time that Pass 1 is being run }
  349. NotFirstIteration: Boolean;
  350. { Actually updates a used register }
  351. class procedure UpdateReg(var Regs : TAllUsedRegs; p: tai_regalloc); static; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  352. private
  353. procedure DebugMsg(const s: string; p: tai);
  354. { Utilty function for the UpdateUsedRegs family of methods }
  355. class function GetNextRegUpdatePoint(var p : Tai; pTerm: tai): Boolean; static;
  356. End;
  357. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  358. { Returns a pointer to the operand that contains the destination label }
  359. function JumpTargetOp(ai: taicpu): poper;
  360. { Returns True if hp is any jump to a label }
  361. function IsJumpToLabel(hp: taicpu): boolean;
  362. { Returns True if hp is an unconditional jump to a label }
  363. function IsJumpToLabelUncond(hp: taicpu): boolean;
  364. { ***************************** Implementation **************************** }
  365. Implementation
  366. uses
  367. cutils,
  368. globals,
  369. verbose,
  370. aoptutils,
  371. aasmcfi,
  372. {$if defined(ARM)}
  373. cpuinfo,
  374. {$endif defined(ARM)}
  375. procinfo;
  376. {$ifdef DEBUG_AOPTOBJ}
  377. const
  378. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  379. {$else DEBUG_AOPTOBJ}
  380. { Empty strings help the optimizer to remove string concatenations that won't
  381. ever appear to the user on release builds. [Kit] }
  382. const
  383. SPeepholeOptimization = '';
  384. {$endif DEBUG_AOPTOBJ}
  385. function JumpTargetOp(ai: taicpu): poper; {$IFDEF USEINLINE}inline;{$ENDIF}
  386. begin
  387. {$if defined(MIPS) or defined(riscv64) or defined(riscv32) or defined(xtensa) or defined(loongarch64)}
  388. { Branches of above archs can have 1,2 or 3 operands, target label is the last one. }
  389. result:=ai.oper[ai.ops-1];
  390. {$elseif defined(SPARC64)}
  391. if ai.ops=2 then
  392. result:=ai.oper[1]
  393. else
  394. result:=ai.oper[0];
  395. {$else MIPS}
  396. result:=ai.oper[0];
  397. {$endif}
  398. end;
  399. { ************************************************************************* }
  400. { ******************************** TUsedRegs ****************************** }
  401. { ************************************************************************* }
  402. Constructor TUsedRegs.create(aTyp : TRegisterType);
  403. Begin
  404. Typ:=aTyp;
  405. UsedRegs := [];
  406. End;
  407. Constructor TUsedRegs.create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  408. Begin
  409. Typ:=aTyp;
  410. UsedRegs := _RegSet;
  411. End;
  412. {
  413. updates UsedRegs with the RegAlloc Information coming after P
  414. }
  415. Procedure TUsedRegs.Update(p: Tai;IgnoreNewAllocs : Boolean = false);
  416. Begin
  417. { this code is normally not used because updating the register allocation information is done in
  418. TAOptObj.UpdateUsedRegs for speed reasons }
  419. repeat
  420. while assigned(p) and
  421. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  422. (p.typ = ait_label) or
  423. ((p.typ = ait_marker) and
  424. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  425. p := tai(p.next);
  426. while assigned(p) and
  427. (p.typ=ait_RegAlloc) Do
  428. begin
  429. if (getregtype(tai_regalloc(p).reg) = typ) then
  430. begin
  431. case tai_regalloc(p).ratype of
  432. ra_alloc :
  433. if not(IgnoreNewAllocs) then
  434. Include(UsedRegs, getsupreg(tai_regalloc(p).reg));
  435. ra_dealloc :
  436. Exclude(UsedRegs, getsupreg(tai_regalloc(p).reg));
  437. else
  438. ;
  439. end;
  440. end;
  441. p := tai(p.next);
  442. end;
  443. until not(assigned(p)) or
  444. (not(p.typ in SkipInstr) and
  445. not((p.typ = ait_label) and
  446. labelCanBeSkipped(tai_label(p))));
  447. End;
  448. Function TUsedRegs.IsUsed(Reg: TRegister): Boolean; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  449. Begin
  450. IsUsed := (getregtype(Reg)=Typ) and (getsupreg(Reg) in UsedRegs);
  451. End;
  452. Function TUsedRegs.GetUsedRegs: TRegSet; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  453. Begin
  454. GetUsedRegs := UsedRegs;
  455. End;
  456. procedure TUsedRegs.Dump(var t: text);
  457. var
  458. i: dword;
  459. begin
  460. write(t,Typ,' ');
  461. for i:=low(TRegSet) to high(TRegSet) do
  462. if i in UsedRegs then
  463. write(t,i,' ');
  464. writeln(t);
  465. end;
  466. Destructor TUsedRegs.Destroy;
  467. Begin
  468. inherited destroy;
  469. end;
  470. procedure TUsedRegs.Clear;
  471. begin
  472. UsedRegs := [];
  473. end;
  474. { ************************************************************************* }
  475. { **************************** TPaiProp *********************************** }
  476. { ************************************************************************* }
  477. Constructor TPaiProp.Create;
  478. Begin
  479. {!!!!!!
  480. UsedRegs.Init;
  481. CondRegs.init;
  482. }
  483. { DirFlag: TFlagContents; I386 specific}
  484. End;
  485. Function TPaiProp.RegInSequence(Reg, which: TRegister): Boolean;
  486. {
  487. Var p: Tai;
  488. RegsChecked: TRegSet;
  489. content: TContent;
  490. Counter: Byte;
  491. TmpResult: Boolean;
  492. }
  493. begin
  494. Result:=False; { unimplemented }
  495. (*!!!!!!!!!!1
  496. RegsChecked := [];
  497. content := regs[which];
  498. p := content.StartMod;
  499. TmpResult := False;
  500. Counter := 1;
  501. While Not(TmpResult) And
  502. (Counter <= Content.NrOfMods) Do
  503. Begin
  504. If IsLoadMemReg(p) Then
  505. With PInstr(p)^.oper[LoadSrc]^.ref^ Do
  506. If (Base = ProcInfo.FramePointer)
  507. {$ifdef cpurefshaveindexreg}
  508. And (Index = R_NO)
  509. {$endif cpurefshaveindexreg} Then
  510. Begin
  511. RegsChecked := RegsChecked +
  512. [RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg)];
  513. If Reg = RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg) Then
  514. Break;
  515. End
  516. Else
  517. Begin
  518. If (Base = Reg) And
  519. Not(Base In RegsChecked)
  520. Then TmpResult := True;
  521. {$ifdef cpurefshaveindexreg}
  522. If Not(TmpResult) And
  523. (Index = Reg) And
  524. Not(Index In RegsChecked)
  525. Then TmpResult := True;
  526. {$Endif cpurefshaveindexreg}
  527. End
  528. Else TmpResult := RegInInstruction(Reg, p);
  529. Inc(Counter);
  530. GetNextInstruction(p,p)
  531. End;
  532. RegInSequence := TmpResult
  533. *)
  534. End;
  535. Procedure TPaiProp.DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  536. TInstrSinceLastMod);
  537. { Destroys the contents of the register Reg in the PPaiProp p1, as well as }
  538. { the contents of registers are loaded with a memory location based on Reg }
  539. {
  540. Var TmpWState, TmpRState: Byte;
  541. Counter: TRegister;
  542. }
  543. Begin
  544. {!!!!!!!
  545. Reg := RegMaxSize(Reg);
  546. If (Reg in [LoGPReg..HiGPReg]) Then
  547. For Counter := LoGPReg to HiGPReg Do
  548. With Regs[Counter] Do
  549. If (Counter = reg) Or
  550. ((Typ = Con_Ref) And
  551. RegInSequence(Reg, Counter)) Then
  552. Begin
  553. InstrSinceLastMod[Counter] := 0;
  554. IncWState(Counter);
  555. TmpWState := GetWState(Counter);
  556. TmpRState := GetRState(Counter);
  557. FillChar(Regs[Counter], SizeOf(TContent), 0);
  558. WState := TmpWState;
  559. RState := TmpRState
  560. End
  561. }
  562. End;
  563. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  564. Begin
  565. Result:=False; { unimplemented }
  566. (*!!!!!!!!!!
  567. ArrayRefsEq := (R1.Offset+R1.OffsetFixup = R2.Offset+R2.OffsetFixup) And
  568. {$ifdef refsHaveSegmentReg}
  569. (R1.Segment = R2.Segment) And
  570. {$endif}
  571. (R1.Base = R2.Base) And
  572. (R1.Symbol=R2.Symbol);
  573. *)
  574. End;
  575. Procedure TPaiProp.DestroyRefs(Const Ref: TReference; WhichReg: TRegister;
  576. var InstrSinceLastMod: TInstrSinceLastMod);
  577. { destroys all registers which possibly contain a reference to Ref, WhichReg }
  578. { is the register whose contents are being written to memory (if this proc }
  579. { is called because of a "mov?? %reg, (mem)" instruction) }
  580. {
  581. Var RefsEq: TRefCompare;
  582. Counter: TRegister;
  583. }
  584. Begin
  585. (*!!!!!!!!!!!
  586. WhichReg := RegMaxSize(WhichReg);
  587. If (Ref.base = procinfo.FramePointer) or
  588. Assigned(Ref.Symbol) Then
  589. Begin
  590. If
  591. {$ifdef cpurefshaveindexreg}
  592. (Ref.Index = R_NO) And
  593. {$endif cpurefshaveindexreg}
  594. (Not(Assigned(Ref.Symbol)) or
  595. (Ref.base = R_NO)) Then
  596. { local variable which is not an array }
  597. RefsEq := @RefsEqual
  598. Else
  599. { local variable which is an array }
  600. RefsEq := @ArrayRefsEq;
  601. {write something to a parameter, a local or global variable, so
  602. * with uncertain optimizations on:
  603. - destroy the contents of registers whose contents have somewhere a
  604. "mov?? (Ref), %reg". WhichReg (this is the register whose contents
  605. are being written to memory) is not destroyed if it's StartMod is
  606. of that form and NrOfMods = 1 (so if it holds ref, but is not a
  607. pointer or value based on Ref)
  608. * with uncertain optimizations off:
  609. - also destroy registers that contain any pointer}
  610. For Counter := LoGPReg to HiGPReg Do
  611. With Regs[Counter] Do
  612. Begin
  613. If (typ = Con_Ref) And
  614. ((Not(cs_opt_size in current_settings.optimizerswitches) And
  615. (NrOfMods <> 1)
  616. ) Or
  617. (RefInSequence(Ref,Regs[Counter], RefsEq) And
  618. ((Counter <> WhichReg) Or
  619. ((NrOfMods <> 1) And
  620. {StarMod is always of the type ait_instruction}
  621. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  622. RefsEq(PInstr(StartMod)^.oper[0].ref^, Ref)
  623. )
  624. )
  625. )
  626. )
  627. Then
  628. DestroyReg(Counter, InstrSinceLastMod)
  629. End
  630. End
  631. Else
  632. {write something to a pointer location, so
  633. * with uncertain optimzations on:
  634. - do not destroy registers which contain a local/global variable or a
  635. parameter, except if DestroyRefs is called because of a "movsl"
  636. * with uncertain optimzations off:
  637. - destroy every register which contains a memory location
  638. }
  639. For Counter := LoGPReg to HiGPReg Do
  640. With Regs[Counter] Do
  641. If (typ = Con_Ref) And
  642. (Not(cs_opt_size in current_settings.optimizerswitches) Or
  643. {$ifdef x86}
  644. {for movsl}
  645. (Ref.Base = R_EDI) Or
  646. {$endif}
  647. {don't destroy if reg contains a parameter, local or global variable}
  648. Not((NrOfMods = 1) And
  649. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  650. ((PInstr(StartMod)^.oper[0].ref^.base = ProcInfo.FramePointer) Or
  651. Assigned(PInstr(StartMod)^.oper[0].ref^.Symbol)
  652. )
  653. )
  654. )
  655. Then DestroyReg(Counter, InstrSinceLastMod)
  656. *)
  657. End;
  658. Procedure TPaiProp.DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  659. {Var Counter: TRegister;}
  660. Begin {initializes/desrtoys all registers}
  661. (*!!!!!!!!!
  662. For Counter := LoGPReg To HiGPReg Do
  663. Begin
  664. ReadReg(Counter);
  665. DestroyReg(Counter, InstrSinceLastMod);
  666. End;
  667. CondRegs.Init;
  668. { FPURegs.Init; }
  669. *)
  670. End;
  671. Procedure TPaiProp.DestroyOp(const o:Toper; var InstrSinceLastMod:
  672. TInstrSinceLastMod);
  673. Begin
  674. {!!!!!!!
  675. Case o.typ Of
  676. top_reg: DestroyReg(o.reg, InstrSinceLastMod);
  677. top_ref:
  678. Begin
  679. ReadRef(o.ref);
  680. DestroyRefs(o.ref^, R_NO, InstrSinceLastMod);
  681. End;
  682. top_symbol:;
  683. End;
  684. }
  685. End;
  686. Procedure TPaiProp.ReadReg(Reg: TRegister);
  687. Begin
  688. {!!!!!!!
  689. Reg := RegMaxSize(Reg);
  690. If Reg in General_Registers Then
  691. IncRState(RegMaxSize(Reg))
  692. }
  693. End;
  694. Procedure TPaiProp.ReadRef(Ref: PReference);
  695. Begin
  696. (*!!!!!!
  697. If Ref^.Base <> R_NO Then
  698. ReadReg(Ref^.Base);
  699. {$ifdef cpurefshaveindexreg}
  700. If Ref^.Index <> R_NO Then
  701. ReadReg(Ref^.Index);
  702. {$endif cpurefshaveindexreg}
  703. *)
  704. End;
  705. Procedure TPaiProp.ReadOp(const o:toper);
  706. Begin
  707. Case o.typ Of
  708. top_reg: ReadReg(o.reg);
  709. top_ref: ReadRef(o.ref);
  710. else
  711. internalerror(200410241);
  712. End;
  713. End;
  714. Procedure TPaiProp.ModifyReg(reg: TRegister; Var InstrSinceLastMod:
  715. TInstrSinceLastMod);
  716. Begin
  717. (*!!!!!!!
  718. With Regs[reg] Do
  719. If (Typ = Con_Ref)
  720. Then
  721. Begin
  722. IncState(WState);
  723. {also store how many instructions are part of the sequence in the first
  724. instructions PPaiProp, so it can be easily accessed from within
  725. CheckSequence}
  726. Inc(NrOfMods, InstrSinceLastMod[Reg]);
  727. PPaiProp(StartMod.OptInfo)^.Regs[Reg].NrOfMods := NrOfMods;
  728. InstrSinceLastMod[Reg] := 0;
  729. End
  730. Else
  731. DestroyReg(Reg, InstrSinceLastMod);
  732. *)
  733. End;
  734. Procedure TPaiProp.ModifyOp(const oper: TOper; var InstrSinceLastMod:
  735. TInstrSinceLastMod);
  736. Begin
  737. If oper.typ = top_reg Then
  738. ModifyReg(RegMaxSize(oper.reg),InstrSinceLastMod)
  739. Else
  740. Begin
  741. ReadOp(oper);
  742. DestroyOp(oper, InstrSinceLastMod);
  743. End
  744. End;
  745. Procedure TPaiProp.IncWState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  746. Begin
  747. //!!!! IncState(Regs[Reg].WState);
  748. End;
  749. Procedure TPaiProp.IncRState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  750. Begin
  751. //!!!! IncState(Regs[Reg].RState);
  752. End;
  753. Function TPaiProp.GetWState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  754. Begin
  755. Result:=0; { unimplemented }
  756. //!!!! GetWState := Regs[Reg].WState
  757. End;
  758. Function TPaiProp.GetRState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  759. Begin
  760. Result:=0; { unimplemented }
  761. //!!!! GetRState := Regs[Reg].RState
  762. End;
  763. Function TPaiProp.GetRegContentType(Reg: TRegister): Byte; {$ifdef inl} inline;{$endif inl}
  764. Begin
  765. Result:=0; { unimplemented }
  766. //!!!! GetRegContentType := Regs[Reg].typ
  767. End;
  768. Destructor TPaiProp.Done;
  769. Begin
  770. //!!!! UsedRegs.Done;
  771. //!!!! CondRegs.Done;
  772. { DirFlag: TFlagContents; I386 specific}
  773. End;
  774. { ************************ private TPaiProp stuff ************************* }
  775. Procedure TPaiProp.IncState(Var s: TStateInt); {$ifdef inl} inline;{$endif inl}
  776. Begin
  777. If s <> High(TStateInt) Then Inc(s)
  778. Else s := 0
  779. End;
  780. class Function TPaiProp.RefInInstruction(Const Ref: TReference; p: Tai;
  781. RefsEq: TRefCompare): Boolean;
  782. Var Count: AWord;
  783. TmpResult: Boolean;
  784. Begin
  785. TmpResult := False;
  786. If (p.typ = ait_instruction) Then
  787. Begin
  788. Count := 0;
  789. Repeat
  790. If (TInstr(p).oper[Count]^.typ = Top_Ref) Then
  791. TmpResult := RefsEq(Ref, PInstr(p)^.oper[Count]^.ref^);
  792. Inc(Count);
  793. Until (Count = max_operands) or TmpResult;
  794. End;
  795. RefInInstruction := TmpResult;
  796. End;
  797. class function TPaiProp.RefInSequence(Const Ref: TReference; Content: TContent;
  798. RefsEq: TRefCompare): Boolean;
  799. Var p: Tai;
  800. Counter: Byte;
  801. TmpResult: Boolean;
  802. Begin
  803. p := Content.StartMod;
  804. TmpResult := False;
  805. Counter := 1;
  806. While Not(TmpResult) And
  807. (Counter <= Content.NrOfMods) Do
  808. Begin
  809. If (p.typ = ait_instruction) And
  810. RefInInstruction(Ref, p, @references_equal)
  811. Then TmpResult := True;
  812. Inc(Counter);
  813. GetNextInstruction(p,p)
  814. End;
  815. RefInSequence := TmpResult
  816. End;
  817. { ************************************************************************* }
  818. { ***************************** TAoptObj ********************************** }
  819. { ************************************************************************* }
  820. Constructor TAoptObj.create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  821. _LabelInfo: PLabelInfo);
  822. Begin
  823. AsmL := _AsmL;
  824. BlockStart := _BlockStart;
  825. BlockEnd := _BlockEnd;
  826. LabelInfo := _LabelInfo;
  827. CreateUsedRegs(UsedRegs);
  828. End;
  829. destructor TAOptObj.Destroy;
  830. var
  831. i : TRegisterType;
  832. begin
  833. for i:=low(TRegisterType) to high(TRegisterType) do
  834. UsedRegs[i].Destroy;
  835. inherited Destroy;
  836. end;
  837. {$ifdef DEBUG_AOPTOBJ}
  838. procedure TAOptObj.DebugMsg(const s: string;p : tai);
  839. begin
  840. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  841. end;
  842. {$else DEBUG_AOPTOBJ}
  843. procedure TAOptObj.DebugMsg(const s: string;p : tai);inline;
  844. begin
  845. end;
  846. {$endif DEBUG_AOPTOBJ}
  847. procedure TAOptObj.CreateUsedRegs(var regs: TAllUsedRegs);
  848. var
  849. i : TRegisterType;
  850. begin
  851. for i:=low(TRegisterType) to high(TRegisterType) do
  852. Regs[i]:=TUsedRegs.Create(i);
  853. end;
  854. procedure TAOptObj.ClearUsedRegs;
  855. var
  856. i : TRegisterType;
  857. begin
  858. for i:=low(TRegisterType) to high(TRegisterType) do
  859. UsedRegs[i].Clear;
  860. end;
  861. { If UpdateUsedRegsAndOptimize has read ahead, the result is one before
  862. the next valid entry (so "p.Next" returns what's expected). If no
  863. reading ahead happened, then the result is equal to p. }
  864. function TAOptObj.UpdateUsedRegsAndOptimize(p : Tai): Tai;
  865. var
  866. NotFirst: Boolean;
  867. begin
  868. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  869. the code is duplicated here }
  870. Result := p;
  871. if (p.typ in [ait_instruction, ait_label]) then
  872. begin
  873. if (p.next <> BlockEnd) and (tai(p.next).typ <> ait_instruction) then
  874. begin
  875. { Advance one, otherwise the routine exits immediately and wastes time }
  876. p := tai(p.Next);
  877. NotFirst := True;
  878. end
  879. else
  880. { If the next entry is an instruction, nothing will be updated or
  881. optimised here, so exit now to save time }
  882. Exit;
  883. end
  884. else
  885. NotFirst := False;
  886. repeat
  887. while assigned(p) and
  888. ((p.typ in (SkipInstr + [ait_label] - [ait_RegAlloc])) or
  889. ((p.typ = ait_marker) and
  890. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  891. begin
  892. prefetch(pointer(p.Next)^);
  893. { Here's the optimise part }
  894. if (p.typ in [ait_align, ait_label]) then
  895. begin
  896. if StripDeadLabels(p, p) then
  897. begin
  898. { Note, if the first instruction is stripped and is
  899. the only one that gets removed, Result will now
  900. contain a dangling pointer, so compensate for this. }
  901. if not NotFirst then
  902. Result := tai(p.Previous);
  903. Continue;
  904. end;
  905. if ((p.typ = ait_label) and not labelCanBeSkipped(tai_label(p))) then
  906. Break;
  907. end;
  908. Result := p;
  909. p := tai(p.next);
  910. end;
  911. while assigned(p) and
  912. (p.typ=ait_RegAlloc) Do
  913. begin
  914. prefetch(pointer(p.Next)^);
  915. case tai_regalloc(p).ratype of
  916. ra_alloc :
  917. Include(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  918. ra_dealloc :
  919. Exclude(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  920. else
  921. { Do nothing };
  922. end;
  923. Result := p;
  924. p := tai(p.next);
  925. end;
  926. NotFirst := True;
  927. until not(assigned(p)) or
  928. (not(p.typ in SkipInstr) and
  929. not((p.typ = ait_label) and
  930. labelCanBeSkipped(tai_label(p))));
  931. end;
  932. procedure TAOptObj.UpdateUsedRegs(p : Tai); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  933. begin
  934. UpdateUsedRegs(UsedRegs, p);
  935. end;
  936. class function TAOptObj.GetNextRegUpdatePoint(var p : Tai; pTerm: tai): Boolean;
  937. begin
  938. Result := False; { Needed to suppress compiler warning }
  939. while SetAndTest(Assigned(p) and (p <> pTerm), Result) and
  940. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  941. ((p.typ = ait_label) and
  942. labelCanBeSkipped(tai_label(p))) or
  943. ((p.typ = ait_marker) and
  944. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd])) or
  945. (
  946. Assigned(pTerm) and { Causes p to stop on any live label or instruction if pTerm is nil }
  947. (p.typ in [ait_label, ait_instruction])
  948. )
  949. ) do
  950. p := tai(p.next);
  951. end;
  952. class procedure TAOptObj.UpdateReg(var Regs : TAllUsedRegs; p: tai_regalloc);
  953. begin
  954. case tai_regalloc(p).ratype of
  955. ra_alloc :
  956. Include(Regs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  957. ra_dealloc :
  958. Exclude(Regs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  959. else
  960. ;
  961. end;
  962. end;
  963. class procedure TAOptObj.UpdateUsedRegs(var Regs : TAllUsedRegs;p : Tai);
  964. begin
  965. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  966. the code is duplicated here }
  967. repeat
  968. if not GetNextRegUpdatePoint(p, nil) then
  969. Exit;
  970. while assigned(p) and
  971. (p.typ=ait_RegAlloc) Do
  972. begin
  973. prefetch(pointer(p.Next)^);
  974. UpdateReg(Regs, tai_regalloc(p));
  975. p := tai(p.next);
  976. end;
  977. until not(assigned(p)) or
  978. (not(p.typ in SkipInstr) and
  979. not((p.typ = ait_label) and
  980. labelCanBeSkipped(tai_label(p))));
  981. end;
  982. class procedure TAOptObj.UpdateUsedRegsBetween(var Regs: TAllUsedRegs; p1, p2: Tai);
  983. begin
  984. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  985. the code is duplicated here }
  986. repeat
  987. if not GetNextRegUpdatePoint(p1, p2) then
  988. Exit;
  989. while assigned(p1) and (p1 <> p2) and
  990. (p1.typ=ait_RegAlloc) Do
  991. begin
  992. prefetch(pointer(p1.Next)^);
  993. UpdateReg(Regs, tai_regalloc(p1));
  994. p1 := tai(p1.next);
  995. end;
  996. { Only stop if either p2 or a terminating marker is reached }
  997. until not Assigned(p1) or (p1 = p2) or
  998. not (p1.typ in (SkipInstr + [ait_label, ait_instruction])) or
  999. (
  1000. (p1.typ = ait_marker) and
  1001. not (tai_Marker(p1).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd])
  1002. );
  1003. if (p1 <> p2) then
  1004. { Reached the end of the procedure or a terminating marker that wasn't p2 }
  1005. InternalError(2022010701);
  1006. end;
  1007. function TAOptObj.CopyUsedRegs(var dest: TAllUsedRegs): boolean;
  1008. var
  1009. i : TRegisterType;
  1010. begin
  1011. Result:=true;
  1012. for i:=low(TRegisterType) to high(TRegisterType) do
  1013. dest[i]:=TUsedRegs.Create_Regset(i,UsedRegs[i].GetUsedRegs);
  1014. end;
  1015. procedure TAOptObj.RestoreUsedRegs(const Regs: TAllUsedRegs);
  1016. var
  1017. i : TRegisterType;
  1018. begin
  1019. { Note that the constructor Create_Regset is being called as a regular
  1020. method - it is not instantiating a new object. This is because it is
  1021. the only published means to modify the internal state en-masse. [Kit] }
  1022. for i:=low(TRegisterType) to high(TRegisterType) do
  1023. UsedRegs[i].Create_Regset(i,Regs[i].GetUsedRegs);
  1024. end;
  1025. procedure TAOptObj.TransferUsedRegs(var dest: TAllUsedRegs);
  1026. var
  1027. i : TRegisterType;
  1028. begin
  1029. { Note that the constructor Create_Regset is being called as a regular
  1030. method - it is not instantiating a new object. This is because it is
  1031. the only published means to modify the internal state en-masse. [Kit] }
  1032. for i:=low(TRegisterType) to high(TRegisterType) do
  1033. dest[i].Create_Regset(i, UsedRegs[i].GetUsedRegs);
  1034. end;
  1035. class procedure TAOptObj.ReleaseUsedRegs(const regs: TAllUsedRegs);
  1036. var
  1037. i : TRegisterType;
  1038. begin
  1039. for i:=low(TRegisterType) to high(TRegisterType) do
  1040. regs[i].Free;
  1041. end;
  1042. class Function TAOptObj.RegInUsedRegs(reg : TRegister; var regs : TAllUsedRegs) : boolean;
  1043. begin
  1044. result:=regs[getregtype(reg)].IsUsed(reg);
  1045. end;
  1046. class procedure TAOptObj.IncludeRegInUsedRegs(reg: TRegister;
  1047. var regs: TAllUsedRegs); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  1048. begin
  1049. include(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  1050. end;
  1051. class procedure TAOptObj.ExcludeRegFromUsedRegs(reg: TRegister;
  1052. var regs: TAllUsedRegs); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  1053. begin
  1054. exclude(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  1055. end;
  1056. class function TAOptObj.GetAllocationString(const regs: TAllUsedRegs): string;
  1057. var
  1058. i : TRegisterType;
  1059. j : TSuperRegister;
  1060. begin
  1061. Result:='';
  1062. for i:=low(TRegisterType) to high(TRegisterType) do
  1063. for j in regs[i].UsedRegs do
  1064. Result:=Result+std_regname(newreg(i,j,R_SUBWHOLE))+' ';
  1065. end;
  1066. class function TAOptObj.FindLabel(L: TasmLabel; Var hp: Tai): Boolean;
  1067. Var TempP: Tai;
  1068. Begin
  1069. TempP := hp;
  1070. While Assigned(TempP) and
  1071. (TempP.typ In SkipInstr + [ait_label,ait_align]) Do
  1072. If (TempP.typ <> ait_Label) Or
  1073. (Tai_label(TempP).labsym <> L)
  1074. Then GetNextInstruction(TempP, TempP)
  1075. Else
  1076. Begin
  1077. hp := TempP;
  1078. FindLabel := True;
  1079. exit
  1080. End;
  1081. FindLabel := False;
  1082. End;
  1083. Procedure TAOptObj.InsertLLItem(prev, foll, new_one : TLinkedListItem);
  1084. Begin
  1085. If Assigned(prev) Then
  1086. If Assigned(foll) Then
  1087. Begin
  1088. If Assigned(new_one) Then
  1089. Begin
  1090. new_one.previous := prev;
  1091. new_one.next := foll;
  1092. prev.next := new_one;
  1093. foll.previous := new_one;
  1094. { should we update line information? }
  1095. if (not (tai(new_one).typ in SkipLineInfo)) and
  1096. (not (tai(foll).typ in SkipLineInfo)) then
  1097. Tailineinfo(new_one).fileinfo := Tailineinfo(foll).fileinfo
  1098. End
  1099. End
  1100. Else AsmL.Concat(new_one)
  1101. Else If Assigned(Foll) Then AsmL.Insert(new_one)
  1102. End;
  1103. class function TAOptObj.SkipHead(P: Tai): Tai;
  1104. Var OldP: Tai;
  1105. Begin
  1106. Repeat
  1107. OldP := P;
  1108. If (P.typ in SkipInstr) Or
  1109. ((P.typ = ait_marker) And
  1110. (Tai_Marker(P).Kind = mark_AsmBlockEnd)) Then
  1111. GetNextInstruction(P, P)
  1112. Else If ((P.Typ = Ait_Marker) And
  1113. (Tai_Marker(P).Kind = mark_NoPropInfoStart)) Then
  1114. { a marker of the type mark_NoPropInfoStart can't be the first instruction of a }
  1115. { paasmoutput list }
  1116. GetNextInstruction(Tai(P.Previous),P);
  1117. If (P.Typ = Ait_Marker) And
  1118. (Tai_Marker(P).Kind = mark_AsmBlockStart) Then
  1119. Begin
  1120. P := Tai(P.Next);
  1121. While (P.typ <> Ait_Marker) Or
  1122. (Tai_Marker(P).Kind <> mark_AsmBlockEnd) Do
  1123. P := Tai(P.Next)
  1124. End;
  1125. Until P = OldP;
  1126. SkipHead := P;
  1127. End;
  1128. class function TAOptObj.OpsEqual(const o1,o2:toper): Boolean;
  1129. Begin
  1130. if o1.typ=o2.typ then
  1131. Case o1.typ Of
  1132. Top_Reg :
  1133. OpsEqual:=o1.reg=o2.reg;
  1134. Top_Ref :
  1135. OpsEqual:=
  1136. references_equal(o1.ref^, o2.ref^) and
  1137. (o1.ref^.volatility=[]) and
  1138. (o2.ref^.volatility=[]);
  1139. Top_Const :
  1140. OpsEqual:=o1.val=o2.val;
  1141. Top_None :
  1142. OpsEqual := True
  1143. else OpsEqual := False
  1144. End
  1145. else
  1146. OpsEqual := False;
  1147. End;
  1148. class function TAOptObj.FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  1149. Begin
  1150. Result:=nil;
  1151. Repeat
  1152. While Assigned(StartPai) And
  1153. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  1154. {$ifdef cpudelayslot}
  1155. ((startpai.typ=ait_instruction) and (taicpu(startpai).opcode=A_NOP)) or
  1156. {$endif cpudelayslot}
  1157. ((StartPai.typ = ait_label) and
  1158. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1159. StartPai := Tai(StartPai.Next);
  1160. If Assigned(StartPai) And
  1161. (StartPai.typ = ait_regAlloc) Then
  1162. Begin
  1163. if (tai_regalloc(StartPai).ratype=ra_alloc) and
  1164. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  1165. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  1166. begin
  1167. Result:=tai_regalloc(StartPai);
  1168. exit;
  1169. end;
  1170. StartPai := Tai(StartPai.Next);
  1171. End
  1172. else
  1173. exit;
  1174. Until false;
  1175. End;
  1176. class function TAOptObj.FindRegAllocBackward(Reg: TRegister; StartPai: Tai): tai_regalloc;
  1177. Begin
  1178. Result:=nil;
  1179. Repeat
  1180. While Assigned(StartPai) And
  1181. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  1182. ((StartPai.typ = ait_label) and
  1183. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1184. StartPai := Tai(StartPai.Previous);
  1185. If Assigned(StartPai) And
  1186. (StartPai.typ = ait_regAlloc) Then
  1187. Begin
  1188. if SuperRegistersEqual(tai_regalloc(StartPai).Reg,Reg) then
  1189. begin
  1190. { If we find a dealloc first, say, return nil }
  1191. if (tai_regalloc(StartPai).ratype<>ra_dealloc) then
  1192. Result:=tai_regalloc(StartPai);
  1193. exit;
  1194. end;
  1195. StartPai := Tai(StartPai.Previous);
  1196. End
  1197. else
  1198. exit;
  1199. Until false;
  1200. End;
  1201. class function TAOptObj.FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  1202. Begin
  1203. Result:=nil;
  1204. Repeat
  1205. While Assigned(StartPai) And
  1206. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  1207. ((StartPai.typ = ait_label) and
  1208. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1209. StartPai := Tai(StartPai.Next);
  1210. If Assigned(StartPai) And
  1211. (StartPai.typ = ait_regAlloc) Then
  1212. Begin
  1213. if (tai_regalloc(StartPai).ratype=ra_dealloc) and
  1214. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  1215. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  1216. begin
  1217. Result:=tai_regalloc(StartPai);
  1218. exit;
  1219. end;
  1220. StartPai := Tai(StartPai.Next);
  1221. End
  1222. else
  1223. exit;
  1224. Until false;
  1225. End;
  1226. class function TAOptObj.FindTempDeAlloc(Offset: ASizeInt; StartPai: Tai): tai_tempalloc;
  1227. Begin
  1228. Result:=nil;
  1229. Repeat
  1230. While Assigned(StartPai) And
  1231. ((StartPai.typ in (SkipInstr - [ait_tempalloc])) Or
  1232. ((StartPai.typ = ait_label) and
  1233. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1234. StartPai := Tai(StartPai.Next);
  1235. If Assigned(StartPai) And
  1236. (StartPai.typ = ait_tempalloc) Then
  1237. Begin
  1238. if not(tai_tempalloc(StartPai).allocation) and
  1239. (tai_tempalloc(StartPai).temppos = Offset) then
  1240. begin
  1241. Result:=tai_tempalloc(StartPai);
  1242. exit;
  1243. end;
  1244. StartPai := Tai(StartPai.Next);
  1245. End
  1246. else
  1247. exit;
  1248. Until false;
  1249. End;
  1250. { allocates register reg between (and including) instructions p1 and p2
  1251. the type of p1 and p2 must not be in SkipInstr }
  1252. procedure TAOptObj.AllocRegBetween(reg: tregister; p1, p2: tai; var initialusedregs: TAllUsedRegs);
  1253. var
  1254. hp, start: tai;
  1255. Po: PInteger;
  1256. removedsomething,
  1257. firstRemovedWasAlloc,
  1258. lastRemovedWasDealloc: boolean;
  1259. begin
  1260. {$ifdef EXTDEBUG}
  1261. { if assigned(p1.optinfo) and
  1262. (ptaiprop(p1.optinfo)^.usedregs <> initialusedregs) then
  1263. internalerror(2004101010); }
  1264. {$endif EXTDEBUG}
  1265. if not Assigned(p2) then
  1266. { We need a valid final instruction }
  1267. InternalError(2022010401);
  1268. start := p1;
  1269. if (reg = NR_STACK_POINTER_REG) or
  1270. (reg = current_procinfo.framepointer) or
  1271. not(assigned(p1)) then
  1272. { this happens with registers which are loaded implicitely, outside the }
  1273. { current block (e.g. esi with self) }
  1274. exit;
  1275. {$ifdef allocregdebug}
  1276. insertllitem(p1.previous,p1,tai_comment.Create(strpnew('allocating '+std_regname(reg)+' from here...')));
  1277. insertllitem(p2,p2.next,tai_comment.Create(strpnew('allocated '+std_regname(reg)+' till here...')));
  1278. {$endif allocregdebug}
  1279. { make sure we allocate it for this instruction }
  1280. getnextinstruction(p2,p2);
  1281. lastRemovedWasDealloc := false;
  1282. removedSomething := false;
  1283. firstRemovedWasAlloc := false;
  1284. { do it the safe way: always allocate the full super register,
  1285. as we do no register re-allocation in the peephole optimizer,
  1286. this does not hurt
  1287. }
  1288. case getregtype(reg) of
  1289. R_MMREGISTER:
  1290. reg:=newreg(R_MMREGISTER,getsupreg(reg),R_SUBMMWHOLE);
  1291. R_INTREGISTER:
  1292. reg:=newreg(R_INTREGISTER,getsupreg(reg),R_SUBWHOLE);
  1293. R_FPUREGISTER:
  1294. reg:=newreg(R_FPUREGISTER,getsupreg(reg),R_SUBWHOLE);
  1295. R_ADDRESSREGISTER:
  1296. reg:=newreg(R_ADDRESSREGISTER,getsupreg(reg),R_SUBWHOLE);
  1297. R_SPECIALREGISTER:
  1298. reg:=newreg(R_SPECIALREGISTER,getsupreg(reg),R_SUBWHOLE);
  1299. else
  1300. Internalerror(2018030701);
  1301. end;
  1302. if not(RegInUsedRegs(reg,initialusedregs)) then
  1303. begin
  1304. hp := tai_regalloc.alloc(reg,nil);
  1305. insertllItem(p1.previous,p1,hp);
  1306. IncludeRegInUsedRegs(reg,initialusedregs);
  1307. lastRemovedWasDealloc := True; { If no tai_regallocs are found at all, treat as if the last one was a deallocation }
  1308. end;
  1309. while assigned(p1) and
  1310. (p1 <> p2) do
  1311. begin
  1312. if assigned(p1.optinfo) then
  1313. internalerror(2014022301); // IncludeRegInUsedRegs(reg,ptaiprop(p1.optinfo)^.usedregs);
  1314. p1 := tai(p1.next);
  1315. repeat
  1316. while assigned(p1) and
  1317. (p1.typ in (SkipInstr-[ait_regalloc])) Do
  1318. p1 := tai(p1.next);
  1319. { remove all allocation/deallocation info about the register in between }
  1320. if assigned(p1) and
  1321. (p1.typ = ait_regalloc) then
  1322. begin
  1323. { same super register, different sub register? }
  1324. if SuperRegistersEqual(reg,tai_regalloc(p1).reg) and (tai_regalloc(p1).reg<>reg) then
  1325. begin
  1326. if (getsubreg(reg)<>R_SUBMMWHOLE) and { R_SUBMMWHOLE is below R_SUBMMX, R_SUBMMY and R_SUBMMZ }
  1327. ((getsubreg(tai_regalloc(p1).reg)>getsubreg(reg)) or (getsubreg(reg)=R_SUBH)) then
  1328. internalerror(2016101501);
  1329. tai_regalloc(p1).reg:=reg;
  1330. end;
  1331. if tai_regalloc(p1).reg=reg then
  1332. begin
  1333. if not removedSomething then
  1334. begin
  1335. firstRemovedWasAlloc := tai_regalloc(p1).ratype=ra_alloc;
  1336. removedSomething := true;
  1337. end;
  1338. lastRemovedWasDealloc := (tai_regalloc(p1).ratype=ra_dealloc);
  1339. hp := tai(p1.Next);
  1340. asml.Remove(p1);
  1341. p1.free;
  1342. p1 := hp;
  1343. end
  1344. else
  1345. p1 := tai(p1.next);
  1346. end;
  1347. until not(assigned(p1)) or
  1348. not(p1.typ in SkipInstr);
  1349. end;
  1350. if assigned(p1) then
  1351. begin
  1352. if firstRemovedWasAlloc then
  1353. begin
  1354. hp := tai_regalloc.Alloc(reg,nil);
  1355. insertLLItem(start.previous,start,hp);
  1356. end;
  1357. if lastRemovedWasDealloc then
  1358. begin
  1359. hp := tai_regalloc.DeAlloc(reg,nil);
  1360. insertLLItem(p1.previous,p1,hp);
  1361. end;
  1362. end;
  1363. end;
  1364. function TAOptObj.RegUsedAfterInstruction(reg: Tregister; p: tai;var AllUsedRegs: TAllUsedRegs): Boolean;
  1365. begin
  1366. AllUsedRegs[getregtype(reg)].Update(tai(p.Next),true);
  1367. RegUsedAfterInstruction :=
  1368. AllUsedRegs[getregtype(reg)].IsUsed(reg) and
  1369. not(regLoadedWithNewValue(reg,p)) and
  1370. (
  1371. not(GetNextInstruction(p,p)) or
  1372. InstructionLoadsFromReg(reg,p) or
  1373. not(regLoadedWithNewValue(reg,p))
  1374. );
  1375. end;
  1376. function TAOptObj.RegEndOfLife(reg : TRegister;p : taicpu) : boolean;
  1377. begin
  1378. Result:=assigned(FindRegDealloc(reg,tai(p.Next))) or
  1379. RegLoadedWithNewValue(reg,p);
  1380. end;
  1381. function TAOptObj.RemoveCurrentP(var p : tai) : boolean;
  1382. var
  1383. hp1 : tai;
  1384. begin
  1385. result:=GetNextInstruction(p,hp1);
  1386. { p will be removed, update used register as we continue
  1387. with the next instruction after p }
  1388. UpdateUsedRegs(tai(p.Next));
  1389. AsmL.Remove(p);
  1390. p.Free;
  1391. p:=hp1;
  1392. end;
  1393. procedure TAOptObj.RemoveCurrentP(var p: tai; const hp1: tai); inline;
  1394. begin
  1395. if (p=hp1) then
  1396. internalerror(2020120501);
  1397. UpdateUsedRegs(tai(p.Next));
  1398. AsmL.Remove(p);
  1399. p.Free;
  1400. p := hp1;
  1401. end;
  1402. procedure TAOptObj.RemoveInstruction(const hp: tai); inline;
  1403. begin
  1404. AsmL.Remove(hp);
  1405. hp.Free;
  1406. end;
  1407. function FindLiveLabel(hp: tai; var l: tasmlabel): Boolean;
  1408. var
  1409. next: tai;
  1410. begin
  1411. FindLiveLabel := false;
  1412. while True do
  1413. begin
  1414. while assigned(hp.next) and
  1415. (tai(hp.next).typ in (SkipInstr+[ait_align])) Do
  1416. hp := tai(hp.next);
  1417. next := tai(hp.next);
  1418. if assigned(next) and
  1419. (tai(next).typ = ait_label) then
  1420. begin
  1421. l := tai_label(next).labsym;
  1422. if not l.is_used then
  1423. begin
  1424. { Unsafe label }
  1425. hp := next;
  1426. Continue;
  1427. end;
  1428. FindLiveLabel := true;
  1429. end;
  1430. Exit;
  1431. end;
  1432. end;
  1433. {$push}
  1434. {$r-}
  1435. function TAOptObj.getlabelwithsym(sym: tasmlabel): tai;
  1436. begin
  1437. if (int64(sym.labelnr) >= int64(labelinfo^.lowlabel)) and
  1438. (int64(sym.labelnr) <= int64(labelinfo^.highlabel)) then { range check, a jump can go past an assembler block! }
  1439. getlabelwithsym := labelinfo^.labeltable[sym.labelnr-labelinfo^.lowlabel].paiobj
  1440. else
  1441. getlabelwithsym := nil;
  1442. end;
  1443. {$pop}
  1444. { Returns True if hp is an unconditional jump to a label }
  1445. function IsJumpToLabelUncond(hp: taicpu): boolean;
  1446. begin
  1447. {$if defined(avr) or defined(z80)}
  1448. result:=(hp.opcode in aopt_uncondjmp) and
  1449. {$else}
  1450. result:=(hp.opcode=aopt_uncondjmp) and
  1451. {$endif}
  1452. {$if defined(arm) or defined(aarch64) or defined(z80)}
  1453. (hp.condition=c_None) and
  1454. {$endif arm or aarch64 or z80}
  1455. (hp.ops>0) and
  1456. {$if defined(riscv32) or defined(riscv64)}
  1457. (hp.oper[0]^.reg=NR_X0) and
  1458. {$endif riscv}
  1459. (JumpTargetOp(hp)^.typ = top_ref) and
  1460. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1461. end;
  1462. { Returns True if hp is any jump to a label }
  1463. function IsJumpToLabel(hp: taicpu): boolean;
  1464. begin
  1465. result:=hp.is_jmp and
  1466. (hp.ops>0) and
  1467. (JumpTargetOp(hp)^.typ = top_ref) and
  1468. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1469. end;
  1470. procedure TAOptObj.RemoveDelaySlot(hp1:tai);
  1471. var
  1472. hp2: tai;
  1473. begin
  1474. hp2:=tai(hp1.next);
  1475. while assigned(hp2) and (hp2.typ in SkipInstr) do
  1476. hp2:=tai(hp2.next);
  1477. if assigned(hp2) and (hp2.typ=ait_instruction) and
  1478. (taicpu(hp2).opcode=A_NOP) then
  1479. begin
  1480. asml.remove(hp2);
  1481. hp2.free;
  1482. end;
  1483. { Anything except A_NOP must be left in place: these instructions
  1484. execute before branch, so code stays correct if branch is removed. }
  1485. end;
  1486. { Output debug message to console - null function if EXTDEBUG is not defined }
  1487. class procedure TAOptObj.DebugWrite(Message: string); inline;
  1488. begin
  1489. {$ifdef DEBUG_JUMP}
  1490. WriteLn(Message);
  1491. {$else DEBUG_JUMP}
  1492. { Do nothing }
  1493. {$endif DEBUG_JUMP}
  1494. end;
  1495. { Converts a conditional jump into an unconditional jump. Only call this
  1496. procedure on an instruction that you already know is a conditional jump }
  1497. procedure TAOptObj.MakeUnconditional(p: taicpu);
  1498. begin
  1499. { TODO: If anyone can improve this particular optimisation to work on
  1500. AVR, please do (it's currently not called at all). [Kit] }
  1501. {$if not defined(avr)}
  1502. {$if defined(powerpc) or defined(powerpc64)}
  1503. p.condition.cond := C_None;
  1504. p.condition.simple := True;
  1505. {$else powerpc}
  1506. p.condition := C_None;
  1507. {$endif powerpc}
  1508. {$ifndef z80}
  1509. p.opcode := aopt_uncondjmp;
  1510. {$endif not z80}
  1511. {$ifdef RISCV}
  1512. p.loadoper(1, p.oper[p.ops-1]^);
  1513. p.loadreg(0, NR_X0);
  1514. p.ops:=2;
  1515. {$endif}
  1516. {$ifdef xtensa}
  1517. p.opcode := aopt_uncondjmp;
  1518. p.loadoper(0, p.oper[p.ops-1]^);
  1519. p.ops:=1;
  1520. {$endif}
  1521. {$endif not avr}
  1522. {$ifdef mips}
  1523. { MIPS conditional jump instructions also conntain register
  1524. operands. A proper implementation is needed here. }
  1525. internalerror(2020071301);
  1526. {$endif}
  1527. end;
  1528. { Removes all instructions between an unconditional jump and the next label.
  1529. Returns True if a jump in between was removed (as it may open up new
  1530. optimisations if the label appeared earlier in the stream) }
  1531. function TAOptObj.RemoveDeadCodeAfterJump(p: tai): Boolean;
  1532. const
  1533. {$ifdef JVM}
  1534. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label, ait_jcatch];
  1535. {$else JVM}
  1536. { Stop if it reaches SEH directive information in the form of
  1537. consts, which may occur if RemoveDeadCodeAfterJump is called on
  1538. the final RET instruction on x86, for example }
  1539. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label];
  1540. {$endif JVM}
  1541. var
  1542. hp1, hp2: tai;
  1543. begin
  1544. { the following code removes all code between a jmp and the next label,
  1545. because it can never be executed
  1546. }
  1547. Result := False;
  1548. while GetNextInstruction(p, hp1) and
  1549. (hp1 <> BlockEnd) and
  1550. not (hp1.typ in TaiFence) do
  1551. begin
  1552. if (hp1.typ = ait_instruction) and
  1553. taicpu(hp1).is_jmp and
  1554. (JumpTargetOp(taicpu(hp1))^.typ = top_ref) and
  1555. (JumpTargetOp(taicpu(hp1))^.ref^.symbol is TAsmLabel) then
  1556. begin
  1557. { If the destination label appears earlier, it may permit
  1558. further optimisations, so signal this in the Result }
  1559. Result := True;
  1560. TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).decrefs;
  1561. end;
  1562. { don't kill start/end of assembler block,
  1563. no-line-info-start/end etc }
  1564. if (hp1.typ<>ait_marker) and
  1565. ((hp1.typ<>ait_cfi) or
  1566. (tai_cfi_base(hp1).cfityp<>cfi_endproc)) then
  1567. begin
  1568. {$ifdef cpudelayslot}
  1569. if (hp1.typ=ait_instruction) and (taicpu(hp1).is_jmp) then
  1570. RemoveDelaySlot(hp1);
  1571. {$endif cpudelayslot}
  1572. hp2 := hp1;
  1573. while (hp2.typ = ait_align) do
  1574. begin
  1575. { Only remove the align if a label doesn't immediately follow }
  1576. if GetNextInstruction(hp2, hp2) and (hp2.typ = ait_label) then
  1577. { The label is unskippable }
  1578. Exit;
  1579. { Check again in case there's more than one adjacent alignment entry
  1580. (a frequent construct under x86, for example). [Kit] }
  1581. end;
  1582. asml.remove(hp1);
  1583. hp1.free;
  1584. end
  1585. else
  1586. p:=hp1;
  1587. end;
  1588. end;
  1589. { If hp is a label, strip it if its reference count is zero. Repeat until
  1590. a non-label is found, or a label with a non-zero reference count.
  1591. True is returned if something was stripped }
  1592. function TAOptObj.StripDeadLabels(hp: tai; var NextValid: tai): Boolean;
  1593. var
  1594. tmp, tmpNext: tai;
  1595. hp1: tai;
  1596. CurrentAlign: tai;
  1597. FoundLabels: Boolean;
  1598. begin
  1599. CurrentAlign := nil;
  1600. Result := False;
  1601. hp1 := hp;
  1602. NextValid := hp;
  1603. { Stop if hp is an instruction, for example }
  1604. while (hp1 <> BlockEnd) and (hp1.typ in [ait_label,ait_align]) do
  1605. begin
  1606. prefetch(pointer(hp1.Next)^);
  1607. case hp1.typ of
  1608. ait_label:
  1609. begin
  1610. { Set tmp to the next valid entry }
  1611. tmp := tai(hp1.Next);
  1612. with tai_label(hp1).labsym do
  1613. begin
  1614. if (labeltype <> alt_jump) then
  1615. begin
  1616. { Non-jump label - skip over }
  1617. hp1 := tmp;
  1618. Continue;
  1619. end;
  1620. if is_used or (bind <> AB_LOCAL) then
  1621. begin
  1622. { Valid label }
  1623. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1624. Exit;
  1625. end;
  1626. end;
  1627. DebugWrite('JUMP DEBUG: Removed label ' + tostr(TAsmLabel(tai_label(hp1).labsym).labelnr));
  1628. { Remove label }
  1629. if (NextValid = hp1) then
  1630. NextValid := tmp;
  1631. RemoveInstruction(hp1);
  1632. hp1 := tmp;
  1633. Result := True;
  1634. Continue;
  1635. end;
  1636. { Also remove the align if it comes before an unused label }
  1637. ait_align:
  1638. begin
  1639. { Signal that we can possibly delete this align entry }
  1640. CurrentAlign := hp1;
  1641. tmp := tai(hp1.Next);
  1642. if tmp = BlockEnd then
  1643. { End of block }
  1644. Exit;
  1645. repeat
  1646. case tmp.typ of
  1647. ait_align: { Merge the aligns if permissible }
  1648. begin
  1649. { Check the maxbytes field though, since this may result in the
  1650. alignment being ignored }
  1651. if ((tai_align_abstract(hp1).maxbytes = 0) and (tai_align_abstract(tmp).maxbytes = 0)) or
  1652. { If a maxbytes field is present, only merge if the aligns have the same granularity }
  1653. ((tai_align_abstract(hp1).aligntype = tai_align_abstract(tmp).aligntype)) then
  1654. begin
  1655. with tai_align_abstract(hp1) do
  1656. begin
  1657. aligntype := max(aligntype, tai_align_abstract(tmp).aligntype);
  1658. maxbytes := max(maxbytes, tai_align_abstract(tmp).maxbytes);
  1659. fillsize := max(fillsize, tai_align_abstract(tmp).fillsize);
  1660. use_op := use_op or tai_align_abstract(tmp).use_op;
  1661. if use_op and (tai_align_abstract(tmp).fillop <> 0) then
  1662. fillop := tai_align_abstract(tmp).fillop;
  1663. end;
  1664. tmpNext := tai(tmp.Next);
  1665. RemoveInstruction(tmp);
  1666. Result := True;
  1667. tmp := tmpNext;
  1668. end
  1669. else
  1670. tmp := tai(tmp.Next);
  1671. Continue;
  1672. end;
  1673. ait_label:
  1674. begin
  1675. repeat
  1676. with tai_label(tmp).labsym do
  1677. begin
  1678. { alt_addr is needed so alignment directives before
  1679. jump tables e.g. for arm thumb are not removed }
  1680. if not(labeltype in [alt_addr,alt_jump]) then
  1681. begin
  1682. { Non-jump label - skip over }
  1683. tmp := tai(tmp.Next);
  1684. Continue;
  1685. end;
  1686. if is_used or (bind <> AB_LOCAL) then
  1687. begin
  1688. { Valid label }
  1689. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1690. Exit;
  1691. end;
  1692. end;
  1693. DebugWrite('JUMP DEBUG: Removed label ' + tai_label(tmp).labsym.name);
  1694. { Remove label }
  1695. tmpNext := tai(tmp.Next);
  1696. RemoveInstruction(tmp);
  1697. Result := True;
  1698. tmp := tmpNext;
  1699. { Loop here for a minor performance gain }
  1700. until (tmp = BlockEnd) or (tmp.typ <> ait_label);
  1701. { Re-evaluate the align and see what follows }
  1702. Continue;
  1703. end
  1704. else
  1705. begin
  1706. if tmp.typ in SkipInstr then
  1707. begin
  1708. tmp := tai(tmp.Next);
  1709. Continue;
  1710. end;
  1711. { Set hp1 to the instruction after the align, because the
  1712. align might get deleted later and hence set NextValid
  1713. to a dangling pointer. [Kit] }
  1714. hp1 := tmp;
  1715. Break;
  1716. end;
  1717. end;
  1718. until (tmp = BlockEnd);
  1719. { Break out of the outer loop if the above Break is called }
  1720. if (hp1 = tmp) then
  1721. Break;
  1722. end
  1723. else
  1724. Break;
  1725. end;
  1726. hp1 := tai(hp1.Next);
  1727. end;
  1728. if Assigned(CurrentAlign) then
  1729. begin
  1730. { Remember what the first one was }
  1731. tmpNext := CurrentAlign;
  1732. { Remove the alignment field (but only if the next valid entry is not a live label) }
  1733. repeat
  1734. tmp := tai(CurrentAlign.next);
  1735. { Any labels found are non-jump labels and will be skipped over }
  1736. if CurrentAlign.typ = ait_align then
  1737. begin
  1738. DebugWrite('JUMP DEBUG: Alignment field removed');
  1739. RemoveInstruction(CurrentAlign);
  1740. end;
  1741. CurrentAlign := tmp;
  1742. until not Assigned(CurrentAlign) or not (CurrentAlign.typ in [ait_align, ait_label]);
  1743. if (NextValid = tmpNext) then
  1744. NextValid := tmp;
  1745. end;
  1746. end;
  1747. { Strips a label and any aligns that appear before it (if hp points to
  1748. them rather than the label). Only call this procedure on a label that
  1749. you already know is no longer referenced }
  1750. procedure TAOptObj.StripLabelFast(hp: tai);
  1751. var
  1752. tmp: tai;
  1753. begin
  1754. repeat
  1755. case hp.typ of
  1756. ait_align:
  1757. begin
  1758. tmp := tai(hp.Next);
  1759. asml.Remove(hp);
  1760. hp.Free;
  1761. hp := tmp;
  1762. { Control flow will now return to 'repeat' }
  1763. end;
  1764. ait_label:
  1765. begin
  1766. {$ifdef EXTDEBUG}
  1767. { When not in debug mode, deleting a live label will cause an
  1768. access violation later on. [Kit] }
  1769. if tai_label(hp).labsym.getrefs <> 0 then
  1770. InternalError(2019110802);
  1771. {$endif EXTDEBUG}
  1772. asml.Remove(hp);
  1773. hp.Free;
  1774. Exit;
  1775. end;
  1776. else
  1777. begin
  1778. { Might be a comment or temporary allocation entry }
  1779. if not (hp.typ in SkipInstr) then
  1780. InternalError(2019110801);
  1781. hp := tai(hp.Next);
  1782. end;
  1783. end;
  1784. until False;
  1785. end;
  1786. { If a group of labels are clustered, change the jump to point to the last one
  1787. that is still referenced }
  1788. function TAOptObj.CollapseLabelCluster(jump: tai; var lbltai: tai): TAsmLabel;
  1789. var
  1790. LastLabel: TAsmLabel;
  1791. hp2: tai;
  1792. begin
  1793. Result := tai_label(lbltai).labsym;
  1794. LastLabel := Result;
  1795. hp2 := tai(lbltai.next);
  1796. while (hp2 <> BlockEnd) and (hp2.typ in SkipInstr + [ait_align, ait_label]) do
  1797. begin
  1798. if (hp2.typ = ait_label) and
  1799. (tai_label(hp2).labsym.is_used) and
  1800. (tai_label(hp2).labsym.labeltype = alt_jump) then
  1801. LastLabel := tai_label(hp2).labsym;
  1802. hp2 := tai(hp2.next);
  1803. end;
  1804. if (Result <> LastLabel) then
  1805. begin
  1806. Result.decrefs;
  1807. JumpTargetOp(taicpu(jump))^.ref^.symbol := LastLabel;
  1808. LastLabel.increfs;
  1809. Result := LastLabel;
  1810. lbltai := hp2;
  1811. end;
  1812. end;
  1813. {$ifdef CPU_SUPPORTS_OPT_COND_JUMP}
  1814. function TAOptObj.OptimizeConditionalJump(CJLabel: TAsmLabel; var p: tai; hp1: tai; var stoploop: Boolean): Boolean;
  1815. var
  1816. hp2: tai;
  1817. NCJLabel: TAsmLabel;
  1818. begin
  1819. Result := False;
  1820. while (hp1 <> BlockEnd) do
  1821. begin
  1822. StripDeadLabels(hp1, hp1);
  1823. if (hp1 <> BlockEnd) and
  1824. (tai(hp1).typ=ait_instruction) and
  1825. IsJumpToLabel(taicpu(hp1)) then
  1826. begin
  1827. NCJLabel := TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol);
  1828. if IsJumpToLabelUncond(taicpu(hp1)) then
  1829. begin
  1830. { Do it now to get it out of the way and to aid optimisations
  1831. later on in this method }
  1832. if RemoveDeadCodeAfterJump(taicpu(hp1)) then
  1833. stoploop := False;
  1834. hp2 := getlabelwithsym(NCJLabel);
  1835. if Assigned(hp2) then
  1836. { Collapse the cluster now to aid optimisation and potentially
  1837. cut down on the number of iterations required }
  1838. NCJLabel := CollapseLabelCluster(hp1, hp2);
  1839. { GetNextInstruction could be factored out, but hp2 might be
  1840. different after "RemoveDeadCodeAfterJump" }
  1841. GetNextInstruction(hp1, hp2);
  1842. { Check for:
  1843. jmp<cond> @Lbl
  1844. jmp @Lbl
  1845. }
  1846. if (CJLabel = NCJLabel) then
  1847. begin
  1848. DebugMsg(SPeepholeOptimization+'Short-circuited conditional jump',p);
  1849. { Both jumps go to the same label }
  1850. CJLabel.decrefs;
  1851. {$ifdef cpudelayslot}
  1852. RemoveDelaySlot(p);
  1853. {$endif cpudelayslot}
  1854. RemoveCurrentP(p, hp1);
  1855. Result := True;
  1856. Exit;
  1857. end;
  1858. if FindLabel(CJLabel, hp2) then
  1859. begin
  1860. { change the following jumps:
  1861. jmp<cond> CJLabel jmp<inv_cond> NCJLabel
  1862. jmp NCJLabel >>> <code>
  1863. CJLabel: NCJLabel:
  1864. <code>
  1865. NCJLabel:
  1866. }
  1867. {$if defined(arm) or defined(aarch64)}
  1868. if (taicpu(p).condition<>C_None)
  1869. {$if defined(aarch64)}
  1870. { can't have conditional branches to
  1871. global labels on AArch64, because the
  1872. offset may become too big }
  1873. and (NCJLabel.bind=AB_LOCAL)
  1874. {$endif aarch64}
  1875. then
  1876. begin
  1877. {$endif arm or aarch64}
  1878. DebugMsg(SPeepholeOptimization+'Conditional jump inversion',p);
  1879. taicpu(p).condition:=inverse_cond(taicpu(p).condition);
  1880. CJLabel.decrefs;
  1881. JumpTargetOp(taicpu(p))^.ref^.symbol := NCJLabel;
  1882. { when freeing hp1, the reference count
  1883. isn't decreased, so don't increase }
  1884. {$ifdef cpudelayslot}
  1885. RemoveDelaySlot(hp1);
  1886. {$endif cpudelayslot}
  1887. RemoveInstruction(hp1);
  1888. stoploop := False;
  1889. if not CJLabel.is_used then
  1890. begin
  1891. CJLabel := NCJLabel;
  1892. StripDeadLabels(tai(p.Next), hp1);
  1893. if (hp1 = BlockEnd) then
  1894. Exit;
  1895. { Attempt another iteration in case more jumps follow }
  1896. if (hp1.typ in SkipInstr) then
  1897. GetNextInstruction(hp1, hp1);
  1898. Continue;
  1899. end;
  1900. {$if defined(arm) or defined(aarch64)}
  1901. end;
  1902. {$endif arm or aarch64}
  1903. end
  1904. else if CollapseZeroDistJump(hp1, NCJLabel) then
  1905. begin
  1906. if (hp1 = BlockEnd) then
  1907. Exit;
  1908. { Attempt another iteration in case more jumps follow }
  1909. if (hp1.typ in SkipInstr) then
  1910. GetNextInstruction(hp1, hp1);
  1911. Continue;
  1912. end;
  1913. end
  1914. else
  1915. begin
  1916. { Do not try to optimize if the test generating the condition
  1917. is the same instruction, like 'bne $v0,$zero,.Lj3' for MIPS }
  1918. if (taicpu(p).ops>1) or (taicpu(hp1).ops>1) then
  1919. exit;
  1920. { Check for:
  1921. jmp<cond1> @Lbl1
  1922. jmp<cond2> @Lbl2
  1923. Remove 2nd jump if conditions are equal or cond2 is a subset of cond1
  1924. (as if the first jump didn't branch, then neither will the 2nd)
  1925. }
  1926. if condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  1927. begin
  1928. DebugMsg(SPeepholeOptimization+'Dominated conditional jump',p);
  1929. NCJLabel.decrefs;
  1930. GetNextInstruction(hp1, hp2);
  1931. {$ifdef cpudelayslot}
  1932. RemoveDelaySlot(hp1);
  1933. {$endif cpudelayslot}
  1934. RemoveInstruction(hp1);
  1935. hp1 := hp2;
  1936. { Flag another pass in case @Lbl2 appeared earlier in the procedure and is now a dead label }
  1937. stoploop := False;
  1938. { Attempt another iteration in case more jumps follow }
  1939. Continue;
  1940. end;
  1941. { Check for:
  1942. jmp<cond1> @Lbl1
  1943. jmp<cond2> @Lbl2
  1944. And inv(cond1) is a subset of cond2 (e.g. je followed by jne, or jae followed by jbe) )
  1945. }
  1946. if condition_in(inverse_cond(taicpu(p).condition), taicpu(hp1).condition) then
  1947. begin
  1948. GetNextInstruction(hp1, hp2);
  1949. { If @lbl1 immediately follows jmp<cond2>, we can remove
  1950. the first jump completely }
  1951. if FindLabel(CJLabel, hp2) then
  1952. begin
  1953. { However, to be absolutely correct, cond2 must be changed to inv(cond1) }
  1954. taicpu(hp1).condition := inverse_cond(taicpu(p).condition);
  1955. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - removed first jump',p);
  1956. CJLabel.decrefs;
  1957. {$ifdef cpudelayslot}
  1958. RemoveDelaySlot(p);
  1959. {$endif cpudelayslot}
  1960. RemoveCurrentP(p, hp1);
  1961. Result := True;
  1962. Exit;
  1963. {$if not defined(avr)}
  1964. end
  1965. else
  1966. { NOTE: There is currently no watertight, cross-platform way to create
  1967. an unconditional jump without access to the cg object. If anyone can
  1968. improve this particular optimisation to work on AVR,
  1969. please do. [Kit] }
  1970. begin
  1971. { Since inv(cond1) is a subset of cond2, jmp<cond2> will always branch if
  1972. jmp<cond1> does not, so change jmp<cond2> to an unconditional jump. }
  1973. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - made second jump unconditional',p);
  1974. MakeUnconditional(taicpu(hp1));
  1975. { NOTE: Changing the jump to unconditional won't open up new opportunities
  1976. for GetFinalDestination on earlier jumps because there's no live label
  1977. between the two jump instructions, so setting 'stoploop' to False only
  1978. wastes time. [Kit] }
  1979. { See if more optimisations are possible }
  1980. Continue;
  1981. {$endif}
  1982. end;
  1983. end;
  1984. end;
  1985. end;
  1986. if GetFinalDestination(taicpu(p),0) then
  1987. stoploop := False;
  1988. Exit;
  1989. end;
  1990. end;
  1991. {$endif CPU_SUPPORTS_OPT_COND_JUMP}
  1992. function TAOptObj.CollapseZeroDistJump(var p: tai; ThisLabel: TAsmLabel): Boolean;
  1993. var
  1994. hp1: tai;
  1995. begin
  1996. Result := False;
  1997. if not GetNextInstruction(p,hp1) then
  1998. exit;
  1999. if (hp1 = BlockEnd) then
  2000. Exit;
  2001. { remove jumps to labels coming right after them }
  2002. if FindLabel(ThisLabel, hp1) and
  2003. { Cannot remove the first instruction }
  2004. (p<>StartPoint) then
  2005. begin
  2006. ThisLabel.decrefs;
  2007. {$ifdef cpudelayslot}
  2008. RemoveDelaySlot(p);
  2009. {$endif cpudelayslot}
  2010. hp1 := tai(p.Next);
  2011. { Use RemoveInstruction, not RemoveCurrentP, since the latter also
  2012. updates the registers }
  2013. RemoveInstruction(p);
  2014. p := hp1;
  2015. Result := True;
  2016. end;
  2017. end;
  2018. function TAOptObj.CanDoJumpOpts: Boolean;
  2019. begin
  2020. { Always allow by default }
  2021. Result := True;
  2022. end;
  2023. function TAOptObj.DoJumpOptimizations(var p: tai; var stoploop: Boolean): Boolean;
  2024. var
  2025. hp1, hp2: tai;
  2026. ThisLabel: TAsmLabel;
  2027. ThisPassResult: Boolean;
  2028. begin
  2029. Result := False;
  2030. if (p.typ <> ait_instruction) or not IsJumpToLabel(taicpu(p)) then
  2031. Exit;
  2032. repeat
  2033. ThisPassResult := False;
  2034. if GetNextInstruction(p, hp1) and (hp1 <> BlockEnd) then
  2035. begin
  2036. SkipEntryExitMarker(hp1,hp1);
  2037. if (hp1 = BlockEnd) then
  2038. Exit;
  2039. ThisLabel := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  2040. hp2 := getlabelwithsym(ThisLabel);
  2041. { getlabelwithsym returning nil occurs if a label is in a
  2042. different block (e.g. on the other side of an asm...end pair). }
  2043. if Assigned(hp2) then
  2044. begin
  2045. { If there are multiple labels in a row, change the destination to the last one
  2046. in order to aid optimisation later }
  2047. ThisLabel := CollapseLabelCluster(p, hp2);
  2048. if CollapseZeroDistJump(p, ThisLabel) then
  2049. begin
  2050. stoploop := False;
  2051. Result := True;
  2052. Exit;
  2053. end;
  2054. if IsJumpToLabelUncond(taicpu(p)) then
  2055. begin
  2056. { Remove unreachable code between the jump and the next label }
  2057. ThisPassResult := RemoveDeadCodeAfterJump(taicpu(p));
  2058. if GetFinalDestination(taicpu(p), 0) or ThisPassResult then
  2059. { Might have caused some earlier labels to become dead }
  2060. stoploop := False;
  2061. end
  2062. {$ifdef CPU_SUPPORTS_OPT_COND_JUMP}
  2063. else if (taicpu(p).opcode {$ifdef z80}in{$else}={$endif} aopt_condjmp) then
  2064. ThisPassResult := OptimizeConditionalJump(ThisLabel, p, hp1, stoploop)
  2065. {$endif CPU_SUPPORTS_OPT_COND_JUMP}
  2066. ;
  2067. end;
  2068. end;
  2069. Result := Result or ThisPassResult;
  2070. until not (ThisPassResult and (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)));
  2071. end;
  2072. function TAOptObj.GetFinalDestination(hp: taicpu; level: longint): boolean;
  2073. {traces sucessive jumps to their final destination and sets it, e.g.
  2074. je l1 je l3 <code> <code>
  2075. l1: becomes l1:
  2076. je l2 je l3
  2077. <code> <code>
  2078. l2: l2:
  2079. jmp l3 jmp l3
  2080. the level parameter denotes how deep we have already followed the jump,
  2081. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  2082. var p1: tai;
  2083. p2: tai;
  2084. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2085. p3: tai;
  2086. {$endif}
  2087. ThisLabel, l: tasmlabel;
  2088. begin
  2089. GetFinalDestination := false;
  2090. if level > 20 then
  2091. exit;
  2092. ThisLabel := TAsmLabel(JumpTargetOp(hp)^.ref^.symbol);
  2093. p1 := getlabelwithsym(ThisLabel);
  2094. if assigned(p1) then
  2095. begin
  2096. SkipLabels(p1,p1);
  2097. if (p1.typ = ait_instruction) and
  2098. (taicpu(p1).is_jmp) then
  2099. begin
  2100. p2 := tai(p1.Next);
  2101. if p2 = BlockEnd then
  2102. Exit;
  2103. { Collapse any zero distance jumps we stumble across }
  2104. while (p1<>StartPoint) and CollapseZeroDistJump(p1, TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol)) do
  2105. begin
  2106. { Note: Cannot remove the first instruction }
  2107. if (p1.typ in [ait_align, ait_label]) then
  2108. SkipLabels(p1, p1);
  2109. if not Assigned(p1) then
  2110. { No more valid commands }
  2111. Exit;
  2112. { Check to see that we are actually still at a jump }
  2113. if not ((tai(p1).typ = ait_instruction) and (taicpu(p1).is_jmp)) then
  2114. begin
  2115. { Required to ensure recursion works properly, but to also
  2116. return false if a jump isn't modified. [Kit] }
  2117. if level > 0 then GetFinalDestination := True;
  2118. Exit;
  2119. end;
  2120. p2 := tai(p1.Next);
  2121. if p2 = BlockEnd then
  2122. Exit;
  2123. end;
  2124. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2125. p3 := p2;
  2126. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64 and not WASM}
  2127. if { the next instruction after the label where the jump hp arrives}
  2128. { is unconditional or of the same type as hp, so continue }
  2129. IsJumpToLabelUncond(taicpu(p1))
  2130. { TODO: For anyone with experience with MIPS or RISC-V, please add support for tracing
  2131. conditional jumps. [Kit] }
  2132. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2133. { for MIPS, it isn't enough to check the condition; first operands must be same, too. }
  2134. or
  2135. condition_in(hp.condition, taicpu(p1).condition) or
  2136. { the next instruction after the label where the jump hp arrives
  2137. is the opposite of hp (so this one is never taken), but after
  2138. that one there is a branch that will be taken, so perform a
  2139. little hack: set p1 equal to this instruction }
  2140. (condition_in(hp.condition, inverse_cond(taicpu(p1).condition)) and
  2141. SkipLabels(p3,p2) and
  2142. (p2.typ = ait_instruction) and
  2143. (taicpu(p2).is_jmp) and
  2144. (IsJumpToLabelUncond(taicpu(p2)) or
  2145. (condition_in(hp.condition, taicpu(p2).condition))
  2146. ) and
  2147. SetAndTest(p2,p1)
  2148. )
  2149. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64 and not WASM}
  2150. then
  2151. begin
  2152. { quick check for loops of the form "l5: ; jmp l5" }
  2153. if (TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).labelnr = ThisLabel.labelnr) then
  2154. exit;
  2155. if not GetFinalDestination(taicpu(p1),succ(level)) then
  2156. exit;
  2157. { NOTE: Do not move this before the "l5: ; jmp l5" check,
  2158. because GetFinalDestination may change the destination
  2159. label of p1. [Kit] }
  2160. l := tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol);
  2161. {$if defined(aarch64)}
  2162. { can't have conditional branches to
  2163. global labels on AArch64, because the
  2164. offset may become too big }
  2165. if not(taicpu(hp).condition in [C_None,C_AL,C_NV]) and
  2166. (l.bind<>AB_LOCAL) then
  2167. exit;
  2168. {$endif aarch64}
  2169. ThisLabel.decrefs;
  2170. JumpTargetOp(hp)^.ref^.symbol:=l;
  2171. l.increfs;
  2172. GetFinalDestination := True;
  2173. Exit;
  2174. end
  2175. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2176. else
  2177. if condition_in(inverse_cond(hp.condition), taicpu(p1).condition) then
  2178. begin
  2179. if not FindLiveLabel(p1,l) then
  2180. begin
  2181. {$ifdef finaldestdebug}
  2182. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2183. strpnew('previous label inserted'))));
  2184. {$endif finaldestdebug}
  2185. current_asmdata.getjumplabel(l);
  2186. insertllitem(p1,p1.next,tai_label.Create(l));
  2187. ThisLabel.decrefs;
  2188. JumpTargetOp(hp)^.ref^.symbol := l;
  2189. l.increfs;
  2190. GetFinalDestination := True;
  2191. { this won't work, since the new label isn't in the labeltable }
  2192. { so it will fail the rangecheck. Labeltable should become a }
  2193. { hashtable to support this: }
  2194. { GetFinalDestination(asml, hp); }
  2195. end
  2196. else
  2197. begin
  2198. {$ifdef finaldestdebug}
  2199. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2200. strpnew('next label reused'))));
  2201. {$endif finaldestdebug}
  2202. l.increfs;
  2203. ThisLabel.decrefs;
  2204. JumpTargetOp(hp)^.ref^.symbol := l;
  2205. if not GetFinalDestination(hp,succ(level)) then
  2206. exit;
  2207. end;
  2208. GetFinalDestination := True;
  2209. Exit;
  2210. end;
  2211. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64 and not WASM}
  2212. end;
  2213. end;
  2214. { Required to ensure recursion works properly, but to also
  2215. return false if a jump isn't modified. [Kit] }
  2216. if level > 0 then GetFinalDestination := True;
  2217. end;
  2218. { Attempts to reconfigure the Regallocs and Regdeallocs before p1 and
  2219. after p2 so Reg is no longer allocated between them. Returns True if the
  2220. register is no longer allocated at p1 }
  2221. function TAOptObj.TryRemoveRegAlloc(const Reg: TRegister; p1, p2: tai): Boolean;
  2222. var
  2223. CurrentAlloc: tai;
  2224. begin
  2225. Result := False;
  2226. if RegInInstruction(Reg, p1) then
  2227. { Register is definitely in use }
  2228. Exit;
  2229. { Search for the first de/alloc before p1 that relates to Reg }
  2230. CurrentAlloc := tai(p1.Previous);
  2231. repeat
  2232. while Assigned(CurrentAlloc) and
  2233. ((CurrentAlloc.typ in (SkipInstr - [ait_regAlloc])) or
  2234. ((CurrentAlloc.typ = ait_label) and
  2235. not(Tai_Label(CurrentAlloc).labsym.Is_Used))) do
  2236. CurrentAlloc := Tai(CurrentAlloc.Previous);
  2237. if Assigned(CurrentAlloc) and
  2238. (CurrentAlloc.typ = ait_regalloc) then
  2239. begin
  2240. if (getregtype(tai_regalloc(CurrentAlloc).Reg) = getregtype(Reg)) and
  2241. (getsupreg(tai_regalloc(CurrentAlloc).Reg) = getsupreg(Reg)) then
  2242. begin
  2243. Break;
  2244. end;
  2245. CurrentAlloc := Tai(CurrentAlloc.Previous);
  2246. end
  2247. else
  2248. begin
  2249. CurrentAlloc := nil;
  2250. Break;
  2251. end;
  2252. until false;
  2253. { Remove any register allocation prior to p1 }
  2254. if Assigned(CurrentAlloc) and (CurrentAlloc.typ = ait_regalloc) and
  2255. (tai_regalloc(CurrentAlloc).ratype = ra_alloc) then
  2256. begin
  2257. RemoveInstruction(CurrentAlloc);
  2258. Result := True;
  2259. end
  2260. else if not Assigned(CurrentAlloc) or (CurrentAlloc.typ <> ait_regalloc) or
  2261. (tai_regalloc(CurrentAlloc).ratype <> ra_dealloc) then
  2262. begin
  2263. AsmL.InsertBefore(tai_regalloc.dealloc(Reg, nil), p1);
  2264. Result := True;
  2265. end;
  2266. if (p1 <> p2) and RegInInstruction(Reg, p2) then
  2267. begin
  2268. { Reg is in use, so insert allocation before it }
  2269. AsmL.InsertBefore(tai_regalloc.alloc(Reg, nil), p2);
  2270. Exit;
  2271. end;
  2272. { If a deallocation exists, remove it since the register will no longer be allocated by this time }
  2273. CurrentAlloc := FindRegDealloc(Reg, tai(p2.Next));
  2274. if Assigned(CurrentAlloc) and (CurrentAlloc.typ = ait_regalloc) and
  2275. (tai_regalloc(CurrentAlloc).ratype = ra_dealloc) then
  2276. begin
  2277. RemoveInstruction(CurrentAlloc);
  2278. end
  2279. else
  2280. begin
  2281. { Since no deallocation was found, Register may end up being used afterwards, so add a new alloc to play safe }
  2282. AsmL.InsertAfter(tai_regalloc.alloc(Reg, nil), p2);
  2283. end;
  2284. end;
  2285. procedure TAOptObj.PrePeepHoleOpts;
  2286. var
  2287. p: tai;
  2288. begin
  2289. p := BlockStart;
  2290. ClearUsedRegs;
  2291. while (p <> BlockEnd) Do
  2292. begin
  2293. prefetch(pointer(p.Next)^);
  2294. if PrePeepHoleOptsCpu(p) then
  2295. continue;
  2296. if assigned(p) then
  2297. begin
  2298. p:=tai(p.next);
  2299. UpdateUsedRegs(p);
  2300. end;
  2301. end;
  2302. end;
  2303. procedure TAOptObj.PeepHoleOptPass1;
  2304. const
  2305. MaxPasses_Pass1: array[1..3] of Cardinal = (1, 2, 8);
  2306. var
  2307. p : tai;
  2308. stoploop, FirstInstruction, JumpOptsAvailable: boolean;
  2309. PassCount, MaxCount: Cardinal;
  2310. begin
  2311. JumpOptsAvailable := CanDoJumpOpts();
  2312. StartPoint := BlockStart;
  2313. PassCount := 0;
  2314. { Determine the maximum number of passes allowed based on the compiler switches }
  2315. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2316. { it should never take more than 8 passes, but the limit is finite to protect against faulty optimisations }
  2317. MaxCount := MaxPasses_Pass1[3]
  2318. else if (cs_opt_level2 in current_settings.optimizerswitches) then
  2319. MaxCount := MaxPasses_Pass1[2] { The original double run of Pass 1 }
  2320. else
  2321. MaxCount := MaxPasses_Pass1[1];
  2322. NotFirstIteration := False;
  2323. repeat
  2324. stoploop:=true;
  2325. p := StartPoint;
  2326. FirstInstruction := True;
  2327. ClearUsedRegs;
  2328. while Assigned(p) and (p <> BlockEnd) Do
  2329. begin
  2330. prefetch(pointer(p.Next)^);
  2331. { I'am not sure why this is done, UsedRegs should reflect the register usage before the instruction
  2332. If an instruction needs the information of this, it can easily create a TempUsedRegs (FK)
  2333. UpdateUsedRegs(tai(p.next));
  2334. }
  2335. {$ifdef DEBUG_OPTALLOC}
  2336. if p.Typ=ait_instruction then
  2337. InsertLLItem(tai(p.Previous),p,tai_comment.create(strpnew(GetAllocationString(UsedRegs))));
  2338. {$endif DEBUG_OPTALLOC}
  2339. { Handle jump optimizations first }
  2340. if JumpOptsAvailable and DoJumpOptimizations(p, stoploop) then
  2341. begin
  2342. if FirstInstruction then
  2343. { Update StartPoint, since the old p was removed;
  2344. don't set FirstInstruction to False though, as
  2345. the new p might get removed too. }
  2346. StartPoint := p;
  2347. if (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)) then
  2348. Continue;
  2349. end;
  2350. if PeepHoleOptPass1Cpu(p) then
  2351. begin
  2352. stoploop:=false;
  2353. UpdateUsedRegs(p);
  2354. if FirstInstruction then
  2355. { Update StartPoint, since the old p was modified;
  2356. don't set FirstInstruction to False though, as
  2357. the new p might get modified too. }
  2358. StartPoint := p;
  2359. continue;
  2360. end;
  2361. FirstInstruction := False;
  2362. if assigned(p) then
  2363. begin
  2364. p:=tai(p.next);
  2365. UpdateUsedRegs(p);
  2366. end;
  2367. end;
  2368. Inc(PassCount);
  2369. if not stoploop then
  2370. NotFirstIteration := True;
  2371. until stoploop or (PassCount >= MaxCount);
  2372. end;
  2373. procedure TAOptObj.PeepHoleOptPass2;
  2374. const
  2375. MaxPasses_Pass2 = 8;
  2376. var
  2377. p: tai;
  2378. stoploop: Boolean;
  2379. PassCount: Cardinal;
  2380. begin
  2381. PassCount := 0;
  2382. { Pass 2 is only executed multiple times under -O3 and above }
  2383. repeat
  2384. stoploop := True;
  2385. p := BlockStart;
  2386. ClearUsedRegs;
  2387. while (p <> BlockEnd) Do
  2388. begin
  2389. prefetch(pointer(p.Next)^);
  2390. if PeepHoleOptPass2Cpu(p) then
  2391. begin
  2392. stoploop := False;
  2393. continue;
  2394. end;
  2395. if assigned(p) then
  2396. begin
  2397. p:=tai(p.next);
  2398. UpdateUsedRegs(p);
  2399. end;
  2400. end;
  2401. Inc(PassCount);
  2402. until stoploop or not (cs_opt_level3 in current_settings.optimizerswitches) or (PassCount >= MaxPasses_Pass2);
  2403. end;
  2404. procedure TAOptObj.PostPeepHoleOpts;
  2405. var
  2406. p: tai;
  2407. begin
  2408. p := BlockStart;
  2409. ClearUsedRegs;
  2410. while (p <> BlockEnd) Do
  2411. begin
  2412. prefetch(pointer(p.Next)^);
  2413. if PostPeepHoleOptsCpu(p) then
  2414. continue;
  2415. if assigned(p) then
  2416. p := tai(UpdateUsedRegsAndOptimize(p).Next);
  2417. end;
  2418. end;
  2419. function TAOptObj.PrePeepHoleOptsCpu(var p : tai) : boolean;
  2420. begin
  2421. result := false;
  2422. end;
  2423. function TAOptObj.PeepHoleOptPass1Cpu(var p: tai): boolean;
  2424. begin
  2425. result := false;
  2426. end;
  2427. function TAOptObj.PeepHoleOptPass2Cpu(var p : tai) : boolean;
  2428. begin
  2429. result := false;
  2430. end;
  2431. function TAOptObj.PostPeepHoleOptsCpu(var p: tai): boolean;
  2432. begin
  2433. result := false;
  2434. end;
  2435. procedure TAOptObj.Debug_InsertInstrRegisterDependencyInfo;
  2436. var
  2437. p: tai;
  2438. ri: tregisterindex;
  2439. reg: TRegister;
  2440. commentstr: AnsiString;
  2441. registers_found: Boolean;
  2442. begin
  2443. p:=tai(AsmL.First);
  2444. while (p<>AsmL.Last) Do
  2445. begin
  2446. if p.typ=ait_instruction then
  2447. begin
  2448. {$ifdef x86}
  2449. taicpu(p).SetOperandOrder(op_att);
  2450. {$endif x86}
  2451. commentstr:='Instruction reads from';
  2452. registers_found:=false;
  2453. for ri in tregisterindex do
  2454. begin
  2455. reg:=regnumber_table[ri];
  2456. if (reg<>NR_NO) and InstructionLoadsFromReg(reg,p) and
  2457. { Modified registers are handled below }
  2458. not RegModifiedByInstruction(reg,p) then
  2459. begin
  2460. commentstr:=commentstr+' '+std_regname(reg);
  2461. registers_found:=true;
  2462. end;
  2463. end;
  2464. if not registers_found then
  2465. commentstr:=commentstr+' no registers';
  2466. commentstr:=commentstr+', modifies';
  2467. registers_found:=false;
  2468. for ri in tregisterindex do
  2469. begin
  2470. reg:=regnumber_table[ri];
  2471. if (reg<>NR_NO) and RegModifiedByInstruction(reg,p) and
  2472. { Pure writes are handled below }
  2473. not RegLoadedWithNewValue(reg,p) then
  2474. begin
  2475. commentstr:=commentstr+' '+std_regname(reg);
  2476. registers_found:=true;
  2477. end;
  2478. end;
  2479. if not registers_found then
  2480. commentstr:=commentstr+' no registers';
  2481. commentstr:=commentstr+' and writes new values to';
  2482. registers_found:=false;
  2483. for ri in tregisterindex do
  2484. begin
  2485. reg:=regnumber_table[ri];
  2486. if (reg<>NR_NO) and RegLoadedWithNewValue(reg,p) then
  2487. begin
  2488. commentstr:=commentstr+' '+std_regname(reg);
  2489. registers_found:=true;
  2490. end;
  2491. end;
  2492. if not registers_found then
  2493. commentstr:=commentstr+' no registers';
  2494. AsmL.InsertAfter(tai_comment.Create(strpnew(commentstr)),p);
  2495. end;
  2496. p:=tai(p.next);
  2497. end;
  2498. end;
  2499. End.