aoptobj.pas 92 KB

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