-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLuaDecompNaming.inc
More file actions
1190 lines (1118 loc) · 44.3 KB
/
Copy pathLuaDecompNaming.inc
File metadata and controls
1190 lines (1118 loc) · 44.3 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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function TDecompiler.NodeIdx(Reg, Ver: Integer): Integer;
begin
if (Reg < 0) or (Reg >= FProto^.MaxStack) then
Result := -1
else
Result := Reg * FMaxVer + Ver;
end;
function TDecompiler.CountPhiUses(Reg, Ver: Integer): Integer;
var
I, J: Integer;
begin
Result := 0;
for I := 0 to High(FSF^.AllNodes) do
if (FSF^.AllNodes[I]^.Kind = SSA_PHI) and
(Length(FSF^.AllNodes[I]^.Operands) > 0) then
for J := 0 to High(FSF^.AllNodes[I]^.Operands) do
if (FSF^.AllNodes[I]^.Operands[J].Reg = Reg) and
(FSF^.AllNodes[I]^.Operands[J].Version = Ver) then
Inc(Result);
end;
function TDecompiler.ConstStr(Idx: Integer): AnsiString;
begin
if (Idx < 0) or (Idx >= Length(FProto^.K)) then begin
Result := '?K' + IntToStr(Idx); Exit;
end;
case FProto^.K[Idx].Kind of
lckNil: Result := 'nil';
lckBoolean: if FProto^.K[Idx].BValue then Result := 'true' else Result := 'false';
lckNumber: begin
if (Frac(FProto^.K[Idx].NValue) = 0) and
(FProto^.K[Idx].NValue >= -1e15) and
(FProto^.K[Idx].NValue <= 1e15) then
Result := IntToStr(Trunc(FProto^.K[Idx].NValue))
else
Result := FloatToStr(FProto^.K[Idx].NValue);
end;
lckString: Result := '"' + EscapeString(FProto^.K[Idx].SValue) + '"';
lckInteger: Result := IntToStr(FProto^.K[Idx].IValue);
lckFloat: begin
if (Frac(FProto^.K[Idx].NValue) = 0) and
(FProto^.K[Idx].NValue >= -1e15) and
(FProto^.K[Idx].NValue <= 1e15) then
Result := IntToStr(Trunc(FProto^.K[Idx].NValue))
else
Result := FloatToStr(FProto^.K[Idx].NValue);
end;
else
Result := '?';
end;
end;
function TDecompiler.LocVarInScope(VarIdx, PC: Integer): Boolean;
{ Check whether LocVar at index VarIdx is "in scope" at the given PC.
Normal case: StartPC <= PC <= EndPC.
We use <= EndPC (not < EndPC) because the decompiler emits PHI nodes at
the exact boundary where the Lua VM considers the variable "just dead".
For example, the last or/and assignment to a local before RETURN creates
a PHI at PC = EndPC. The standard Lua convention (StartPC <= PC < EndPC)
would miss this, causing the assignment to be dropped.
Degenerate case: StartPC = EndPC (last local before RETURN).
Lua 5.1 compiler sets startpc to the PC after the defining instruction,
and endpc = startpc when the local goes out of scope immediately.
Treat as in-scope at the defining instruction (StartPC - 1) too.
MMBIN scope shift (Lua 5.4+):
In Lua 5.4+, arithmetic ops (ADD, SUB, MUL, etc.) are followed by
MMBIN/MMBINI/MMBINK metamethod hint instructions. The compiler sets
LocVar StartPC to the MMBIN instruction rather than the defining
arithmetic instruction. So when PC = StartPC - 1, the actual defining
instruction is at PC and the variable should be considered in scope. }
var
SOp: TSemanticOp;
begin
with FProto^.LocVars[VarIdx] do begin
if (StartPC <= PC) and (PC <= EndPC) then
Result := True
else if (StartPC = EndPC) and (StartPC > 0) and
(PC = StartPC - 1) then
Result := True
{ Lua 5.4+ MMBIN scope shift: arithmetic ops are followed by
MMBIN/MMBINI/MMBINK metamethod hints. The compiler sets LocVar
StartPC to the instruction AFTER the MMBIN, so the defining
arithmetic instruction is at StartPC - 2 and the MMBIN is at
StartPC - 1. Extend scope backward to cover the MMBIN only.
The defining instruction at StartPC-2 gets coverage via callers
that check IsUserLocal(reg, PC+1) since (StartPC-2)+1 = StartPC-1.
We do NOT extend to StartPC-2 directly to avoid false positives
where an earlier CALL at StartPC-3 checks IsUserLocal(reg, PC+1)
and incorrectly matches StartPC-2. }
else if (FSF^.LuaVersion >= $54) and (FOpts.OT <> nil) and
(StartPC >= 2) and (PC = StartPC - 1) and
(StartPC - 1 < Length(FProto^.Code)) then begin
SOp := DecodeOp(FOpts.OT^, FProto^.Code[StartPC - 1]);
Result := SOp in [semMMBIN, semMMBINI, semMMBINK];
end
else
Result := False;
end;
end;
function TDecompiler.LocalName(Reg, PC: Integer): AnsiString;
var
I: Integer;
CurReg: Integer;
J: Integer;
begin
for I := 0 to High(FProto^.LocVars) do
if LocVarInScope(I, PC) then begin
{ Count how many LocVars are in scope before this one at the same register }
CurReg := 0;
for J := 0 to I do begin
if LocVarInScope(J, PC) then begin
if CurReg = Reg then begin
Result := FProto^.LocVars[J].Name;
Exit;
end;
Inc(CurReg);
end;
end;
end;
{ No LocVar found: check parameter overrides (for upvalue collision avoidance),
then use 'a<N>' for parameter registers, 't<N>' for temporaries. }
if (Reg < FProto^.NumParams) and (Reg < Length(FParamOverrides)) and
(FParamOverrides[Reg] <> '') then
Result := FParamOverrides[Reg]
else
Result := TempName(Reg);
end;
function TDecompiler.IsUserLocal(Reg, PC: Integer): Boolean;
var
VName: AnsiString;
begin
VName := LocalName(Reg, PC);
{ A user local has a real name, not a generated t<N> or a<N> temp }
if (VName = 't' + IntToStr(Reg)) or (VName = TempName(Reg)) then begin
Result := False; Exit; { generated temp name }
end;
if (VName = 'a' + IntToStr(Reg)) or (VName = TempName(Reg)) then begin
Result := False; Exit; { generated param name (stripped bytecode) }
end;
{ Also exclude internal for-loop variables (for index), (for limit) etc. }
if (Length(VName) > 0) and (VName[1] = '(') then begin
Result := False; Exit;
end;
{ Skip the implicit "arg" local in Lua 5.0/5.1 compat vararg functions.
This is an auto-generated variable that shouldn't be treated as user-written.
Only applies to 5.1 where bit 0 (VARARG_HASARG) indicates the implicit arg table. }
if (FSF^.LuaVersion <= $51) and
(VName = 'arg') and (FProto^.IsVarArg and 1 <> 0) and
(Reg = FProto^.NumParams) then begin
Result := False; Exit;
end;
Result := True;
end;
function TDecompiler.IsUserLocalStrict(Reg, PC: Integer): Boolean;
{ Like IsUserLocal, but uses strict Lua convention (PC < EndPC) for the
upper bound instead of the relaxed (PC <= EndPC). Use this for definition
sites (MOVE, LOADK, etc.) where we need to distinguish "variable still
alive for reassignment" from "variable just died and register is reused".
The relaxed form in LocVarInScope extends scope to include EndPC for PHI
boundary nodes, but that causes false positives at definition sites. }
var
I, J, CurReg: Integer;
begin
{ Check if any LocVar is in scope using strict upper bound }
CurReg := 0;
for I := 0 to High(FProto^.LocVars) do begin
with FProto^.LocVars[I] do begin
if (StartPC <= PC) and (PC < EndPC) then begin
if CurReg = Reg then begin
{ Found matching register - apply same filters as IsUserLocal }
if (Length(Name) > 0) and (Name[1] = '(') then begin
Result := False; Exit;
end;
if (Name = 't' + IntToStr(Reg)) or (Name = TempName(Reg)) then begin
Result := False; Exit;
end;
if (Name = 'a' + IntToStr(Reg)) or (Name = TempName(Reg)) then begin
Result := False; Exit;
end;
if (FSF^.LuaVersion <= $51) and
(Name = 'arg') and (FProto^.IsVarArg and 1 <> 0) and
(Reg = FProto^.NumParams) then begin
Result := False; Exit;
end;
Result := True;
Exit;
end;
Inc(CurReg);
end
else if (StartPC = EndPC) and (StartPC > 0) and (PC = StartPC - 1) then begin
if CurReg = Reg then begin
if (Length(Name) > 0) and (Name[1] = '(') then begin
Result := False; Exit;
end;
Result := True;
Exit;
end;
Inc(CurReg);
end;
end;
end;
Result := False;
end;
function TDecompiler.ShouldEmitAsLocal(Reg, PC: Integer): Boolean;
var
I, J, CurReg: Integer;
begin
Result := False;
for I := 0 to 16 do begin
if IsUserLocal(Reg, PC + I) then begin
Result := True;
Exit;
end;
end;
{ Also check for degenerate LocVars (StartPC > EndPC) that are never
in scope via the normal LocVarInScope check. If PC is near StartPC-1,
this register should still be treated as a local. }
for I := 0 to High(FProto^.LocVars) do begin
if (FProto^.LocVars[I].StartPC > FProto^.LocVars[I].EndPC) and
(FProto^.LocVars[I].StartPC > 0) then begin
{ Check if PC is within range of the defining instruction (StartPC-1) }
if (PC >= FProto^.LocVars[I].StartPC - 1 - 16) and
(PC <= FProto^.LocVars[I].StartPC - 1) then begin
{ Verify register mapping: count LocVars in scope at StartPC-1 }
CurReg := 0;
for J := 0 to I do begin
if LocVarInScope(J, FProto^.LocVars[I].StartPC - 1) or
((FProto^.LocVars[J].StartPC > FProto^.LocVars[J].EndPC) and
(J = I)) then begin
if CurReg = Reg then begin
if J = I then Result := True;
Exit;
end;
Inc(CurReg);
end;
end;
end;
end;
end;
end;
function TDecompiler.LocalNameForEmit(Reg, PC: Integer): AnsiString;
var
I, J, CurReg: Integer;
Name0, Name1: AnsiString;
begin
for I := 0 to 16 do begin
if IsUserLocal(Reg, PC + I) then begin
Result := LocalName(Reg, PC + I);
{ When we found a match at the exact PC (i=0), check if the NEXT PC
has a DIFFERENT name for the same register. If so, the current name
is at its EndPC boundary (scope ending), and the next one is the
new LocVar being defined. Prefer the new LocVar for assignments. }
if (I = 0) and IsUserLocal(Reg, PC + 1) then begin
Name0 := Result;
Name1 := LocalName(Reg, PC + 1);
if Name0 <> Name1 then begin
if FOpts.Debug then
WriteLn(StdErr, 'LocalNameForEmit: Reg=', Reg, ' PC=', PC,
' boundary override: ', Name0, ' -> ', Name1);
Result := Name1;
end;
end;
if FOpts.Debug then
WriteLn(StdErr, 'LocalNameForEmit: Reg=', Reg, ' PC=', PC,
' i=', I, ' Result=', Result);
Exit;
end;
end;
{ Check degenerate LocVars (StartPC > EndPC) }
for I := 0 to High(FProto^.LocVars) do begin
if (FProto^.LocVars[I].StartPC > FProto^.LocVars[I].EndPC) and
(FProto^.LocVars[I].StartPC > 0) and
(PC >= FProto^.LocVars[I].StartPC - 1 - 16) and
(PC <= FProto^.LocVars[I].StartPC - 1) then begin
CurReg := 0;
for J := 0 to I do begin
if LocVarInScope(J, FProto^.LocVars[I].StartPC - 1) or
((FProto^.LocVars[J].StartPC > FProto^.LocVars[J].EndPC) and
(J = I)) then begin
if CurReg = Reg then begin
if J = I then begin
Result := FProto^.LocVars[I].Name;
Exit;
end;
Break;
end;
Inc(CurReg);
end;
end;
end;
end;
Result := TempName(Reg);
end;
function TDecompiler.NeedsLocalDecl(Reg, PC: Integer): Boolean;
var
I, J, CurReg, CheckPC: Integer;
FoundLocVar: Boolean;
begin
Result := False;
FoundLocVar := False;
if Length(FDeclared) > 0 then begin
for I := 0 to High(FProto^.LocVars) do begin
if I >= Length(FDeclared) then Break;
if FDeclared[I] then Continue;
{ Skip internal for-loop variables }
if (Length(FProto^.LocVars[I].Name) > 0) and
(FProto^.LocVars[I].Name[1] = '(') then Continue;
{ Skip generated temp names }
if FProto^.LocVars[I].Name = '' then Continue;
{ Skip the implicit "arg" local in Lua 5.0/5.1 compat vararg functions.
IsVarArg bit 0 (VARARG_HASARG) = has implicit arg table.
The "arg" LocVar is always the first non-param local (index = NumParams).
Only applies to 5.1 where bit 0 means VARARG_HASARG. }
if (FSF^.LuaVersion <= $51) and
(FProto^.IsVarArg and 1 <> 0) and (I = FProto^.NumParams) and
(FProto^.LocVars[I].Name = 'arg') then Continue;
{ The defining instruction is typically at StartPC-1 or within a few PCs before.
For degenerate LocVars (StartPC = EndPC, last local before RETURN),
use StartPC-1 as the check point since that's the actual defining instruction. }
CheckPC := FProto^.LocVars[I].StartPC;
if (FProto^.LocVars[I].StartPC = FProto^.LocVars[I].EndPC) and
(CheckPC > 0) then
Dec(CheckPC);
if (PC < CheckPC - 16) or (PC > CheckPC) then Continue;
{ Verify register mapping: count in-scope LocVars at CheckPC to find which register this LocVar maps to }
CurReg := 0;
for J := 0 to I do begin
if LocVarInScope(J, CheckPC) then begin
if CurReg = Reg then begin
if J = I then begin
FDeclared[I] := True;
Result := True;
FoundLocVar := True;
end;
Exit;
end;
Inc(CurReg);
end;
end;
end;
end;
{ For temp registers with no LocVar match (stripped bytecode), check FTempDeclared.
Only applies when the register is NOT a user local (would be handled above). }
if (not FoundLocVar) and (not Result) and
(not IsUserLocal(Reg, PC)) and (not IsUserLocal(Reg, PC + 1)) then
Result := NeedsTempLocal(Reg);
end;
function TDecompiler.IsBareLocalDecl(Reg, PC: Integer): Boolean;
{ Returns True when the LocVar for Reg at PC has StartPC = PC, meaning
the Lua source had a bare "local a" declaration with no initializer.
In that case, the instruction at PC is a plain assignment, not a
"local a = expr" combined declaration+init.
Lua 5.1 compiler convention:
local a = expr -> StartPC = PC_of_init_instr + 1
local a -> StartPC = current_PC (no instruction emitted) }
var
I, J, CurReg: Integer;
begin
Result := False;
for I := 0 to High(FProto^.LocVars) do begin
if FProto^.LocVars[I].StartPC <> PC then Continue;
{ Skip internal for-loop variables }
if (Length(FProto^.LocVars[I].Name) > 0) and
(FProto^.LocVars[I].Name[1] = '(') then Continue;
{ Verify register mapping at StartPC }
CurReg := 0;
for J := 0 to I do begin
if LocVarInScope(J, PC) then begin
if CurReg = Reg then begin
if J = I then
Result := True;
Exit;
end;
Inc(CurReg);
end;
end;
end;
end;
function TDecompiler.IsOnlyPhiUsed(Reg, Version: Integer): Boolean;
var
I, J: Integer;
Node: PSSANode;
Ref: TSSARef;
Found: Boolean;
begin
{ Returns True if ALL consumers of (Reg, Version) are PHI nodes.
This means the value cannot be inlined and must be emitted as a statement. }
Result := False;
Found := False;
Ref.Reg := Reg;
Ref.Version := Version;
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
if Node^.Kind = SSA_PHI then begin
{ PHI operands are in Operands array }
for J := 0 to High(Node^.Operands) do
if (Node^.Operands[J].Reg = Reg) and (Node^.Operands[J].Version = Version) then
Found := True;
end else begin
{ Non-PHI: check OpA, OpB, OpC, ArgRefs }
if (Node^.OpA.Reg = Reg) and (Node^.OpA.Version = Version) then Exit;
if (Node^.OpB.Reg = Reg) and (Node^.OpB.Version = Version) then Exit;
if (Node^.OpC.Reg = Reg) and (Node^.OpC.Version = Version) then Exit;
for J := 0 to High(Node^.ArgRefs) do
if (Node^.ArgRefs[J].Reg = Reg) and (Node^.ArgRefs[J].Version = Version) then Exit;
end;
end;
Result := Found; { Only return True if at least one PHI uses it, and no non-PHI uses it }
end;
function TDecompiler.IsOnlyTrivialPhiUsed(Reg, Version: Integer): Boolean;
{ Returns True if (Reg, Version) is only consumed by PHI nodes where ALL
operands of each consuming PHI trace back to the same kind of defining
node with the same constant. Currently checks for GETGLOBAL trivial PHIs
(all operands are GETGLOBAL with the same constant index).
When True, the value can be safely inlined rather than emitted as a temp. }
var
I, J, K, M: Integer;
Node, OpDef, FirstOpDef: PSSANode;
Found, AllTrivial: Boolean;
begin
Result := False;
Found := False;
AllTrivial := True;
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
if Node^.Kind = SSA_PHI then begin
{ Check if this PHI uses (Reg, Version) in any operand }
for J := 0 to High(Node^.Operands) do
if (Node^.Operands[J].Reg = Reg) and (Node^.Operands[J].Version = Version) then begin
Found := True;
{ Check if ALL operands of this PHI are the same GETGLOBAL }
FirstOpDef := nil;
for K := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[K]^.Dest, Node^.Operands[0]) then begin
FirstOpDef := FSF^.AllNodes[K]; Break;
end;
if (FirstOpDef = nil) or (FirstOpDef^.Kind <> SSA_GETGLOBAL) then begin
AllTrivial := False; Break;
end;
for K := 1 to High(Node^.Operands) do begin
OpDef := nil;
for M := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[M]^.Dest, Node^.Operands[K]) then begin
OpDef := FSF^.AllNodes[M]; Break;
end;
if (OpDef = nil) or (OpDef^.Kind <> SSA_GETGLOBAL) or
(OpDef^.ConstIdx <> FirstOpDef^.ConstIdx) then begin
AllTrivial := False; Break;
end;
end;
Break; { Done checking this PHI }
end;
if not AllTrivial then Break;
end else begin
{ Non-PHI: check OpA, OpB, OpC, ArgRefs - if any non-PHI use exists,
this is not "only trivial PHI used" }
if (Node^.OpA.Reg = Reg) and (Node^.OpA.Version = Version) then Exit;
if (Node^.OpB.Reg = Reg) and (Node^.OpB.Version = Version) then Exit;
if (Node^.OpC.Reg = Reg) and (Node^.OpC.Version = Version) then Exit;
for J := 0 to High(Node^.ArgRefs) do
if (Node^.ArgRefs[J].Reg = Reg) and (Node^.ArgRefs[J].Version = Version) then Exit;
end;
end;
Result := Found and AllTrivial;
end;
function TDecompiler.IsUpvalCaptured(Reg, DefPC: Integer): Boolean;
{ Returns True if the given register at DefPC is captured as an upvalue by
any sub-proto CLOSURE. Uses SSA info: for each CLOSURE that captures Reg
via pseudo-MOVE, check if the register is NOT redefined (by a non-NOP SSA
node) between DefPC and the CLOSURE PC. }
var
I, J, K, NUps, PseudoPC, B: Integer;
Node, ScanNode: PSSANode;
SubProto: PProto;
Inst: TInstruction;
Redefined: Boolean;
begin
Result := False;
for I := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[I];
if Node^.Kind <> SSA_CLOSURE then Continue;
if Node^.PC <= DefPC then Continue; { CLOSURE must come after definition }
if (Node^.ConstIdx < 0) or (Node^.ConstIdx >= Length(FProto^.P)) then Continue;
SubProto := FProto^.P[Node^.ConstIdx];
NUps := SubProto^.NUps;
for J := 0 to NUps - 1 do begin
PseudoPC := Node^.PC + 1 + J;
if PseudoPC >= Length(FProto^.Code) then Continue;
Inst := FProto^.Code[PseudoPC];
if GET_OPCODE(Inst) = OP_MOVE then begin
B := GETARG_B(Inst);
if B = Reg then begin
{ Check SSA nodes between DefPC and CLOSURE PC for redefinition }
Redefined := False;
for K := 0 to High(FSF^.AllNodes) do begin
ScanNode := FSF^.AllNodes[K];
if ScanNode^.Kind in [SSA_NOP, SSA_PHI, SSA_JUMP] then Continue;
if (ScanNode^.Dest.Reg = Reg) and
(ScanNode^.PC > DefPC) and (ScanNode^.PC < Node^.PC) then begin
Redefined := True;
Break;
end;
end;
if not Redefined then begin
Result := True;
Exit;
end;
end;
end;
end;
end;
end;
function TDecompiler.ShouldEmitTemp(Reg, Version, PC: Integer): Boolean;
{ Returns True if a register with no LocVar should still be emitted as a
temp variable statement (not inlined). This catches:
1. Values with multiple non-PHI uses that cannot be safely inlined
2. Values used only by PHI nodes (cannot be inlined)
3. Values captured as upvalues (zero SSA uses but needed at runtime)
4. Parameter registers being reassigned (Version > 0) - must emit so the
RETURN/subsequent code sees the updated value, not the original param. }
var
Idx, RealUses, PhiUses: Integer;
begin
Result := False;
{ Parameter reassignment: if a parameter register (Reg < NumParams) gets
a new SSA version (Version > 0), this is a reassignment like
"easing = easing or 'linear'". Must emit as a statement so the new
value is visible to subsequent code and RETURNs. }
if (Reg < FProto^.NumParams) and (Version > 0) then begin
Result := True;
Exit;
end;
Idx := NodeIdx(Reg, Version);
if (Idx >= 0) and (Idx < Length(FUseCnt)) then begin
PhiUses := CountPhiUses(Reg, Version);
RealUses := FUseCnt[Idx] - PhiUses;
{ Multiple non-PHI uses: must emit to avoid expression duplication }
if RealUses > 1 then begin
Result := True;
Exit;
end;
{ PHI-only use: value feeds into a PHI merge, cannot be inlined.
Exception: if ALL consuming PHIs are trivial (all operands resolve to
the same GETGLOBAL constant), the value can be safely inlined because
the PHI will fold to the common expression at the usage site. }
if (RealUses = 0) and (PhiUses > 0) then begin
if not IsOnlyTrivialPhiUsed(Reg, Version) then begin
Result := True;
Exit;
end;
end;
{ Upvalue-captured: zero SSA uses but the register is live at runtime }
if (FUseCnt[Idx] = 0) and IsUpvalCaptured(Reg, PC) then begin
Result := True;
Exit;
end;
end else begin
{ No use count info - check PHI-only and upvalue capture }
if IsOnlyPhiUsed(Reg, Version) then begin
Result := True;
Exit;
end;
if IsUpvalCaptured(Reg, PC) then begin
Result := True;
Exit;
end;
end;
end;
function TDecompiler.NeedsTempLocal(Reg: Integer): Boolean;
{ Returns True if temp register tN has not been declared local yet in this
function. Marks it as declared so subsequent uses return False. }
begin
Result := False;
if (Reg >= 0) and (Reg < Length(FTempDeclared)) and (not FTempDeclared[Reg]) then begin
FTempDeclared[Reg] := True;
Result := True;
end;
end;
function TDecompiler.TempName(Reg: Integer): AnsiString;
{ Returns the appropriate temp/param name for a register in stripped mode.
Parameter registers (Reg < NumParams) get 'a<N>', others get 't<N>'. }
var
BaseName: AnsiString;
I, Suffix: Integer;
Conflict: Boolean;
begin
if Reg < FProto^.NumParams then
BaseName := 'a' + IntToStr(Reg)
else
BaseName := 't' + IntToStr(Reg);
Result := BaseName;
Suffix := 0;
repeat
Conflict := False;
for I := 0 to High(FUpvalNames) do
if (FUpvalNames[I] <> '') and (FUpvalNames[I] = Result) then begin
Conflict := True;
Break;
end;
if Conflict then begin
Inc(Suffix);
Result := BaseName + '_' + IntToStr(Suffix);
end;
until not Conflict;
end;
function TDecompiler.UpvalName(Idx: Integer): AnsiString;
begin
{ 1. Try debug upvalue names first }
if (Idx >= 0) and (Idx < Length(FProto^.UpvalueNames)) and
(FProto^.UpvalueNames[Idx] <> '') then
Result := FProto^.UpvalueNames[Idx]
{ 2. Try parent-resolved upvalue names (for stripped bytecode) }
else if (Idx >= 0) and (Idx < Length(FUpvalNames)) and
(FUpvalNames[Idx] <> '') then
Result := FUpvalNames[Idx]
else
Result := '_upval' + IntToStr(Idx);
end;
function TDecompiler.RegRef(const R: TSSARef; PC: Integer): AnsiString;
begin
if R.Reg = SSA_CONST_REG then
Result := ConstStr(R.ConstIdx)
else if R.Reg < 0 then
Result := 'nil'
else
Result := LocalName(R.Reg, PC);
end;
{ ======================================================================
Node-based naming (LocVarIdx-based, no PC heuristics)
====================================================================== }
function TDecompiler.NodeIsLocal(Node: PSSANode): Boolean;
begin
Result := (Node <> nil) and (Node^.LocVarIdx >= 0);
end;
function TDecompiler.NodeNeedsDecl(Node: PSSANode): Boolean;
begin
Result := (Node <> nil) and (Node^.LocVarIdx >= 0) and
(Node^.LocVarIdx < Length(FDeclared)) and
(not FDeclared[Node^.LocVarIdx]);
end;
function TDecompiler.NodeLocalName(Node: PSSANode): AnsiString;
begin
if (Node <> nil) and (Node^.LocVarIdx >= 0) and
(Node^.LocVarIdx < Length(FProto^.LocVars)) then
Result := FProto^.LocVars[Node^.LocVarIdx].Name
else
Result := 't' + IntToStr(Node^.Dest.Reg);
end;
procedure TDecompiler.NodeMarkDeclared(Node: PSSANode);
begin
if (Node <> nil) and (Node^.LocVarIdx >= 0) and
(Node^.LocVarIdx < Length(FDeclared)) then
FDeclared[Node^.LocVarIdx] := True;
end;
{ ======================================================================
BindLocVarsToSSA - Bind LocVars to SSA values using CFG-aware analysis
====================================================================== }
procedure TDecompiler.BindLocVarsToSSA;
var
I, J, K, R, V, BIdx, NBlocks, NRegs: Integer;
ClosedCount: Integer;
Node: PSSANode;
Blk: PBasicBlock;
BlockEntryVer: array of array of Integer; { [BlockIdx, Reg] -> version, -1 = unknown }
BlockExitVer: array of array of Integer;
NPreds, MatchCount: Integer;
AllAgree: Boolean;
CommonVer: Integer;
BestPC, BestVer: Integer;
FoundNode: PSSANode;
function FindBlockForPC(PC: Integer): Integer;
{ Find the basic block that contains the given PC. Returns block index or -1. }
var
BI: Integer;
begin
Result := -1;
for BI := 0 to NBlocks - 1 do
if (FSF^.Blocks[BI].StartPC <= PC) and (PC <= FSF^.Blocks[BI].EndPC) then begin
Result := BI;
Exit;
end;
{ If PC is past all blocks (e.g. EndPC of last LocVar), use last block }
if (NBlocks > 0) and (PC >= FSF^.Blocks[NBlocks - 1].StartPC) then
Result := NBlocks - 1;
end;
function HasScopeGap(Reg, FromPC, ToPC: Integer): Boolean;
{ Check if any LocVar on the same register ends between FromPC and ToPC,
indicating a scope boundary crossing. }
var
LI, LJ, LReg, LC: Integer;
begin
Result := False;
for LI := 0 to High(FProto^.LocVars) do begin
if (FProto^.LocVars[LI].EndPC > FromPC) and
(FProto^.LocVars[LI].EndPC < ToPC) then begin
{ Compute register for this LocVar }
LC := 0;
for LJ := 0 to LI - 1 do
if FProto^.LocVars[LJ].EndPC < FProto^.LocVars[LI].StartPC then
Inc(LC);
LReg := LI - LC;
if LReg = Reg then begin
Result := True;
Exit;
end;
end;
end;
end;
begin
NBlocks := Length(FSF^.Blocks);
NRegs := FSF^.NumRegs;
if (NBlocks = 0) or (NRegs = 0) or (Length(FProto^.LocVars) = 0) then Exit;
{ --- Phase 1: Build block-entry and block-exit version maps --- }
SetLength(BlockEntryVer, NBlocks, NRegs);
SetLength(BlockExitVer, NBlocks, NRegs);
{ Initialize to -1 (unknown) }
for I := 0 to NBlocks - 1 do
for J := 0 to NRegs - 1 do begin
BlockEntryVer[I][J] := -1;
BlockExitVer[I][J] := -1;
end;
{ Entry block: version 0 for all registers (initial values) }
for J := 0 to NRegs - 1 do
BlockEntryVer[0][J] := 0;
{ Compute entry/exit versions by scanning nodes in each block.
For PHIs: they define the entry version for their register.
For other defs: they update the exit version. }
for I := 0 to NBlocks - 1 do begin
Blk := @FSF^.Blocks[I];
{ Start with entry version }
for J := 0 to NRegs - 1 do
BlockExitVer[I][J] := BlockEntryVer[I][J];
for K := 0 to High(Blk^.Nodes) do begin
Node := Blk^.Nodes[K];
if Node^.IsMetaOnly then Continue;
if Node^.Kind = SSA_PHI then begin
{ PHI defines entry version for its register }
if Node^.Dest.Reg >= 0 then begin
BlockEntryVer[I][Node^.Dest.Reg] := Node^.Dest.Version;
BlockExitVer[I][Node^.Dest.Reg] := Node^.Dest.Version;
end;
end else if Node^.Dest.Reg >= 0 then begin
{ Non-PHI def: update exit version }
BlockExitVer[I][Node^.Dest.Reg] := Node^.Dest.Version;
end;
end;
end;
{ Propagate entry versions from predecessors (iterate to fixpoint).
For blocks without PHIs, entry version = predecessor exit version.
Multi-pred without PHI: all preds must agree or version is -1. }
for K := 0 to NBlocks do begin { max NBlocks+1 iterations for fixpoint }
for I := 1 to NBlocks - 1 do begin { skip entry block }
Blk := @FSF^.Blocks[I];
NPreds := Length(Blk^.Preds);
if NPreds = 0 then Continue;
for J := 0 to NRegs - 1 do begin
{ Skip registers that have a PHI in this block - already set }
V := -2; { sentinel: not yet checked }
for R := 0 to High(Blk^.Nodes) do begin
if Blk^.Nodes[R]^.Kind <> SSA_PHI then Break;
if Blk^.Nodes[R]^.Dest.Reg = J then begin
V := Blk^.Nodes[R]^.Dest.Version;
Break;
end;
end;
if V <> -2 then Continue; { PHI defines it }
{ Check predecessor exit versions }
if NPreds = 1 then begin
{ Single predecessor: inherit directly }
V := BlockExitVer[Blk^.Preds[0]][J];
if BlockEntryVer[I][J] <> V then begin
BlockEntryVer[I][J] := V;
{ Update exit if no def in this block overrides it }
{ (We recompute exit below) }
end;
end else begin
{ Multiple predecessors: check if all agree }
AllAgree := True;
CommonVer := BlockExitVer[Blk^.Preds[0]][J];
for R := 1 to NPreds - 1 do begin
if BlockExitVer[Blk^.Preds[R]][J] <> CommonVer then begin
AllAgree := False;
Break;
end;
end;
if AllAgree then
V := CommonVer
else
V := -1; { inconsistent - no PHI, so shouldn't happen in well-formed SSA }
BlockEntryVer[I][J] := V;
end;
end;
{ Recompute exit versions based on new entry versions }
for J := 0 to NRegs - 1 do
BlockExitVer[I][J] := BlockEntryVer[I][J];
for R := 0 to High(Blk^.Nodes) do begin
Node := Blk^.Nodes[R];
if Node^.IsMetaOnly then Continue;
if Node^.Dest.Reg >= 0 then
BlockExitVer[I][Node^.Dest.Reg] := Node^.Dest.Version;
end;
end;
end;
{ --- Phase 2: Bind each LocVar to the SSA value live at its StartPC --- }
for I := 0 to High(FProto^.LocVars) do begin
{ Skip internal for-loop variables }
if (Length(FProto^.LocVars[I].Name) > 0) and
(FProto^.LocVars[I].Name[1] = '(') then Continue;
{ Skip empty names }
if FProto^.LocVars[I].Name = '' then Continue;
{ Skip the implicit "arg" local }
if (FSF^.LuaVersion <= $51) and (FProto^.IsVarArg and 1 <> 0) and
(I = FProto^.NumParams) and (FProto^.LocVars[I].Name = 'arg') then Continue;
{ Compute register R for this LocVar using closed-predecessor formula }
ClosedCount := 0;
for J := 0 to I - 1 do
if FProto^.LocVars[J].EndPC < FProto^.LocVars[I].StartPC then
Inc(ClosedCount);
R := I - ClosedCount;
if (R < 0) or (R >= NRegs) then Continue;
{ Find block containing StartPC }
BIdx := FindBlockForPC(FProto^.LocVars[I].StartPC);
if BIdx < 0 then Continue;
{ Determine live SSA version of R at StartPC:
Start with BlockEntryVer, then scan defs in the block BEFORE StartPC }
V := BlockEntryVer[BIdx][R];
{ Scan block nodes for defs of R with PC < StartPC (strict less-than).
Include MetaOnly pseudo-defs - they represent LOADNIL per-register
definitions that need to participate in LocVar binding. }
Blk := @FSF^.Blocks[BIdx];
for K := 0 to High(Blk^.Nodes) do begin
Node := Blk^.Nodes[K];
if (Node^.Dest.Reg = R) and (Node^.PC < FProto^.LocVars[I].StartPC) then
V := Node^.Dest.Version;
end;
if FOpts.Debug then
WriteLn(StdErr, 'BindLocVarsToSSA: TRACE L', I, ' "', FProto^.LocVars[I].Name,
'" R', R, ' initial V=', V, ' BIdx=', BIdx, ' StartPC=', FProto^.LocVars[I].StartPC);
{ V = -1 means unknown/inconsistent - try def-use recovery }
if V = -1 then begin
{ Find first real use of R inside the scope and use its operand version }
for K := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[K];
if Node^.IsMetaOnly then Continue;
if Node^.Kind in [SSA_PHI, SSA_NOP] then Continue;
if (Node^.PC < FProto^.LocVars[I].StartPC) or
(Node^.PC > FProto^.LocVars[I].EndPC) then Continue;
if (Node^.OpA.Reg = R) then begin V := Node^.OpA.Version; Break; end;
if (Node^.OpB.Reg = R) then begin V := Node^.OpB.Version; Break; end;
if (Node^.OpC.Reg = R) then begin V := Node^.OpC.Version; Break; end;
for J := 0 to High(Node^.ArgRefs) do
if Node^.ArgRefs[J].Reg = R then begin V := Node^.ArgRefs[J].Version; Break; end;
if V >= 0 then Break;
end;
if V < 0 then begin
if FOpts.Debug then
WriteLn(StdErr, 'BindLocVarsToSSA: SKIP L', I, ' "', FProto^.LocVars[I].Name,
'" R', R, ' - no use found in scope');
Continue;
end;
end;
{ Find the SSA node whose Dest = (R, V) }
FoundNode := nil;
for K := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[K];
if (Node^.Dest.Reg = R) and (Node^.Dest.Version = V) then begin
FoundNode := Node;
Break;
end;
end;
if FoundNode = nil then begin
{ V=0 (or anomalous V>0) with no defining SSA node.
This happens for parameters (no bytecode defines them) and for
locals whose LOADNIL was optimized away by the compiler.
Fall through: find the earliest real definition of R within scope. }
if FOpts.Debug then
WriteLn(StdErr, 'BindLocVarsToSSA: no node for R', R, '_', V,
', scanning for first def in scope [',
FProto^.LocVars[I].StartPC, '..', FProto^.LocVars[I].EndPC, ']');
BestPC := MaxInt;
for K := 0 to High(FSF^.AllNodes) do begin
Node := FSF^.AllNodes[K];
if Node^.IsMetaOnly then Continue;
if Node^.Kind in [SSA_PHI, SSA_NOP] then Continue;
if (Node^.Dest.Reg = R) and
(Node^.PC >= FProto^.LocVars[I].StartPC) and
(Node^.PC < FProto^.LocVars[I].EndPC) and
(Node^.PC < BestPC) then begin
FoundNode := Node;
BestPC := Node^.PC;
end;
end;
if FoundNode = nil then begin
if FOpts.Debug then
WriteLn(StdErr, 'BindLocVarsToSSA: SKIP L', I, ' "', FProto^.LocVars[I].Name,
'" R', R, ' - no def within scope (parameter or unused)');
Continue;
end;
end;
{ Watch-out H: Prevent duplicate LocVarIdx bindings }
if FoundNode^.LocVarIdx >= 0 then begin
if FOpts.Debug then
WriteLn(StdErr, 'BindLocVarsToSSA: DUPLICATE bind attempt for R', R,
'_', V, ': already bound to L', FoundNode^.LocVarIdx,
', skipping L', I, ' "', FProto^.LocVars[I].Name, '"');
Continue;
end;
{ Scope-gap guard: verify no other LocVar on same register ends between
FoundNode^.PC and StartPC }
if (FoundNode^.PC < FProto^.LocVars[I].StartPC) and
HasScopeGap(R, FoundNode^.PC, FProto^.LocVars[I].StartPC) then begin
if FOpts.Debug then
WriteLn(StdErr, 'BindLocVarsToSSA: scope gap for L', I,
' "', FProto^.LocVars[I].Name, '" R', R, '_', V);
Continue;
end;
{ Bind! }
FoundNode^.LocVarIdx := I;
if FOpts.Debug then
WriteLn(StdErr, 'BindLocVarsToSSA: L', I, ' "', FProto^.LocVars[I].Name,
'" -> R', R, '_', V, ' (Kind=', Ord(FoundNode^.Kind),
' PC=', FoundNode^.PC, ')');
end;
{ --- Phase 3: Bind additional definitions within each LocVar scope ---
Write-back MOVEs in multi-assign patterns define new versions of registers
that are already bound to LocVars. Bind these additional definitions so
NodeIsLocal works for them. Process LocVars from narrowest scope first
(reverse order since LocVars are ordered by StartPC, inner scopes last)
to ensure inner scopes take priority over outer scopes on the same
register. }
for I := High(FProto^.LocVars) downto 0 do begin
{ Skip internal/filtered LocVars (same filters as Phase 2) }
if (Length(FProto^.LocVars[I].Name) > 0) and
(FProto^.LocVars[I].Name[1] = '(') then Continue;
if FProto^.LocVars[I].Name = '' then Continue;
if (FSF^.LuaVersion <= $51) and (FProto^.IsVarArg and 1 <> 0) and
(I = FProto^.NumParams) and (FProto^.LocVars[I].Name = 'arg') then Continue;
{ Compute register R for this LocVar (same formula as Phase 2) }
ClosedCount := 0;
for J := 0 to I - 1 do
if FProto^.LocVars[J].EndPC < FProto^.LocVars[I].StartPC then
Inc(ClosedCount);
R := I - ClosedCount;
if (R < 0) or (R >= NRegs) then Continue;
{ Scan AllNodes for additional defs of R within this LocVar's scope }
for K := 0 to High(FSF^.AllNodes) do begin