-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLuaSSAPasses.pas
More file actions
800 lines (696 loc) · 23.4 KB
/
Copy pathLuaSSAPasses.pas
File metadata and controls
800 lines (696 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
unit LuaSSAPasses;
{
LuaSSAPasses.pas - SSA pass manager and built-in optimisation passes.
Provides a lightweight pass manager that runs a sequence of named SSA
transformation passes over a PSSAFunction. Five built-in passes are
included:
1. TrivialPhiElim - collapse trivial PHI nodes
2. CopyPropagation - forward MOVE sources, eliminate dead MOVEs
3. ConstantFolding - evaluate BINOP / UNOP on compile-time constants
4. StrengthReduction - simplify algebraic identities (x*1, x+0, ...)
5. DeadCodeElim - remove nodes whose results are never used
All pass procedures are standalone (not class methods) so they can be
registered individually or composed into custom pipelines.
Usage:
var PM: TSSAPassManager;
PM := CreateDefaultPassManager;
try
PM.RunAll(SF);
finally
PM.Free;
end;
}
{$mode objfpc}{$H+}
interface
uses
SysUtils, LuaChunk, LuaSSA;
{ ======================================================================
Global change flag -- passes set this to True when they modify the IR.
Used by the pass manager for iterative convergence.
====================================================================== }
var
GPassChanged: Boolean;
{ ======================================================================
Pass manager
====================================================================== }
type
TSSAPassProc = procedure(SF: PSSAFunction);
TSSAPassInfo = record
Name : AnsiString;
Proc : TSSAPassProc;
Iterative: Boolean; { if True, run until no changes (max 10) }
end;
TSSAPassManager = class
private
FPasses: array of TSSAPassInfo;
FCount : Integer;
FDebug : Boolean;
public
constructor Create(Debug: Boolean = False);
procedure AddPass(const Name: AnsiString; Proc: TSSAPassProc;
Iterative: Boolean = False);
procedure RunAll(SF: PSSAFunction);
end;
{ ======================================================================
Built-in pass procedures
====================================================================== }
{ Replace SSA_MOVE defs with their source, eliminating redundant copies. }
procedure PassCopyPropagation(SF: PSSAFunction);
{ Collapse PHI nodes whose non-self-referencing operands are all identical. }
procedure PassTrivialPhiElim(SF: PSSAFunction);
{ Evaluate BINOP / UNOP on constant operands at compile time. }
procedure PassConstantFolding(SF: PSSAFunction);
{ Remove nodes whose Dest has zero uses (excluding side-effecting ops). }
procedure PassDeadCodeElim(SF: PSSAFunction);
{ Simplify algebraic identities like x*1, x+0, not not x. }
procedure PassStrengthReduction(SF: PSSAFunction);
{ ======================================================================
Factory
====================================================================== }
{ Create a pass manager with the standard optimisation pipeline. }
function CreateDefaultPassManager(Debug: Boolean = False): TSSAPassManager;
implementation
{ ======================================================================
TSSAPassManager
====================================================================== }
constructor TSSAPassManager.Create(Debug: Boolean);
begin
inherited Create;
FDebug := Debug;
FCount := 0;
SetLength(FPasses, 0);
end;
procedure TSSAPassManager.AddPass(const Name: AnsiString; Proc: TSSAPassProc;
Iterative: Boolean);
begin
Inc(FCount);
SetLength(FPasses, FCount);
FPasses[FCount - 1].Name := Name;
FPasses[FCount - 1].Proc := Proc;
FPasses[FCount - 1].Iterative := Iterative;
end;
procedure TSSAPassManager.RunAll(SF: PSSAFunction);
const
MaxIter = 10;
var
I, Iter: Integer;
begin
for I := 0 to FCount - 1 do begin
if FPasses[I].Iterative then begin
{ Run the pass repeatedly until it makes no changes, or MaxIter. }
Iter := 0;
repeat
GPassChanged := False;
if FDebug then
WriteLn('[PassManager] Running "', FPasses[I].Name,
'" (iteration ', Iter + 1, ')');
FPasses[I].Proc(SF);
Inc(Iter);
until (not GPassChanged) or (Iter >= MaxIter);
if FDebug and (Iter >= MaxIter) then
WriteLn('[PassManager] "', FPasses[I].Name,
'" hit max iterations (', MaxIter, ')');
end else begin
GPassChanged := False;
if FDebug then
WriteLn('[PassManager] Running "', FPasses[I].Name, '"');
FPasses[I].Proc(SF);
end;
end;
end;
{ ======================================================================
Internal helpers
====================================================================== }
{ Return True when two refs address the same SSA value. }
function SameValue(const A, B: TSSARef): Boolean; inline;
begin
Result := RefEqual(A, B);
end;
{ Return True if the node kind has side effects and must not be eliminated. }
function HasSideEffects(Kind: TSSAKind): Boolean;
begin
Result := Kind in [SSA_CALL, SSA_TAILCALL, SSA_RETURN,
SSA_SETGLOBAL, SSA_SETTABLE, SSA_SETUPVAL,
SSA_SETLIST, SSA_CLOSE];
end;
{ Helper math: floor function matching Lua semantics. }
function LuaFloor(X: Double): Double;
begin
Result := Int(X);
if (X < 0) and (Frac(X) <> 0) then
Result := Result - 1.0;
end;
{ Helper math: power function for constant folding. }
function LuaPower(Base, Exp: Double): Double;
begin
if Exp = 0.0 then
Result := 1.0
else if (Base = 0.0) and (Exp > 0) then
Result := 0.0
else if (Frac(Exp) = 0) and (Abs(Exp) < 100) then begin
{ Integer exponent -- iterate to avoid precision issues. }
Result := 1.0;
if Exp > 0 then begin
while Exp >= 1.0 do begin
Result := Result * Base;
Exp := Exp - 1.0;
end;
end else begin
while Exp <= -1.0 do begin
Result := Result / Base;
Exp := Exp + 1.0;
end;
end;
end else
{ General case -- use FPC built-in. }
Result := System.Exp(Exp * System.Ln(Abs(Base)));
end;
{ ------------------------------------------------------------------
Use-count map keyed by (Reg, Version).
Implemented as a flat array of (Reg, Version, Count) triples with
linear probing -- good enough for the small node counts we see.
------------------------------------------------------------------ }
type
TUseEntry = record
Reg, Version: Integer;
Count : Integer;
end;
TUseMap = record
Entries: array of TUseEntry;
Cap : Integer;
Len : Integer;
end;
procedure InitUseMap(out M: TUseMap; Cap: Integer);
var
I: Integer;
begin
M.Cap := Cap;
M.Len := 0;
SetLength(M.Entries, Cap);
for I := 0 to Cap - 1 do begin
M.Entries[I].Reg := -1;
M.Entries[I].Version := 0;
M.Entries[I].Count := 0;
end;
end;
function UseMapHash(Reg, Ver, Cap: Integer): Integer;
var
H: LongWord;
begin
H := LongWord(Reg) * 2654435761 + LongWord(Ver) * 40503;
Result := Integer(H mod LongWord(Cap));
end;
procedure IncUse(var M: TUseMap; Reg, Ver: Integer);
var
H: Integer;
begin
if Reg < 0 then Exit; { not a register ref }
H := UseMapHash(Reg, Ver, M.Cap);
while True do begin
if M.Entries[H].Reg = -1 then begin
{ empty slot -- insert }
M.Entries[H].Reg := Reg;
M.Entries[H].Version := Ver;
M.Entries[H].Count := 1;
Inc(M.Len);
Exit;
end;
if (M.Entries[H].Reg = Reg) and (M.Entries[H].Version = Ver) then begin
Inc(M.Entries[H].Count);
Exit;
end;
H := (H + 1) mod M.Cap;
end;
end;
function GetUseCount(const M: TUseMap; Reg, Ver: Integer): Integer;
var
H: Integer;
begin
Result := 0;
if Reg < 0 then Exit;
H := UseMapHash(Reg, Ver, M.Cap);
while True do begin
if M.Entries[H].Reg = -1 then Exit;
if (M.Entries[H].Reg = Reg) and (M.Entries[H].Version = Ver) then begin
Result := M.Entries[H].Count;
Exit;
end;
H := (H + 1) mod M.Cap;
end;
end;
{ Count a single ref into the use map. }
procedure CountRef(var M: TUseMap; const R: TSSARef); inline;
begin
if R.Reg >= 0 then
IncUse(M, R.Reg, R.Version);
end;
{ Rewrite every use of OldRef to NewRef across the entire function. }
procedure RewriteUses(SF: PSSAFunction; const OldRef, NewRef: TSSARef);
procedure Patch(var R: TSSARef); inline;
begin
if SameValue(R, OldRef) then
R := NewRef;
end;
var
I, J: Integer;
N: PSSANode;
begin
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
if N^.Kind = SSA_NOP then Continue;
Patch(N^.OpA);
Patch(N^.OpB);
Patch(N^.OpC);
for J := 0 to High(N^.ArgRefs) do
Patch(N^.ArgRefs[J]);
for J := 0 to High(N^.Operands) do
Patch(N^.Operands[J]);
end;
end;
{ Check whether any PHI node in the function uses the given ref. }
function UsedByPhi(SF: PSSAFunction; const R: TSSARef): Boolean;
var
I, J: Integer;
N: PSSANode;
begin
Result := False;
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
if N^.Kind <> SSA_PHI then Continue;
for J := 0 to High(N^.Operands) do begin
if SameValue(N^.Operands[J], R) then begin
Result := True;
Exit;
end;
end;
end;
end;
{ Try to resolve a constant value from a proto's K table.
Returns True if the ref is a constant and the value was extracted.
OutKind indicates what type of constant it is. }
function ResolveConst(Proto: PProto; const R: TSSARef;
out OutKind: TLuaConstKind;
out NVal: Double; out IVal: Int64;
out SVal: AnsiString; out BVal: Boolean): Boolean;
var
Idx: Integer;
begin
Result := False;
if R.Reg <> SSA_CONST_REG then Exit;
Idx := R.ConstIdx;
if (Idx < 0) or (Idx >= Length(Proto^.K)) then Exit;
OutKind := Proto^.K[Idx].Kind;
NVal := Proto^.K[Idx].NValue;
IVal := Proto^.K[Idx].IValue;
SVal := Proto^.K[Idx].SValue;
BVal := Proto^.K[Idx].BValue;
Result := True;
end;
{ Convenience: resolve a numeric constant (integer or float/number).
Returns True and sets Val if the ref is a numeric constant. }
function ResolveNumericConst(Proto: PProto; const R: TSSARef;
out Val: Double): Boolean;
var
Kind: TLuaConstKind;
NV: Double;
IV: Int64;
SV: AnsiString;
BV: Boolean;
begin
Result := False;
if not ResolveConst(Proto, R, Kind, NV, IV, SV, BV) then Exit;
case Kind of
lckNumber, lckFloat: begin Val := NV; Result := True; end;
lckInteger: begin Val := IV; Result := True; end;
end;
end;
{ ======================================================================
Pass 1 -- Trivial PHI elimination
======================================================================
A PHI node is trivial when all of its non-self-referencing operands
resolve to the same SSA value. In that case the PHI can be replaced
by a simple MOVE (or NOP if the source equals the destination). }
procedure PassTrivialPhiElim(SF: PSSAFunction);
var
I, J: Integer;
N: PSSANode;
Common: TSSARef;
AllSame: Boolean;
begin
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
if N^.Kind <> SSA_PHI then Continue;
if Length(N^.Operands) = 0 then Continue;
{ Find the first non-self operand as the candidate common value. }
Common := SSA_NO_REF;
AllSame := True;
for J := 0 to High(N^.Operands) do begin
{ Skip self-references (operand equals the PHI's own Dest). }
if SameValue(N^.Operands[J], N^.Dest) then Continue;
if Common.Reg = -1 then begin
{ First real operand -- set as the candidate. }
Common := N^.Operands[J];
end else if not SameValue(N^.Operands[J], Common) then begin
AllSame := False;
Break;
end;
end;
{ If all operands were self-refs, the PHI is unreachable -- nop it. }
if Common.Reg = -1 then begin
N^.Kind := SSA_NOP;
GPassChanged := True;
Continue;
end;
if not AllSame then Continue;
{ All non-self operands are identical. Replace the PHI. }
RewriteUses(SF, N^.Dest, Common);
if SameValue(N^.Dest, Common) then
N^.Kind := SSA_NOP
else begin
N^.Kind := SSA_MOVE;
N^.OpA := Common;
SetLength(N^.Operands, 0);
SetLength(N^.PhiBlocks, 0);
end;
GPassChanged := True;
end;
end;
{ ======================================================================
Pass 2 -- Copy propagation
======================================================================
For every MOVE node (Dest := OpA), replace all uses of Dest with OpA
throughout the function, then convert the MOVE to NOP. Skip if the
source is not a valid register ref or if the Dest is used by a PHI
node (PHI nodes are sensitive to register identity for control-flow
recovery in the decompiler). }
procedure PassCopyPropagation(SF: PSSAFunction);
var
I: Integer;
N: PSSANode;
begin
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
if N^.Kind <> SSA_MOVE then Continue;
{ Source must be a valid register reference. }
if N^.OpA.Reg < 0 then Continue;
{ Do not propagate copies that are consumed by PHI nodes -- the
decompiler's control-flow recovery depends on the register
identity of PHI operands. }
if UsedByPhi(SF, N^.Dest) then Continue;
{ Rewrite all uses of Dest -> OpA and kill the MOVE. }
RewriteUses(SF, N^.Dest, N^.OpA);
N^.Kind := SSA_NOP;
GPassChanged := True;
end;
end;
{ ======================================================================
Pass 3 -- Constant folding
======================================================================
Evaluate BINOP and UNOP nodes whose operands are compile-time
constants. The result is stored as a new synthetic constant in the
proto's K table and the node is rewritten to SSA_LOADK. }
procedure PassConstantFolding(SF: PSSAFunction);
var
I: Integer;
N: PSSANode;
ValA, ValB, ValR: Double;
Proto: PProto;
NewIdx: Integer;
Kind: TLuaConstKind;
NV: Double;
IV: Int64;
SV: AnsiString;
BV: Boolean;
BoolResult: Boolean;
begin
Proto := SF^.Proto;
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
{ --- BINOP constant folding --- }
if N^.Kind = SSA_BINOP then begin
if not ResolveNumericConst(Proto, N^.OpA, ValA) then Continue;
if not ResolveNumericConst(Proto, N^.OpB, ValB) then Continue;
case N^.BinOp of
bopAdd: ValR := ValA + ValB;
bopSub: ValR := ValA - ValB;
bopMul: ValR := ValA * ValB;
bopDiv: begin
if ValB = 0 then Continue; { avoid division by zero }
ValR := ValA / ValB;
end;
bopMod: begin
if ValB = 0 then Continue;
{ Lua mod: a - floor(a/b)*b }
ValR := ValA - LuaFloor(ValA / ValB) * ValB;
end;
bopPow: ValR := LuaPower(ValA, ValB);
bopIDiv: begin
if ValB = 0 then Continue;
ValR := LuaFloor(ValA / ValB);
end;
else
Continue; { unsupported binop for folding }
end;
{ Choose integer or float constant based on result. }
if (Frac(ValR) = 0) and (ValR >= Low(Int64)) and
(ValR <= High(Int64)) then
NewIdx := AddSyntheticConst(Proto, Trunc(ValR))
else
NewIdx := AddSyntheticFloatConst(Proto, ValR);
{ Rewrite node to LOADK. }
N^.Kind := SSA_LOADK;
N^.ConstIdx := NewIdx;
N^.OpA := SSA_NO_REF;
N^.OpB := SSA_NO_REF;
GPassChanged := True;
Continue;
end;
{ --- UNOP constant folding --- }
if N^.Kind = SSA_UNOP then begin
if not ResolveConst(Proto, N^.OpA, Kind, NV, IV, SV, BV) then
Continue;
case N^.UnOp of
uopNeg: begin
{ Negate a numeric constant. }
if not (Kind in [lckNumber, lckFloat, lckInteger]) then Continue;
if Kind = lckInteger then
NewIdx := AddSyntheticConst(Proto, -IV)
else
NewIdx := AddSyntheticFloatConst(Proto, -NV);
end;
uopNot: begin
{ Boolean inversion. In Lua, nil and false are falsy,
everything else is truthy. For constants we handle
booleans and nil. }
case Kind of
lckNil: BoolResult := True;
lckBoolean: BoolResult := not BV;
else
{ "not <number>" or "not <string>" is always false. }
BoolResult := False;
end;
{ Store as integer 0/1 constant (Lua LOADBOOL semantics). }
NewIdx := AddSyntheticConst(Proto, Ord(BoolResult));
end;
uopLen: begin
{ String length. }
if Kind <> lckString then Continue;
NewIdx := AddSyntheticConst(Proto, Length(SV));
end;
else
Continue;
end;
{ Rewrite node to LOADK. }
N^.Kind := SSA_LOADK;
N^.ConstIdx := NewIdx;
N^.OpA := SSA_NO_REF;
GPassChanged := True;
end;
end;
end;
{ ======================================================================
Pass 4 -- Strength reduction
======================================================================
Simplify algebraic identities where one operand is a known constant:
x * 1 => MOVE x x * 0 => LOADK 0
x + 0 => MOVE x x - 0 => MOVE x
not not x => MOVE x (double boolean negation)
The pass also handles the commutative variants (1 * x, 0 + x). }
procedure PassStrengthReduction(SF: PSSAFunction);
var
I, J: Integer;
N: PSSANode;
Proto: PProto;
ValA, ValB: Double;
AConst, BConst: Boolean;
ZeroIdx: Integer;
Inner: PSSANode;
begin
Proto := SF^.Proto;
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
{ --- BINOP identities --- }
if N^.Kind = SSA_BINOP then begin
AConst := ResolveNumericConst(Proto, N^.OpA, ValA);
BConst := ResolveNumericConst(Proto, N^.OpB, ValB);
{ At least one operand must be constant. }
if not (AConst or BConst) then Continue;
case N^.BinOp of
bopMul: begin
{ x * 1 => MOVE x }
if BConst and (ValB = 1.0) then begin
N^.Kind := SSA_MOVE;
{ OpA already holds the non-constant operand. }
N^.OpB := SSA_NO_REF;
GPassChanged := True;
end
{ 1 * x => MOVE x }
else if AConst and (ValA = 1.0) then begin
N^.Kind := SSA_MOVE;
N^.OpA := N^.OpB;
N^.OpB := SSA_NO_REF;
GPassChanged := True;
end
{ x * 0 => LOADK 0 }
else if BConst and (ValB = 0.0) then begin
ZeroIdx := AddSyntheticConst(Proto, 0);
N^.Kind := SSA_LOADK;
N^.ConstIdx := ZeroIdx;
N^.OpA := SSA_NO_REF;
N^.OpB := SSA_NO_REF;
GPassChanged := True;
end
{ 0 * x => LOADK 0 }
else if AConst and (ValA = 0.0) then begin
ZeroIdx := AddSyntheticConst(Proto, 0);
N^.Kind := SSA_LOADK;
N^.ConstIdx := ZeroIdx;
N^.OpA := SSA_NO_REF;
N^.OpB := SSA_NO_REF;
GPassChanged := True;
end;
end;
bopAdd: begin
{ x + 0 => MOVE x }
if BConst and (ValB = 0.0) then begin
N^.Kind := SSA_MOVE;
N^.OpB := SSA_NO_REF;
GPassChanged := True;
end
{ 0 + x => MOVE x }
else if AConst and (ValA = 0.0) then begin
N^.Kind := SSA_MOVE;
N^.OpA := N^.OpB;
N^.OpB := SSA_NO_REF;
GPassChanged := True;
end;
end;
bopSub: begin
{ x - 0 => MOVE x }
if BConst and (ValB = 0.0) then begin
N^.Kind := SSA_MOVE;
N^.OpB := SSA_NO_REF;
GPassChanged := True;
end;
{ Note: 0 - x is negation, NOT identity -- do not reduce. }
end;
end; { case BinOp }
Continue;
end;
{ --- UNOP: double boolean negation (not not x) --- }
if (N^.Kind = SSA_UNOP) and (N^.UnOp = uopNot) then begin
{ Check if the operand is itself a "not" node. }
if N^.OpA.Reg < 0 then Continue;
{ Find the defining node of OpA by scanning AllNodes. }
Inner := nil;
for J := 0 to High(SF^.AllNodes) do begin
if SF^.AllNodes[J]^.Kind = SSA_NOP then Continue;
if SameValue(SF^.AllNodes[J]^.Dest, N^.OpA) then begin
Inner := SF^.AllNodes[J];
Break;
end;
end;
if (Inner <> nil) and (Inner^.Kind = SSA_UNOP) and
(Inner^.UnOp = uopNot) then begin
{ not (not x) => MOVE x }
N^.Kind := SSA_MOVE;
N^.OpA := Inner^.OpA;
GPassChanged := True;
end;
end;
end;
end;
{ ======================================================================
Pass 5 -- Dead code elimination
======================================================================
Count uses for every SSA value. Any node whose Dest has zero uses
and no side effects is converted to SSA_NOP. PHI self-references
are excluded from the use count (a PHI that only references itself
is considered dead). }
procedure PassDeadCodeElim(SF: PSSAFunction);
var
UseMap: TUseMap;
I, J, Cap: Integer;
N: PSSANode;
UseCnt: Integer;
begin
{ Build use-count map, counting all nodes. }
Cap := Length(SF^.AllNodes) * 4 + 16;
InitUseMap(UseMap, Cap);
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
if N^.Kind = SSA_NOP then Continue;
CountRef(UseMap, N^.OpA);
CountRef(UseMap, N^.OpB);
CountRef(UseMap, N^.OpC);
for J := 0 to High(N^.ArgRefs) do
CountRef(UseMap, N^.ArgRefs[J]);
{ For PHI operands, count them -- self-refs will be subtracted below. }
for J := 0 to High(N^.Operands) do
CountRef(UseMap, N^.Operands[J]);
end;
{ Now eliminate dead nodes. }
for I := 0 to High(SF^.AllNodes) do begin
N := SF^.AllNodes[I];
if N^.Kind = SSA_NOP then Continue;
if N^.Dest.Reg < 0 then Continue; { no destination -- skip }
{ Never eliminate side-effecting nodes. }
if HasSideEffects(N^.Kind) then Continue;
{ Also preserve control-flow nodes. }
if N^.Kind in [SSA_JUMP, SSA_BRANCH, SSA_FORPREP, SSA_FORLOOP,
SSA_TFORLOOP] then Continue;
{ Get the raw use count. }
UseCnt := GetUseCount(UseMap, N^.Dest.Reg, N^.Dest.Version);
{ Subtract self-references for PHI nodes. }
if N^.Kind = SSA_PHI then begin
for J := 0 to High(N^.Operands) do begin
if SameValue(N^.Operands[J], N^.Dest) then
Dec(UseCnt);
end;
end;
{ If no external uses, the node is dead. }
if UseCnt <= 0 then begin
N^.Kind := SSA_NOP;
GPassChanged := True;
end;
end;
end;
{ ======================================================================
Factory function
====================================================================== }
function CreateDefaultPassManager(Debug: Boolean): TSSAPassManager;
begin
Result := TSSAPassManager.Create(Debug);
{ Standard pipeline order:
1. Eliminate trivial PHIs first -- simplifies the graph.
2. Propagate copies -- reduces MOVEs.
3. Fold constants -- evaluate compile-time expressions.
4. Reduce strength -- simplify algebraic patterns.
5. Eliminate dead code -- clean up unused nodes last. }
Result.AddPass('TrivialPhiElim', @PassTrivialPhiElim);
Result.AddPass('CopyPropagation', @PassCopyPropagation);
Result.AddPass('ConstantFolding', @PassConstantFolding);
Result.AddPass('StrengthReduction', @PassStrengthReduction);
Result.AddPass('DeadCodeElim', @PassDeadCodeElim);
end;
end.