2
0

aoptobj.pas 93 KB

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