aoptobj.pas 94 KB

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