aoptobj.pas 102 KB

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