aoptobj.pas 96 KB

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