aoptobj.pas 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  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. {$i fpcdefs.inc}
  22. { general, processor independent objects for use by the assembler optimizer }
  23. Interface
  24. uses
  25. globtype,
  26. aasmbase,aasmcpu,aasmtai,aasmdata,
  27. cclasses,
  28. cgbase,cgutils,
  29. cpubase,
  30. aoptbase,aoptcpub,aoptda;
  31. { ************************************************************************* }
  32. { ********************************* Constants ***************************** }
  33. { ************************************************************************* }
  34. Const
  35. {Possible register content types}
  36. con_Unknown = 0;
  37. con_ref = 1;
  38. con_const = 2;
  39. {***************** Types ****************}
  40. Type
  41. { ************************************************************************* }
  42. { ************************* Some general type definitions ***************** }
  43. { ************************************************************************* }
  44. TRefCompare = Function(const r1, r2: TReference): Boolean;
  45. //!!! FIXME
  46. TRegArray = Array[byte] of tsuperregister;
  47. TRegSet = tcpuregisterset;
  48. { possible actions on an operand: read, write or modify (= read & write) }
  49. TOpAction = (OpAct_Read, OpAct_Write, OpAct_Modify, OpAct_Unknown);
  50. { ************************************************************************* }
  51. { * Object to hold information on which regiters are in use and which not * }
  52. { ************************************************************************* }
  53. { TUsedRegs }
  54. TUsedRegs = class
  55. Constructor create(aTyp : TRegisterType);
  56. Constructor create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  57. Destructor Destroy;override;
  58. Procedure Clear;
  59. { update the info with the pairegalloc objects coming after
  60. p }
  61. procedure Update(p: Tai; IgnoreNewAllocs: Boolean=false);
  62. { is Reg currently in use }
  63. Function IsUsed(Reg: TRegister): Boolean;
  64. { get all the currently used registers }
  65. Function GetUsedRegs: TRegSet;
  66. { outputs the current set }
  67. Procedure Dump(var t : text);
  68. Private
  69. Typ : TRegisterType;
  70. UsedRegs: TRegSet;
  71. End;
  72. { ************************************************************************* }
  73. { ******************* Contents of the integer registers ******************* }
  74. { ************************************************************************* }
  75. { size of the integer that holds the state number of a register. Can be any }
  76. { integer type, so it can be changed to reduce the size of the TContent }
  77. { structure or to improve alignment }
  78. TStateInt = Byte;
  79. TContent = Record
  80. { start and end of block instructions that defines the }
  81. { content of this register. If Typ = con_const, then }
  82. { Longint(StartMod) = value of the constant) }
  83. StartMod: Tai;
  84. { starts at 0, gets increased everytime the register is }
  85. { written to }
  86. WState: TStateInt;
  87. { starts at 0, gets increased everytime the register is read }
  88. { from }
  89. RState: TStateInt;
  90. { how many instructions starting with StarMod does the block }
  91. { consist of }
  92. NrOfMods: Byte;
  93. { the type of the content of the register: unknown, memory }
  94. { (variable) or constant }
  95. Typ: Byte;
  96. End;
  97. //!!! FIXME
  98. TRegContent = Array[byte] Of TContent;
  99. { ************************************************************************** }
  100. { information object with the contents of every register. Every Tai object }
  101. { gets one of these assigned: a pointer to it is stored in the OptInfo field }
  102. { ************************************************************************** }
  103. { TPaiProp }
  104. TPaiProp = class(TAoptBaseCpu)
  105. Regs: TRegContent;
  106. { can this instruction be removed? }
  107. CanBeRemoved: Boolean;
  108. Constructor create; reintroduce;
  109. { checks the whole sequence of which (so regs[which].StartMod and and }
  110. { the next NrOfMods Tai objects) to see whether Reg is used somewhere, }
  111. { without it being loaded with something else first }
  112. Function RegInSequence(Reg, which: TRegister): Boolean;
  113. { destroy the contents of a register, as well as those whose contents }
  114. { are based on those of that register }
  115. Procedure DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  116. TInstrSinceLastMod);
  117. { if the contents of WhichReg (can be R_NO in case of a constant) are }
  118. { written to memory at the location Ref, the contents of the registers }
  119. { that depend on Ref have to be destroyed }
  120. Procedure DestroyRefs(Const Ref: TReference; WhichReg: TRegister; var
  121. InstrSinceLastMod: TInstrSinceLastMod);
  122. { an instruction reads from operand o }
  123. Procedure ReadOp(const o:toper);
  124. { an instruction reads from reference Ref }
  125. Procedure ReadRef(Ref: PReference);
  126. { an instruction reads from register Reg }
  127. Procedure ReadReg(Reg: TRegister);
  128. { an instruction writes/modifies operand o and this has special }
  129. { side-effects or modifies the contents in such a way that we can't }
  130. { simply add this instruction to the sequence of instructions that }
  131. { describe the contents of the operand, so destroy it }
  132. Procedure DestroyOp(const o:Toper; var InstrSinceLastMod:
  133. TInstrSinceLastMod);
  134. { destroy the contents of all registers }
  135. Procedure DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  136. { a register's contents are modified, but not destroyed (the new value
  137. depends on the old one) }
  138. Procedure ModifyReg(reg: TRegister; var InstrSinceLastMod:
  139. TInstrSinceLastMod);
  140. { an operand's contents are modified, but not destroyed (the new value
  141. depends on the old one) }
  142. Procedure ModifyOp(const oper: TOper; var InstrSinceLastMod:
  143. TInstrSinceLastMod);
  144. { increase the write state of a register (call every time a register is
  145. written to) }
  146. Procedure IncWState(Reg: TRegister);
  147. { increase the read state of a register (call every time a register is }
  148. { read from) }
  149. Procedure IncRState(Reg: TRegister);
  150. { get the write state of a register }
  151. Function GetWState(Reg: TRegister): TStateInt;
  152. { get the read state of a register }
  153. Function GetRState(Reg: TRegister): TStateInt;
  154. { get the type of contents of a register }
  155. Function GetRegContentType(Reg: TRegister): Byte;
  156. Destructor Done;
  157. Private
  158. Procedure IncState(var s: TStateInt);
  159. { returns whether the reference Ref is used somewhere in the loading }
  160. { sequence Content }
  161. Function RefInSequence(Const Ref: TReference; Content: TContent;
  162. RefsEq: TRefCompare): Boolean;
  163. { returns whether the instruction P reads from and/or writes }
  164. { to Reg }
  165. Function RefInInstruction(Const Ref: TReference; p: Tai;
  166. RefsEq: TRefCompare): Boolean;
  167. { returns whether two references with at least one pointing to an array }
  168. { may point to the same memory location }
  169. End;
  170. { ************************************************************************* }
  171. { ************************ Label information ****************************** }
  172. { ************************************************************************* }
  173. TLabelTableItem = Record
  174. PaiObj: Tai;
  175. End;
  176. TLabelTable = Array[0..2500000] Of TLabelTableItem;
  177. PLabelTable = ^TLabelTable;
  178. PLabelInfo = ^TLabelInfo;
  179. TLabelInfo = Record
  180. { the highest and lowest label number occurring in the current code }
  181. { fragment }
  182. LowLabel, HighLabel: longint;
  183. LabelDif: cardinal;
  184. { table that contains the addresses of the Pai_Label objects associated
  185. with each label number }
  186. LabelTable: PLabelTable;
  187. End;
  188. { ************************************************************************* }
  189. { ********** General optimizer object, used to derive others from ********* }
  190. { ************************************************************************* }
  191. TAllUsedRegs = array[TRegisterType] of TUsedRegs;
  192. { TAOptObj }
  193. TAOptObj = class(TAoptBaseCpu)
  194. { the PAasmOutput list this optimizer instance works on }
  195. AsmL: TAsmList;
  196. { The labelinfo record contains the addresses of the Tai objects }
  197. { that are labels, how many labels there are and the min and max }
  198. { label numbers }
  199. LabelInfo: PLabelInfo;
  200. { Start and end of the block that is currently being optimized }
  201. BlockStart, BlockEnd: Tai;
  202. DFA: TAOptDFA;
  203. UsedRegs: TAllUsedRegs;
  204. { _AsmL is the PAasmOutpout list that has to be optimized, }
  205. { _BlockStart and _BlockEnd the start and the end of the block }
  206. { that has to be optimized and _LabelInfo a pointer to a }
  207. { TLabelInfo record }
  208. Constructor create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  209. _LabelInfo: PLabelInfo); virtual; reintroduce;
  210. Destructor Destroy;override;
  211. { processor independent methods }
  212. Procedure CreateUsedRegs(var regs: TAllUsedRegs);
  213. Procedure ClearUsedRegs;
  214. Procedure UpdateUsedRegs(p : Tai);
  215. class procedure UpdateUsedRegs(var Regs: TAllUsedRegs; p: Tai);
  216. Function CopyUsedRegs(var dest : TAllUsedRegs) : boolean;
  217. class Procedure ReleaseUsedRegs(const regs : TAllUsedRegs);
  218. class Function RegInUsedRegs(reg : TRegister;regs : TAllUsedRegs) : boolean;
  219. class Procedure IncludeRegInUsedRegs(reg : TRegister;var regs : TAllUsedRegs);
  220. class Procedure ExcludeRegFromUsedRegs(reg: TRegister;var regs : TAllUsedRegs);
  221. Function GetAllocationString(const regs : TAllUsedRegs) : string;
  222. { returns true if the label L is found between hp and the next }
  223. { instruction }
  224. Function FindLabel(L: TasmLabel; Var hp: Tai): Boolean;
  225. { inserts new_one between prev and foll in AsmL }
  226. Procedure InsertLLItem(prev, foll, new_one: TLinkedListItem);
  227. { If P is a Tai object releveant to the optimizer, P is returned
  228. If it is not relevant tot he optimizer, the first object after P
  229. that is relevant is returned }
  230. Function SkipHead(P: Tai): Tai;
  231. { returns true if the operands o1 and o2 are completely equal }
  232. Function OpsEqual(const o1,o2:toper): Boolean;
  233. { Returns the next ait_alloc object with ratype ra_alloc for
  234. Reg is found in the block
  235. of Tai's starting with StartPai and ending with the next "real"
  236. instruction. If none is found, it returns
  237. nil
  238. }
  239. Function FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  240. { Returns the last ait_alloc object with ratype ra_alloc for
  241. Reg is found in the block
  242. of Tai's starting with StartPai and ending with the next "real"
  243. instruction. If none is found, it returns
  244. nil
  245. }
  246. Function FindRegAllocBackward(Reg : TRegister; StartPai : Tai) : tai_regalloc;
  247. { Returns the next ait_alloc object with ratype ra_dealloc
  248. for Reg which is found in the block of Tai's starting with StartPai
  249. and ending with the next "real" instruction. If none is found, it returns
  250. nil }
  251. Function FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  252. { allocates register reg between (and including) instructions p1 and p2
  253. the type of p1 and p2 must not be in SkipInstr }
  254. procedure AllocRegBetween(reg : tregister; p1,p2 : tai; var initialusedregs : TAllUsedRegs);
  255. { reg used after p? }
  256. function RegUsedAfterInstruction(reg: Tregister; p: tai; var AllUsedRegs: TAllUsedRegs): Boolean;
  257. { returns true if reg reaches it's end of life at p, this means it is either
  258. reloaded with a new value or it is deallocated afterwards }
  259. function RegEndOfLife(reg: TRegister;p: taicpu): boolean;
  260. { removes p from asml, updates registers and replaces it by a valid value, if this is the case true is returned }
  261. function RemoveCurrentP(var p : tai): boolean;
  262. { traces sucessive jumps to their final destination and sets it, e.g.
  263. je l1 je l3
  264. <code> <code>
  265. l1: becomes l1:
  266. je l2 je l3
  267. <code> <code>
  268. l2: l2:
  269. jmp l3 jmp l3
  270. the level parameter denotes how deeep we have already followed the jump,
  271. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  272. function GetFinalDestination(hp: taicpu; level: longint): boolean;
  273. function getlabelwithsym(sym: tasmlabel): tai;
  274. { Removes an instruction following hp1 (possibly with reg.deallocations in between),
  275. if its opcode is A_NOP. }
  276. procedure RemoveDelaySlot(hp1: tai);
  277. { peephole optimizer }
  278. procedure PrePeepHoleOpts; virtual;
  279. procedure PeepHoleOptPass1; virtual;
  280. procedure PeepHoleOptPass2; virtual;
  281. procedure PostPeepHoleOpts; virtual;
  282. { processor dependent methods }
  283. // if it returns true, perform a "continue"
  284. function PrePeepHoleOptsCpu(var p: tai): boolean; virtual;
  285. function PeepHoleOptPass1Cpu(var p: tai): boolean; virtual;
  286. function PeepHoleOptPass2Cpu(var p: tai): boolean; virtual;
  287. function PostPeepHoleOptsCpu(var p: tai): boolean; virtual;
  288. { insert debug comments about which registers are read and written by
  289. each instruction. Useful for debugging the InstructionLoadsFromReg and
  290. other similar functions. }
  291. procedure Debug_InsertInstrRegisterDependencyInfo; virtual;
  292. End;
  293. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  294. { ***************************** Implementation **************************** }
  295. Implementation
  296. uses
  297. cutils,
  298. globals,
  299. verbose,
  300. aoptutils,
  301. procinfo;
  302. function JumpTargetOp(ai: taicpu): poper; inline;
  303. begin
  304. {$if defined(MIPS) or defined(riscv64) or defined(riscv32)}
  305. { MIPS or RiscV branches can have 1,2 or 3 operands, target label is the last one. }
  306. result:=ai.oper[ai.ops-1];
  307. {$elseif defined(SPARC64)}
  308. if ai.ops=2 then
  309. result:=ai.oper[1]
  310. else
  311. result:=ai.oper[0];
  312. {$else MIPS}
  313. result:=ai.oper[0];
  314. {$endif}
  315. end;
  316. { ************************************************************************* }
  317. { ******************************** TUsedRegs ****************************** }
  318. { ************************************************************************* }
  319. Constructor TUsedRegs.create(aTyp : TRegisterType);
  320. Begin
  321. Typ:=aTyp;
  322. UsedRegs := [];
  323. End;
  324. Constructor TUsedRegs.create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  325. Begin
  326. Typ:=aTyp;
  327. UsedRegs := _RegSet;
  328. End;
  329. {
  330. updates UsedRegs with the RegAlloc Information coming after P
  331. }
  332. Procedure TUsedRegs.Update(p: Tai;IgnoreNewAllocs : Boolean = false);
  333. Begin
  334. { this code is normally not used because updating the register allocation information is done in
  335. TAOptObj.UpdateUsedRegs for speed reasons }
  336. repeat
  337. while assigned(p) and
  338. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  339. (p.typ = ait_label) or
  340. ((p.typ = ait_marker) and
  341. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  342. p := tai(p.next);
  343. while assigned(p) and
  344. (p.typ=ait_RegAlloc) Do
  345. begin
  346. if (getregtype(tai_regalloc(p).reg) = typ) then
  347. begin
  348. case tai_regalloc(p).ratype of
  349. ra_alloc :
  350. if not(IgnoreNewAllocs) then
  351. Include(UsedRegs, getsupreg(tai_regalloc(p).reg));
  352. ra_dealloc :
  353. Exclude(UsedRegs, getsupreg(tai_regalloc(p).reg));
  354. end;
  355. end;
  356. p := tai(p.next);
  357. end;
  358. until not(assigned(p)) or
  359. (not(p.typ in SkipInstr) and
  360. not((p.typ = ait_label) and
  361. labelCanBeSkipped(tai_label(p))));
  362. End;
  363. Function TUsedRegs.IsUsed(Reg: TRegister): Boolean;
  364. Begin
  365. IsUsed := (getregtype(Reg)=Typ) and (getsupreg(Reg) in UsedRegs);
  366. End;
  367. Function TUsedRegs.GetUsedRegs: TRegSet;
  368. Begin
  369. GetUsedRegs := UsedRegs;
  370. End;
  371. procedure TUsedRegs.Dump(var t: text);
  372. var
  373. i: dword;
  374. begin
  375. write(t,Typ,' ');
  376. for i:=low(TRegSet) to high(TRegSet) do
  377. if i in UsedRegs then
  378. write(t,i,' ');
  379. writeln(t);
  380. end;
  381. Destructor TUsedRegs.Destroy;
  382. Begin
  383. inherited destroy;
  384. end;
  385. procedure TUsedRegs.Clear;
  386. begin
  387. UsedRegs := [];
  388. end;
  389. { ************************************************************************* }
  390. { **************************** TPaiProp *********************************** }
  391. { ************************************************************************* }
  392. Constructor TPaiProp.Create;
  393. Begin
  394. {!!!!!!
  395. UsedRegs.Init;
  396. CondRegs.init;
  397. }
  398. { DirFlag: TFlagContents; I386 specific}
  399. End;
  400. Function TPaiProp.RegInSequence(Reg, which: TRegister): Boolean;
  401. {
  402. Var p: Tai;
  403. RegsChecked: TRegSet;
  404. content: TContent;
  405. Counter: Byte;
  406. TmpResult: Boolean;
  407. }
  408. begin
  409. Result:=False; { unimplemented }
  410. (*!!!!!!!!!!1
  411. RegsChecked := [];
  412. content := regs[which];
  413. p := content.StartMod;
  414. TmpResult := False;
  415. Counter := 1;
  416. While Not(TmpResult) And
  417. (Counter <= Content.NrOfMods) Do
  418. Begin
  419. If IsLoadMemReg(p) Then
  420. With PInstr(p)^.oper[LoadSrc]^.ref^ Do
  421. If (Base = ProcInfo.FramePointer)
  422. {$ifdef cpurefshaveindexreg}
  423. And (Index = R_NO)
  424. {$endif cpurefshaveindexreg} Then
  425. Begin
  426. RegsChecked := RegsChecked +
  427. [RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg)];
  428. If Reg = RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg) Then
  429. Break;
  430. End
  431. Else
  432. Begin
  433. If (Base = Reg) And
  434. Not(Base In RegsChecked)
  435. Then TmpResult := True;
  436. {$ifdef cpurefshaveindexreg}
  437. If Not(TmpResult) And
  438. (Index = Reg) And
  439. Not(Index In RegsChecked)
  440. Then TmpResult := True;
  441. {$Endif cpurefshaveindexreg}
  442. End
  443. Else TmpResult := RegInInstruction(Reg, p);
  444. Inc(Counter);
  445. GetNextInstruction(p,p)
  446. End;
  447. RegInSequence := TmpResult
  448. *)
  449. End;
  450. Procedure TPaiProp.DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  451. TInstrSinceLastMod);
  452. { Destroys the contents of the register Reg in the PPaiProp p1, as well as }
  453. { the contents of registers are loaded with a memory location based on Reg }
  454. {
  455. Var TmpWState, TmpRState: Byte;
  456. Counter: TRegister;
  457. }
  458. Begin
  459. {!!!!!!!
  460. Reg := RegMaxSize(Reg);
  461. If (Reg in [LoGPReg..HiGPReg]) Then
  462. For Counter := LoGPReg to HiGPReg Do
  463. With Regs[Counter] Do
  464. If (Counter = reg) Or
  465. ((Typ = Con_Ref) And
  466. RegInSequence(Reg, Counter)) Then
  467. Begin
  468. InstrSinceLastMod[Counter] := 0;
  469. IncWState(Counter);
  470. TmpWState := GetWState(Counter);
  471. TmpRState := GetRState(Counter);
  472. FillChar(Regs[Counter], SizeOf(TContent), 0);
  473. WState := TmpWState;
  474. RState := TmpRState
  475. End
  476. }
  477. End;
  478. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  479. Begin
  480. Result:=False; { unimplemented }
  481. (*!!!!!!!!!!
  482. ArrayRefsEq := (R1.Offset+R1.OffsetFixup = R2.Offset+R2.OffsetFixup) And
  483. {$ifdef refsHaveSegmentReg}
  484. (R1.Segment = R2.Segment) And
  485. {$endif}
  486. (R1.Base = R2.Base) And
  487. (R1.Symbol=R2.Symbol);
  488. *)
  489. End;
  490. Procedure TPaiProp.DestroyRefs(Const Ref: TReference; WhichReg: TRegister;
  491. var InstrSinceLastMod: TInstrSinceLastMod);
  492. { destroys all registers which possibly contain a reference to Ref, WhichReg }
  493. { is the register whose contents are being written to memory (if this proc }
  494. { is called because of a "mov?? %reg, (mem)" instruction) }
  495. {
  496. Var RefsEq: TRefCompare;
  497. Counter: TRegister;
  498. }
  499. Begin
  500. (*!!!!!!!!!!!
  501. WhichReg := RegMaxSize(WhichReg);
  502. If (Ref.base = procinfo.FramePointer) or
  503. Assigned(Ref.Symbol) Then
  504. Begin
  505. If
  506. {$ifdef cpurefshaveindexreg}
  507. (Ref.Index = R_NO) And
  508. {$endif cpurefshaveindexreg}
  509. (Not(Assigned(Ref.Symbol)) or
  510. (Ref.base = R_NO)) Then
  511. { local variable which is not an array }
  512. RefsEq := @RefsEqual
  513. Else
  514. { local variable which is an array }
  515. RefsEq := @ArrayRefsEq;
  516. {write something to a parameter, a local or global variable, so
  517. * with uncertain optimizations on:
  518. - destroy the contents of registers whose contents have somewhere a
  519. "mov?? (Ref), %reg". WhichReg (this is the register whose contents
  520. are being written to memory) is not destroyed if it's StartMod is
  521. of that form and NrOfMods = 1 (so if it holds ref, but is not a
  522. pointer or value based on Ref)
  523. * with uncertain optimizations off:
  524. - also destroy registers that contain any pointer}
  525. For Counter := LoGPReg to HiGPReg Do
  526. With Regs[Counter] Do
  527. Begin
  528. If (typ = Con_Ref) And
  529. ((Not(cs_opt_size in current_settings.optimizerswitches) And
  530. (NrOfMods <> 1)
  531. ) Or
  532. (RefInSequence(Ref,Regs[Counter], RefsEq) And
  533. ((Counter <> WhichReg) Or
  534. ((NrOfMods <> 1) And
  535. {StarMod is always of the type ait_instruction}
  536. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  537. RefsEq(PInstr(StartMod)^.oper[0].ref^, Ref)
  538. )
  539. )
  540. )
  541. )
  542. Then
  543. DestroyReg(Counter, InstrSinceLastMod)
  544. End
  545. End
  546. Else
  547. {write something to a pointer location, so
  548. * with uncertain optimzations on:
  549. - do not destroy registers which contain a local/global variable or a
  550. parameter, except if DestroyRefs is called because of a "movsl"
  551. * with uncertain optimzations off:
  552. - destroy every register which contains a memory location
  553. }
  554. For Counter := LoGPReg to HiGPReg Do
  555. With Regs[Counter] Do
  556. If (typ = Con_Ref) And
  557. (Not(cs_opt_size in current_settings.optimizerswitches) Or
  558. {$ifdef x86}
  559. {for movsl}
  560. (Ref.Base = R_EDI) Or
  561. {$endif}
  562. {don't destroy if reg contains a parameter, local or global variable}
  563. Not((NrOfMods = 1) And
  564. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  565. ((PInstr(StartMod)^.oper[0].ref^.base = ProcInfo.FramePointer) Or
  566. Assigned(PInstr(StartMod)^.oper[0].ref^.Symbol)
  567. )
  568. )
  569. )
  570. Then DestroyReg(Counter, InstrSinceLastMod)
  571. *)
  572. End;
  573. Procedure TPaiProp.DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  574. {Var Counter: TRegister;}
  575. Begin {initializes/desrtoys all registers}
  576. (*!!!!!!!!!
  577. For Counter := LoGPReg To HiGPReg Do
  578. Begin
  579. ReadReg(Counter);
  580. DestroyReg(Counter, InstrSinceLastMod);
  581. End;
  582. CondRegs.Init;
  583. { FPURegs.Init; }
  584. *)
  585. End;
  586. Procedure TPaiProp.DestroyOp(const o:Toper; var InstrSinceLastMod:
  587. TInstrSinceLastMod);
  588. Begin
  589. {!!!!!!!
  590. Case o.typ Of
  591. top_reg: DestroyReg(o.reg, InstrSinceLastMod);
  592. top_ref:
  593. Begin
  594. ReadRef(o.ref);
  595. DestroyRefs(o.ref^, R_NO, InstrSinceLastMod);
  596. End;
  597. top_symbol:;
  598. End;
  599. }
  600. End;
  601. Procedure TPaiProp.ReadReg(Reg: TRegister);
  602. Begin
  603. {!!!!!!!
  604. Reg := RegMaxSize(Reg);
  605. If Reg in General_Registers Then
  606. IncRState(RegMaxSize(Reg))
  607. }
  608. End;
  609. Procedure TPaiProp.ReadRef(Ref: PReference);
  610. Begin
  611. (*!!!!!!
  612. If Ref^.Base <> R_NO Then
  613. ReadReg(Ref^.Base);
  614. {$ifdef cpurefshaveindexreg}
  615. If Ref^.Index <> R_NO Then
  616. ReadReg(Ref^.Index);
  617. {$endif cpurefshaveindexreg}
  618. *)
  619. End;
  620. Procedure TPaiProp.ReadOp(const o:toper);
  621. Begin
  622. Case o.typ Of
  623. top_reg: ReadReg(o.reg);
  624. top_ref: ReadRef(o.ref);
  625. else
  626. internalerror(200410241);
  627. End;
  628. End;
  629. Procedure TPaiProp.ModifyReg(reg: TRegister; Var InstrSinceLastMod:
  630. TInstrSinceLastMod);
  631. Begin
  632. (*!!!!!!!
  633. With Regs[reg] Do
  634. If (Typ = Con_Ref)
  635. Then
  636. Begin
  637. IncState(WState);
  638. {also store how many instructions are part of the sequence in the first
  639. instructions PPaiProp, so it can be easily accessed from within
  640. CheckSequence}
  641. Inc(NrOfMods, InstrSinceLastMod[Reg]);
  642. PPaiProp(StartMod.OptInfo)^.Regs[Reg].NrOfMods := NrOfMods;
  643. InstrSinceLastMod[Reg] := 0;
  644. End
  645. Else
  646. DestroyReg(Reg, InstrSinceLastMod);
  647. *)
  648. End;
  649. Procedure TPaiProp.ModifyOp(const oper: TOper; var InstrSinceLastMod:
  650. TInstrSinceLastMod);
  651. Begin
  652. If oper.typ = top_reg Then
  653. ModifyReg(RegMaxSize(oper.reg),InstrSinceLastMod)
  654. Else
  655. Begin
  656. ReadOp(oper);
  657. DestroyOp(oper, InstrSinceLastMod);
  658. End
  659. End;
  660. Procedure TPaiProp.IncWState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  661. Begin
  662. //!!!! IncState(Regs[Reg].WState);
  663. End;
  664. Procedure TPaiProp.IncRState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  665. Begin
  666. //!!!! IncState(Regs[Reg].RState);
  667. End;
  668. Function TPaiProp.GetWState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  669. Begin
  670. Result:=0; { unimplemented }
  671. //!!!! GetWState := Regs[Reg].WState
  672. End;
  673. Function TPaiProp.GetRState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  674. Begin
  675. Result:=0; { unimplemented }
  676. //!!!! GetRState := Regs[Reg].RState
  677. End;
  678. Function TPaiProp.GetRegContentType(Reg: TRegister): Byte; {$ifdef inl} inline;{$endif inl}
  679. Begin
  680. Result:=0; { unimplemented }
  681. //!!!! GetRegContentType := Regs[Reg].typ
  682. End;
  683. Destructor TPaiProp.Done;
  684. Begin
  685. //!!!! UsedRegs.Done;
  686. //!!!! CondRegs.Done;
  687. { DirFlag: TFlagContents; I386 specific}
  688. End;
  689. { ************************ private TPaiProp stuff ************************* }
  690. Procedure TPaiProp.IncState(Var s: TStateInt); {$ifdef inl} inline;{$endif inl}
  691. Begin
  692. If s <> High(TStateInt) Then Inc(s)
  693. Else s := 0
  694. End;
  695. Function TPaiProp.RefInInstruction(Const Ref: TReference; p: Tai;
  696. RefsEq: TRefCompare): Boolean;
  697. Var Count: AWord;
  698. TmpResult: Boolean;
  699. Begin
  700. TmpResult := False;
  701. If (p.typ = ait_instruction) Then
  702. Begin
  703. Count := 0;
  704. Repeat
  705. If (TInstr(p).oper[Count]^.typ = Top_Ref) Then
  706. TmpResult := RefsEq(Ref, PInstr(p)^.oper[Count]^.ref^);
  707. Inc(Count);
  708. Until (Count = max_operands) or TmpResult;
  709. End;
  710. RefInInstruction := TmpResult;
  711. End;
  712. Function TPaiProp.RefInSequence(Const Ref: TReference; Content: TContent;
  713. RefsEq: TRefCompare): Boolean;
  714. Var p: Tai;
  715. Counter: Byte;
  716. TmpResult: Boolean;
  717. Begin
  718. p := Content.StartMod;
  719. TmpResult := False;
  720. Counter := 1;
  721. While Not(TmpResult) And
  722. (Counter <= Content.NrOfMods) Do
  723. Begin
  724. If (p.typ = ait_instruction) And
  725. RefInInstruction(Ref, p, @references_equal)
  726. Then TmpResult := True;
  727. Inc(Counter);
  728. GetNextInstruction(p,p)
  729. End;
  730. RefInSequence := TmpResult
  731. End;
  732. { ************************************************************************* }
  733. { ***************************** TAoptObj ********************************** }
  734. { ************************************************************************* }
  735. Constructor TAoptObj.create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  736. _LabelInfo: PLabelInfo);
  737. Begin
  738. AsmL := _AsmL;
  739. BlockStart := _BlockStart;
  740. BlockEnd := _BlockEnd;
  741. LabelInfo := _LabelInfo;
  742. CreateUsedRegs(UsedRegs);
  743. End;
  744. destructor TAOptObj.Destroy;
  745. var
  746. i : TRegisterType;
  747. begin
  748. for i:=low(TRegisterType) to high(TRegisterType) do
  749. UsedRegs[i].Destroy;
  750. inherited Destroy;
  751. end;
  752. procedure TAOptObj.CreateUsedRegs(var regs: TAllUsedRegs);
  753. var
  754. i : TRegisterType;
  755. begin
  756. for i:=low(TRegisterType) to high(TRegisterType) do
  757. Regs[i]:=TUsedRegs.Create(i);
  758. end;
  759. procedure TAOptObj.ClearUsedRegs;
  760. var
  761. i : TRegisterType;
  762. begin
  763. for i:=low(TRegisterType) to high(TRegisterType) do
  764. UsedRegs[i].Clear;
  765. end;
  766. procedure TAOptObj.UpdateUsedRegs(p : Tai);
  767. begin
  768. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  769. the code is duplicated here }
  770. repeat
  771. while assigned(p) and
  772. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  773. ((p.typ = ait_label) and
  774. labelCanBeSkipped(tai_label(p))) or
  775. ((p.typ = ait_marker) and
  776. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  777. p := tai(p.next);
  778. while assigned(p) and
  779. (p.typ=ait_RegAlloc) Do
  780. begin
  781. case tai_regalloc(p).ratype of
  782. ra_alloc :
  783. Include(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  784. ra_dealloc :
  785. Exclude(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  786. end;
  787. p := tai(p.next);
  788. end;
  789. until not(assigned(p)) or
  790. (not(p.typ in SkipInstr) and
  791. not((p.typ = ait_label) and
  792. labelCanBeSkipped(tai_label(p))));
  793. end;
  794. class procedure TAOptObj.UpdateUsedRegs(var Regs : TAllUsedRegs;p : Tai);
  795. var
  796. i : TRegisterType;
  797. begin
  798. for i:=low(TRegisterType) to high(TRegisterType) do
  799. Regs[i].Update(p);
  800. end;
  801. function TAOptObj.CopyUsedRegs(var dest: TAllUsedRegs): boolean;
  802. var
  803. i : TRegisterType;
  804. begin
  805. Result:=true;
  806. for i:=low(TRegisterType) to high(TRegisterType) do
  807. dest[i]:=TUsedRegs.Create_Regset(i,UsedRegs[i].GetUsedRegs);
  808. end;
  809. class procedure TAOptObj.ReleaseUsedRegs(const regs: TAllUsedRegs);
  810. var
  811. i : TRegisterType;
  812. begin
  813. for i:=low(TRegisterType) to high(TRegisterType) do
  814. regs[i].Free;
  815. end;
  816. class Function TAOptObj.RegInUsedRegs(reg : TRegister;regs : TAllUsedRegs) : boolean;
  817. begin
  818. result:=regs[getregtype(reg)].IsUsed(reg);
  819. end;
  820. class procedure TAOptObj.IncludeRegInUsedRegs(reg: TRegister;
  821. var regs: TAllUsedRegs);
  822. begin
  823. include(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  824. end;
  825. class procedure TAOptObj.ExcludeRegFromUsedRegs(reg: TRegister;
  826. var regs: TAllUsedRegs);
  827. begin
  828. exclude(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  829. end;
  830. function TAOptObj.GetAllocationString(const regs: TAllUsedRegs): string;
  831. var
  832. i : TRegisterType;
  833. j : TSuperRegister;
  834. begin
  835. Result:='';
  836. for i:=low(TRegisterType) to high(TRegisterType) do
  837. for j in regs[i].UsedRegs do
  838. Result:=Result+std_regname(newreg(i,j,R_SUBWHOLE))+' ';
  839. end;
  840. Function TAOptObj.FindLabel(L: TasmLabel; Var hp: Tai): Boolean;
  841. Var TempP: Tai;
  842. Begin
  843. TempP := hp;
  844. While Assigned(TempP) and
  845. (TempP.typ In SkipInstr + [ait_label,ait_align]) Do
  846. If (TempP.typ <> ait_Label) Or
  847. (Tai_label(TempP).labsym <> L)
  848. Then GetNextInstruction(TempP, TempP)
  849. Else
  850. Begin
  851. hp := TempP;
  852. FindLabel := True;
  853. exit
  854. End;
  855. FindLabel := False;
  856. End;
  857. Procedure TAOptObj.InsertLLItem(prev, foll, new_one : TLinkedListItem);
  858. Begin
  859. If Assigned(prev) Then
  860. If Assigned(foll) Then
  861. Begin
  862. If Assigned(new_one) Then
  863. Begin
  864. new_one.previous := prev;
  865. new_one.next := foll;
  866. prev.next := new_one;
  867. foll.previous := new_one;
  868. { should we update line information? }
  869. if (not (tai(new_one).typ in SkipLineInfo)) and
  870. (not (tai(foll).typ in SkipLineInfo)) then
  871. Tailineinfo(new_one).fileinfo := Tailineinfo(foll).fileinfo
  872. End
  873. End
  874. Else AsmL.Concat(new_one)
  875. Else If Assigned(Foll) Then AsmL.Insert(new_one)
  876. End;
  877. Function TAOptObj.SkipHead(P: Tai): Tai;
  878. Var OldP: Tai;
  879. Begin
  880. Repeat
  881. OldP := P;
  882. If (P.typ in SkipInstr) Or
  883. ((P.typ = ait_marker) And
  884. (Tai_Marker(P).Kind = mark_AsmBlockEnd)) Then
  885. GetNextInstruction(P, P)
  886. Else If ((P.Typ = Ait_Marker) And
  887. (Tai_Marker(P).Kind = mark_NoPropInfoStart)) Then
  888. { a marker of the type mark_NoPropInfoStart can't be the first instruction of a }
  889. { paasmoutput list }
  890. GetNextInstruction(Tai(P.Previous),P);
  891. If (P.Typ = Ait_Marker) And
  892. (Tai_Marker(P).Kind = mark_AsmBlockStart) Then
  893. Begin
  894. P := Tai(P.Next);
  895. While (P.typ <> Ait_Marker) Or
  896. (Tai_Marker(P).Kind <> mark_AsmBlockEnd) Do
  897. P := Tai(P.Next)
  898. End;
  899. Until P = OldP;
  900. SkipHead := P;
  901. End;
  902. Function TAOptObj.OpsEqual(const o1,o2:toper): Boolean;
  903. Begin
  904. if o1.typ=o2.typ then
  905. Case o1.typ Of
  906. Top_Reg :
  907. OpsEqual:=o1.reg=o2.reg;
  908. Top_Ref :
  909. OpsEqual:=
  910. references_equal(o1.ref^, o2.ref^) and
  911. (o1.ref^.volatility=[]) and
  912. (o2.ref^.volatility=[]);
  913. Top_Const :
  914. OpsEqual:=o1.val=o2.val;
  915. Top_None :
  916. OpsEqual := True
  917. else OpsEqual := False
  918. End
  919. else
  920. OpsEqual := False;
  921. End;
  922. Function TAOptObj.FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  923. Begin
  924. Result:=nil;
  925. Repeat
  926. While Assigned(StartPai) And
  927. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  928. {$ifdef cpudelayslot}
  929. ((startpai.typ=ait_instruction) and (taicpu(startpai).opcode=A_NOP)) or
  930. {$endif cpudelayslot}
  931. ((StartPai.typ = ait_label) and
  932. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  933. StartPai := Tai(StartPai.Next);
  934. If Assigned(StartPai) And
  935. (StartPai.typ = ait_regAlloc) Then
  936. Begin
  937. if (tai_regalloc(StartPai).ratype=ra_alloc) and
  938. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  939. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  940. begin
  941. Result:=tai_regalloc(StartPai);
  942. exit;
  943. end;
  944. StartPai := Tai(StartPai.Next);
  945. End
  946. else
  947. exit;
  948. Until false;
  949. End;
  950. Function TAOptObj.FindRegAllocBackward(Reg: TRegister; StartPai: Tai): tai_regalloc;
  951. Begin
  952. Result:=nil;
  953. Repeat
  954. While Assigned(StartPai) And
  955. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  956. ((StartPai.typ = ait_label) and
  957. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  958. StartPai := Tai(StartPai.Previous);
  959. If Assigned(StartPai) And
  960. (StartPai.typ = ait_regAlloc) Then
  961. Begin
  962. if (tai_regalloc(StartPai).ratype=ra_alloc) and
  963. SuperRegistersEqual(tai_regalloc(StartPai).Reg,Reg) then
  964. begin
  965. Result:=tai_regalloc(StartPai);
  966. exit;
  967. end;
  968. StartPai := Tai(StartPai.Previous);
  969. End
  970. else
  971. exit;
  972. Until false;
  973. End;
  974. function TAOptObj.FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  975. Begin
  976. Result:=nil;
  977. Repeat
  978. While Assigned(StartPai) And
  979. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  980. ((StartPai.typ = ait_label) and
  981. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  982. StartPai := Tai(StartPai.Next);
  983. If Assigned(StartPai) And
  984. (StartPai.typ = ait_regAlloc) Then
  985. Begin
  986. if (tai_regalloc(StartPai).ratype=ra_dealloc) and
  987. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  988. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  989. begin
  990. Result:=tai_regalloc(StartPai);
  991. exit;
  992. end;
  993. StartPai := Tai(StartPai.Next);
  994. End
  995. else
  996. exit;
  997. Until false;
  998. End;
  999. { allocates register reg between (and including) instructions p1 and p2
  1000. the type of p1 and p2 must not be in SkipInstr }
  1001. procedure TAOptObj.AllocRegBetween(reg: tregister; p1, p2: tai; var initialusedregs: TAllUsedRegs);
  1002. var
  1003. hp, start: tai;
  1004. removedsomething,
  1005. firstRemovedWasAlloc,
  1006. lastRemovedWasDealloc: boolean;
  1007. begin
  1008. {$ifdef EXTDEBUG}
  1009. { if assigned(p1.optinfo) and
  1010. (ptaiprop(p1.optinfo)^.usedregs <> initialusedregs) then
  1011. internalerror(2004101010); }
  1012. {$endif EXTDEBUG}
  1013. start := p1;
  1014. if (reg = NR_STACK_POINTER_REG) or
  1015. (reg = current_procinfo.framepointer) or
  1016. not(assigned(p1)) then
  1017. { this happens with registers which are loaded implicitely, outside the }
  1018. { current block (e.g. esi with self) }
  1019. exit;
  1020. { make sure we allocate it for this instruction }
  1021. getnextinstruction(p2,p2);
  1022. lastRemovedWasDealloc := false;
  1023. removedSomething := false;
  1024. firstRemovedWasAlloc := false;
  1025. {$ifdef allocregdebug}
  1026. hp := tai_comment.Create(strpnew('allocating '+std_regname(newreg(R_INTREGISTER,supreg,R_SUBWHOLE))+
  1027. ' from here...'));
  1028. insertllitem(asml,p1.previous,p1,hp);
  1029. hp := tai_comment.Create(strpnew('allocated '+std_regname(newreg(R_INTREGISTER,supreg,R_SUBWHOLE))+
  1030. ' till here...'));
  1031. insertllitem(asml,p2,p2.next,hp);
  1032. {$endif allocregdebug}
  1033. { do it the safe way: always allocate the full super register,
  1034. as we do no register re-allocation in the peephole optimizer,
  1035. this does not hurt
  1036. }
  1037. case getregtype(reg) of
  1038. R_MMREGISTER:
  1039. reg:=newreg(R_MMREGISTER,getsupreg(reg),R_SUBMMWHOLE);
  1040. R_INTREGISTER:
  1041. reg:=newreg(R_INTREGISTER,getsupreg(reg),R_SUBWHOLE);
  1042. R_FPUREGISTER:
  1043. reg:=newreg(R_FPUREGISTER,getsupreg(reg),R_SUBWHOLE);
  1044. R_ADDRESSREGISTER:
  1045. reg:=newreg(R_ADDRESSREGISTER,getsupreg(reg),R_SUBWHOLE);
  1046. else
  1047. Internalerror(2018030701);
  1048. end;
  1049. if not(RegInUsedRegs(reg,initialusedregs)) then
  1050. begin
  1051. hp := tai_regalloc.alloc(reg,nil);
  1052. insertllItem(p1.previous,p1,hp);
  1053. IncludeRegInUsedRegs(reg,initialusedregs);
  1054. end;
  1055. while assigned(p1) and
  1056. (p1 <> p2) do
  1057. begin
  1058. if assigned(p1.optinfo) then
  1059. internalerror(2014022301); // IncludeRegInUsedRegs(reg,ptaiprop(p1.optinfo)^.usedregs);
  1060. p1 := tai(p1.next);
  1061. repeat
  1062. while assigned(p1) and
  1063. (p1.typ in (SkipInstr-[ait_regalloc])) Do
  1064. p1 := tai(p1.next);
  1065. { remove all allocation/deallocation info about the register in between }
  1066. if assigned(p1) and
  1067. (p1.typ = ait_regalloc) then
  1068. begin
  1069. { same super register, different sub register? }
  1070. if SuperRegistersEqual(reg,tai_regalloc(p1).reg) and (tai_regalloc(p1).reg<>reg) then
  1071. begin
  1072. if (getsubreg(tai_regalloc(p1).reg)>getsubreg(reg)) or (getsubreg(reg)=R_SUBH) then
  1073. internalerror(2016101501);
  1074. tai_regalloc(p1).reg:=reg;
  1075. end;
  1076. if tai_regalloc(p1).reg=reg then
  1077. begin
  1078. if not removedSomething then
  1079. begin
  1080. firstRemovedWasAlloc := tai_regalloc(p1).ratype=ra_alloc;
  1081. removedSomething := true;
  1082. end;
  1083. lastRemovedWasDealloc := (tai_regalloc(p1).ratype=ra_dealloc);
  1084. hp := tai(p1.Next);
  1085. asml.Remove(p1);
  1086. p1.free;
  1087. p1 := hp;
  1088. end
  1089. else
  1090. p1 := tai(p1.next);
  1091. end;
  1092. until not(assigned(p1)) or
  1093. not(p1.typ in SkipInstr);
  1094. end;
  1095. if assigned(p1) then
  1096. begin
  1097. if firstRemovedWasAlloc then
  1098. begin
  1099. hp := tai_regalloc.Alloc(reg,nil);
  1100. insertLLItem(start.previous,start,hp);
  1101. end;
  1102. if lastRemovedWasDealloc then
  1103. begin
  1104. hp := tai_regalloc.DeAlloc(reg,nil);
  1105. insertLLItem(p1.previous,p1,hp);
  1106. end;
  1107. end;
  1108. end;
  1109. function TAOptObj.RegUsedAfterInstruction(reg: Tregister; p: tai;var AllUsedRegs: TAllUsedRegs): Boolean;
  1110. begin
  1111. AllUsedRegs[getregtype(reg)].Update(tai(p.Next),true);
  1112. RegUsedAfterInstruction :=
  1113. AllUsedRegs[getregtype(reg)].IsUsed(reg) and
  1114. not(regLoadedWithNewValue(reg,p)) and
  1115. (
  1116. not(GetNextInstruction(p,p)) or
  1117. InstructionLoadsFromReg(reg,p) or
  1118. not(regLoadedWithNewValue(reg,p))
  1119. );
  1120. end;
  1121. function TAOptObj.RegEndOfLife(reg : TRegister;p : taicpu) : boolean;
  1122. begin
  1123. Result:=assigned(FindRegDealloc(reg,tai(p.Next))) or
  1124. RegLoadedWithNewValue(reg,p);
  1125. end;
  1126. function TAOptObj.RemoveCurrentP(var p : tai) : boolean;
  1127. var
  1128. hp1 : tai;
  1129. begin
  1130. result:=GetNextInstruction(p,hp1);
  1131. { p will be removed, update used register as we continue
  1132. with the next instruction after p }
  1133. UpdateUsedRegs(tai(p.Next));
  1134. AsmL.Remove(p);
  1135. p.Free;
  1136. p:=hp1;
  1137. end;
  1138. function FindAnyLabel(hp: tai; var l: tasmlabel): Boolean;
  1139. begin
  1140. FindAnyLabel := false;
  1141. while assigned(hp.next) and
  1142. (tai(hp.next).typ in (SkipInstr+[ait_align])) Do
  1143. hp := tai(hp.next);
  1144. if assigned(hp.next) and
  1145. (tai(hp.next).typ = ait_label) then
  1146. begin
  1147. FindAnyLabel := true;
  1148. l := tai_label(hp.next).labsym;
  1149. end
  1150. end;
  1151. {$push}
  1152. {$r-}
  1153. function TAOptObj.getlabelwithsym(sym: tasmlabel): tai;
  1154. begin
  1155. if (int64(sym.labelnr) >= int64(labelinfo^.lowlabel)) and
  1156. (int64(sym.labelnr) <= int64(labelinfo^.highlabel)) then { range check, a jump can go past an assembler block! }
  1157. getlabelwithsym := labelinfo^.labeltable^[sym.labelnr-labelinfo^.lowlabel].paiobj
  1158. else
  1159. getlabelwithsym := nil;
  1160. end;
  1161. {$pop}
  1162. { Returns True if hp is an unconditional jump to a label }
  1163. function IsJumpToLabelUncond(hp: taicpu): boolean;
  1164. begin
  1165. {$if defined(avr)}
  1166. result:=(hp.opcode in aopt_uncondjmp) and
  1167. {$else avr}
  1168. result:=(hp.opcode=aopt_uncondjmp) and
  1169. {$endif avr}
  1170. {$if defined(arm) or defined(aarch64)}
  1171. (hp.condition=c_None) and
  1172. {$endif arm or aarch64}
  1173. {$if defined(riscv32) or defined(riscv64)}
  1174. (hp.ops>0) and
  1175. (hp.oper[0]^.reg=NR_X0) and
  1176. {$else riscv}
  1177. (hp.ops>0) and
  1178. {$endif riscv}
  1179. (JumpTargetOp(hp)^.typ = top_ref) and
  1180. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1181. end;
  1182. { Returns True if hp is any jump to a label }
  1183. function IsJumpToLabel(hp: taicpu): boolean;
  1184. begin
  1185. result:=hp.is_jmp and
  1186. (hp.ops>0) and
  1187. (JumpTargetOp(hp)^.typ = top_ref) and
  1188. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1189. end;
  1190. procedure TAOptObj.RemoveDelaySlot(hp1:tai);
  1191. var
  1192. hp2: tai;
  1193. begin
  1194. hp2:=tai(hp1.next);
  1195. while assigned(hp2) and (hp2.typ in SkipInstr) do
  1196. hp2:=tai(hp2.next);
  1197. if assigned(hp2) and (hp2.typ=ait_instruction) and
  1198. (taicpu(hp2).opcode=A_NOP) then
  1199. begin
  1200. asml.remove(hp2);
  1201. hp2.free;
  1202. end;
  1203. { Anything except A_NOP must be left in place: these instructions
  1204. execute before branch, so code stays correct if branch is removed. }
  1205. end;
  1206. function TAOptObj.GetFinalDestination(hp: taicpu; level: longint): boolean;
  1207. {traces sucessive jumps to their final destination and sets it, e.g.
  1208. je l1 je l3
  1209. <code> <code>
  1210. l1: becomes l1:
  1211. je l2 je l3
  1212. <code> <code>
  1213. l2: l2:
  1214. jmp l3 jmp l3
  1215. the level parameter denotes how deeep we have already followed the jump,
  1216. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  1217. var p1: tai;
  1218. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM)}
  1219. p2: tai;
  1220. l: tasmlabel;
  1221. {$endif}
  1222. begin
  1223. GetfinalDestination := false;
  1224. if level > 20 then
  1225. exit;
  1226. p1 := getlabelwithsym(tasmlabel(JumpTargetOp(hp)^.ref^.symbol));
  1227. if assigned(p1) then
  1228. begin
  1229. SkipLabels(p1,p1);
  1230. if (tai(p1).typ = ait_instruction) and
  1231. (taicpu(p1).is_jmp) then
  1232. if { the next instruction after the label where the jump hp arrives}
  1233. { is unconditional or of the same type as hp, so continue }
  1234. IsJumpToLabelUncond(taicpu(p1))
  1235. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM)}
  1236. { for MIPS, it isn't enough to check the condition; first operands must be same, too. }
  1237. or
  1238. conditions_equal(taicpu(p1).condition,hp.condition) or
  1239. { the next instruction after the label where the jump hp arrives
  1240. is the opposite of hp (so this one is never taken), but after
  1241. that one there is a branch that will be taken, so perform a
  1242. little hack: set p1 equal to this instruction (that's what the
  1243. last SkipLabels is for, only works with short bool evaluation)}
  1244. (conditions_equal(taicpu(p1).condition,inverse_cond(hp.condition)) and
  1245. SkipLabels(p1,p2) and
  1246. (p2.typ = ait_instruction) and
  1247. (taicpu(p2).is_jmp) and
  1248. (IsJumpToLabelUncond(taicpu(p2)) or
  1249. (conditions_equal(taicpu(p2).condition,hp.condition))) and
  1250. SkipLabels(p1,p1))
  1251. {$endif not MIPS and not RV64 and not RV32 and not JVM}
  1252. then
  1253. begin
  1254. { quick check for loops of the form "l5: ; jmp l5 }
  1255. if (tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).labelnr =
  1256. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).labelnr) then
  1257. exit;
  1258. if not GetFinalDestination(taicpu(p1),succ(level)) then
  1259. exit;
  1260. {$if defined(aarch64)}
  1261. { can't have conditional branches to
  1262. global labels on AArch64, because the
  1263. offset may become too big }
  1264. if not(taicpu(hp).condition in [C_None,C_AL,C_NV]) and
  1265. (tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).bind<>AB_LOCAL) then
  1266. exit;
  1267. {$endif aarch64}
  1268. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).decrefs;
  1269. JumpTargetOp(hp)^.ref^.symbol:=JumpTargetOp(taicpu(p1))^.ref^.symbol;
  1270. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).increfs;
  1271. end
  1272. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM)}
  1273. else
  1274. if conditions_equal(taicpu(p1).condition,inverse_cond(hp.condition)) then
  1275. if not FindAnyLabel(p1,l) then
  1276. begin
  1277. {$ifdef finaldestdebug}
  1278. insertllitem(asml,p1,p1.next,tai_comment.Create(
  1279. strpnew('previous label inserted'))));
  1280. {$endif finaldestdebug}
  1281. current_asmdata.getjumplabel(l);
  1282. insertllitem(p1,p1.next,tai_label.Create(l));
  1283. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).decrefs;
  1284. JumpTargetOp(hp)^.ref^.symbol := l;
  1285. l.increfs;
  1286. { this won't work, since the new label isn't in the labeltable }
  1287. { so it will fail the rangecheck. Labeltable should become a }
  1288. { hashtable to support this: }
  1289. { GetFinalDestination(asml, hp); }
  1290. end
  1291. else
  1292. begin
  1293. {$ifdef finaldestdebug}
  1294. insertllitem(asml,p1,p1.next,tai_comment.Create(
  1295. strpnew('next label reused'))));
  1296. {$endif finaldestdebug}
  1297. l.increfs;
  1298. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).decrefs;
  1299. JumpTargetOp(hp)^.ref^.symbol := l;
  1300. if not GetFinalDestination(hp,succ(level)) then
  1301. exit;
  1302. end;
  1303. {$endif not MIPS and not RV64 and not RV32 and not JVM}
  1304. end;
  1305. GetFinalDestination := true;
  1306. end;
  1307. procedure TAOptObj.PrePeepHoleOpts;
  1308. var
  1309. p: tai;
  1310. begin
  1311. p := BlockStart;
  1312. ClearUsedRegs;
  1313. while (p <> BlockEnd) Do
  1314. begin
  1315. UpdateUsedRegs(tai(p.next));
  1316. if PrePeepHoleOptsCpu(p) then
  1317. continue;
  1318. if assigned(p) then
  1319. begin
  1320. UpdateUsedRegs(p);
  1321. p:=tai(p.next);
  1322. end;
  1323. end;
  1324. end;
  1325. procedure TAOptObj.PeepHoleOptPass1;
  1326. var
  1327. p,hp1,hp2 : tai;
  1328. stoploop:boolean;
  1329. begin
  1330. repeat
  1331. stoploop:=true;
  1332. p := BlockStart;
  1333. ClearUsedRegs;
  1334. while (p <> BlockEnd) Do
  1335. begin
  1336. { I'am not sure why this is done, UsedRegs should reflect the register usage before the instruction
  1337. If an instruction needs the information of this, it can easily create a TempUsedRegs (FK)
  1338. UpdateUsedRegs(tai(p.next));
  1339. }
  1340. {$ifdef DEBUG_OPTALLOC}
  1341. if p.Typ=ait_instruction then
  1342. InsertLLItem(tai(p.Previous),p,tai_comment.create(strpnew(GetAllocationString(UsedRegs))));
  1343. {$endif DEBUG_OPTALLOC}
  1344. if PeepHoleOptPass1Cpu(p) then
  1345. begin
  1346. stoploop:=false;
  1347. UpdateUsedRegs(p);
  1348. continue;
  1349. end;
  1350. case p.Typ Of
  1351. ait_instruction:
  1352. begin
  1353. { Handle Jmp Optimizations }
  1354. if taicpu(p).is_jmp then
  1355. begin
  1356. { the following if-block removes all code between a jmp and the next label,
  1357. because it can never be executed
  1358. }
  1359. if IsJumpToLabelUncond(taicpu(p)) then
  1360. begin
  1361. hp2:=p;
  1362. while GetNextInstruction(hp2, hp1) and
  1363. (hp1.typ <> ait_label)
  1364. {$ifdef JVM}
  1365. and (hp1.typ <> ait_jcatch)
  1366. {$endif}
  1367. do
  1368. if not(hp1.typ in ([ait_label]+skipinstr)) then
  1369. begin
  1370. if (hp1.typ = ait_instruction) and
  1371. taicpu(hp1).is_jmp and
  1372. (JumpTargetOp(taicpu(hp1))^.typ = top_ref) and
  1373. (JumpTargetOp(taicpu(hp1))^.ref^.symbol is TAsmLabel) then
  1374. TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).decrefs;
  1375. { don't kill start/end of assembler block,
  1376. no-line-info-start/end etc }
  1377. if not(hp1.typ in [ait_align,ait_marker]) then
  1378. begin
  1379. {$ifdef cpudelayslot}
  1380. if (hp1.typ=ait_instruction) and (taicpu(hp1).is_jmp) then
  1381. RemoveDelaySlot(hp1);
  1382. {$endif cpudelayslot}
  1383. asml.remove(hp1);
  1384. hp1.free;
  1385. stoploop:=false;
  1386. end
  1387. else
  1388. hp2:=hp1;
  1389. end
  1390. else break;
  1391. end;
  1392. if GetNextInstruction(p, hp1) then
  1393. begin
  1394. SkipEntryExitMarker(hp1,hp1);
  1395. { remove unconditional jumps to a label coming right after them }
  1396. if IsJumpToLabelUncond(taicpu(p)) and
  1397. FindLabel(tasmlabel(JumpTargetOp(taicpu(p))^.ref^.symbol), hp1) and
  1398. { TODO: FIXME removing the first instruction fails}
  1399. (p<>blockstart) then
  1400. begin
  1401. tasmlabel(JumpTargetOp(taicpu(p))^.ref^.symbol).decrefs;
  1402. {$ifdef cpudelayslot}
  1403. RemoveDelaySlot(p);
  1404. {$endif cpudelayslot}
  1405. hp2:=tai(hp1.next);
  1406. asml.remove(p);
  1407. p.free;
  1408. p:=hp2;
  1409. stoploop:=false;
  1410. continue;
  1411. end
  1412. else if assigned(hp1) then
  1413. begin
  1414. { change the following jumps:
  1415. jmp<cond> lab_1 jmp<cond_inverted> lab_2
  1416. jmp lab_2 >>> <code>
  1417. lab_1: lab_2:
  1418. <code>
  1419. lab_2:
  1420. }
  1421. if hp1.typ = ait_label then
  1422. SkipLabels(hp1,hp1);
  1423. if (tai(hp1).typ=ait_instruction) and
  1424. IsJumpToLabelUncond(taicpu(hp1)) and
  1425. GetNextInstruction(hp1, hp2) and
  1426. IsJumpToLabel(taicpu(p)) and
  1427. FindLabel(tasmlabel(JumpTargetOp(taicpu(p))^.ref^.symbol), hp2) then
  1428. begin
  1429. if (taicpu(p).opcode=aopt_condjmp)
  1430. {$if defined(arm) or defined(aarch64)}
  1431. and (taicpu(p).condition<>C_None)
  1432. {$endif arm or aarch64}
  1433. {$if defined(aarch64)}
  1434. { can't have conditional branches to
  1435. global labels on AArch64, because the
  1436. offset may become too big }
  1437. and (tasmlabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).bind=AB_LOCAL)
  1438. {$endif aarch64}
  1439. then
  1440. begin
  1441. taicpu(p).condition:=inverse_cond(taicpu(p).condition);
  1442. tai_label(hp2).labsym.decrefs;
  1443. JumpTargetOp(taicpu(p))^.ref^.symbol:=JumpTargetOp(taicpu(hp1))^.ref^.symbol;
  1444. { when freeing hp1, the reference count
  1445. isn't decreased, so don't increase
  1446. taicpu(p).oper[0]^.ref^.symbol.increfs;
  1447. }
  1448. {$ifdef cpudelayslot}
  1449. RemoveDelaySlot(hp1);
  1450. {$endif cpudelayslot}
  1451. asml.remove(hp1);
  1452. hp1.free;
  1453. stoploop:=false;
  1454. GetFinalDestination(taicpu(p),0);
  1455. end
  1456. else
  1457. begin
  1458. GetFinalDestination(taicpu(p),0);
  1459. p:=tai(p.next);
  1460. continue;
  1461. end;
  1462. end
  1463. else if IsJumpToLabel(taicpu(p)) then
  1464. GetFinalDestination(taicpu(p),0);
  1465. end;
  1466. end;
  1467. end
  1468. else
  1469. { All other optimizes }
  1470. begin
  1471. end; { if is_jmp }
  1472. end;
  1473. end;
  1474. if assigned(p) then
  1475. begin
  1476. UpdateUsedRegs(p);
  1477. p:=tai(p.next);
  1478. end;
  1479. end;
  1480. until stoploop or not(cs_opt_level3 in current_settings.optimizerswitches);
  1481. end;
  1482. procedure TAOptObj.PeepHoleOptPass2;
  1483. var
  1484. p: tai;
  1485. begin
  1486. p := BlockStart;
  1487. ClearUsedRegs;
  1488. while (p <> BlockEnd) Do
  1489. begin
  1490. if PeepHoleOptPass2Cpu(p) then
  1491. continue;
  1492. if assigned(p) then
  1493. begin
  1494. UpdateUsedRegs(p);
  1495. p:=tai(p.next);
  1496. end;
  1497. end;
  1498. end;
  1499. procedure TAOptObj.PostPeepHoleOpts;
  1500. var
  1501. p: tai;
  1502. begin
  1503. p := BlockStart;
  1504. ClearUsedRegs;
  1505. while (p <> BlockEnd) Do
  1506. begin
  1507. UpdateUsedRegs(tai(p.next));
  1508. if PostPeepHoleOptsCpu(p) then
  1509. continue;
  1510. if assigned(p) then
  1511. begin
  1512. UpdateUsedRegs(p);
  1513. p:=tai(p.next);
  1514. end;
  1515. end;
  1516. end;
  1517. function TAOptObj.PrePeepHoleOptsCpu(var p : tai) : boolean;
  1518. begin
  1519. result := false;
  1520. end;
  1521. function TAOptObj.PeepHoleOptPass1Cpu(var p: tai): boolean;
  1522. begin
  1523. result := false;
  1524. end;
  1525. function TAOptObj.PeepHoleOptPass2Cpu(var p : tai) : boolean;
  1526. begin
  1527. result := false;
  1528. end;
  1529. function TAOptObj.PostPeepHoleOptsCpu(var p: tai): boolean;
  1530. begin
  1531. result := false;
  1532. end;
  1533. procedure TAOptObj.Debug_InsertInstrRegisterDependencyInfo;
  1534. var
  1535. p: tai;
  1536. ri: tregisterindex;
  1537. reg: TRegister;
  1538. commentstr: AnsiString;
  1539. registers_found: Boolean;
  1540. begin
  1541. p:=tai(AsmL.First);
  1542. while (p<>AsmL.Last) Do
  1543. begin
  1544. if p.typ=ait_instruction then
  1545. begin
  1546. {$ifdef x86}
  1547. taicpu(p).SetOperandOrder(op_att);
  1548. {$endif x86}
  1549. commentstr:='Instruction reads';
  1550. registers_found:=false;
  1551. for ri in tregisterindex do
  1552. begin
  1553. reg:=regnumber_table[ri];
  1554. if (reg<>NR_NO) and InstructionLoadsFromReg(reg,p) then
  1555. begin
  1556. commentstr:=commentstr+' '+std_regname(reg);
  1557. registers_found:=true;
  1558. end;
  1559. end;
  1560. if not registers_found then
  1561. commentstr:=commentstr+' no registers';
  1562. commentstr:=commentstr+' and writes new values in';
  1563. registers_found:=false;
  1564. for ri in tregisterindex do
  1565. begin
  1566. reg:=regnumber_table[ri];
  1567. if (reg<>NR_NO) and RegLoadedWithNewValue(reg,p) then
  1568. begin
  1569. commentstr:=commentstr+' '+std_regname(reg);
  1570. registers_found:=true;
  1571. end;
  1572. end;
  1573. if not registers_found then
  1574. commentstr:=commentstr+' no registers';
  1575. AsmL.InsertAfter(tai_comment.Create(strpnew(commentstr)),p);
  1576. end;
  1577. p:=tai(p.next);
  1578. end;
  1579. end;
  1580. End.