-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLuaDecompEmitNode.inc
More file actions
992 lines (972 loc) · 45.5 KB
/
Copy pathLuaDecompEmitNode.inc
File metadata and controls
992 lines (972 loc) · 45.5 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
procedure TDecompiler.EmitNode(Node: PSSANode; BIdx: Integer);
var
PC : Integer;
LHS, RHS, FuncName, Args, Expr: AnsiString;
ArgI, I : Integer;
Idx : Integer;
Key, KName: AnsiString;
ClosureNode: PSSANode;
NextOp: TOpCode;
SemOp: TSemanticOp;
PhiUses, RealUses: Integer;
CallN: PSSANode;
CallBase, CallRets: Integer;
MoveDest, MoveSrcReg, MoveIdx: Integer;
HasMutatingUse: Boolean;
function RefCarriesRoot(const R, Root: TSSARef; Depth: Integer): Boolean;
var
DefN: PSSANode;
K: Integer;
begin
Result := False;
if RefEqual(R, Root) then begin
Result := True;
Exit;
end;
if Depth > 16 then Exit;
DefN := DefNodeFor(R);
if DefN = nil then Exit;
if DefN^.Kind = SSA_MOVE then begin
Result := RefCarriesRoot(DefN^.OpA, Root, Depth + 1);
Exit;
end;
if DefN^.Kind <> SSA_PHI then Exit;
for K := 0 to High(DefN^.Operands) do
if RefEqual(DefN^.Operands[K], R) then
Continue
else
if RefCarriesRoot(DefN^.Operands[K], Root, Depth + 1) then begin
Result := True;
Exit;
end;
end;
begin
PC := Node^.PC;
FAnnotatePC := PC;
case Node^.Kind of
SSA_NOP, SSA_JUMP, SSA_FORPREP, SSA_FORLOOP, SSA_TFORLOOP,
SSA_CLOSE: begin
{ These are structural / don't emit direct statements }
end;
SSA_PHI: begin
{ PHIs are normally structural, but comparison-to-boolean PHIs that assign
to user locals must be emitted as explicit assignments (e.g., a = x < y).
We ONLY do this for the LOADBOOL comparison pattern, NOT for or/and PHIs,
because or/and PHIs are intermediate values consumed by other expressions. }
if (Node^.Dest.Reg >= 0) and
(Length(Node^.Operands) = 2) and (Length(Node^.PhiBlocks) = 2) then begin
Expr := TryBuildComparisonExpr(Node);
if (Expr <> '') and
(NodeIsLocal(Node) or
IsUserLocal(Node^.Dest.Reg, PC) or
IsUserLocal(Node^.Dest.Reg, PC + 1)) then begin
if NodeIsLocal(Node) then
LHS := NodeLocalName(Node)
else
LHS := LocalNameForEmit(Node^.Dest.Reg, PC);
if NodeNeedsDecl(Node) then begin
NodeMarkDeclared(Node);
EmitLine('local ' + LHS + ' = ' + Expr);
end else if NeedsLocalDecl(Node^.Dest.Reg, PC) then
EmitLine('local ' + LHS + ' = ' + Expr)
else
EmitLine(LHS + ' = ' + Expr);
end;
end;
end;
SSA_MOVE: begin
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
{ Check if this node was marked as inlined (e.g. for-loop setup MOVE) }
if (Idx >= 0) and (Idx < Length(FInlined)) and FInlined[Idx] then Exit;
{ Check user-local via LocVarIdx binding first, then fall back to PC-based.
Use IsUserLocalStrict (PC < EndPC) for definition sites to avoid
boundary false positives where LocVarInScope's <= EndPC treats a
dead variable as alive at the register-reuse point.
When neither NodeIsLocal nor IsUserLocalStrict matches, this MOVE
is NOT a local definition - skip ShouldEmitAsLocal lookahead which
could false-match an upcoming LocVar for the same register. }
if NodeIsLocal(Node) then
LHS := NodeLocalName(Node)
else if IsUserLocalStrict(Node^.Dest.Reg, PC) or
IsUserLocalStrict(Node^.Dest.Reg, PC + 1) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else if ShouldEmitTemp(Node^.Dest.Reg, Node^.Dest.Version, PC) then begin
{ Check if this is a pre-CALL arg-save MOVE that should be inlined.
Pattern: MOVE R_temp := R_param (save before multi-return CALL)
followed by a CALL that uses R_temp as both arg and return register,
then post-CALL MOVEs distribute the return values.
In this case, the MOVE should NOT be emitted; it will be inlined
when the CALL expression is built (ExprOf traverses OpA --> MOVE src). }
LHS := '';
if (BIdx >= 0) and (BIdx < Length(FSF^.Blocks)) then begin
for I := 0 to High(FSF^.Blocks[BIdx].Nodes) do begin
CallN := FSF^.Blocks[BIdx].Nodes[I];
if (CallN^.Kind = SSA_CALL) and (CallN^.ImmC >= 3) and
(CallN^.PC > PC) then begin
CallBase := CallN^.ImmA;
CallRets := CallN^.ImmC - 1;
{ Check: dest reg is in CALL arg range AND return range }
if (Node^.Dest.Reg >= CallBase) and
(Node^.Dest.Reg < CallBase + CallRets) then begin
LHS := '__skip__';
Break;
end;
end;
end;
end;
if LHS = '__skip__' then
Exit; { pre-CALL arg-save - will be inlined into CALL expression }
LHS := TempName(Node^.Dest.Reg);
end
else if (Idx >= 0) and (Idx < Length(FUseCnt)) and
(CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version) > 0) and
(FUseCnt[Idx] - CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version) = 1) and
((Node^.OpA.Reg = Node^.Dest.Reg) or
(Node^.OpB.Reg = Node^.Dest.Reg)) then begin
{ Loop-tail self update feeding an until condition and the next
iteration PHI, e.g. gen = gen + 1; until gen > limit. Inlining this
into the condition would drop the state update in stripped chunks
with no LocVar name. }
if IsUserLocal(Node^.Dest.Reg, PC) or
IsUserLocal(Node^.Dest.Reg, PC + 1) or
ShouldEmitAsLocal(Node^.Dest.Reg, PC) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else
LHS := TempName(Node^.Dest.Reg);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
end
else begin
if (Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0) then Exit;
Exit; { temp with uses - will be inlined }
end;
RHS := ExprOf(Node^.OpA, PC);
{ Cache the LHS name so future ExprOf(R3_1,...) returns "a3" instead
of re-expanding the MOVE's source expression. This prevents
re-inlining a MOVE that was already emitted as a statement. }
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
if LHS <> RHS then begin
if NodeNeedsDecl(Node) then begin
NodeMarkDeclared(Node);
EmitLine('local ' + LHS + ' = ' + StripOuterParens(RHS));
end else if NeedsLocalDecl(Node^.Dest.Reg, PC) then
EmitLine('local ' + LHS + ' = ' + StripOuterParens(RHS))
else
EmitLine(LHS + ' = ' + StripOuterParens(RHS));
end;
end;
SSA_LOADK, SSA_LOADBOOL, SSA_LOADNIL: begin
{ Skip LOADNIL pseudo-def nodes (metadata only, not emitted) }
if Node^.IsMetaOnly then Exit;
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
{ Check if this node was marked as inlined (e.g. for-loop setup LOADNIL) }
if (Idx >= 0) and (Idx < Length(FInlined)) and FInlined[Idx] then Exit;
{ Suppress LOADNIL that initializes generic for-loop internal state registers.
The for-loop setup pattern is: CALL(iter) + LOADNIL R(base+1)..R(base+N) + TFORPREP.
In 5.4, LOADNIL covers 3 regs (state/control/to-be-closed), all "(for state)".
In 5.5 (and 5.1-5.3), LOADNIL may cover state/control + first user var.
We suppress if: (a) all regs are "(for state)", OR (b) at least one reg is
"(for state)" AND the next node in this block is a JUMP (= compiled TFORPREP). }
if (Node^.Kind = SSA_LOADNIL) and (Node^.ImmA <= Node^.ImmB) then begin
ArgI := 0;
for I := Node^.ImmA to Node^.ImmB do begin
LHS := LocalName(I, PC + 1);
if (Length(LHS) > 4) and (Copy(LHS, 1, 4) = '(for') then
Inc(ArgI);
end;
if ArgI = (Node^.ImmB - Node^.ImmA + 1) then
Exit; { all registers are for-loop internal state }
{ Partial match: some "(for state)" - check if next node is JUMP (TFORPREP) }
if (ArgI > 0) and (BIdx >= 0) and (BIdx < Length(FSF^.Blocks)) then begin
for I := 0 to High(FSF^.Blocks[BIdx].Nodes) do begin
if FSF^.Blocks[BIdx].Nodes[I] = Node then begin
if (I + 1 <= High(FSF^.Blocks[BIdx].Nodes)) and
(FSF^.Blocks[BIdx].Nodes[I + 1]^.Kind = SSA_JUMP) then
Exit; { LOADNIL before TFORPREP - for-loop setup, suppress }
Break;
end;
end;
end;
end;
{ For LOADNIL with a range (ImmA < ImmB), check if user locals exist
in the range. If so, declare them as a combined "local a, b, c".
In 5.4+, LOADNIL may cover both user locals AND temp registers
(e.g. LOADNIL R0 4 covers R0..R4 where only R0-R2 are locals).
Only declare the user-local registers; skip non-locals. }
if (Node^.Kind = SSA_LOADNIL) and (Node^.ImmA < Node^.ImmB) then begin
LHS := '';
ArgI := 0;
for I := Node^.ImmA to Node^.ImmB do begin
if IsUserLocal(I, PC) or IsUserLocal(I, PC + 1) then
Inc(ArgI);
end;
if ArgI > 0 then begin
{ Declare user locals in range that haven't been declared yet }
LHS := '';
for I := Node^.ImmA to Node^.ImmB do begin
if (IsUserLocal(I, PC) or IsUserLocal(I, PC + 1)) and
NeedsLocalDecl(I, PC) then begin
if LHS <> '' then LHS := LHS + ', ';
if IsUserLocal(I, PC + 1) then
LHS := LHS + LocalName(I, PC + 1)
else
LHS := LHS + LocalName(I, PC);
end;
end;
if LHS <> '' then
EmitLine('local ' + LHS);
Exit;
end;
end;
{ Check user-local via LocVarIdx binding first, then fall back to PC-based.
Use IsUserLocalStrict for definition sites. }
if NodeIsLocal(Node) then
LHS := NodeLocalName(Node)
else if IsUserLocalStrict(Node^.Dest.Reg, PC) or
IsUserLocalStrict(Node^.Dest.Reg, PC + 1) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else if ShouldEmitAsLocal(Node^.Dest.Reg, PC) and
(IsOnlyPhiUsed(Node^.Dest.Reg, Node^.Dest.Version) or
((Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0))) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else if ShouldEmitTemp(Node^.Dest.Reg, Node^.Dest.Version, PC) then
LHS := TempName(Node^.Dest.Reg)
else begin
if (Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0) then Exit;
Exit; { temp with uses - will be inlined }
end;
{ Cache the LHS name so future ExprOf(R_v,...) returns the variable name
instead of re-expanding the LOADK/LOADBOOL literal. This prevents
re-inlining a LOADK that was already emitted as "local t1 = ..." -
without this, ExprOf would return the literal value on every use. }
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
RHS := NodeExpr(Node);
if NodeNeedsDecl(Node) then begin
NodeMarkDeclared(Node);
{ Check for bare "local a" (StartPC = PC: no initializer in source) }
if FProto^.LocVars[Node^.LocVarIdx].StartPC = PC then begin
EmitLine('local ' + LHS);
if Node^.Kind <> SSA_LOADNIL then
EmitLine(LHS + ' = ' + RHS);
end else begin
if Node^.Kind = SSA_LOADNIL then
EmitLine('local ' + LHS)
else
EmitLine('local ' + LHS + ' = ' + RHS);
end;
end else if NeedsLocalDecl(Node^.Dest.Reg, PC) then begin
{ Check for bare "local a" declaration (StartPC = PC means no initializer).
In this case, emit "local a" first, then "a = expr" as separate assignment.
Exception: LOADNIL - bare "local a" already implies nil, so just emit "local a". }
if IsBareLocalDecl(Node^.Dest.Reg, PC) then begin
EmitLine('local ' + LHS);
if Node^.Kind <> SSA_LOADNIL then
EmitLine(LHS + ' = ' + RHS);
end else begin
{ For LOADNIL declarations, emit "local a" instead of "local a = nil"
since nil is the default value for local variables in Lua }
if Node^.Kind = SSA_LOADNIL then
EmitLine('local ' + LHS)
else
EmitLine('local ' + LHS + ' = ' + RHS);
end;
end else begin
{ For non-declaration LOADNIL assignments (e.g. "a = nil" reset),
emit with the nil value explicitly }
EmitLine(LHS + ' = ' + RHS);
end;
end;
SSA_NEWTABLE: begin
{ NEWTABLE creates a mutable table object. When the result is assigned
to a user-local variable (e.g. "local t = {}"), we must emit the
assignment rather than inlining, because later SETTABLEs reference it
and re-inlining '{}' would produce wrong code like "{}.w = 3".
But when the NEWTABLE is a temp used only once (e.g., t[y] = {}),
it should be inlined into the consuming expression.
Note: The LocVar for a table constructor may start several PCs later
(after SETTABLE/SETLIST instructions that initialize the table).
We look ahead up to 32 PCs to find the user local name.
Important: check user-local BEFORE use-count, because upvalue-captured
locals (e.g. "local c = {}" in cache()) have zero SSA uses but must
still be emitted. }
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
LHS := '';
{ Check if another node in the same block writes to this register later.
If so, this NEWTABLE is a temp and we should not look ahead for LocVars. }
RealUses := 0; { reuse as flag: 0=no later write, 1=has later write }
for I := 0 to High(FSF^.Blocks[BIdx].Nodes) do begin
if (FSF^.Blocks[BIdx].Nodes[I]^.PC > PC) and
(FSF^.Blocks[BIdx].Nodes[I]^.Dest.Reg = Node^.Dest.Reg) and
(FSF^.Blocks[BIdx].Nodes[I]^.Kind <> SSA_PHI) and
(FSF^.Blocks[BIdx].Nodes[I]^.Kind <> SSA_NOP) then begin
RealUses := 1; Break;
end;
end;
{ Check node-based LocVar binding first (exact), then fall back to PC lookahead }
if NodeIsLocal(Node) then
LHS := NodeLocalName(Node)
else begin
for ArgI := 0 to 32 do begin
if IsUserLocal(Node^.Dest.Reg, PC + ArgI) then begin
{ Skip this match if ArgI > 0 (look-ahead) and the register is
rewritten later in the block - the later write owns the LocVar }
if (ArgI > 0) and (RealUses <> 0) then Continue;
LHS := LocalName(Node^.Dest.Reg, PC + ArgI);
Break;
end;
end;
end;
{ If not a user local: skip if zero real (non-PHI) uses, inline if
exactly 1 real use. PHI references are SSA artifacts from control-flow
merges and should not prevent inlining of temporary tables. }
if LHS = '' then begin
if (Idx >= 0) and (Idx < Length(FUseCnt)) then begin
ArgI := CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version);
RealUses := FUseCnt[Idx] - ArgI;
HasMutatingUse := False;
for I := 0 to High(FSF^.AllNodes) do begin
if FSF^.AllNodes[I] = Node then Continue;
if (FSF^.AllNodes[I]^.Kind = SSA_SETTABLE) and
RefCarriesRoot(FSF^.AllNodes[I]^.OpA, Node^.Dest, 0) then begin
HasMutatingUse := True;
Break;
end;
if (FSF^.AllNodes[I]^.Kind = SSA_SETLIST) and
(FSF^.AllNodes[I]^.ImmA = Node^.Dest.Reg) and
(FSF^.AllNodes[I]^.PC >= Node^.PC) then begin
HasMutatingUse := True;
Break;
end;
end;
if (RealUses <= 1) and (not HasMutatingUse) then Exit;
end;
LHS := TempName(Node^.Dest.Reg);
end;
{ Cache the LHS name so that later ExprOf lookups for this NEWTABLE
return the variable name (e.g. "t15") instead of re-building the
expression as "{}" which would produce wrong code like "{}.field = v" }
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
RHS := NodeExpr(Node);
if NodeNeedsDecl(Node) then begin
NodeMarkDeclared(Node);
EmitLine('local ' + LHS + ' = ' + RHS);
end else if NeedsLocalDecl(Node^.Dest.Reg, PC) then
EmitLine('local ' + LHS + ' = ' + RHS)
else
EmitLine(LHS + ' = ' + RHS);
end;
SSA_GETUPVAL, SSA_GETGLOBAL, SSA_GETTABLE,
SSA_SELF, SSA_VARARG: begin
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
{ Check if this node was marked as inlined (e.g. for-loop setup) }
if (Idx >= 0) and (Idx < Length(FInlined)) and FInlined[Idx] then Exit;
{ Check node-based LocVar binding first, then fall back to PC-based.
Use IsUserLocalStrict (PC < EndPC) for definitions to avoid matching
a dead LocVar whose register is being reused at exactly EndPC. }
if NodeIsLocal(Node) then
LHS := NodeLocalName(Node)
else if IsUserLocalStrict(Node^.Dest.Reg, PC) or
IsUserLocalStrict(Node^.Dest.Reg, PC + 1) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else if ShouldEmitAsLocal(Node^.Dest.Reg, PC) and
(IsOnlyPhiUsed(Node^.Dest.Reg, Node^.Dest.Version) or
((Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0))) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else if ShouldEmitTemp(Node^.Dest.Reg, Node^.Dest.Version, PC) then begin
LHS := TempName(Node^.Dest.Reg);
{ Cache the temp name so later ExprOf returns it }
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
end
else begin
{ Not a user local - skip zero-use or inlineable temps }
if (Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0) then Exit;
Exit; { temp with uses - will be inlined by consuming expression }
end;
RHS := NodeExpr(Node);
if NodeNeedsDecl(Node) then begin
NodeMarkDeclared(Node);
EmitLine('local ' + LHS + ' = ' + RHS);
end else if NeedsLocalDecl(Node^.Dest.Reg, PC) then
EmitLine('local ' + LHS + ' = ' + RHS)
else
EmitLine(LHS + ' = ' + RHS);
end;
SSA_CLOSURE: begin
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
{ Self-referencing closure: must be emitted as a local variable first,
because it references itself via an upvalue and cannot be inlined.
Only use the stripped-mode func_N naming when no LocVars are available. }
if IsSelfRefClosure(Node) and (Length(FProto^.LocVars) = 0) then begin
LHS := 'func_' + IntToStr(Node^.ConstIdx);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
if TryEmitLocalFunction(Node, LHS, True) then
{ emitted as local function declaration }
else begin
RHS := NodeExpr(Node);
EmitLine('local ' + LHS + ' = ' + RHS);
end;
Exit;
end;
{ Check if a following instruction consumes this closure via
SETGLOBAL/SETUPVAL/SETTABLE - if so, skip; the consumer emits it.
In Lua 5.1, after CLOSURE the compiler may emit MOVE/GETUPVAL
pseudo-instructions as upvalue hints before the real consumer.
For 5.2+ use the semantic opcode table (raw opcode numbers differ).
EXCEPTION: If the closure register is a named user local, we must
emit it as a separate local variable (e.g. "local handler = function
...end") rather than inlining into the consumer. This preserves the
original pattern: local handler = function(x)...end; result[i] = handler }
{ Check if the closure register is a named user local. In Lua 5.1,
CLOSURE is followed by MOVE/GETUPVAL upvalue hint pseudo-instructions
before the real consumer. The LocVar StartPC typically points to the
instruction AFTER the hints. Scan forward through pseudo-MOVEs only. }
ArgI := PC + 1;
while (ArgI < Length(FProto^.Code)) and (ArgI <= PC + 4) do begin
if FOpts.OT <> nil then begin
SemOp := DecodeOp(FOpts.OT^, FProto^.Code[ArgI]);
if not (SemOp in [semMOVE, semGETUPVAL]) then Break;
end else begin
NextOp := GET_OPCODE(FProto^.Code[ArgI]);
if not (NextOp in [OP_MOVE, OP_GETUPVAL]) then Break;
end;
Inc(ArgI);
end;
{ ArgI now points to first real instruction after CLOSURE + hints.
Check IsUserLocal at that PC (where the LocVar typically starts). }
if NodeIsLocal(Node) or
IsUserLocal(Node^.Dest.Reg, PC) or
IsUserLocal(Node^.Dest.Reg, PC + 1) or
((ArgI > PC + 1) and IsUserLocal(Node^.Dest.Reg, ArgI)) then begin
{ Fall through to local function emission below }
end else begin
ArgI := PC + 1;
while ArgI < Length(FProto^.Code) do begin
if FOpts.OT <> nil then begin
SemOp := DecodeOp(FOpts.OT^, FProto^.Code[ArgI]);
if SemOp in [semSETGLOBAL, semSETUPVAL, semSETTABLE, semSETTABUP,
semSETFIELD, semSETI] then
Exit; { consumer will inline the closure expr }
if not (SemOp in [semMOVE, semGETUPVAL]) then
Break;
end else begin
NextOp := GET_OPCODE(FProto^.Code[ArgI]);
if NextOp in [OP_SETGLOBAL, OP_SETUPVAL, OP_SETTABLE] then
Exit; { consumer (SETGLOBAL etc.) will inline the closure expr }
{ Skip past upvalue hint pseudo-instructions }
if not (NextOp in [OP_MOVE, OP_GETUPVAL]) then
Break;
end;
Inc(ArgI);
end;
{ Also check if a nearby CALL consumes this closure as an argument
or as the function being called (IIFE pattern).
Scan up to 8 instructions ahead (past arg setup LOADKs etc.). }
for ArgI := PC + 1 to PC + 8 do begin
if ArgI >= Length(FProto^.Code) then Break;
if FOpts.OT <> nil then begin
SemOp := DecodeOp(FOpts.OT^, FProto^.Code[ArgI]);
if SemOp = semCALL then begin
if Node^.Dest.Reg >= DecodeA(FOpts.OT^, FProto^.Code[ArgI]) then
Exit; { closure is consumed by this call --> inline }
Break;
end;
if SemOp in [semCLOSURE, semLOADNIL] then Break;
if (DecodeA(FOpts.OT^, FProto^.Code[ArgI]) = Node^.Dest.Reg) and
not (SemOp in [semMOVE, semGETUPVAL, semLOADK, semLOADKX,
semLOADBOOL, semGETGLOBAL, semGETTABUP,
semGETTABLE, semNEWTABLE, semSELF]) then
Break;
end else begin
NextOp := GET_OPCODE(FProto^.Code[ArgI]);
if NextOp = OP_CALL then begin
{ CALL A B --> calls R(A) with args R(A+1)..R(A+B-1).
If closure reg >= call base reg, it's consumed (arg or IIFE). }
if Node^.Dest.Reg >= GETARG_A(FProto^.Code[ArgI]) then
Exit; { closure is consumed by this call --> inline }
Break; { CALL found but closure is not consumed }
end;
{ Stop scanning at instructions that could redefine the closure register }
if (NextOp in [OP_CLOSURE, OP_LOADNIL]) then Break;
if (GETARG_A(FProto^.Code[ArgI]) = Node^.Dest.Reg) and
not (NextOp in [OP_MOVE, OP_GETUPVAL, OP_LOADK, OP_LOADBOOL,
OP_GETGLOBAL, OP_GETTABLE, OP_NEWTABLE,
OP_SELF]) then
Break;
end;
end;
end; { end of else (non-user-local consumer check) }
{ For closures assigned to user locals (local function pattern),
emit as "local function name(params)...end".
e.g. "local function factorial(n) ... end"
compiles to CLOSURE Rn; NOP (MOVE Rn Rn for self-reference).
In Lua 5.2+, CLOSURE may target a temp register, then MOVE to
the actual local: CLOSURE Rx Pn; MOVE Ry Rx. Detect this and
use the MOVE destination as the LHS instead. }
MoveDest := -1;
if (FSF^.LuaVersion >= $52) and (PC + 1 < Length(FProto^.Code)) then begin
if FOpts.OT <> nil then begin
if DecodeOp(FOpts.OT^, FProto^.Code[PC + 1]) = semMOVE then begin
MoveSrcReg := DecodeB(FOpts.OT^, FProto^.Code[PC + 1]);
if MoveSrcReg = Node^.Dest.Reg then
MoveDest := DecodeA(FOpts.OT^, FProto^.Code[PC + 1]);
end;
end else begin
if GET_OPCODE(FProto^.Code[PC + 1]) = OP_MOVE then begin
if GETARG_B(FProto^.Code[PC + 1]) = Node^.Dest.Reg then
MoveDest := GETARG_A(FProto^.Code[PC + 1]);
end;
end;
end;
if (MoveDest >= 0) and
(IsUserLocal(MoveDest, PC + 1) or IsUserLocal(MoveDest, PC + 2)) and
{ Don't fold CLOSURE+MOVE when the CLOSURE dest is itself a named
local different from the MOVE dest. In that case, the CLOSURE is
the local function definition and the MOVE is a separate assignment.
e.g. "local function positive(x)...end; handler = positive" compiles
to CLOSURE R2(positive), MOVE R1(handler) R2 - emit them separately. }
not ((IsUserLocal(Node^.Dest.Reg, PC) or
IsUserLocal(Node^.Dest.Reg, PC + 1)) and
(MoveDest <> Node^.Dest.Reg)) then begin
LHS := LocalNameForEmit(MoveDest, PC + 1);
{ Cache expression on the original CLOSURE register so the MOVE node
can find it (the MOVE will be a NOP since we handle it here). }
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
{ Also cache on the MOVE destination }
MoveIdx := NodeIdx(MoveDest, 0);
{ Find the correct version for the MOVE dest }
for ArgI := 0 to High(FSF^.AllNodes) do begin
if (FSF^.AllNodes[ArgI]^.Kind = SSA_MOVE) and
(FSF^.AllNodes[ArgI]^.PC = PC + 1) and
(FSF^.AllNodes[ArgI]^.Dest.Reg = MoveDest) then begin
MoveIdx := NodeIdx(FSF^.AllNodes[ArgI]^.Dest.Reg,
FSF^.AllNodes[ArgI]^.Dest.Version);
Break;
end;
end;
if (MoveIdx >= 0) and (MoveIdx < Length(FExprStr)) then
FExprStr[MoveIdx] := LHS;
{ Emit the closure with the MOVE's local name }
if TryEmitLocalFunction(Node, LHS,
NeedsLocalDecl(MoveDest, PC + 1)) then
{ emitted as local function declaration }
else begin
RHS := NodeExpr(Node);
if NeedsLocalDecl(MoveDest, PC + 1) then
EmitLine('local ' + LHS + ' = ' + RHS)
else
EmitLine(LHS + ' = ' + RHS);
end;
Exit;
end
else if NodeIsLocal(Node) then
LHS := NodeLocalName(Node)
else if IsUserLocal(Node^.Dest.Reg, PC) or
IsUserLocal(Node^.Dest.Reg, PC + 1) or
((ArgI > PC + 1) and IsUserLocal(Node^.Dest.Reg, ArgI)) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else if ShouldEmitAsLocal(Node^.Dest.Reg, PC) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else if (Idx >= 0) and (Idx < Length(FUseCnt)) and
(CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version) > 0) then
LHS := TempName(Node^.Dest.Reg)
else if (Idx >= 0) and (Idx < Length(FUseCnt)) and
((FUseCnt[Idx] - CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version)) > 1) then
LHS := TempName(Node^.Dest.Reg)
else begin
{ Not a user local. In stripped mode, closures used only via upvalue
captures have FUseCnt=0 (upvalue hints are NOPs, not tracked as uses).
These must still be emitted as local functions so the upvalue captures
resolve correctly. Emit as "local func_N = function(...)...end". }
if (Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0) then begin
LHS := 'func_' + IntToStr(Node^.ConstIdx);
if (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
if TryEmitLocalFunction(Node, LHS, True) then
{ emitted }
else begin
RHS := NodeExpr(Node);
EmitLine('local ' + LHS + ' = ' + RHS);
end;
Exit;
end;
Exit; { temp with uses - will be inlined by consuming expression }
end;
{ Cache the variable name so ExprOf returns the name instead of
re-computing the full closure expression when referenced later. }
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
{ Emit as "local function name(params)...end" with proper indentation }
if TryEmitLocalFunction(Node, LHS,
NodeNeedsDecl(Node) or NeedsLocalDecl(Node^.Dest.Reg, PC)) then begin
if NodeNeedsDecl(Node) then NodeMarkDeclared(Node);
end
else begin
{ Fallback: emit as assignment }
RHS := NodeExpr(Node);
if NodeNeedsDecl(Node) then begin
NodeMarkDeclared(Node);
EmitLine('local ' + LHS + ' = ' + RHS);
end else if NeedsLocalDecl(Node^.Dest.Reg, PC) then
EmitLine('local ' + LHS + ' = ' + RHS)
else
EmitLine(LHS + ' = ' + RHS);
end;
end;
SSA_BINOP, SSA_UNOP, SSA_CONCAT: begin
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
{ Accumulator pattern detection: if this BINOP writes to R and has exactly
1 non-PHI use, and that use is another BINOP/UNOP/CONCAT writing to the
same register R, then this is an intermediate accumulator step (e.g.,
R2_6 = R2_5 + c, where R2_7 = R2_6 + d follows). Let it be inlined
into the final expression rather than emitting as a separate statement. }
if (Idx >= 0) and (Idx < Length(FUseCnt)) then begin
ArgI := FUseCnt[Idx] - CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version);
if ArgI = 1 then begin
{ Check if the single consumer writes to the same register }
for I := 0 to High(FSF^.AllNodes) do begin
if (FSF^.AllNodes[I]^.Kind in [SSA_BINOP, SSA_UNOP, SSA_CONCAT]) and
(FSF^.AllNodes[I]^.Dest.Reg = Node^.Dest.Reg) then begin
{ Check if it consumes our value }
if ((FSF^.AllNodes[I]^.OpA.Reg = Node^.Dest.Reg) and
(FSF^.AllNodes[I]^.OpA.Version = Node^.Dest.Version)) or
((FSF^.AllNodes[I]^.OpB.Reg = Node^.Dest.Reg) and
(FSF^.AllNodes[I]^.OpB.Version = Node^.Dest.Version)) then begin
{ Pre-compute and cache the expression so ExprOf inlines it
rather than resolving to a user-local name }
RHS := NodeExpr(Node);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := RHS;
Exit; { Skip - will be inlined into the consuming expression }
end;
end;
end;
end;
end;
{ Check node-based LocVar binding first, then fall back to PC-based.
But skip for accumulator intermediates: if another BINOP/UNOP/CONCAT
in the same block writes to the same register and consumes this version,
this is NOT the final defining instruction - let it be inlined instead. }
if NodeIsLocal(Node) then begin
LHS := NodeLocalName(Node);
{ Cache the local name so ExprOf returns "c" instead of re-expanding
the defining expression (e.g., "a + b") for subsequent references }
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
end
else if IsUserLocal(Node^.Dest.Reg, PC) or
IsUserLocal(Node^.Dest.Reg, PC + 1) then begin
LHS := LocalNameForEmit(Node^.Dest.Reg, PC);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
end
else if ShouldEmitAsLocal(Node^.Dest.Reg, PC) and
(IsOnlyPhiUsed(Node^.Dest.Reg, Node^.Dest.Version) or
((Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0))) then begin
LHS := LocalNameForEmit(Node^.Dest.Reg, PC);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
end
else if ShouldEmitTemp(Node^.Dest.Reg, Node^.Dest.Version, PC) then begin
LHS := TempName(Node^.Dest.Reg);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
end
else if (Idx >= 0) and (Idx < Length(FUseCnt)) and
(CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version) > 0) and
(FUseCnt[Idx] - CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version) <> 1) then begin
{ BINOP/UNOP/CONCAT with PHI use(s) and NOT exactly 1 non-PHI use.
When RealUses=1, the single consumer can inline the expression and
the PHI just carries register liveness across block boundaries.
When RealUses=0 (PHI-only) or RealUses>1 (multi-use), must emit as
statement AND cache the name for later resolution. }
if IsUserLocal(Node^.Dest.Reg, PC) or
IsUserLocal(Node^.Dest.Reg, PC + 1) or
ShouldEmitAsLocal(Node^.Dest.Reg, PC) then
LHS := LocalNameForEmit(Node^.Dest.Reg, PC)
else
LHS := TempName(Node^.Dest.Reg);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
end
else begin
if (Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] = 0) then Exit;
Exit; { temp with uses - will be inlined by consuming expression }
end;
RHS := NodeExpr(Node);
if NodeNeedsDecl(Node) then begin
NodeMarkDeclared(Node);
EmitLine('local ' + LHS + ' = ' + RHS);
end else if NeedsLocalDecl(Node^.Dest.Reg, PC) then
EmitLine('local ' + LHS + ' = ' + RHS)
else
EmitLine(LHS + ' = ' + RHS);
end;
SSA_SETGLOBAL: begin
LHS := ConstStr(Node^.ConstIdx);
if (Length(LHS) >= 2) and (LHS[1] = '"') then
LHS := Copy(LHS, 2, Length(LHS) - 2);
{ Try to emit as inline function definition }
if TryEmitInlineFunction(Node, LHS) then
{ done - was emitted inline }
else begin
RHS := ExprOf(Node^.OpA, PC);
{ Skip self-assignment (x = x) only when the source is a PHI that was
already emitted by TryEmitOrAnd. This avoids emitting the assignment
twice. Legitimate self-assignments (where OpA resolves to the same
name through normal variable flow) are NOT skipped. }
ClosureNode := nil;
if StripOuterParens(RHS) = LHS then begin
{ Check if OpA resolves to a PHI node }
for I := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[I]^.Dest, Node^.OpA) then begin
ClosureNode := FSF^.AllNodes[I]; Break;
end;
end;
if (ClosureNode <> nil) and (ClosureNode^.Kind = SSA_PHI) then
{ PHI-sourced self-assignment --> already emitted by TryEmitOrAnd }
else
EmitLine(LHS + ' = ' + StripOuterParens(RHS));
end;
end;
SSA_SETUPVAL: begin
LHS := UpvalName(Node^.UpvalIdx);
RHS := ExprOf(Node^.OpA, PC);
EmitLine(LHS + ' = ' + StripOuterParens(RHS));
end;
SSA_SETTABLE: begin
{ Try to emit as inline function/method definition first }
if TryEmitSettableFunction(Node) then
{ done - emitted as function definition }
else begin
{ When OpA is SSA_NO_REF but UpvalIdx is set, this is an upvalue table
write (SETTABUP with non-_ENV upvalue). Use the upvalue name. }
if (Node^.OpA.Reg < 0) and (Node^.UpvalIdx >= 0) then
LHS := UpvalName(Node^.UpvalIdx)
else
LHS := ExprOf(Node^.OpA, PC);
Key := ExprOf(Node^.OpB, PC);
RHS := ExprOf(Node^.OpC, PC);
{ _ENV table write --> emit as plain global assignment (e.g. _ENV.x = 1 --> x = 1) }
if LHS = '_ENV' then begin
if (Length(Key) >= 2) and (Key[1] = '"') then begin
KName := Copy(Key, 2, Length(Key) - 2);
if IsValidLuaIdent(KName) then
EmitLine(KName + ' = ' + StripOuterParens(RHS))
else
EmitLine('_ENV[' + Key + '] = ' + StripOuterParens(RHS));
end else
EmitLine('_ENV[' + Key + '] = ' + StripOuterParens(RHS));
Exit;
end;
{ Dot notation for simple string keys }
if (Length(Key) >= 2) and (Key[1] = '"') then begin
KName := Copy(Key, 2, Length(Key) - 2);
if IsValidLuaIdent(KName) then begin
EmitLine(LHS + '.' + KName + ' = ' + StripOuterParens(RHS));
Exit;
end;
end;
EmitLine(LHS + '[' + Key + '] = ' + StripOuterParens(RHS));
end;
end;
SSA_CALL: begin
{ Suppress CALL that sets up generic for loop registers (for generator/state/control) }
begin
LHS := LocalName(Node^.ImmA, PC + 1);
if (Length(LHS) > 4) and (Copy(LHS, 1, 4) = '(for') then
Exit;
end;
{ If this CALL produces results consumed as temporaries, suppress statement.
But don't suppress if the result is a user-local variable (needs assignment).
Note: LocVar StartPC is typically PC+1, so check both PC and PC+1.
Also don't suppress if result is used more than once (calls have side effects,
must not be duplicated - emit as temp variable assignment instead).
Use RealUses (total - PHI uses) since PHI merge-edges just carry register
liveness and don't actually consume the value in emitted code. }
if (Node^.ImmC >= 2) and
(not IsUserLocal(Node^.ImmA, PC)) and
(not IsUserLocal(Node^.ImmA, PC + 1)) then begin
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
if (Idx >= 0) and (Idx < Length(FUseCnt)) then begin
PhiUses := CountPhiUses(Node^.Dest.Reg, Node^.Dest.Version);
RealUses := FUseCnt[Idx] - PhiUses;
if (RealUses <= 1) and
not ((PhiUses > 0) and (RealUses = 0)) and
(not IsUpvalCaptured(Node^.ImmA, PC)) then
Exit; { single non-PHI use, not upval captured - will be inlined }
end;
{ Multi-use or upval-captured: fall through to emit as statement with temp name }
end;
{ C=0: variable returns - suppress if consumed by another expression }
if Node^.ImmC = 0 then begin
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
if (Idx >= 0) and (Idx < Length(FUseCnt)) and (FUseCnt[Idx] > 0) then
Exit;
end;
{ Build function name from SSA-versioned OpA }
FuncName := ExprOf(Node^.OpA, PC);
{ IIFE: if FuncName is a function literal, wrap in parens so that
"function(...)...end(args)" becomes "(function(...)...end)(args)" }
if Copy(FuncName, 1, 8) = 'function' then
FuncName := '(' + FuncName + ')';
{ Detect SELF-based method call - skip implicit "self" first argument }
ArgI := 0;
if (Node^.OpA.Reg >= 0) and (Node^.OpA.Reg <> SSA_CONST_REG) then begin
for I := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[I]^.Dest, Node^.OpA) and
(FSF^.AllNodes[I]^.Kind = SSA_SELF) then begin
ArgI := 1; Break;
end;
end;
{ Build arguments from SSA-versioned ArgRefs }
Args := '';
if Length(Node^.ArgRefs) > ArgI then begin
while ArgI <= High(Node^.ArgRefs) do begin
if Args <> '' then Args := Args + ', ';
RHS := StripOuterParens(ExprOf(Node^.ArgRefs[ArgI], PC));
{ Detect "(g())" adjustment for the last argument }
if ArgI = High(Node^.ArgRefs) then begin
ClosureNode := nil;
for I := 0 to High(FSF^.AllNodes) do begin
if RefEqual(FSF^.AllNodes[I]^.Dest, Node^.ArgRefs[ArgI]) then begin
ClosureNode := FSF^.AllNodes[I]; Break;
end;
end;
if (ClosureNode <> nil) and (ClosureNode^.Kind = SSA_CALL) and
(ClosureNode^.ImmC = 2) then
RHS := '(' + RHS + ')';
end;
Args := Args + RHS;
Inc(ArgI);
end;
end else if (Node^.ImmB = 0) and (Length(Node^.ArgRefs) = 0) then
Args := '...';
if (Node^.ImmC = 0) or (Node^.ImmC = 1) then begin
{ no results or variable returns as statement }
EmitLine(FuncName + '(' + Args + ')');
end else if Node^.ImmC = 2 then begin
{ single result }
LHS := LocalNameForEmit(Node^.ImmA, PC);
{ Cache the variable name for multi-use temps so ExprOf returns the
temp name instead of re-computing the call expression. }
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := LHS;
if NeedsLocalDecl(Node^.ImmA, PC) then
EmitLine('local ' + LHS + ' = ' + FuncName + '(' + Args + ')')
else
EmitLine(LHS + ' = ' + FuncName + '(' + Args + ')');
end else begin
{ multiple results (C >= 3) - check if ANY return register needs local decl }
LHS := '';
Key := ''; { reuse Key as "needs local" flag }
Expr := ''; { capture first (R(A)) name for caching }
for ArgI := Node^.ImmA to Node^.ImmA + Node^.ImmC - 2 do begin
if LHS <> '' then LHS := LHS + ', ';
RHS := LocalNameForEmit(ArgI, PC);
if Expr = '' then Expr := RHS; { first iteration = R(A) name }
LHS := LHS + RHS;
if NeedsLocalDecl(ArgI, PC) then Key := 'local ';
end;
EmitLine(Key + LHS + ' = ' + FuncName + '(' + Args + ')');
{ Cache primary result name so ExprOf returns it, not a re-built call.
Uses Node^.Dest (Reg,Version) for NodeIdx - matches ImmC=2 pattern. }
Idx := NodeIdx(Node^.Dest.Reg, Node^.Dest.Version);
if (Idx >= 0) and (Idx < Length(FExprStr)) then
FExprStr[Idx] := Expr;
end;
end;
SSA_TAILCALL: begin
FuncName := ExprOf(Node^.OpA, PC);
{ Detect SELF-based method call - skip implicit "self" first argument }
ArgI := 0;
if (Node^.OpA.Reg >= 0) and (Node^.OpA.Reg <> SSA_CONST_REG) then begin
for I := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[I]^.Dest, Node^.OpA) and
(FSF^.AllNodes[I]^.Kind = SSA_SELF) then begin
ArgI := 1; Break;
end;
end;
Args := '';
while ArgI <= High(Node^.ArgRefs) do begin
if Args <> '' then Args := Args + ', ';
Args := Args + ExprOf(Node^.ArgRefs[ArgI], PC);
Inc(ArgI);
end;
{ Fallback: if B=0 (variable args) but no ArgRefs were resolved,
the only argument is the vararg itself }
if (Node^.ImmB = 0) and (Length(Node^.ArgRefs) = 0) and (Args = '') then
Args := '...';
EmitLine('return ' + FuncName + '(' + Args + ')');
end;
SSA_RETURN: begin
{ Suppress the implicit trailing return (last instruction, no values) }
if (Node^.ImmB = 1) and (PC = Length(FProto^.Code) - 1) then
{ skip implicit trailing return }
else if Node^.ImmB = 1 then
EmitLine('return')
else if Length(Node^.ArgRefs) > 0 then begin
{ Check if returning a single CLOSURE - emit as multi-line block }
if (Length(Node^.ArgRefs) = 1) and
(Node^.ArgRefs[0].Reg >= 0) and (Node^.ArgRefs[0].Reg <> SSA_CONST_REG) then begin
{ Find defining node }
ClosureNode := nil;
for ArgI := 0 to High(FSF^.AllNodes) do
if RefEqual(FSF^.AllNodes[ArgI]^.Dest, Node^.ArgRefs[0]) then begin
ClosureNode := FSF^.AllNodes[ArgI]; Break;
end;
if (ClosureNode <> nil) and (ClosureNode^.Kind = SSA_CLOSURE) then begin
{ If the closure was already emitted as a named local/variable,
return the name instead of re-inlining the closure body. }
I := NodeIdx(ClosureNode^.Dest.Reg, ClosureNode^.Dest.Version);
if (I >= 0) and (I < Length(FExprStr)) and (FExprStr[I] <> '') and
(Pos('function', FExprStr[I]) = 0) and (Length(FExprStr[I]) < 80) then
EmitLine('return ' + FExprStr[I])
else
EmitClosureReturn(ClosureNode);
end else begin
Args := '';
for ArgI := 0 to High(Node^.ArgRefs) do begin
if Args <> '' then Args := Args + ', ';
Args := Args + StripOuterParens(ExprOf(Node^.ArgRefs[ArgI], PC));
end;
{ Detect value-adjustment pattern: return (f()) wraps a single CALL
return in parens to adjust to exactly 1 value.
Bytecode: CALL R C=2 (1 ret) + RETURN R B=2 (1 value).
When the defining node is a CALL with ImmC=2 AND the return value
is NOT a named local variable, wrap in parens.
If it's a local (e.g., "local c = f(); ... return c"), the CALL
result was already stored - no value-adjustment needed. }
if (Node^.ImmB = 2) and (ClosureNode <> nil) and
(ClosureNode^.Kind = SSA_CALL) and (ClosureNode^.ImmC = 2) and
not IsUserLocal(Node^.ArgRefs[0].Reg, PC) and
not IsUserLocal(Node^.ArgRefs[0].Reg, ClosureNode^.PC + 1) then
Args := '(' + Args + ')';
EmitLine('return ' + Args);
end;
end else begin
Args := '';
for ArgI := 0 to High(Node^.ArgRefs) do begin
if Args <> '' then Args := Args + ', ';
Args := Args + StripOuterParens(ExprOf(Node^.ArgRefs[ArgI], PC));
end;
EmitLine('return ' + Args);
end;
end else
EmitLine('return');
end;
SSA_BRANCH: begin
{ Branches are handled structurally in EmitRegion; nothing to emit here }
end;
SSA_SETLIST: begin
{ Emitted as table constructor assignments; individual items already emitted }
end;
end;
FAnnotatePC := -1;
end;