aoptobj.pas 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  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. start := p1;
  1182. if (reg = NR_STACK_POINTER_REG) or
  1183. (reg = current_procinfo.framepointer) or
  1184. not(assigned(p1)) then
  1185. { this happens with registers which are loaded implicitely, outside the }
  1186. { current block (e.g. esi with self) }
  1187. exit;
  1188. { make sure we allocate it for this instruction }
  1189. getnextinstruction(p2,p2);
  1190. lastRemovedWasDealloc := false;
  1191. removedSomething := false;
  1192. firstRemovedWasAlloc := false;
  1193. {$ifdef allocregdebug}
  1194. hp := tai_comment.Create(strpnew('allocating '+std_regname(reg)+' from here...'));
  1195. insertllitem(p1.previous,p1,hp);
  1196. hp := tai_comment.Create(strpnew('allocated '+std_regname(reg)+' till here...'));
  1197. insertllitem(p2,p2.next,hp);
  1198. {$endif allocregdebug}
  1199. { do it the safe way: always allocate the full super register,
  1200. as we do no register re-allocation in the peephole optimizer,
  1201. this does not hurt
  1202. }
  1203. case getregtype(reg) of
  1204. R_MMREGISTER:
  1205. reg:=newreg(R_MMREGISTER,getsupreg(reg),R_SUBMMWHOLE);
  1206. R_INTREGISTER:
  1207. reg:=newreg(R_INTREGISTER,getsupreg(reg),R_SUBWHOLE);
  1208. R_FPUREGISTER:
  1209. reg:=newreg(R_FPUREGISTER,getsupreg(reg),R_SUBWHOLE);
  1210. R_ADDRESSREGISTER:
  1211. reg:=newreg(R_ADDRESSREGISTER,getsupreg(reg),R_SUBWHOLE);
  1212. R_SPECIALREGISTER:
  1213. reg:=newreg(R_SPECIALREGISTER,getsupreg(reg),R_SUBWHOLE);
  1214. else
  1215. Internalerror(2018030701);
  1216. end;
  1217. if not(RegInUsedRegs(reg,initialusedregs)) then
  1218. begin
  1219. hp := tai_regalloc.alloc(reg,nil);
  1220. insertllItem(p1.previous,p1,hp);
  1221. IncludeRegInUsedRegs(reg,initialusedregs);
  1222. lastRemovedWasDealloc := True; { If no tai_regallocs are found at all, treat as if the last one was a deallocation }
  1223. end;
  1224. while assigned(p1) and
  1225. (p1 <> p2) do
  1226. begin
  1227. if assigned(p1.optinfo) then
  1228. internalerror(2014022301); // IncludeRegInUsedRegs(reg,ptaiprop(p1.optinfo)^.usedregs);
  1229. p1 := tai(p1.next);
  1230. repeat
  1231. while assigned(p1) and
  1232. (p1.typ in (SkipInstr-[ait_regalloc])) Do
  1233. p1 := tai(p1.next);
  1234. { remove all allocation/deallocation info about the register in between }
  1235. if assigned(p1) and
  1236. (p1.typ = ait_regalloc) then
  1237. begin
  1238. { same super register, different sub register? }
  1239. if SuperRegistersEqual(reg,tai_regalloc(p1).reg) and (tai_regalloc(p1).reg<>reg) then
  1240. begin
  1241. if (getsubreg(tai_regalloc(p1).reg)>getsubreg(reg)) or (getsubreg(reg)=R_SUBH) then
  1242. internalerror(2016101501);
  1243. tai_regalloc(p1).reg:=reg;
  1244. end;
  1245. if tai_regalloc(p1).reg=reg then
  1246. begin
  1247. if not removedSomething then
  1248. begin
  1249. firstRemovedWasAlloc := tai_regalloc(p1).ratype=ra_alloc;
  1250. removedSomething := true;
  1251. end;
  1252. lastRemovedWasDealloc := (tai_regalloc(p1).ratype=ra_dealloc);
  1253. hp := tai(p1.Next);
  1254. asml.Remove(p1);
  1255. p1.free;
  1256. p1 := hp;
  1257. end
  1258. else
  1259. p1 := tai(p1.next);
  1260. end;
  1261. until not(assigned(p1)) or
  1262. not(p1.typ in SkipInstr);
  1263. end;
  1264. if assigned(p1) then
  1265. begin
  1266. if firstRemovedWasAlloc then
  1267. begin
  1268. hp := tai_regalloc.Alloc(reg,nil);
  1269. insertLLItem(start.previous,start,hp);
  1270. end;
  1271. if lastRemovedWasDealloc then
  1272. begin
  1273. hp := tai_regalloc.DeAlloc(reg,nil);
  1274. insertLLItem(p1.previous,p1,hp);
  1275. end;
  1276. end;
  1277. end;
  1278. function TAOptObj.RegUsedAfterInstruction(reg: Tregister; p: tai;var AllUsedRegs: TAllUsedRegs): Boolean;
  1279. begin
  1280. AllUsedRegs[getregtype(reg)].Update(tai(p.Next),true);
  1281. RegUsedAfterInstruction :=
  1282. AllUsedRegs[getregtype(reg)].IsUsed(reg) and
  1283. not(regLoadedWithNewValue(reg,p)) and
  1284. (
  1285. not(GetNextInstruction(p,p)) or
  1286. InstructionLoadsFromReg(reg,p) or
  1287. not(regLoadedWithNewValue(reg,p))
  1288. );
  1289. end;
  1290. function TAOptObj.RegEndOfLife(reg : TRegister;p : taicpu) : boolean;
  1291. begin
  1292. Result:=assigned(FindRegDealloc(reg,tai(p.Next))) or
  1293. RegLoadedWithNewValue(reg,p);
  1294. end;
  1295. function TAOptObj.RemoveCurrentP(var p : tai) : boolean;
  1296. var
  1297. hp1 : tai;
  1298. begin
  1299. result:=GetNextInstruction(p,hp1);
  1300. { p will be removed, update used register as we continue
  1301. with the next instruction after p }
  1302. UpdateUsedRegs(tai(p.Next));
  1303. AsmL.Remove(p);
  1304. p.Free;
  1305. p:=hp1;
  1306. end;
  1307. procedure TAOptObj.RemoveCurrentP(var p: tai; const hp1: tai); inline;
  1308. begin
  1309. if (p=hp1) then
  1310. internalerror(2020120501);
  1311. UpdateUsedRegs(tai(p.Next));
  1312. AsmL.Remove(p);
  1313. p.Free;
  1314. p := hp1;
  1315. end;
  1316. procedure TAOptObj.RemoveInstruction(const hp: tai); inline;
  1317. begin
  1318. AsmL.Remove(hp);
  1319. hp.Free;
  1320. end;
  1321. function FindLiveLabel(hp: tai; var l: tasmlabel): Boolean;
  1322. var
  1323. next: tai;
  1324. begin
  1325. FindLiveLabel := false;
  1326. while True do
  1327. begin
  1328. while assigned(hp.next) and
  1329. (tai(hp.next).typ in (SkipInstr+[ait_align])) Do
  1330. hp := tai(hp.next);
  1331. next := tai(hp.next);
  1332. if assigned(next) and
  1333. (tai(next).typ = ait_label) then
  1334. begin
  1335. l := tai_label(next).labsym;
  1336. if not l.is_used then
  1337. begin
  1338. { Unsafe label }
  1339. hp := next;
  1340. Continue;
  1341. end;
  1342. FindLiveLabel := true;
  1343. end;
  1344. Exit;
  1345. end;
  1346. end;
  1347. {$push}
  1348. {$r-}
  1349. function TAOptObj.getlabelwithsym(sym: tasmlabel): tai;
  1350. begin
  1351. if (int64(sym.labelnr) >= int64(labelinfo^.lowlabel)) and
  1352. (int64(sym.labelnr) <= int64(labelinfo^.highlabel)) then { range check, a jump can go past an assembler block! }
  1353. getlabelwithsym := labelinfo^.labeltable^[sym.labelnr-labelinfo^.lowlabel].paiobj
  1354. else
  1355. getlabelwithsym := nil;
  1356. end;
  1357. {$pop}
  1358. { Returns True if hp is an unconditional jump to a label }
  1359. function IsJumpToLabelUncond(hp: taicpu): boolean;
  1360. begin
  1361. {$if defined(avr) or defined(z80)}
  1362. result:=(hp.opcode in aopt_uncondjmp) and
  1363. {$else}
  1364. result:=(hp.opcode=aopt_uncondjmp) and
  1365. {$endif}
  1366. {$if defined(arm) or defined(aarch64) or defined(z80)}
  1367. (hp.condition=c_None) and
  1368. {$endif arm or aarch64 or z80}
  1369. (hp.ops>0) and
  1370. {$if defined(riscv32) or defined(riscv64)}
  1371. (hp.oper[0]^.reg=NR_X0) and
  1372. {$endif riscv}
  1373. (JumpTargetOp(hp)^.typ = top_ref) and
  1374. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1375. end;
  1376. { Returns True if hp is any jump to a label }
  1377. function IsJumpToLabel(hp: taicpu): boolean;
  1378. begin
  1379. result:=hp.is_jmp and
  1380. (hp.ops>0) and
  1381. (JumpTargetOp(hp)^.typ = top_ref) and
  1382. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1383. end;
  1384. procedure TAOptObj.RemoveDelaySlot(hp1:tai);
  1385. var
  1386. hp2: tai;
  1387. begin
  1388. hp2:=tai(hp1.next);
  1389. while assigned(hp2) and (hp2.typ in SkipInstr) do
  1390. hp2:=tai(hp2.next);
  1391. if assigned(hp2) and (hp2.typ=ait_instruction) and
  1392. (taicpu(hp2).opcode=A_NOP) then
  1393. begin
  1394. asml.remove(hp2);
  1395. hp2.free;
  1396. end;
  1397. { Anything except A_NOP must be left in place: these instructions
  1398. execute before branch, so code stays correct if branch is removed. }
  1399. end;
  1400. { Output debug message to console - null function if EXTDEBUG is not defined }
  1401. class procedure TAOptObj.DebugWrite(Message: string); inline;
  1402. begin
  1403. {$ifdef DEBUG_JUMP}
  1404. WriteLn(Message);
  1405. {$else DEBUG_JUMP}
  1406. { Do nothing }
  1407. {$endif DEBUG_JUMP}
  1408. end;
  1409. { Converts a conditional jump into an unconditional jump. Only call this
  1410. procedure on an instruction that you already know is a conditional jump }
  1411. procedure TAOptObj.MakeUnconditional(p: taicpu);
  1412. begin
  1413. { TODO: If anyone can improve this particular optimisation to work on
  1414. AVR, please do (it's currently not called at all). [Kit] }
  1415. {$if not defined(avr)}
  1416. {$if defined(powerpc) or defined(powerpc64)}
  1417. p.condition.cond := C_None;
  1418. p.condition.simple := True;
  1419. {$else powerpc}
  1420. p.condition := C_None;
  1421. {$endif powerpc}
  1422. {$ifndef z80}
  1423. p.opcode := aopt_uncondjmp;
  1424. {$endif not z80}
  1425. {$ifdef RISCV}
  1426. p.loadoper(1, p.oper[p.ops-1]^);
  1427. p.loadreg(0, NR_X0);
  1428. p.ops:=2;
  1429. {$endif}
  1430. {$ifdef xtensa}
  1431. p.opcode := aopt_uncondjmp;
  1432. p.loadoper(0, p.oper[p.ops-1]^);
  1433. p.ops:=1;
  1434. {$endif}
  1435. {$endif not avr}
  1436. {$ifdef mips}
  1437. { MIPS conditional jump instructions also conntain register
  1438. operands. A proper implementation is needed here. }
  1439. internalerror(2020071301);
  1440. {$endif}
  1441. end;
  1442. { Removes all instructions between an unconditional jump and the next label.
  1443. Returns True if a jump in between was removed (as it may open up new
  1444. optimisations if the label appeared earlier in the stream) }
  1445. function TAOptObj.RemoveDeadCodeAfterJump(p: tai): Boolean;
  1446. const
  1447. {$ifdef JVM}
  1448. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label, ait_jcatch];
  1449. {$else JVM}
  1450. { Stop if it reaches SEH directive information in the form of
  1451. consts, which may occur if RemoveDeadCodeAfterJump is called on
  1452. the final RET instruction on x86, for example }
  1453. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label];
  1454. {$endif JVM}
  1455. var
  1456. hp1, hp2: tai;
  1457. begin
  1458. { the following code removes all code between a jmp and the next label,
  1459. because it can never be executed
  1460. }
  1461. Result := False;
  1462. while GetNextInstruction(p, hp1) and
  1463. (hp1 <> BlockEnd) and
  1464. not (hp1.typ in TaiFence) do
  1465. begin
  1466. if (hp1.typ = ait_instruction) and
  1467. taicpu(hp1).is_jmp and
  1468. (JumpTargetOp(taicpu(hp1))^.typ = top_ref) and
  1469. (JumpTargetOp(taicpu(hp1))^.ref^.symbol is TAsmLabel) then
  1470. begin
  1471. { If the destination label appears earlier, it may permit
  1472. further optimisations, so signal this in the Result }
  1473. Result := True;
  1474. TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).decrefs;
  1475. end;
  1476. { don't kill start/end of assembler block,
  1477. no-line-info-start/end etc }
  1478. if (hp1.typ<>ait_marker) and
  1479. ((hp1.typ<>ait_cfi) or
  1480. (tai_cfi_base(hp1).cfityp<>cfi_endproc)) then
  1481. begin
  1482. {$ifdef cpudelayslot}
  1483. if (hp1.typ=ait_instruction) and (taicpu(hp1).is_jmp) then
  1484. RemoveDelaySlot(hp1);
  1485. {$endif cpudelayslot}
  1486. hp2 := hp1;
  1487. while (hp2.typ = ait_align) do
  1488. begin
  1489. { Only remove the align if a label doesn't immediately follow }
  1490. if GetNextInstruction(hp2, hp2) and (hp2.typ = ait_label) then
  1491. { The label is unskippable }
  1492. Exit;
  1493. { Check again in case there's more than one adjacent alignment entry
  1494. (a frequent construct under x86, for example). [Kit] }
  1495. end;
  1496. asml.remove(hp1);
  1497. hp1.free;
  1498. end
  1499. else
  1500. p:=hp1;
  1501. end;
  1502. end;
  1503. { If hp is a label, strip it if its reference count is zero. Repeat until
  1504. a non-label is found, or a label with a non-zero reference count.
  1505. True is returned if something was stripped }
  1506. function TAOptObj.StripDeadLabels(hp: tai; var NextValid: tai): Boolean;
  1507. var
  1508. tmp, tmpNext: tai;
  1509. hp1: tai;
  1510. CurrentAlign: tai;
  1511. begin
  1512. CurrentAlign := nil;
  1513. Result := False;
  1514. hp1 := hp;
  1515. NextValid := hp;
  1516. { Stop if hp is an instruction, for example }
  1517. while (hp1 <> BlockEnd) and (hp1.typ in [ait_label,ait_align]) do
  1518. begin
  1519. prefetch(pointer(hp1.Next)^);
  1520. case hp1.typ of
  1521. ait_label:
  1522. begin
  1523. with tai_label(hp1).labsym do
  1524. if is_used or (bind <> AB_LOCAL) or (labeltype <> alt_jump) then
  1525. begin
  1526. { Valid label }
  1527. if Result then
  1528. NextValid := hp1;
  1529. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1530. Exit;
  1531. end;
  1532. DebugWrite('JUMP DEBUG: Removed label ' + tostr(TAsmLabel(tai_label(hp1).labsym).labelnr));
  1533. { Set tmp to the next valid entry }
  1534. tmp := tai(hp1.Next);
  1535. { Remove label }
  1536. AsmL.Remove(hp1);
  1537. hp1.Free;
  1538. hp1 := tmp;
  1539. Result := True;
  1540. Continue;
  1541. end;
  1542. { Also remove the align if it comes before an unused label }
  1543. ait_align:
  1544. begin
  1545. tmp := tai(hp1.Next);
  1546. if tmp = BlockEnd then
  1547. { End of block }
  1548. Exit;
  1549. repeat
  1550. case tmp.typ of
  1551. ait_align: { Merge the aligns if permissible }
  1552. begin
  1553. { Check the maxbytes field though, since this may result in the
  1554. alignment being ignored }
  1555. if ((tai_align_abstract(hp1).maxbytes = 0) and (tai_align_abstract(tmp).maxbytes = 0)) or
  1556. { If a maxbytes field is present, only merge if the aligns have the same granularity }
  1557. ((tai_align_abstract(hp1).aligntype = tai_align_abstract(tmp).aligntype)) then
  1558. begin
  1559. with tai_align_abstract(hp1) do
  1560. begin
  1561. aligntype := max(aligntype, tai_align_abstract(tmp).aligntype);
  1562. maxbytes := max(maxbytes, tai_align_abstract(tmp).maxbytes);
  1563. fillsize := max(fillsize, tai_align_abstract(tmp).fillsize);
  1564. use_op := use_op or tai_align_abstract(tmp).use_op;
  1565. if use_op and (tai_align_abstract(tmp).fillop <> 0) then
  1566. fillop := tai_align_abstract(tmp).fillop;
  1567. end;
  1568. tmpNext := tai(tmp.Next);
  1569. AsmL.Remove(tmp);
  1570. tmp.Free;
  1571. Result := True;
  1572. tmp := tmpNext;
  1573. end
  1574. else
  1575. tmp := tai(tmp.Next);
  1576. Continue;
  1577. end;
  1578. ait_label:
  1579. begin
  1580. { Signal that we can possibly delete this align entry }
  1581. CurrentAlign := hp1;
  1582. repeat
  1583. with tai_label(tmp).labsym do
  1584. if is_used or (bind <> AB_LOCAL) or (labeltype <> alt_jump) then
  1585. begin
  1586. { Valid label }
  1587. if Result then
  1588. NextValid := tmp;
  1589. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1590. Exit;
  1591. end;
  1592. DebugWrite('JUMP DEBUG: Removed label ' + tostr(TAsmLabel(tai_label(tmp).labsym).labelnr));
  1593. { Remove label }
  1594. tmpNext := tai(tmp.Next);
  1595. AsmL.Remove(tmp);
  1596. tmp.Free;
  1597. Result := True;
  1598. tmp := tmpNext;
  1599. { Loop here for a minor performance gain }
  1600. until (tmp = BlockEnd) or (tmp.typ <> ait_label);
  1601. { Re-evaluate the align and see what follows }
  1602. Continue;
  1603. end
  1604. else
  1605. begin
  1606. { Set hp1 to the instruction after the align, because the
  1607. align might get deleted later and hence set NextValid
  1608. to a dangling pointer. [Kit] }
  1609. hp1 := tmp;
  1610. Break;
  1611. end;
  1612. end;
  1613. until (tmp = BlockEnd);
  1614. { Break out of the outer loop if the above Break is called }
  1615. if (hp1 = tmp) then
  1616. Break;
  1617. end
  1618. else
  1619. Break;
  1620. end;
  1621. hp1 := tai(hp1.Next);
  1622. end;
  1623. { hp1 will be the next valid entry }
  1624. NextValid := hp1;
  1625. { Remove the alignment field (but only if the next valid entry is not a live label) }
  1626. while Assigned(CurrentAlign) and (CurrentAlign.typ = ait_align) do
  1627. begin
  1628. DebugWrite('JUMP DEBUG: Alignment field removed');
  1629. tmp := tai(CurrentAlign.next);
  1630. AsmL.Remove(CurrentAlign);
  1631. CurrentAlign.Free;
  1632. CurrentAlign := tmp;
  1633. end;
  1634. end;
  1635. { Strips a label and any aligns that appear before it (if hp points to
  1636. them rather than the label). Only call this procedure on a label that
  1637. you already know is no longer referenced }
  1638. procedure TAOptObj.StripLabelFast(hp: tai); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  1639. var
  1640. tmp: tai;
  1641. begin
  1642. repeat
  1643. case hp.typ of
  1644. ait_align:
  1645. begin
  1646. tmp := tai(hp.Next);
  1647. asml.Remove(hp);
  1648. hp.Free;
  1649. hp := tmp;
  1650. { Control flow will now return to 'repeat' }
  1651. end;
  1652. ait_label:
  1653. begin
  1654. {$ifdef EXTDEBUG}
  1655. { When not in debug mode, deleting a live label will cause an
  1656. access violation later on. [Kit] }
  1657. if tai_label(hp).labsym.getrefs <> 0 then
  1658. InternalError(2019110802);
  1659. {$endif EXTDEBUG}
  1660. asml.Remove(hp);
  1661. hp.Free;
  1662. Exit;
  1663. end;
  1664. else
  1665. begin
  1666. { Might be a comment or temporary allocation entry }
  1667. if not (hp.typ in SkipInstr) then
  1668. InternalError(2019110801);
  1669. hp := tai(hp.Next);
  1670. end;
  1671. end;
  1672. until False;
  1673. end;
  1674. { If a group of labels are clustered, change the jump to point to the last one
  1675. that is still referenced }
  1676. function TAOptObj.CollapseLabelCluster(jump: tai; var lbltai: tai): TAsmLabel;
  1677. var
  1678. LastLabel: TAsmLabel;
  1679. hp2: tai;
  1680. begin
  1681. Result := tai_label(lbltai).labsym;
  1682. LastLabel := Result;
  1683. hp2 := tai(lbltai.next);
  1684. while (hp2 <> BlockEnd) and (hp2.typ in SkipInstr + [ait_align, ait_label]) do
  1685. begin
  1686. if (hp2.typ = ait_label) and
  1687. (tai_label(hp2).labsym.is_used) and
  1688. (tai_label(hp2).labsym.labeltype = alt_jump) then
  1689. LastLabel := tai_label(hp2).labsym;
  1690. hp2 := tai(hp2.next);
  1691. end;
  1692. if (Result <> LastLabel) then
  1693. begin
  1694. Result.decrefs;
  1695. JumpTargetOp(taicpu(jump))^.ref^.symbol := LastLabel;
  1696. LastLabel.increfs;
  1697. Result := LastLabel;
  1698. lbltai := hp2;
  1699. end;
  1700. end;
  1701. {$ifndef JVM}
  1702. function TAOptObj.OptimizeConditionalJump(CJLabel: TAsmLabel; var p: tai; hp1: tai; var stoploop: Boolean): Boolean;
  1703. var
  1704. hp2: tai;
  1705. NCJLabel: TAsmLabel;
  1706. begin
  1707. Result := False;
  1708. while (hp1 <> BlockEnd) do
  1709. begin
  1710. StripDeadLabels(hp1, hp1);
  1711. if (hp1 <> BlockEnd) and
  1712. (tai(hp1).typ=ait_instruction) and
  1713. IsJumpToLabel(taicpu(hp1)) then
  1714. begin
  1715. NCJLabel := TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol);
  1716. if IsJumpToLabelUncond(taicpu(hp1)) then
  1717. begin
  1718. { Do it now to get it out of the way and to aid optimisations
  1719. later on in this method }
  1720. if RemoveDeadCodeAfterJump(taicpu(hp1)) then
  1721. stoploop := False;
  1722. hp2 := getlabelwithsym(NCJLabel);
  1723. if Assigned(hp2) then
  1724. { Collapse the cluster now to aid optimisation and potentially
  1725. cut down on the number of iterations required }
  1726. NCJLabel := CollapseLabelCluster(hp1, hp2);
  1727. { GetNextInstruction could be factored out, but hp2 might be
  1728. different after "RemoveDeadCodeAfterJump" }
  1729. GetNextInstruction(hp1, hp2);
  1730. { Check for:
  1731. jmp<cond> @Lbl
  1732. jmp @Lbl
  1733. }
  1734. if (CJLabel = NCJLabel) then
  1735. begin
  1736. DebugMsg(SPeepholeOptimization+'Short-circuited conditional jump',p);
  1737. { Both jumps go to the same label }
  1738. CJLabel.decrefs;
  1739. {$ifdef cpudelayslot}
  1740. RemoveDelaySlot(p);
  1741. {$endif cpudelayslot}
  1742. RemoveCurrentP(p, hp1);
  1743. Result := True;
  1744. Exit;
  1745. end;
  1746. if FindLabel(CJLabel, hp2) then
  1747. begin
  1748. { change the following jumps:
  1749. jmp<cond> CJLabel jmp<inv_cond> NCJLabel
  1750. jmp NCJLabel >>> <code>
  1751. CJLabel: NCJLabel:
  1752. <code>
  1753. NCJLabel:
  1754. }
  1755. {$if defined(arm) or defined(aarch64)}
  1756. if (taicpu(p).condition<>C_None)
  1757. {$if defined(aarch64)}
  1758. { can't have conditional branches to
  1759. global labels on AArch64, because the
  1760. offset may become too big }
  1761. and (NCJLabel.bind=AB_LOCAL)
  1762. {$endif aarch64}
  1763. then
  1764. begin
  1765. {$endif arm or aarch64}
  1766. DebugMsg(SPeepholeOptimization+'Conditional jump inversion',p);
  1767. taicpu(p).condition:=inverse_cond(taicpu(p).condition);
  1768. CJLabel.decrefs;
  1769. JumpTargetOp(taicpu(p))^.ref^.symbol := NCJLabel;
  1770. { when freeing hp1, the reference count
  1771. isn't decreased, so don't increase }
  1772. {$ifdef cpudelayslot}
  1773. RemoveDelaySlot(hp1);
  1774. {$endif cpudelayslot}
  1775. RemoveInstruction(hp1);
  1776. stoploop := False;
  1777. if not CJLabel.is_used then
  1778. begin
  1779. CJLabel := NCJLabel;
  1780. StripDeadLabels(tai(p.Next), hp1);
  1781. if (hp1 = BlockEnd) then
  1782. Exit;
  1783. { Attempt another iteration in case more jumps follow }
  1784. if (hp1.typ in SkipInstr) then
  1785. GetNextInstruction(hp1, hp1);
  1786. Continue;
  1787. end;
  1788. {$if defined(arm) or defined(aarch64)}
  1789. end;
  1790. {$endif arm or aarch64}
  1791. end
  1792. else if CollapseZeroDistJump(hp1, NCJLabel) then
  1793. begin
  1794. if (hp1 = BlockEnd) then
  1795. Exit;
  1796. { Attempt another iteration in case more jumps follow }
  1797. if (hp1.typ in SkipInstr) then
  1798. GetNextInstruction(hp1, hp1);
  1799. Continue;
  1800. end;
  1801. end
  1802. else
  1803. begin
  1804. { Do not try to optimize if the test generating the condition
  1805. is the same instruction, like 'bne $v0,$zero,.Lj3' for MIPS }
  1806. if (taicpu(p).ops>1) or (taicpu(hp1).ops>1) then
  1807. exit;
  1808. { Check for:
  1809. jmp<cond1> @Lbl1
  1810. jmp<cond2> @Lbl2
  1811. Remove 2nd jump if conditions are equal or cond2 is a subset of cond1
  1812. (as if the first jump didn't branch, then neither will the 2nd)
  1813. }
  1814. if condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  1815. begin
  1816. DebugMsg(SPeepholeOptimization+'Dominated conditional jump',p);
  1817. NCJLabel.decrefs;
  1818. GetNextInstruction(hp1, hp2);
  1819. {$ifdef cpudelayslot}
  1820. RemoveDelaySlot(hp1);
  1821. {$endif cpudelayslot}
  1822. RemoveInstruction(hp1);
  1823. hp1 := hp2;
  1824. { Flag another pass in case @Lbl2 appeared earlier in the procedure and is now a dead label }
  1825. stoploop := False;
  1826. { Attempt another iteration in case more jumps follow }
  1827. Continue;
  1828. end;
  1829. { Check for:
  1830. jmp<cond1> @Lbl1
  1831. jmp<cond2> @Lbl2
  1832. And inv(cond1) is a subset of cond2 (e.g. je followed by jne, or jae followed by jbe) )
  1833. }
  1834. if condition_in(inverse_cond(taicpu(p).condition), taicpu(hp1).condition) then
  1835. begin
  1836. GetNextInstruction(hp1, hp2);
  1837. { If @lbl1 immediately follows jmp<cond2>, we can remove
  1838. the first jump completely }
  1839. if FindLabel(CJLabel, hp2) then
  1840. begin
  1841. { However, to be absolutely correct, cond2 must be changed to inv(cond1) }
  1842. taicpu(hp1).condition := inverse_cond(taicpu(p).condition);
  1843. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - removed first jump',p);
  1844. CJLabel.decrefs;
  1845. {$ifdef cpudelayslot}
  1846. RemoveDelaySlot(p);
  1847. {$endif cpudelayslot}
  1848. RemoveCurrentP(p, hp1);
  1849. Result := True;
  1850. Exit;
  1851. {$if not defined(avr)}
  1852. end
  1853. else
  1854. { NOTE: There is currently no watertight, cross-platform way to create
  1855. an unconditional jump without access to the cg object. If anyone can
  1856. improve this particular optimisation to work on AVR,
  1857. please do. [Kit] }
  1858. begin
  1859. { Since inv(cond1) is a subset of cond2, jmp<cond2> will always branch if
  1860. jmp<cond1> does not, so change jmp<cond2> to an unconditional jump. }
  1861. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - made second jump unconditional',p);
  1862. MakeUnconditional(taicpu(hp1));
  1863. { NOTE: Changing the jump to unconditional won't open up new opportunities
  1864. for GetFinalDestination on earlier jumps because there's no live label
  1865. between the two jump instructions, so setting 'stoploop' to False only
  1866. wastes time. [Kit] }
  1867. { See if more optimisations are possible }
  1868. Continue;
  1869. {$endif}
  1870. end;
  1871. end;
  1872. end;
  1873. end;
  1874. if GetFinalDestination(taicpu(p),0) then
  1875. stoploop := False;
  1876. Exit;
  1877. end;
  1878. end;
  1879. {$endif JVM}
  1880. function TAOptObj.CollapseZeroDistJump(var p: tai; ThisLabel: TAsmLabel): Boolean;
  1881. var
  1882. tmp, hp1: tai;
  1883. begin
  1884. Result := False;
  1885. if not GetNextInstruction(p,hp1) then
  1886. exit;
  1887. if (hp1 = BlockEnd) then
  1888. Exit;
  1889. { remove jumps to labels coming right after them }
  1890. if FindLabel(ThisLabel, hp1) and
  1891. { Cannot remove the first instruction }
  1892. (p<>StartPoint) then
  1893. begin
  1894. ThisLabel.decrefs;
  1895. {$ifdef cpudelayslot}
  1896. RemoveDelaySlot(p);
  1897. {$endif cpudelayslot}
  1898. tmp := tai(p.Next); { Might be an align before the label, so keep a note of it }
  1899. asml.remove(p);
  1900. p.free;
  1901. StripDeadLabels(tmp, p);
  1902. if p.typ <> ait_instruction then
  1903. GetNextInstruction(UpdateUsedRegsAndOptimize(p), p);
  1904. Result := True;
  1905. end;
  1906. end;
  1907. function TAOptObj.CanDoJumpOpts: Boolean;
  1908. begin
  1909. { Always allow by default }
  1910. Result := True;
  1911. end;
  1912. function TAOptObj.DoJumpOptimizations(var p: tai; var stoploop: Boolean): Boolean;
  1913. var
  1914. hp1, hp2: tai;
  1915. ThisLabel: TAsmLabel;
  1916. ThisPassResult: Boolean;
  1917. begin
  1918. Result := False;
  1919. if (p.typ <> ait_instruction) or not IsJumpToLabel(taicpu(p)) then
  1920. Exit;
  1921. repeat
  1922. ThisPassResult := False;
  1923. if GetNextInstruction(p, hp1) and (hp1 <> BlockEnd) then
  1924. begin
  1925. SkipEntryExitMarker(hp1,hp1);
  1926. if (hp1 = BlockEnd) then
  1927. Exit;
  1928. ThisLabel := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  1929. hp2 := getlabelwithsym(ThisLabel);
  1930. { getlabelwithsym returning nil occurs if a label is in a
  1931. different block (e.g. on the other side of an asm...end pair). }
  1932. if Assigned(hp2) then
  1933. begin
  1934. { If there are multiple labels in a row, change the destination to the last one
  1935. in order to aid optimisation later }
  1936. ThisLabel := CollapseLabelCluster(p, hp2);
  1937. if CollapseZeroDistJump(p, ThisLabel) then
  1938. begin
  1939. stoploop := False;
  1940. Result := True;
  1941. Exit;
  1942. end;
  1943. if IsJumpToLabelUncond(taicpu(p)) then
  1944. begin
  1945. { Remove unreachable code between the jump and the next label }
  1946. ThisPassResult := RemoveDeadCodeAfterJump(taicpu(p));
  1947. if GetFinalDestination(taicpu(p), 0) or ThisPassResult then
  1948. { Might have caused some earlier labels to become dead }
  1949. stoploop := False;
  1950. end
  1951. {$ifndef JVM}
  1952. else if (taicpu(p).opcode {$ifdef z80}in{$else}={$endif} aopt_condjmp) then
  1953. ThisPassResult := OptimizeConditionalJump(ThisLabel, p, hp1, stoploop)
  1954. {$endif JVM}
  1955. ;
  1956. end;
  1957. end;
  1958. Result := Result or ThisPassResult;
  1959. until not (ThisPassResult and (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)));
  1960. end;
  1961. function TAOptObj.GetFinalDestination(hp: taicpu; level: longint): boolean;
  1962. {traces sucessive jumps to their final destination and sets it, e.g.
  1963. je l1 je l3 <code> <code>
  1964. l1: becomes l1:
  1965. je l2 je l3
  1966. <code> <code>
  1967. l2: l2:
  1968. jmp l3 jmp l3
  1969. the level parameter denotes how deep we have already followed the jump,
  1970. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  1971. var p1: tai;
  1972. p2: tai;
  1973. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM)}
  1974. p3: tai;
  1975. {$endif}
  1976. ThisLabel, l: tasmlabel;
  1977. begin
  1978. GetFinalDestination := false;
  1979. if level > 20 then
  1980. exit;
  1981. ThisLabel := TAsmLabel(JumpTargetOp(hp)^.ref^.symbol);
  1982. p1 := getlabelwithsym(ThisLabel);
  1983. if assigned(p1) then
  1984. begin
  1985. SkipLabels(p1,p1);
  1986. if (p1.typ = ait_instruction) and
  1987. (taicpu(p1).is_jmp) then
  1988. begin
  1989. p2 := tai(p1.Next);
  1990. if p2 = BlockEnd then
  1991. Exit;
  1992. { Collapse any zero distance jumps we stumble across }
  1993. while (p1<>StartPoint) and CollapseZeroDistJump(p1, TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol)) do
  1994. begin
  1995. { Note: Cannot remove the first instruction }
  1996. if (p1.typ = ait_label) then
  1997. SkipLabels(p1, p1);
  1998. if not Assigned(p1) then
  1999. { No more valid commands }
  2000. Exit;
  2001. { Check to see that we are actually still at a jump }
  2002. if not ((tai(p1).typ = ait_instruction) and (taicpu(p1).is_jmp)) then
  2003. begin
  2004. { Required to ensure recursion works properly, but to also
  2005. return false if a jump isn't modified. [Kit] }
  2006. if level > 0 then GetFinalDestination := True;
  2007. Exit;
  2008. end;
  2009. p2 := tai(p1.Next);
  2010. if p2 = BlockEnd then
  2011. Exit;
  2012. end;
  2013. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM)}
  2014. p3 := p2;
  2015. {$endif not MIPS and not RV64 and not RV32 and not JVM}
  2016. if { the next instruction after the label where the jump hp arrives}
  2017. { is unconditional or of the same type as hp, so continue }
  2018. IsJumpToLabelUncond(taicpu(p1))
  2019. { TODO: For anyone with experience with MIPS or RISC-V, please add support for tracing
  2020. conditional jumps. [Kit] }
  2021. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM)}
  2022. { for MIPS, it isn't enough to check the condition; first operands must be same, too. }
  2023. or
  2024. condition_in(hp.condition, taicpu(p1).condition) or
  2025. { the next instruction after the label where the jump hp arrives
  2026. is the opposite of hp (so this one is never taken), but after
  2027. that one there is a branch that will be taken, so perform a
  2028. little hack: set p1 equal to this instruction }
  2029. (condition_in(hp.condition, inverse_cond(taicpu(p1).condition)) and
  2030. SkipLabels(p3,p2) and
  2031. (p2.typ = ait_instruction) and
  2032. (taicpu(p2).is_jmp) and
  2033. (IsJumpToLabelUncond(taicpu(p2)) or
  2034. (condition_in(hp.condition, taicpu(p2).condition))
  2035. ) and
  2036. SetAndTest(p2,p1)
  2037. )
  2038. {$endif not MIPS and not RV64 and not RV32 and not JVM}
  2039. then
  2040. begin
  2041. { quick check for loops of the form "l5: ; jmp l5" }
  2042. if (TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).labelnr = ThisLabel.labelnr) then
  2043. exit;
  2044. if not GetFinalDestination(taicpu(p1),succ(level)) then
  2045. exit;
  2046. { NOTE: Do not move this before the "l5: ; jmp l5" check,
  2047. because GetFinalDestination may change the destination
  2048. label of p1. [Kit] }
  2049. l := tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol);
  2050. {$if defined(aarch64)}
  2051. { can't have conditional branches to
  2052. global labels on AArch64, because the
  2053. offset may become too big }
  2054. if not(taicpu(hp).condition in [C_None,C_AL,C_NV]) and
  2055. (l.bind<>AB_LOCAL) then
  2056. exit;
  2057. {$endif aarch64}
  2058. ThisLabel.decrefs;
  2059. JumpTargetOp(hp)^.ref^.symbol:=l;
  2060. l.increfs;
  2061. GetFinalDestination := True;
  2062. Exit;
  2063. end
  2064. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM)}
  2065. else
  2066. if condition_in(inverse_cond(hp.condition), taicpu(p1).condition) then
  2067. begin
  2068. if not FindLiveLabel(p1,l) then
  2069. begin
  2070. {$ifdef finaldestdebug}
  2071. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2072. strpnew('previous label inserted'))));
  2073. {$endif finaldestdebug}
  2074. current_asmdata.getjumplabel(l);
  2075. insertllitem(p1,p1.next,tai_label.Create(l));
  2076. ThisLabel.decrefs;
  2077. JumpTargetOp(hp)^.ref^.symbol := l;
  2078. l.increfs;
  2079. GetFinalDestination := True;
  2080. { this won't work, since the new label isn't in the labeltable }
  2081. { so it will fail the rangecheck. Labeltable should become a }
  2082. { hashtable to support this: }
  2083. { GetFinalDestination(asml, hp); }
  2084. end
  2085. else
  2086. begin
  2087. {$ifdef finaldestdebug}
  2088. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2089. strpnew('next label reused'))));
  2090. {$endif finaldestdebug}
  2091. l.increfs;
  2092. ThisLabel.decrefs;
  2093. JumpTargetOp(hp)^.ref^.symbol := l;
  2094. if not GetFinalDestination(hp,succ(level)) then
  2095. exit;
  2096. end;
  2097. GetFinalDestination := True;
  2098. Exit;
  2099. end;
  2100. {$endif not MIPS and not RV64 and not RV32 and not JVM}
  2101. end;
  2102. end;
  2103. { Required to ensure recursion works properly, but to also
  2104. return false if a jump isn't modified. [Kit] }
  2105. if level > 0 then GetFinalDestination := True;
  2106. end;
  2107. procedure TAOptObj.PrePeepHoleOpts;
  2108. var
  2109. p: tai;
  2110. begin
  2111. p := BlockStart;
  2112. ClearUsedRegs;
  2113. while (p <> BlockEnd) Do
  2114. begin
  2115. prefetch(pointer(p.Next)^);
  2116. if PrePeepHoleOptsCpu(p) then
  2117. continue;
  2118. if assigned(p) then
  2119. begin
  2120. p:=tai(p.next);
  2121. UpdateUsedRegs(p);
  2122. end;
  2123. end;
  2124. end;
  2125. procedure TAOptObj.PeepHoleOptPass1;
  2126. const
  2127. MaxPasses: array[1..3] of Cardinal = (1, 2, 8);
  2128. var
  2129. p : tai;
  2130. stoploop, FirstInstruction, JumpOptsAvailable: boolean;
  2131. PassCount, MaxCount: Cardinal;
  2132. begin
  2133. JumpOptsAvailable := CanDoJumpOpts();
  2134. StartPoint := BlockStart;
  2135. PassCount := 0;
  2136. { Determine the maximum number of passes allowed based on the compiler switches }
  2137. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2138. { it should never take more than 8 passes, but the limit is finite to protect against faulty optimisations }
  2139. MaxCount := MaxPasses[3]
  2140. else if (cs_opt_level2 in current_settings.optimizerswitches) then
  2141. MaxCount := MaxPasses[2] { The original double run of Pass 1 }
  2142. else
  2143. MaxCount := MaxPasses[1];
  2144. repeat
  2145. stoploop:=true;
  2146. p := StartPoint;
  2147. FirstInstruction := True;
  2148. ClearUsedRegs;
  2149. while Assigned(p) and (p <> BlockEnd) Do
  2150. begin
  2151. prefetch(pointer(p.Next)^);
  2152. { I'am not sure why this is done, UsedRegs should reflect the register usage before the instruction
  2153. If an instruction needs the information of this, it can easily create a TempUsedRegs (FK)
  2154. UpdateUsedRegs(tai(p.next));
  2155. }
  2156. {$ifdef DEBUG_OPTALLOC}
  2157. if p.Typ=ait_instruction then
  2158. InsertLLItem(tai(p.Previous),p,tai_comment.create(strpnew(GetAllocationString(UsedRegs))));
  2159. {$endif DEBUG_OPTALLOC}
  2160. { Handle jump optimizations first }
  2161. if JumpOptsAvailable and DoJumpOptimizations(p, stoploop) then
  2162. begin
  2163. if FirstInstruction then
  2164. { Update StartPoint, since the old p was removed;
  2165. don't set FirstInstruction to False though, as
  2166. the new p might get removed too. }
  2167. StartPoint := p;
  2168. if (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)) then
  2169. Continue;
  2170. end;
  2171. if PeepHoleOptPass1Cpu(p) then
  2172. begin
  2173. stoploop:=false;
  2174. UpdateUsedRegs(p);
  2175. if FirstInstruction then
  2176. { Update StartPoint, since the old p was modified;
  2177. don't set FirstInstruction to False though, as
  2178. the new p might get modified too. }
  2179. StartPoint := p;
  2180. continue;
  2181. end;
  2182. FirstInstruction := False;
  2183. if assigned(p) then
  2184. p := tai(UpdateUsedRegsAndOptimize(p).Next);
  2185. end;
  2186. Inc(PassCount);
  2187. until stoploop or (PassCount >= MaxCount);
  2188. end;
  2189. procedure TAOptObj.PeepHoleOptPass2;
  2190. var
  2191. p: tai;
  2192. begin
  2193. p := BlockStart;
  2194. ClearUsedRegs;
  2195. while (p <> BlockEnd) Do
  2196. begin
  2197. prefetch(pointer(p.Next)^);
  2198. if PeepHoleOptPass2Cpu(p) then
  2199. continue;
  2200. if assigned(p) then
  2201. p := tai(UpdateUsedRegsAndOptimize(p).Next);
  2202. end;
  2203. end;
  2204. procedure TAOptObj.PostPeepHoleOpts;
  2205. var
  2206. p: tai;
  2207. begin
  2208. p := BlockStart;
  2209. ClearUsedRegs;
  2210. while (p <> BlockEnd) Do
  2211. begin
  2212. prefetch(pointer(p.Next)^);
  2213. if PostPeepHoleOptsCpu(p) then
  2214. continue;
  2215. if assigned(p) then
  2216. begin
  2217. p:=tai(p.next);
  2218. UpdateUsedRegs(p);
  2219. end;
  2220. end;
  2221. end;
  2222. function TAOptObj.PrePeepHoleOptsCpu(var p : tai) : boolean;
  2223. begin
  2224. result := false;
  2225. end;
  2226. function TAOptObj.PeepHoleOptPass1Cpu(var p: tai): boolean;
  2227. begin
  2228. result := false;
  2229. end;
  2230. function TAOptObj.PeepHoleOptPass2Cpu(var p : tai) : boolean;
  2231. begin
  2232. result := false;
  2233. end;
  2234. function TAOptObj.PostPeepHoleOptsCpu(var p: tai): boolean;
  2235. begin
  2236. result := false;
  2237. end;
  2238. procedure TAOptObj.Debug_InsertInstrRegisterDependencyInfo;
  2239. var
  2240. p: tai;
  2241. ri: tregisterindex;
  2242. reg: TRegister;
  2243. commentstr: AnsiString;
  2244. registers_found: Boolean;
  2245. begin
  2246. p:=tai(AsmL.First);
  2247. while (p<>AsmL.Last) Do
  2248. begin
  2249. if p.typ=ait_instruction then
  2250. begin
  2251. {$ifdef x86}
  2252. taicpu(p).SetOperandOrder(op_att);
  2253. {$endif x86}
  2254. commentstr:='Instruction reads';
  2255. registers_found:=false;
  2256. for ri in tregisterindex do
  2257. begin
  2258. reg:=regnumber_table[ri];
  2259. if (reg<>NR_NO) and InstructionLoadsFromReg(reg,p) then
  2260. begin
  2261. commentstr:=commentstr+' '+std_regname(reg);
  2262. registers_found:=true;
  2263. end;
  2264. end;
  2265. if not registers_found then
  2266. commentstr:=commentstr+' no registers';
  2267. commentstr:=commentstr+' and writes new values in';
  2268. registers_found:=false;
  2269. for ri in tregisterindex do
  2270. begin
  2271. reg:=regnumber_table[ri];
  2272. if (reg<>NR_NO) and RegLoadedWithNewValue(reg,p) then
  2273. begin
  2274. commentstr:=commentstr+' '+std_regname(reg);
  2275. registers_found:=true;
  2276. end;
  2277. end;
  2278. if not registers_found then
  2279. commentstr:=commentstr+' no registers';
  2280. AsmL.InsertAfter(tai_comment.Create(strpnew(commentstr)),p);
  2281. end;
  2282. p:=tai(p.next);
  2283. end;
  2284. end;
  2285. End.